feat(progression): fancy notifications for quest/path progress + completion (#552)

* feat(progression): fancy notifications for quest/path progress + completion (#551)

Surface achievement feedback as in-app toasts when the player advances or
finishes a daily/weekly quest, and when they progress or level up an
instrument path.

- progression-core.js: _diff() now emits two partial-advance events —
  quest-progressed (a still-incomplete quest whose count rose) and
  path-progressed (a challenge toward the next level completed without a
  level-up). Both are guarded so the increment that COMPLETES a quest /
  the level-up itself stays a single quest-completed / path-level-up event
  (no double toast). Period rollovers and brand-new quest ids emit nothing.
  New events added to the capability owner's declared events list.
- notifications.js (new): reusable window.fbNotify toast surface (stacked,
  animated, auto-dismiss; animation + accent via inline styles so no new
  Tailwind utilities) + progression wiring — subtle toasts for advances,
  celebratory toasts for quest completion, path level-up, and rank-up.
- index.html: load notifications.js after progression-core.
- tests: progression_progress_events (diff emission + guards) and
  progression_notifications (toast rendering + wiring) — 11 cases.

No backend change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(progression): unwrap CustomEvent .detail in notification handlers

Codex P2: window.slopsmith.on delivers a CustomEvent (bus.on →
addEventListener), so the progression payload is e.detail — not the raw
argument. All five notifications.js handlers read the arg directly, so in
the browser every field was undefined (e.g. rank-changed never toasted).
Unwrap e.detail in each handler, matching every other sm.on consumer.

The test harness masked this by invoking handlers with raw payloads; it now
wraps them as {detail: payload} like the real bus, so the unwrap is actually
exercised (the tests fail without the fix).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Byron Gamatos
2026-06-21 21:18:28 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent a0867f8bfd
commit 63eb7a4ffc
5 changed files with 449 additions and 4 deletions
+121
View File
@@ -0,0 +1,121 @@
// Contract tests for notifications.js: the fbNotify toast surface and the
// progression:* → toast wiring (period labels, celebratory vs subtle, path
// name lookup, rank-up-only guard).
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { ROOT } = require('./capabilities_test_harness');
const SRC = fs.readFileSync(path.join(ROOT, 'static', 'v3', 'notifications.js'), 'utf8');
// Minimal DOM: enough for createElement/append/insertBefore/getElementById and
// the inline-style/innerHTML the toast sets.
function fakeDom() {
function mkEl(tag) {
return {
tagName: tag, id: '', className: '', innerHTML: '', style: {},
children: [], get firstChild() { return this.children[0] || null; },
appendChild(c) { this.children.push(c); c.parent = this; return c; },
insertBefore(c, ref) {
const i = ref ? this.children.indexOf(ref) : -1;
if (i < 0) this.children.push(c); else this.children.splice(i, 0, c);
c.parent = this; return c;
},
remove() { const p = this.parent; if (p) p.children = p.children.filter((x) => x !== this); },
addEventListener(type, fn) { (this._h || (this._h = {}))[type] = fn; },
_text() { return (this.innerHTML || '').replace(/<[^>]*>/g, ''); },
};
}
const body = mkEl('body');
const byId = (node, id) => {
if (node.id === id) return node;
for (const c of node.children) { const hit = byId(c, id); if (hit) return hit; }
return null;
};
return {
body,
createElement: mkEl,
getElementById: (id) => byId(body, id),
};
}
function load(progressionState) {
const handlers = {};
const sandbox = {
console,
setTimeout: () => 0, clearTimeout: () => {},
requestAnimationFrame: (fn) => fn(), // run animation callbacks synchronously
};
sandbox.window = sandbox;
sandbox.document = fakeDom();
// Deliver a CustomEvent-like wrapper ({detail}), exactly as the real bus
// does (capabilities.js: bus.on → addEventListener, fn gets a CustomEvent).
// Test call sites pass the raw payload; the handler must unwrap e.detail.
sandbox.window.slopsmith = { on: (name, fn) => { handlers[name] = (payload) => fn({ detail: payload }); } };
sandbox.window.v3Progression = { get: () => progressionState };
vm.createContext(sandbox);
vm.runInContext(SRC, sandbox);
const stack = () => sandbox.document.getElementById('fb-notify-stack');
return { sandbox, handlers, stack };
}
test('fbNotify.show renders a card with the title and message', () => {
const { sandbox, stack } = load(null);
assert.equal(typeof sandbox.window.fbNotify.show, 'function');
sandbox.window.fbNotify.show({ title: 'Hello', message: 'World' });
const cards = stack().children;
assert.equal(cards.length, 1);
assert.match(cards[0]._text(), /Hello/);
assert.match(cards[0]._text(), /World/);
});
test('quest-completed makes a celebratory toast with the period label and reward', () => {
const { handlers, stack } = load(null);
handlers['progression:quest-completed']({ id: 'q1', title: 'Play 3 songs', period_type: 'weekly', reward_db: 200 });
const card = stack().children[0];
assert.match(card._text(), /Weekly Quest complete!/);
assert.match(card._text(), /Play 3 songs/);
assert.match(card._text(), /\+200 dB/);
});
test('quest-progressed makes a subtle toast showing N/M and the daily label', () => {
const { handlers, stack } = load(null);
handlers['progression:quest-progressed']({ id: 'q1', title: 'Play 3 songs', period_type: 'daily', count: 2, target: 3 });
assert.match(stack().children[0]._text(), /Daily Quest advanced/);
assert.match(stack().children[0]._text(), /2\/3/);
});
test('path-level-up resolves the path name from progression state', () => {
const { handlers, stack } = load({ paths: [{ id: 'guitar', name: 'Lead Guitar' }] });
handlers['progression:path-level-up']({ path_id: 'guitar', new_level: 4 });
assert.match(stack().children[0]._text(), /Lead Guitar — Level 4!/);
});
test('path-progressed shows path name and challenge count toward the next level', () => {
const { handlers, stack } = load(null);
handlers['progression:path-progressed']({ id: 'bass', name: 'Bass', completed: 2, required: 3, next_level: 2 });
assert.match(stack().children[0]._text(), /Bass progress/);
assert.match(stack().children[0]._text(), /2\/3 to Level 2/);
});
test('rank-changed toasts on a rank up but not a rank drop', () => {
const up = load(null);
up.handlers['progression:rank-changed']({ from: 2, to: 3 });
assert.equal(up.stack().children.length, 1);
assert.match(up.stack().children[0]._text(), /Mastery Rank 3!/);
const down = load(null);
down.handlers['progression:rank-changed']({ from: 3, to: 2 });
assert.equal(down.stack() ? down.stack().children.length : 0, 0); // no toast on a drop
});
test('newest toast is inserted on top of the stack', () => {
const { sandbox, stack } = load(null);
sandbox.window.fbNotify.show({ title: 'first' });
sandbox.window.fbNotify.show({ title: 'second' });
assert.match(stack().children[0]._text(), /second/);
assert.match(stack().children[1]._text(), /first/);
});
@@ -0,0 +1,115 @@
// Contract tests for progression-core's _diff(): the quest-progressed /
// path-progressed "advance" events that feed the achievement toasts, plus the
// guards that keep a completion / level-up from also firing a progress event.
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { ROOT } = require('./capabilities_test_harness');
const SRC = fs.readFileSync(path.join(ROOT, 'static', 'v3', 'progression-core.js'), 'utf8');
// Load progression-core.js in a sandbox whose fetch returns `states` in order.
// Boot consumes states[0] (prev=null → no diff); each later refresh() diffs
// against the previous state.
function load(states) {
const events = [];
let i = 0;
const sandbox = {
console,
setTimeout, clearTimeout,
fetch: async () => ({ ok: true, json: async () => states[Math.min(i++, states.length - 1)] }),
};
sandbox.window = sandbox;
sandbox.window.slopsmith = { emit: (name, detail) => events.push({ name, detail }) };
sandbox.document = { readyState: 'complete', addEventListener: () => {} };
vm.createContext(sandbox);
vm.runInContext(SRC, sandbox);
return { sandbox, events };
}
const stateA = {
mastery_rank: 2,
wallet: { balance: 100 },
quests: {
daily: { quests: [
{ id: 'q1', title: 'Play 3 songs', count: 1, target: 3, completed: false, reward_db: 50 },
{ id: 'q2', title: 'Finish one', count: 0, target: 1, completed: false, reward_db: 20 },
] },
weekly: { quests: [
{ id: 'w1', title: 'Weekly grind', count: 2, target: 10, completed: false, reward_db: 200 },
] },
},
paths: [
{ id: 'guitar', name: 'Guitar', level: 1, max_level: 10, next: { level: 2, required: 3, completed: 1 } },
{ id: 'bass', name: 'Bass', level: 0, max_level: 10, next: { level: 1, required: 2, completed: 0 } },
],
};
const stateB = {
mastery_rank: 3, // rank up
wallet: { balance: 170 }, // dB changed
quests: {
daily: { quests: [
{ id: 'q1', title: 'Play 3 songs', count: 2, target: 3, completed: false, reward_db: 50 }, // advanced
{ id: 'q2', title: 'Finish one', count: 1, target: 1, completed: true, reward_db: 20 }, // COMPLETED
] },
weekly: { quests: [
{ id: 'w1', title: 'Weekly grind', count: 3, target: 10, completed: false, reward_db: 200 }, // advanced
] },
},
paths: [
{ id: 'guitar', name: 'Guitar', level: 1, max_level: 10, next: { level: 2, required: 3, completed: 2 } }, // progressed
{ id: 'bass', name: 'Bass', level: 1, max_level: 10, next: { level: 2, required: 3, completed: 0 } }, // LEVELED UP
],
};
async function diffEvents() {
const { sandbox, events } = load([stateA, stateB]);
await sandbox.window.v3Progression.refresh(); // coalesces with boot → state = A
events.length = 0; // drop boot's progression:updated
await sandbox.window.v3Progression.refresh(); // state = B → _diff(A, B)
return events.filter((e) => e.name !== 'progression:updated');
}
test('quest advance emits quest-progressed with period_type, completion does not', async () => {
const ev = await diffEvents();
const progressed = ev.filter((e) => e.name === 'progression:quest-progressed');
const ids = progressed.map((e) => e.detail.id).sort();
assert.deepEqual(ids, ['q1', 'w1']); // q2 completed → not a progress event
const q1 = progressed.find((e) => e.detail.id === 'q1').detail;
assert.equal(q1.period_type, 'daily');
assert.equal(q1.count, 2);
assert.equal(q1.target, 3);
const w1 = progressed.find((e) => e.detail.id === 'w1').detail;
assert.equal(w1.period_type, 'weekly');
});
test('path challenge progress emits path-progressed; a level-up does not', async () => {
const ev = await diffEvents();
const progressed = ev.filter((e) => e.name === 'progression:path-progressed');
assert.equal(progressed.length, 1);
const g = progressed[0].detail;
assert.equal(g.id, 'guitar');
assert.equal(g.name, 'Guitar');
assert.equal(g.completed, 2);
assert.equal(g.required, 3);
assert.equal(g.next_level, 2);
// bass leveled up (level 0 → 1) → handled by path-level-up, not path-progressed.
assert.ok(!progressed.some((e) => e.detail.id === 'bass'));
});
test('rank-up and dB change still emit their events', async () => {
const ev = await diffEvents();
const rank = ev.find((e) => e.name === 'progression:rank-changed');
assert.ok(rank && rank.detail.from === 2 && rank.detail.to === 3);
assert.ok(ev.some((e) => e.name === 'progression:db-changed'));
});
test('no progress events fire on the very first state (prev=null)', async () => {
const { sandbox, events } = load([stateA]);
await sandbox.window.v3Progression.refresh();
assert.ok(!events.some((e) => /progressed|changed/.test(e.name)));
});