The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(devices): notify less — alert, list or silent per turn, decided once in the daemon (#1438)
0xdiego25a6464ec1c697
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 94efe6375..57449a4e9 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -901,8 +901,8 @@ export function cableStepFor(* kind reaches the cable the day it reaches the socket.*/export function cableEventFor(- frame: { type?: string; agentId?: string; payload?: { kind?: string; text?: string; recap?: string; subagent?: unknown; restored?: unknown; update?: unknown; fullText?: unknown } },-): { kind: 'processing' | 'done' | 'summary' | 'error'; agentId: string; text: string; recap: string; subagent: boolean; update?: string; fullText?: string } | null {+ frame: { type?: string; agentId?: string; payload?: { kind?: string; text?: string; recap?: string; subagent?: unknown; restored?: unknown; update?: unknown; fullText?: unknown; failed?: unknown } },+): { kind: 'processing' | 'done' | 'summary' | 'error'; agentId: string; text: string; recap: string; subagent: boolean; update?: string; fullText?: string; failed?: boolean } | null {if (frame.type !== 'commander_event' || !frame.agentId) return nullconst kind = frame.payload?.kindif (kind !== 'processing' && kind !== 'done' && kind !== 'summary' && kind !== 'error') return null@@ -913,6 +913,7 @@ export function cableEventFor(const fullText = frame.payload?.fullTextreturn { kind, agentId: frame.agentId, text: frame.payload?.text ?? '', recap: frame.payload?.recap ?? '', subagent: silent,...(kind === 'processing' && typeof update === 'string' ? { update } : {}),+ ...(kind === 'summary' && frame.payload?.failed === true ? { failed: true } : {}),...(kind === 'summary' && typeof fullText === 'string' && fullText ? { fullText } : {}) }}diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex df0f6ef2f..7e1c5b8d4 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -2049,7 +2049,7 @@ describe('cable session', () => {port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })await session.summary('a1', 'recap one', 'body one')- await session.summary('a2', 'recap two', 'body two', true)+ await session.summary('a2', 'recap two', 'body two', 'list')const sent = port.sent.filter((m) => m.t === 'summary' && !m.restore)// Absent, not false, on the ordinary path: firmware that predates the flag must keep notifying@@ -2059,12 +2059,20 @@ describe('cable session', () => {expect(sent.find((m) => m.agentId === 'a2')).toMatchObject({ quiet: true, recap: 'recap two' })// A sub-agent's turn: silent — no beep, no drawer row — and the recap still travels.- await session.summary('a1', 'recap three', 'body three', false, true)+ await session.summary('a1', 'recap three', 'body three', 'silent', undefined, true)const silent = port.sent.filter((m) => m.t === 'summary' && m.agentId === 'a1').pop()expect(silent).toMatchObject({ silent: true, recap: 'recap three' })expect(silent).not.toHaveProperty('quiet')})+ it('sends the tier, with quiet for list and silent for silent, and neither for alert', async () => {+ const { session, port } = await connect(makeHost({}))+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })+ for (const tier of ['alert', 'list', 'silent'] as const) await session.summary('a1', `r ${tier}`, 'b', tier)+ const sent = port.sent.filter((m) => m.t === 'summary' && !m.restore)+ expect(sent.map((m) => [m.tier, m.quiet, m.silent])).toEqual([['alert', undefined, undefined], ['list', true, undefined], ['silent', undefined, true]])+ })+it('redraws a reattached dial with what each agent was last doing', async () => {// The summaries were on disk the whole time; a tile with a name and no recap has forgotten the work// it belongs to. Newest LAST on the wire so it ends up on top of the tile's stack.@@ -3131,7 +3139,7 @@ describe('hello capabilities', () => {// A turn with prose and tool cards, a summary carrying the whole answer, and a library request.await session.turnStarted('a1', 'Processing', 'Looking at the spec first')await session.turnStep('a1', 'Read · cableSession.ts')- await session.summary('a1', 'r', 'b', false, false, answer)+ await session.summary('a1', 'r', 'b', 'alert', answer)port.say({ t: 'player.library.get', offset: 0, request: 1 }); await settle()await session.syncSwarms(true)@@ -3139,7 +3147,7 @@ describe('hello capabilities', () => {expect(port.sent.map((m) => JSON.stringify(m))).toEqual(['{"t":"turn.started","agentId":"a1","text":"Processing"}','{"t":"turn.activity","agentId":"a1","text":"Working"}',- '{"t":"summary","agentId":"a1","name":"Fix login screen","engine":"claude","machine":"","recap":"r","text":"b"}',+ '{"t":"summary","agentId":"a1","name":"Fix login screen","engine":"claude","machine":"","recap":"r","text":"b","tier":"alert"}','{"t":"swarms","selected":"t1","items":[{"id":"t1","name":"Tab 1","agents":2,"panes":2},{"id":"t2","name":"Tab 2","agents":1,"panes":1}],"tiles":[]}',])} finally { await session.stop() }@@ -3267,7 +3275,7 @@ describe('hello capabilities', () => {try {port.say(PRO_HELLO)await vi.waitFor(() => expect(port.types()).toContain('notif.replace'))- await session.summary('a1', 'r', 'x'.repeat(7_900), false, false, 'y'.repeat(1_000))+ await session.summary('a1', 'r', 'x'.repeat(7_900), 'alert', 'y'.repeat(1_000))const frame = ofType(port, 'summary').at(-1)!expect(frame.text).toBe('x'.repeat(7_900))expect(frame).not.toHaveProperty('full')@@ -3319,7 +3327,7 @@ describe('hello capabilities', () => {try {port.say(PRO_HELLO)await vi.waitFor(() => expect(port.types()).toContain('notif.replace'))- await session.summary('a1', 'Kết quả', 'Kết quả', false, false, answer)+ await session.summary('a1', 'Kết quả', 'Kết quả', 'alert', answer)const frame = ofType(port, 'summary').at(-1) as { full: string }expect(frame.full.length).toBeLessThanOrEqual(1200)expect(Buffer.byteLength(frame.full)).toBeLessThanOrEqual(3600)@@ -3499,7 +3507,7 @@ describe('hello capabilities', () => {await session.questionClose('session-0', 'q1')await session.syncPlayerLibrary(true)expect(statusOf('session-0')).toBe('working') // answered: the turn goes on- await session.summary('session-0', 'Sub done.', 'Sub done.', false, true)+ await session.summary('session-0', 'Sub done.', 'Sub done.', 'silent', undefined, true)await session.syncPlayerLibrary(true)expect(statusOf('session-0')).toBe('working') // a sub-agent's end is not the turn'sawait session.turnDone('session-0')diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 305b2aef9..b5545c9d0 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -267,6 +267,7 @@ import type { VisitCommand, VisitResult } from './windowVisit.js'import type { FormCommand, FormResult } from './windowForm.js'import { deriveLongRecap, extendShortRecap } from '../lib/deviceRecap.js'import type { TurnStatsFields } from './turnStats.js'+import type { Tier } from '../lib/notifyTier.js'export interface RouteDecision {agentId: string@@ -2816,22 +2817,19 @@ export class CableSession {/*** A finished turn's recap.*- * `quiet` means the window already has this agent on screen: draw the tile,- * skip the notification drawer (the beep still sounds). `silent` means the- * turn was a sub-agent's: draw the tile, skip the beep AND the drawer — the- * main agent's own end is the one the person is waiting for. Extra fields- * rather than different frames, so firmware that predates them simply- * notifies as it always did instead of losing the recap.+ * `tier` is how loudly to tell (lib/notifyTier.ts): `alert` beeps and wakes; `list` is a drawer entry only (`quiet`);+ * `silent` draws the tile only (`silent`). `quiet`/`silent` ride along as well as+ * `tier`, so firmware that predates `tier` still behaves. `subagent`: a sub-agent's end is not its main agent's.*/- async summary(agentId: string, recap: string, text: string, quiet = false, silent = false, fullText?: string): Promise<void> {- if (!silent) this.liveTurns.delete(agentId) // a sub-agent's end is not its main agent's+ async summary(agentId: string, recap: string, text: string, tier: Tier = 'alert', fullText?: string, subagent = false): Promise<void> {+ if (!subagent) this.liveTurns.delete(agentId) // a sub-agent's end is not its main agent'sthis.activityReads.delete(agentId)this.activityEndedAt.set(agentId, Date.now())recap = extendShortRecap(recap, text)const who = this.whoIs(agentId)// The card carries the answer; the host is asked only when it did not, and not for long.const full = this.fullField(this.longRecap ? fullText ?? await this.storedFullText(agentId, text) : undefined)- await this.send(this.withinCap({ t: 'summary', agentId, ...who, recap, text, ...full, ...(quiet ? { quiet: true } : {}), ...(silent ? { silent: true } : {}) }))+ await this.send(this.withinCap({ t: 'summary', agentId, ...who, recap, text, ...full, tier, ...(tier === 'list' ? { quiet: true } : {}), ...(tier === 'silent' ? { silent: true } : {}) }))}/**diff --git a/cli/src/core/agents/cloud.spec.ts b/cli/src/core/agents/cloud.spec.tsindex 38b0a5799..ed3b7cba8 100644--- a/cli/src/core/agents/cloud.spec.ts+++ b/cli/src/core/agents/cloud.spec.ts@@ -86,6 +86,12 @@ describe('agents a service owns', () => {cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'working', said: 'Which one?\n1) 9:30\n2) 11:00' })])cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'failed', said: 'Which one?\n1) 9:30\n2) 11:00' })])expect(cards().at(-1)).toMatchObject({ payload: { kind: 'error', text: 'It stopped with an error.' } })+ // Failing with something new said: the summary carries `failed`, so the tier is an alert.+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'working', said: 'Which one?\n1) 9:30\n2) 11:00' })])+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'failed', said: 'Running migrations…', messages: 9 })])+ expect(cards().at(-1)).toMatchObject({ payload: { kind: 'summary', failed: true } })+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'working', said: 'Which one?\n1) 9:30\n2) 11:00' })])+ cloud.doors.publish([harness({ agent: 'fo', name: 'trip!', state: 'failed', said: 'Which one?\n1) 9:30\n2) 11:00' })])// Idle and changed, with nothing new said: nothing to tell.const before = cards().lengthcloud.doors.publish([harness({ agent: 'fo', name: 'renamed', state: 'failed', said: 'Which one?\n1) 9:30\n2) 11:00' })])diff --git a/cli/src/core/agents/cloud.ts b/cli/src/core/agents/cloud.tsindex 15822ccff..a148f337a 100644--- a/cli/src/core/agents/cloud.ts+++ b/cli/src/core/agents/cloud.ts@@ -71,7 +71,7 @@ export function createCloudAgents({ port, clients, openQuestions, deviceInput, lif (recap && harness.said !== told.get(harness.agentId)) {told.set(harness.agentId, harness.said!)// Waiting on the person, its question rings instead (lib/agentNotifications.ts keeps the same rule).- card(harness, { kind: 'summary', ...recap, notification: harness.state === 'needs_input' ? null : { id: `${harness.agentId}:${harness.messages}`, kind: 'done' } })+ card(harness, { kind: 'summary', ...recap, ...(harness.state === 'failed' ? { failed: true } : {}), notification: harness.state === 'needs_input' ? null : { id: `${harness.agentId}:${harness.messages}`, kind: 'done' } })} else if (busy(before)) {card(harness, harness.state === 'failed' ? { kind: 'error', text: harness.activity ?? 'It stopped with an error.' } : { kind: 'done', text: 'done' })}diff --git a/cli/src/lib/notifyTier.spec.ts b/cli/src/lib/notifyTier.spec.tsnew file mode 100644index 000000000..09d467750--- /dev/null+++ b/cli/src/lib/notifyTier.spec.ts@@ -0,0 +1,95 @@+import { describe, expect, it, vi } from 'vitest'+import { JevUnavailable } from './jev/jevClient.js'+import { createTierDecider, type TierInput } from './notifyTier.js'++const base: TierInput = {+ agent: 'lamp', engine: 'codex', recap: 'Shipped the thing.', durationS: 300,+ stats: { testsPassed: 640, testsFailed: 0, commits: 1 }, subagent: false, onScreen: false, failed: false,+}+const answer = (choice: string) => ({ tier: { choice, probabilities: { alert: 0.1, list: 0.2, silent: 0.7, [choice]: 0.9 } } })+const make = (jev: any, extra: object = {}) => {+ const log = vi.fn()+ return { log, decide: createTierDecider({ jev, log, ...extra }) }+}++describe('notifyTier', () => {+ it('failed → alert by rule, Jev never asked', async () => {+ const jev = vi.fn()+ const { decide } = make(jev)+ const d = await decide({ ...base, failed: true })+ expect(d).toMatchObject({ tier: 'alert', by: 'rule:failed' })+ expect(jev).not.toHaveBeenCalled()+ })++ it('subagent → silent; onScreen → silent; empty recap → silent', async () => {+ const jev = vi.fn()+ const { decide } = make(jev)+ expect(await decide({ ...base, subagent: true })).toMatchObject({ tier: 'silent', by: 'rule:subagent' })+ expect(await decide({ ...base, onScreen: true })).toMatchObject({ tier: 'silent', by: 'rule:onScreen' })+ expect(await decide({ ...base, recap: ' ' })).toMatchObject({ tier: 'silent', by: 'rule:empty' })+ expect(jev).not.toHaveBeenCalled()+ })++ it('otherwise asks Jev once with recap ≤ 600 chars and recent counts; returns its choice', async () => {+ const jev = vi.fn(async () => answer('list'))+ const { decide } = make(jev)+ const d = await decide({ ...base, recap: 'x'.repeat(2000) })+ expect(d).toMatchObject({ tier: 'list', by: 'jev' })+ expect(jev).toHaveBeenCalledTimes(1)+ const [state, questions] = jev.mock.calls[0] as any[]+ expect(state.recap.length).toBeLessThanOrEqual(600)+ expect(state).toMatchObject({+ agent: 'lamp', engine: 'codex', duration_s: 300,+ work: { tests_passed: 640, tests_failed: 0, commits: 1 }, recent: { alerts_30m: 0, lists_30m: 0 },+ })+ expect(Object.keys(questions)).toEqual(['tier'])+ expect(Object.keys(questions.tier.criteria)).toEqual(['alert', 'list', 'silent'])+ })++ it('Jev unavailable / too slow / null answer → fallback by duration', async () => {+ const down = make(vi.fn(async () => { throw new JevUnavailable('NO_KEY', 'no key') }))+ expect(await down.decide(base)).toMatchObject({ tier: 'list', by: 'fallback:NO_KEY' })+ expect(await down.decide({ ...base, durationS: 119 })).toMatchObject({ tier: 'silent' })+ expect(await down.decide({ ...base, durationS: null })).toMatchObject({ tier: 'silent' })+ const slow = make(() => new Promise(() => {}), { budgetMs: 20 })+ expect(await slow.decide(base)).toMatchObject({ tier: 'list', by: 'fallback:timeout' })+ const bad = make(vi.fn(async () => ({})))+ expect(await bad.decide({ ...base, durationS: 10 })).toMatchObject({ tier: 'silent', by: 'fallback:no-answer' })+ })++ it('jev null → fallback without calling anything', async () => {+ const { decide } = make(null)+ expect(await decide(base)).toMatchObject({ tier: 'list', by: 'fallback:off' })+ })++ it('logs exactly one line per decision', async () => {+ const { decide, log } = make(vi.fn(async () => answer('alert')))+ await decide(base)+ await decide({ ...base, failed: true })+ expect(log).toHaveBeenCalledTimes(4) // each decision, then the day's count+ expect(log.mock.calls[1][0]).toMatch(/^notify · day \d{4}-\d\d-\d\d · alert 1 · list 0 · silent 0$/)+ expect(log.mock.calls[0][0]).toMatch(/^notify · lamp · alert · jev · .+ · \d+ms$/)+ expect(log.mock.calls[2][0]).toMatch(/^notify · lamp · alert · rule:failed · .+ · \d+ms$/)+ })++ it('recent counts: alerts in a 30 min window, older ones drop out', async () => {+ let t = 0+ const jev = vi.fn(async () => answer('alert'))+ const { decide } = make(jev, { now: () => t })+ for (let i = 0; i < 3; i++) { t = i * 60_000; await decide(base) }+ t = 4 * 60_000+ await decide(base)+ expect((jev.mock.calls[3] as any[])[0].recent.alerts_30m).toBe(3)+ t = 31 * 60_000+ await decide(base)+ expect((jev.mock.calls[4] as any[])[0].recent.alerts_30m).toBe(2)+ })++ it('5 concurrent decisions resolve independently within the budget', async () => {+ const { decide } = make(() => new Promise(() => {}), { budgetMs: 50 })+ const start = Date.now()+ const all = await Promise.all([1, 2, 3, 4, 5].map(() => decide(base)))+ expect(all.every((d) => d.by === 'fallback:timeout')).toBe(true)+ expect(Date.now() - start).toBeLessThan(250)+ })+})diff --git a/cli/src/lib/notifyTier.ts b/cli/src/lib/notifyTier.tsnew file mode 100644index 000000000..6ded53f29--- /dev/null+++ b/cli/src/lib/notifyTier.ts@@ -0,0 +1,102 @@+/**+ * How loudly a finished turn tells the devices: rules first, Jev for the grey zone, a fallback when Jev+ * cannot answer in time (docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md).+ */+import type { JevChoice, JevDecide } from './jev/jevClient.js'+import { JevUnavailable } from './jev/jevClient.js'++export type Tier = 'alert' | 'list' | 'silent'+export interface TierInput {+ agent: string; engine: string; recap: string+ durationS: number | null // null: unknown start+ stats: { testsPassed?: number; testsFailed?: number; commits?: number }+ subagent: boolean; onScreen: boolean; failed: boolean+}+export interface TierDecision { tier: Tier; by: string; detail: string; ms: number }++const WINDOW_MS = 30 * 60_000+const RECAP_MAX = 600+const LONG_TURN_S = 120++const QUESTIONS: Record<string, JevChoice> = {+ tier: {+ type: 'choice',+ instructions: 'An AI coding agent just finished a turn while its owner was looking at something else. Choose how loudly to tell them.',+ criteria: {+ alert: 'A substantial result the person would want to know about now, such as a long task finished, a build or deploy done, or a requested deliverable ready. Less likely when alerts_30m is already high.',+ list: 'Real progress worth a glance later, such as a small feature or a fix with edits.',+ silent: 'Chatter, such as an acknowledgement, a short answer, a no-op, or a step inside a longer job.',+ },+ },+}++/** Logs one decision line and the day's running count per tier, so the volume can be read from the log (no storage). */+export function createTally(log: (line: string) => void, now: () => number = Date.now): (agent: string, tier: Tier, by: string, detail: string, ms: number) => void {+ let day = ''+ const counts: Record<Tier, number> = { alert: 0, list: 0, silent: 0 }+ return (agent, tier, by, detail, ms) => {+ log(`notify · ${agent} · ${tier} · ${by} · ${detail} · ${ms}ms`)+ const today = new Date(now()).toLocaleDateString('sv') // local YYYY-MM-DD, so a day matches the person's day+ if (today !== day) { day = today; counts.alert = counts.list = counts.silent = 0 }+ counts[tier]+++ log(`notify · day ${day} · alert ${counts.alert} · list ${counts.list} · silent ${counts.silent}`)+ }+}++export function createTierDecider(opts: {+ jev: JevDecide | null; now?: () => number; log: (line: string) => void; budgetMs?: number+ tally?: ReturnType<typeof createTally>+}): (input: TierInput) => Promise<TierDecision> {+ const tally = opts.tally ?? createTally(opts.log, opts.now)+ const now = opts.now ?? Date.now+ const budgetMs = opts.budgetMs ?? 1000+ const recent: { at: number; tier: Tier }[] = []++ const count = (tier: Tier) => {+ const from = now() - WINDOW_MS+ while (recent.length && recent[0].at <= from) recent.shift()+ return recent.filter((r) => r.tier === tier).length+ }++ return async (input) => {+ const start = now()+ const finish = (tier: Tier, by: string, detail: string): TierDecision => {+ const ms = Math.max(0, now() - start)+ if (tier !== 'silent') recent.push({ at: now(), tier })+ tally(input.agent, tier, by, detail, ms)+ return { tier, by, detail, ms }+ }+ const rule = (tier: Tier, name: string) => finish(tier, `rule:${name}`, name)+ if (input.failed) return rule('alert', 'failed')+ if (input.subagent) return rule('silent', 'subagent')+ if (input.onScreen) return rule('silent', 'onScreen')+ if (!input.recap.trim()) return rule('silent', 'empty')++ const fallback = (reason: string) => {+ const long = input.durationS !== null && input.durationS >= LONG_TURN_S+ return finish(long ? 'list' : 'silent', `fallback:${reason}`, input.durationS === null ? 'duration unknown' : `${input.durationS}s`)+ }+ if (!opts.jev) return fallback('off')++ const state = {+ agent: input.agent, engine: input.engine, recap: input.recap.slice(0, RECAP_MAX), duration_s: input.durationS,+ work: { tests_passed: input.stats.testsPassed, tests_failed: input.stats.testsFailed, commits: input.stats.commits },+ recent: { alerts_30m: count('alert'), lists_30m: count('list') },+ }+ const abort = new AbortController()+ let timer: ReturnType<typeof setTimeout> | undefined+ const late = new Promise<'timeout'>((resolve) => { timer = setTimeout(() => { abort.abort(); resolve('timeout') }, budgetMs) })+ try {+ const answers = await Promise.race([opts.jev(state, QUESTIONS, abort.signal), late])+ if (answers === 'timeout') return fallback('timeout')+ const answer = answers.tier+ if (!answer || !(answer.choice in QUESTIONS.tier.criteria)) return fallback('no-answer')+ const p = Object.entries(answer.probabilities).map(([k, v]) => `${k}=${Number(v).toFixed(2)}`).join(',')+ return finish(answer.choice as Tier, 'jev', `p=${p}`)+ } catch (error) {+ return fallback(error instanceof JevUnavailable ? error.code : 'error')+ } finally {+ clearTimeout(timer)+ }+ }+}diff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.tsindex 6d526e507..49ea6df28 100644--- a/cli/src/services/devices.spec.ts+++ b/cli/src/services/devices.spec.ts@@ -57,6 +57,8 @@ vi.mock('../cable/cableFleet.js', async (real) => {turnError = recorder('turnError')petsChanged = recorder('petsChanged')wants = true+ connected = true+ get isConnected() { return this.connected }wantsStats() { return this.wants }petDial = () => ({ supported: false, held: [] as string[], sending: null })setSettings = vi.fn(async (id: string, _patch: unknown) => (id === 'usb' ? { ok: true } : { ok: false, error: 'That device is not plugged into this computer.' }))@@ -118,6 +120,9 @@ vi.mock('../lib/voiceRouter.js', () => ({routeVoiceTask: vi.fn(),}))+const jevMade = vi.hoisted(() => vi.fn())+vi.mock('../lib/jev/jevClient.js', async (orig) => ({ ...(await orig<object>()), createJevDecide: (...a: unknown[]) => { jevMade(...a); return async () => { throw new Error('no jev here') } } }))+const { startDevices } = await import('./devices.js')let dataDir: string@@ -134,7 +139,7 @@ afterEach(() => {vi.restoreAllMocks()})-function start(over: { core?: CoreApi; faults?: string[]; cableDisabled?: boolean; testDialPort?: string; readUsage?: DevicesDeps['readUsage']; now?: () => number } = {}) {+function start(over: { core?: CoreApi; faults?: string[]; cableDisabled?: boolean; testDialPort?: string; readUsage?: DevicesDeps['readUsage']; now?: () => number; decideTier?: DevicesDeps['decideTier'] | null } = {}) {const core = over.core ?? fakeCore({ dataDir })const ports: CorePorts = emptyPorts()const onExit = vi.fn()@@ -146,6 +151,7 @@ function start(over: { core?: CoreApi; faults?: string[]; cableDisabled?: booleacableDisabled: over.cableDisabled,readUsage: over.readUsage,now: over.now,+ decideTier: over.decideTier === null ? undefined : over.decideTier ?? (async () => ({ tier: 'alert', by: 'test', detail: '', ms: 0 })),faults: new Set(over.faults ?? []),log: (line) => { logs.push(line) },onExit,@@ -368,7 +374,106 @@ describe('what the windows say, reaching the dial', () => {port.desk(['a2', 'a1'], false)port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done' } })port.card({ type: 'commander_event', agentId: 'a9', payload: { kind: 'summary', text: 'done', subagent: true } })- expect(calls('summary')).toEqual([['a1', 'fixed it', 'done', true, false], ['a1', 'done', 'done', false, false], ['a9', 'done', 'done', false, true]])+ await vi.waitFor(() => expect(calls('summary')).toHaveLength(3))+ // The one that asked the decider lands last: the other two never wait.+ expect(calls('summary')).toEqual([['a1', 'fixed it', 'done', 'silent', undefined, false], ['a9', 'done', 'done', 'silent', undefined, true], ['a1', 'done', 'done', 'alert', undefined, false]])+ })++ describe('a summary\'s tier', () => {+ afterEach(() => { delete process.env.HARNESS_NOTIFY_SMART })+ it('builds the default decider without Jev when HARNESS_NOTIFY_SMART is 0, and with it otherwise', () => {+ process.env.HARNESS_NOTIFY_SMART = '0'+ start({ decideTier: null })+ expect(jevMade).not.toHaveBeenCalled()+ delete process.env.HARNESS_NOTIFY_SMART+ start({ decideTier: null })+ expect(jevMade).toHaveBeenCalledTimes(1)+ })++ it('keeps the next turn behind a recap still waiting on the decider', async () => {+ vi.useFakeTimers()+ try {+ const decideTier = vi.fn(() => new Promise<{ tier: 'alert'; by: string; detail: string; ms: number }>((r) => setTimeout(() => r({ tier: 'alert', by: 't', detail: '', ms: 0 }), 500)))+ const { port } = start({ decideTier })+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'done', text: 'done' } })+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'r' } })+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'processing', text: 'next' } })+ await vi.advanceTimersByTimeAsync(100)+ expect(seen.cable.calls.map(([n]) => n).filter((n) => n === 'summary' || n === 'turnStarted')).toEqual([])+ await vi.advanceTimersByTimeAsync(600)+ expect(seen.cable.calls.map(([n]) => n).filter((n) => n === 'summary' || n === 'turnStarted')).toEqual(['summary', 'turnStarted'])+ } finally { vi.useRealTimers() }+ })++ it('does not let a sub-agent\'s summary use up the main turn\'s numbers, and times a restarted turn afresh', async () => {+ const decideTier = vi.fn(async (_i: { durationS: number | null }) => ({ tier: 'alert' as const, by: 't', detail: '', ms: 0 }))+ const { port } = start({ decideTier })+ const card = (kind: string, extra = {}) => port.card({ type: 'commander_event', agentId: 'a1', payload: { kind, text: 'x', ...extra } })+ vi.useFakeTimers({ toFake: ['Date'] })+ try {+ vi.setSystemTime(0); card('processing')+ vi.setSystemTime(60_000); card('done')+ card('summary', { subagent: true })+ card('summary', { recap: 'first' })+ await vi.waitFor(() => expect(calls('summary')).toHaveLength(2))+ vi.setSystemTime(100_000); card('processing')+ await vi.waitFor(() => expect(calls('turnStarted')).toHaveLength(2))+ vi.setSystemTime(110_000); card('done')+ await vi.waitFor(() => expect(calls('turnDone')).toHaveLength(2))+ card('summary', { recap: 'second' })+ await vi.waitFor(() => expect(decideTier).toHaveBeenCalledTimes(2))+ } finally { vi.useRealTimers() }+ expect(decideTier.mock.calls.map(([i]) => i.durationS)).toEqual([60, 10])+ })++ const summaryCalls = () => calls('summary')+ it('is silent without asking Jev when the agent is on screen or the turn was a sub-agent\'s', () => {+ const decideTier = vi.fn()+ const { port } = start({ decideTier })+ port.desk(['a1'], true)+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done' } })+ port.card({ type: 'commander_event', agentId: 'a9', payload: { kind: 'summary', text: 'done', subagent: true } })+ expect(summaryCalls()).toEqual([['a1', 'done', 'done', 'silent', undefined, false], ['a9', 'done', 'done', 'silent', undefined, true]])+ expect(decideTier).not.toHaveBeenCalled()+ })++ it('never asks the decider while no device is connected, and still draws the tile', () => {+ const decideTier = vi.fn()+ const { port } = start({ decideTier })+ ;(seen.cable as unknown as { connected: boolean }).connected = false+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'fixed it' } })+ expect(decideTier).not.toHaveBeenCalled()+ expect(summaryCalls()).toEqual([['a1', 'fixed it', 'done', 'silent', undefined, false]])+ })++ it('tells the decider a failed cloud summary failed, and logs rule decisions with the day\'s count', async () => {+ const decideTier = vi.fn(async () => ({ tier: 'alert' as const, by: 't', detail: '', ms: 0 }))+ const { port } = start({ decideTier })+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'x', recap: 'r', failed: true } })+ await vi.waitFor(() => expect(decideTier).toHaveBeenCalledWith(expect.objectContaining({ failed: true })))+ port.desk(['a2'], true)+ port.card({ type: 'commander_event', agentId: 'a2', payload: { kind: 'summary', text: 'x' } })+ port.card({ type: 'commander_event', agentId: 'a2', payload: { kind: 'error', text: 'boom' } })+ expect(logs.some((l) => /notify · .* · silent · rule:onScreen · onScreen · 0ms/.test(l))).toBe(true)+ expect(logs.some((l) => /notify · .* · alert · rule:failed/.test(l))).toBe(true)+ expect(logs.some((l) => /notify · day \d{4}-\d\d-\d\d · alert 1 · list 0 · silent 1/.test(l))).toBe(true)+ })++ it('is the decider\'s, asked with the duration and stats of the turn that just ended', async () => {+ const decideTier = vi.fn(async () => ({ tier: 'list' as const, by: 'test', detail: '', ms: 0 }))+ const { port } = start({ decideTier })+ vi.useFakeTimers()+ try {+ vi.setSystemTime(1_000_000)+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'processing', text: 'go' } })+ vi.setSystemTime(1_000_000 + 95_000)+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'done', text: 'done' } })+ } finally { vi.useRealTimers() }+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'fixed it' } })+ await vi.waitFor(() => expect(summaryCalls()).toHaveLength(1))+ expect(decideTier).toHaveBeenCalledWith(expect.objectContaining({ recap: 'fixed it', durationS: 95, onScreen: false, subagent: false }))+ expect(summaryCalls()[0].slice(0, 4)).toEqual(['a1', 'fixed it', 'done', 'list'])+ })})it('passes the tabs, the unread rows, the window\'s focus and what it saw', () => {@@ -694,10 +799,11 @@ describe('what the windows say, reaching the dial', () => {expect(calls('turnStats')).toEqual([])})- it('hands the dial the whole answer a summary card carries', () => {+ it('hands the dial the whole answer a summary card carries', async () => {const { port } = start()port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'b', recap: 'r', fullText: 'the whole answer' } })- expect(seen.cable.calls.slice(1)).toEqual([['summary', ['a1', 'r', 'b', false, false, 'the whole answer']]])+ await vi.waitFor(() => expect(calls('summary')).toHaveLength(1))+ expect(seen.cable.calls.slice(1)).toEqual([['summary', ['a1', 'r', 'b', 'alert', 'the whole answer', false]]])})it('forgets an agent\'s latest sentence when its processing card has none, and when the agent goes', async () => {@@ -746,7 +852,7 @@ describe('what the windows say, reaching the dial', () => {})describe('the other machines\' cards', () => {- it('reach the dial through the same calls as this computer\'s', () => {+ it('reach the dial through the same calls as this computer\'s', async () => {start()const tell = seen.fleet!.events!tell({ machineId: 'm2', kind: 'state', state: 'ready' })@@ -755,8 +861,9 @@ describe('the other machines\' cards', () => {tell({ machineId: 'm2', kind: 'processing', agentId: 'b1', text: 'go', recap: '' })tell({ machineId: 'm2', kind: 'summary', agentId: 'b1', text: 'done', recap: 'fixed', subagent: true })tell({ machineId: 'm2', kind: 'summary', agentId: 'b1', text: 'done', recap: '' })+ await vi.waitFor(() => expect(calls('summary')).toHaveLength(2))expect(seen.cable.calls.map(([name]) => name)).toEqual(['start', 'syncMachines', 'questionClose', 'question', 'turnStarted', 'summary', 'summary'])- expect(calls('summary')).toEqual([['b1', 'fixed', 'done', false, true], ['b1', 'done', 'done', false, false]])+ expect(calls('summary')).toEqual([['b1', 'fixed', 'done', 'silent', undefined, true], ['b1', 'done', 'done', 'alert', undefined, false]])})})diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.tsindex 39bf4f689..7c4e3d3fa 100644--- a/cli/src/services/devices.ts+++ b/cli/src/services/devices.ts@@ -35,6 +35,8 @@ import { WindowVisit } from '../cable/windowVisit.js'import { MachineListCache } from '../device/machineList.js'import { harnessDevicesRequest } from '../lib/harnessDevices.js'import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from '../lib/voiceRouter.js'+import { createJevDecide } from '../lib/jev/jevClient.js'+import { createTally, createTierDecider, type Tier, type TierDecision, type TierInput } from '../lib/notifyTier.js'import { createPartGuard } from './devicesGuard.js'import { FLEET_FALLBACKS, startFleet, type Fleet } from './fleet.js'@@ -55,6 +57,8 @@ export interface DevicesDeps {/** `HARNESSD_TEST_FAULTS`: parts to fail, for the end-to-end suite. */faults?: ReadonlySet<string>log?: (line: string) => void+ /** How loudly a finished turn tells the devices. Defaults to rules plus Jev (off with `HARNESS_NOTIFY_SMART=0`). */+ decideTier?: (input: TierInput) => Promise<TierDecision>/** A monotonic clock in ms (default `performance.now`), for the reply throttle: a wall-clock step must not stall or burst it. */now?: () => number/** How the voice router's worker is stopped when the process exits: an engine process of its own. */@@ -78,6 +82,12 @@ const sid = (id: string): string => id.slice(0, 8)export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps): ServiceRequests {const log = deps.log ?? ((line: string) => console.log(line))const monotonic = deps.now ?? (() => performance.now())+ const tally = createTally((line) => log(`[cable] ${line}`))+ const tierOf = deps.decideTier ?? createTierDecider({+ tally,+ jev: process.env.HARNESS_NOTIFY_SMART === '0' ? null : createJevDecide({ backend: (method, path, body) => core.account.backend(method, path, body) }),+ log: (line) => log(`[cable] ${line}`),+ })const part = createPartGuard({ log, faults: deps.faults })// What the windows on this computer last said: the desk the dial walks and whether it is in front, and@@ -237,6 +247,10 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)type Reading = { input?: number; cached?: number; output?: number } | null/** Each agent's reading from when its turn started, until the turn ends. */const starts = new Map<string, Promise<Reading>>()+ /** When each agent's turn began (the first `processing`), for the summary's duration. */+ const began = new Map<string, number>()+ /** The turn that just ended, kept for the `summary` that follows its `done`. */+ const ended = new Map<string, { durationS: number | null; stats: TierInput['stats'] }>()const TOKENS_WAIT_MS = 2000const MAX_TOKENS = 50_000_000const settle = (p: Promise<Reading>): Promise<Reading> => p.catch(() => null)@@ -267,9 +281,14 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)if (event.kind === 'processing') {if (event.update) latestUpdate.set(event.agentId, event.update)else latestUpdate.delete(event.agentId)+ if (!began.has(event.agentId)) began.set(event.agentId, Date.now())void cable.turnStarted(event.agentId, event.text, event.update)} else if (event.kind === 'done') {const fields = stats.take(event.agentId)+ const at = began.get(event.agentId)+ began.delete(event.agentId)+ ended.set(event.agentId, { durationS: at === undefined ? null : Math.round((Date.now() - at) / 1000),+ stats: { testsPassed: fields.testsPassed, testsFailed: fields.testsFailed, commits: fields.commits } })const start = starts.get(event.agentId)starts.delete(event.agentId)const finish = (tokens: Pick<TurnStatsFields, 'tokensIn' | 'tokensOut'>): void => {@@ -280,12 +299,30 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)if (!start || !cable.wantsStats()) return finish({})return turnTokens(event.agentId, start).then(finish)}- // Quiet when the window already has this agent on screen; silent when the turn was a sub-agent's. The- // tile still updates — the recap is what it draws — only the beep and the drawer entry are withheld.- else if (event.kind === 'summary') void cable.summary(event.agentId, event.recap || event.text, event.text, alreadyOnScreen(event.agentId), event.subagent, ...(event.fullText ? [event.fullText] : []))+ // On screen or a sub-agent's: silent, Jev is not asked. Otherwise the tier decides how loudly the dial tells. The+ // tile still updates either way — the recap is what it draws.+ else if (event.kind === 'summary') {+ const { agentId } = event+ const recap = event.recap || event.text+ const onScreen = alreadyOnScreen(agentId)+ const noted = (tier: Tier, rule: string): void => tally(cableHost.describe(agentId)?.name ?? '', tier, `rule:${rule}`, rule, 0)+ if (onScreen || event.subagent) { noted('silent', event.subagent ? 'subagent' : 'onScreen'); void cable.summary(agentId, recap, event.text, 'silent', event.fullText, event.subagent); return }+ // No device attached (or the serial side disabled): nobody to tell, so the recap never leaves the machine.+ if (!cable.isConnected) { ended.delete(agentId); void cable.summary(agentId, recap, event.text, 'silent', event.fullText, false); return }+ const turn = ended.get(agentId) // a sub-agent's summary leaves the main turn's numbers alone+ ended.delete(agentId)+ const who = cableHost.describe(agentId)+ // Returned, so the agent's next card waits behind this one (inOrder): a late recap must not follow turn.started.+ return tierOf({ agent: who?.name ?? '', engine: who?.engine ?? '', recap, durationS: turn?.durationS ?? null,+ stats: turn?.stats ?? {}, subagent: false, onScreen: false, failed: event.failed === true })+ .then((d) => d.tier, () => 'list' as const)+ .then((tier) => { void cable.summary(agentId, recap, event.text, tier, event.fullText, false) })+ }else {+ began.delete(event.agentId); ended.delete(event.agentId)stats.take(event.agentId) // a failed turn's sums must not leak into the next turnstarts.delete(event.agentId)+ tally(cableHost.describe(event.agentId)?.name ?? '', 'alert', 'rule:failed', 'turn.error', 0)void cable.turnError(event.agentId, event.text)}}@@ -350,7 +387,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)// "Working…" looks like from the outside.if (event.kind === 'state') { void cable.syncMachines(); return }if (event.kind === 'questionClosed') { inOrder(event.agentId, () => { void cable.questionClose(event.agentId, event.requestId) }); return }- if (event.kind === 'question') { inOrder(event.agentId, () => { void cable.question(event.agentId, event.requestId, event.questions) }); return }+ if (event.kind === 'question') { tally(cableHost.describe(event.agentId)?.name ?? '', 'alert', 'rule:question', 'question', 0); inOrder(event.agentId, () => { void cable.question(event.agentId, event.requestId, event.questions) }); return }toDial({ ...event, subagent: event.subagent === true })}))@@ -365,7 +402,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)const close = cableQuestionCloseFor(frame as Parameters<typeof cableQuestionCloseFor>[0])if (close) { inOrder(close.agentId, () => { void cable.questionClose(close.agentId, close.requestId) }); return }const question = cableQuestionFor(frame as Parameters<typeof cableQuestionFor>[0])- if (question) { inOrder(question.agentId, () => { void cable.question(question.agentId, question.requestId, question.questions) }); return }+ if (question) { tally(cableHost.describe(question.agentId)?.name ?? '', 'alert', 'rule:question', 'question', 0); inOrder(question.agentId, () => { void cable.question(question.agentId, question.requestId, question.questions) }); return }// A shell result is only the stats' input: the dial is told the sums when the turn ends.const ran = frame as { type?: string; agentId?: string; payload?: { kind?: string; id?: string; command?: string; isError?: boolean; outputTail?: string } }if (ran.payload?.kind === 'reply_text' && ran.agentId) {@@ -385,7 +422,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)}// A tool card is a step for a `steps-v1` device and nothing for any other: the session drops it.const gone = (frame as { type?: string; payload?: { agentId?: unknown } })- if (gone.type === 'agent_deleted' && typeof gone.payload?.agentId === 'string') { latestUpdate.delete(gone.payload.agentId); endReplies(gone.payload.agentId, false) }+ if (gone.type === 'agent_deleted' && typeof gone.payload?.agentId === 'string') { latestUpdate.delete(gone.payload.agentId); began.delete(gone.payload.agentId); ended.delete(gone.payload.agentId); endReplies(gone.payload.agentId, false) }const step = cableStepFor(frame as Parameters<typeof cableStepFor>[0])if (step) { inOrder(step.agentId, () => { void cable.turnStep(step.agentId, step.step) }); return }const event = cableEventFor(frame as Parameters<typeof cableEventFor>[0])diff --git a/devices/harness-device/firmware/main/audio_capture.c b/devices/harness-device/firmware/main/audio_capture.cindex b4c7d21bd..2418d0657 100644--- a/devices/harness-device/firmware/main/audio_capture.c+++ b/devices/harness-device/firmware/main/audio_capture.c@@ -175,7 +175,9 @@ void audio_notify_done(void)if (!s_beep_task || audio_notify_is_muted()) return;uint32_t previous = atomic_load(&last_ms);uint32_t now = (uint32_t)(esp_timer_get_time() / 1000);- if (now - previous < 1000) return;+ if (!now) now = 1; // 0 means "never beeped", so the first one always sounds+ // One beep per 30 s: a burst of finished turns is one piece of news, not five.+ if (previous && now - previous < 30000) return;// A concurrent completion owns the notification if it won this exchange.if (!atomic_compare_exchange_strong(&last_ms, &previous, now)) return;xTaskNotifyGive(s_beep_task);diff --git a/devices/harness-device/firmware/main/cable_client.c b/devices/harness-device/firmware/main/cable_client.cindex a2aadaa1b..42d164b07 100644--- a/devices/harness-device/firmware/main/cable_client.c+++ b/devices/harness-device/firmware/main/cable_client.c@@ -1306,35 +1306,15 @@ static void handle_message(const cJSON *root)// emits done THEN summary; an empty or phantom turn emits only done — so a session that briefly// registers and vanishes stays silent, and the notification always carries a real recap.//- // These two lines lived in commander_client.c and went out with it. Nothing else calls them, so- // for a day the dial updated its tile in complete silence: no beep, no wake, nothing in the- // drawer — the one part of a finished turn a person is not looking at the screen for.- //- // A SUB-AGENT'S turn (`silent`, decided by the daemon: an Orchestrator specialist, or its- // Director while specialists are still out) is not news at all — the tile above is redrawn and- // that is the whole of it. A project of four specialists used to ring eight times before the one- // ring that mattered (owner, 2026-09-21: "chỉ cần báo thằng main thôi"). Absent = false, so an- // older daemon rings exactly as before.- if (bool_of(p, "silent")) return;- // THE BEEP ALWAYS SOUNDS. A finished turn is news even when the person is looking straight at- // it: they are reading the last one, not watching for the next to end, and three tones is how- // they learn a task is done without moving their eyes.- audio_notify_done();- // The NOTIFICATION is what gets withheld. It exists to reach someone who is not looking —- // waking a dark panel, filing an entry in the drawer — and `quiet` is the daemon saying the- // desktop window already has this agent on screen. The tile itself is still redrawn above: the- // recap is what it draws, and a stale tile is a worse lie than a missing badge.- //- // The other half of "already looking" is decided inside ui_notify_task_done(), which skips its- // own work when the dial is awake, on the carousel, and centred on this very agent.- //- // Absent field = false, so a daemon that predates this notifies exactly as it always did.- //- // WHO IT IS ABOUT rides on the frame. The dial holds one tab's agents, and this turn may have- // finished on any of them; the drawer row for one off this tab has nobody else to ask.- if (!bool_of(p, "quiet")) {- ui_notify_task_done(agent_id, str_of(p, "name"), str_of(p, "machine"), str_of(p, "recap"));- }+ // THE TIER decides everything else (daemon, 2026-10-19): `alert` beeps, wakes and celebrates,+ // `list` only files a drawer row, `silent` files nothing. ui_notify_summary maps an old daemon's+ // `silent`/`quiet` flags when there is no tier, and says whether to beep: an alert, and not for+ // the pane already on the glass. The beep itself coalesces to one per 30 s in audio_notify_done.+ // WHO IT IS ABOUT rides on the frame: the dial holds one tab's agents, and this turn may have+ // finished on any of them.+ if (ui_notify_summary(agent_id, str_of(p, "name"), str_of(p, "machine"), str_of(p, "recap"),+ str_of(p, "tier"), bool_of(p, "quiet"), bool_of(p, "silent")))+ audio_notify_done();return;}// The WINDOW looked at this agent — its drawer row here is stale. The tap's half of this pair@@ -1354,7 +1334,9 @@ static void handle_message(const cJSON *root)}if (strcmp(t, "turn.error") == 0) {if (agent_id) ui_project_emit(agent_id, "", "done", "", NULL);- ui_cable_toast(str_of(p, "message"));+ // A failure is an alert: it beeps (coalesced) unless that pane is already on the glass.+ if (agent_id ? ui_turn_error(agent_id, str_of(p, "message")) : (ui_cable_toast(str_of(p, "message")), false))+ audio_notify_done();return;}if (strcmp(t,"question.state")==0) { ui_question_state(p); return; }@@ -1362,7 +1344,12 @@ static void handle_message(const cJSON *root)if (strcmp(t, "question") == 0) {const cJSON *questions = cJSON_GetObjectItemCaseSensitive(p, "questions");// The name rides on the frame for the same reason as on `summary`: the asker may be off this tab.- if (agent_id && questions) ui_question_show(agent_id, str_of(p, "name"), str_of(p, "machine"), str_of(p, "id"), questions);+ if (agent_id && questions) {+ // A question is an alert: pinned row, wake and a (coalesced) beep, all but the beep inside+ // ui_question_show, which stays quiet for the pane already on the glass.+ if (ui_question_show(agent_id, str_of(p, "name"), str_of(p, "machine"), str_of(p, "id"), questions))+ audio_notify_done();+ }return;}// Somebody else answered it. A question is a dialog in a tmux pane, not a shared object, so this isdiff --git a/devices/harness-device/firmware/main/cable_client.h b/devices/harness-device/firmware/main/cable_client.hindex efcb9bfb2..f1ed5fa87 100644--- a/devices/harness-device/firmware/main/cable_client.h+++ b/devices/harness-device/firmware/main/cable_client.h@@ -209,6 +209,7 @@ typedef struct {// Local display bookkeeping. Incoming snapshots never supply these values.bool read_on_dial;uint32_t display_revision;+ uint32_t received_ms; // ms() when the row was filed; rows expire 6 h later (notice_expire)} cable_notif_t;bool cable_client_notification_read(const char *agent_id, const char *read_token);diff --git a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.cindex a01f8b1b9..fff276ab1 100644--- a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c+++ b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c@@ -214,6 +214,7 @@ static EXT_RAM_BSS_ATTR struct {uint32_t notice_revision, notice_frame;int notice_count;uint32_t notice_sequence;+ uint32_t error_until; // when the turn-error view clears itself (ms() clock), 0 = not a timed onequestion_t q;char message[256], title[80], pending_focus[ID_MAX], opening_notice[ID_MAX];char voice_target[CABLE_NAME_MAX];@@ -560,6 +561,7 @@ static void view(view_t v)input_cancel();s.voice_retry_until = 0;s.view = v;+ s.error_until = 0; // a timed error view belongs to ui_turn_error alone; any move off or onto MESSAGE ends its.offset = 0;s.pressed = -1;change();@@ -982,9 +984,16 @@ static uint32_t status_wake_ms(uint32_t now)return (ht_shimmer_wake_ms(now * speed) + speed - 1) / speed;}static void dispatch(action_t a); // the hold below acts at once; defined with the other actions+static void notice_expire(uint32_t now);static void surface_tick(uint32_t now){notice_flush_reads(now);+ notice_expire(now);+ if (s.error_until && (s.view != MESSAGE || (int32_t)(now - s.error_until) >= 0)) {+ if (s.view == MESSAGE) view(HOME);+ s.error_until = 0;+ change();+ }if (companion_celebrating && (now-celebration_began>=2400 || s.view!=HOME || s.quiet || !follow_companion || display_is_asleep() || character_mood()==HT_CHARACTER_ATTENTION)) {companion_celebrating=false; select_companion(); change();}@@ -4183,25 +4192,83 @@ static void notice_add(const char *id, const char *name, const char *machine, con->read_on_dial = notice_was_read(n);if (!++s.notice_revision) ++s.notice_revision;n->display_revision = s.notice_revision;+ n->received_ms = ms();notice_restore_selection(selected);notice_sync_view();}-void ui_notify_task_done(const char *id, const char *name, const char *machine, const char *recap)+// Rows are news, and news goes stale: a drawer row left alone for 6 h goes away. A question stays until+// it is answered. The signed difference keeps the 49-day ms() wrap harmless.+#define NOTICE_TTL_MS 21600000u+#define ERROR_VIEW_MS 8000u+static void notice_expire(uint32_t now){- if (!id || !*id || strnlen(id, ID_MAX) >= ID_MAX) return;+ bool gone = false;+ for (int i = s.notice_count - 1; i >= 0; i--)+ if (!s.notice[i].question && (int32_t)(now - s.notice[i].received_ms) >= (int32_t)NOTICE_TTL_MS) {+ notice_remove(s.notice[i].agent_id, false);+ gone = true;+ }+ if (gone) { notice_sync_view(); change(); }+}+// The pane whose face is on the glass already shows its own news.+static bool on_face(const char *id)+{+ const agent_t *a = active();+ return a && !strcmp(a->id, id) && (s.view == HOME || s.view == AGENT) && !s.nap && !display_is_asleep();+}+static void notice_read_now(const char *id)+{+ for (int i = 0; i < s.notice_count; i++)+ if (!strcmp(s.notice[i].agent_id, id)) notice_mark_read(&s.notice[i]);+}+bool ui_notify_summary(const char *id, const char *name, const char *machine, const char *recap,+ const char *tier, bool quiet, bool silent)+{+ if (!id || !*id || strnlen(id, ID_MAX) >= ID_MAX) return false;+ // 0 silent, 1 list, 2 alert. An old daemon sends no tier but does send the flags.+ int level = tier && !strcmp(tier, "silent") ? 0 : tier && !strcmp(tier, "list") ? 1 :+ tier && !strcmp(tier, "alert") ? 2 : silent ? 0 : quiet ? 1 : 2;+ if (!level) return false;display_lock();+ bool face = on_face(id);notice_forget_read(id); // A fresh completion is new even if its words repeat.notice_add(id, name, machine, recap, false, false);+ if (face) notice_read_now(id);s.notice_sequence++;+ bool alert = level == 2 && !face;uint32_t now = ms();- if (!waiting() && !s.nap && !s.quiet && (!s.last_celebration || now - s.last_celebration >= 20000)) {+ if (alert && !waiting() && !s.nap && !s.quiet && (!s.last_celebration || now - s.last_celebration >= 20000)) {s.pet_pose = 3;s.pet_until = now + 2000;s.last_celebration = now;}change();- display_wake();+ if (alert) display_wake();display_unlock();+ return alert;+}+bool ui_turn_error(const char *id, const char *message)+{+ if (!id || !*id || strnlen(id, ID_MAX) >= ID_MAX) { ui_cable_toast(message); return false; }+ if (!message || !*message) message = "The turn failed";+ display_lock();+ bool face = on_face(id);+ int known = find(id);+ notice_forget_read(id);+ notice_add(id, known >= 0 ? s.agents[known].name : NULL, NULL, message, false, true);+ if (face) notice_read_now(id);+ s.notice_sequence++;+ // Like any toast, never over a live recording or the person's own question; the drawer row still keeps the failure.+ if (!s.voice_open && !question_view(s.view)) {+ COPY(s.title, "Harness");+ COPY(s.message, message);+ view(MESSAGE);+ if (s.view == MESSAGE) { s.error_until = ms() + ERROR_VIEW_MS; if (!s.error_until) s.error_until = 1; }+ }+ change();+ if (!face) display_wake();+ display_unlock();+ return !face;}void ui_notif_seen(const char *id){@@ -4306,15 +4373,17 @@ static void question_load(const cJSON *questions)}s.q.valid=s.q.count>0;}-void ui_question_show(const char *id, const char *name, const char *machine, const char *request,+bool ui_question_show(const char *id, const char *name, const char *machine, const char *request,const cJSON *questions){- if (!id || !request) return;+ if (!id || !request) return false;display_lock();+ bool face = on_face(id);const cJSON *first=cJSON_GetArrayItem(questions,0);const cJSON *prompt=cJSON_GetObjectItemCaseSensitive(first,"q");notice_forget_read(id);notice_add(id,name,machine,cJSON_IsString(prompt) ? prompt->valuestring : "Needs your answer",true,false);+ if (face) notice_read_now(id); // already on the glass: shown in place, read at onces.notice_sequence++;// A different agent's alert cannot replace the question being read.if (s.q.valid && !strcmp(s.q.agent,id) && strcmp(s.q.request,request)) {@@ -4324,8 +4393,9 @@ void ui_question_show(const char *id, const char *name, const char *machine, con// The question is shown on the home face, in the recap's place (render_home): no screen opens// for it. The display wakes so a person glancing over sees it.change();- display_wake();+ if (!face) display_wake();display_unlock();+ return !face;}void ui_question_state(const cJSON *p){diff --git a/devices/harness-device/firmware/main/ui/ui_screens.h b/devices/harness-device/firmware/main/ui/ui_screens.hindex 0eb58742a..4b3612cde 100644--- a/devices/harness-device/firmware/main/ui/ui_screens.h+++ b/devices/harness-device/firmware/main/ui/ui_screens.h@@ -390,7 +390,13 @@ void ui_voice_quota_exceeded(void);// A turn finished for this agent → record it in the drawer, badge, and wake the screen if it was off.// `name`, `machine` and `recap` come from the frame: the dial holds one tab, and the agent may be on// another — the row has nobody else to ask. Any may be NULL; a held tile's own model wins when present.-void ui_notify_task_done(const char *project_id, const char *name, const char *machine, const char *recap);+// A live `summary`. TIER is the wire's "alert" | "list" | "silent"; NULL or unknown falls back to the old+// flags (silent, then quiet, else alert). Returns true when the caller should beep: an alert, and not+// for the pane already on the face. A list entry is a drawer row only; silent files nothing.+bool ui_notify_summary(const char *project_id, const char *name, const char *machine, const char *recap,+ const char *tier, bool quiet, bool silent);+// A failed turn: an alert. Files a drawer row, shows the error for 8 s. True when the caller should beep.+bool ui_turn_error(const char *project_id, const char *message);// The WINDOW looked at this agent → drop its FINISHED-turn row here, as a tap on that row does.//// The two screens take a notification away on different gestures — a tap here, a tab coming to the@@ -441,7 +447,8 @@ void ui_project_set_agents(const char *project_id, const struct cJSON *agents);// Also records it behind the bell: a blocked agent is counted, and stays counted until the question is// ANSWERED rather than until somebody looks at it. Not gated on the window having the agent on screen —// showing a question asks the window to bring it forward, so that gate could never open.-void ui_question_show(const char *project_id, const char *agent_name, const char *machine, const char *request_id, const struct cJSON *questions);+// True when the caller should beep: not for the pane already on the face.+bool ui_question_show(const char *project_id, const char *agent_name, const char *machine, const char *request_id, const struct cJSON *questions);// That question was answered somewhere else (the app, or the pane by hand) — leave the screen instead of// waiting for an answer that can no longer be delivered. No-op unless THIS request is the one on screen.void ui_question_close(const char *project_id, const char *request_id);diff --git a/devices/harness-device/firmware/test/test_audio_notify.py b/devices/harness-device/firmware/test/test_audio_notify.pyindex 08452f50b..c074c2cb8 100644--- a/devices/harness-device/firmware/test/test_audio_notify.py+++ b/devices/harness-device/firmware/test/test_audio_notify.py@@ -93,15 +93,17 @@ int main(void) {}reset();open_fail=true;play_beep();assert(!held&&opens==1&&!closes&&!writes);reset();write_fail=true;play_beep();assert(!held&&opens==1&&closes==1&&writes==1);+ // One beep per 30 s: a burst of finishes beeps once. The very first one always sounds.reset();clock_us=1000000;audio_notify_done();assert(notifications==1);- clock_us=1999000;audio_notify_done();assert(notifications==1);- clock_us=2000000;audio_notify_done();assert(notifications==2);- clock_us=3000000;reenter=true;audio_notify_done();assert(notifications==3);+ clock_us=30999000;audio_notify_done();assert(notifications==1);+ clock_us=31000000;audio_notify_done();assert(notifications==2);+ clock_us=70000000;reenter=true;audio_notify_done();assert(notifications==3);clock_us=(int64_t)(UINT32_MAX-500u)*1000;audio_notify_done();assert(notifications==4);clock_us=((INT64_C(1)<<32)+498)*1000;audio_notify_done();assert(notifications==4);- clock_us+=1000;audio_notify_done();assert(notifications==5);- muted=true;clock_us+=1000000;audio_notify_done();assert(notifications==5);- puts("Notification: exact 5760-sample waveform with 640B buffer; mute/mic/error release, concurrent debounce and wrap PASS (offline)");+ clock_us=((INT64_C(1)<<32)+29498)*1000;audio_notify_done();assert(notifications==4);+ clock_us=((INT64_C(1)<<32)+29499)*1000;audio_notify_done();assert(notifications==5);+ muted=true;clock_us+=100000000;audio_notify_done();assert(notifications==5);+ puts("Notification: exact 5760-sample waveform with 640B buffer; mute/mic/error release, 30 s coalescing, concurrency and wrap PASS (offline)");}'''with tempfile.TemporaryDirectory(prefix='harness-notify-') as folder:diff --git a/devices/harness-device/firmware/test/test_question_ui.py b/devices/harness-device/firmware/test/test_question_ui.pyindex e06d1d2ec..bef31a926 100644--- a/devices/harness-device/firmware/test/test_question_ui.py+++ b/devices/harness-device/firmware/test/test_question_ui.py@@ -64,7 +64,10 @@ static int gesture;static void ht_gesture_guard(int *g,uint32_t time) { (void)g;(void)time; }static bool congested,transport_ok=true,pending_receipt;static action_t queued;-static int queued_answers,sent_answers,removed,notices,reads;+static int queued_answers,sent_answers,removed,notices,reads,read_now;+static const char *face_agent="";+static bool on_face(const char *id) { return !strcmp(id,face_agent); }+static void notice_read_now(const char *id) { assert(id && *id);read_now++; }static uint8_t sent_choices[4];static char sent_draft[48];static agent_t *active(void) { return &agents[s.active]; }@@ -240,7 +243,11 @@ int main(int argc,char **argv) {// A question does NOT change the screen — the home face shows it in the recap's place — but it// does wake the display, and it still counts in the bell until it is answered.reset(false);view(HOME);wakes=0;notices=0;- ui_question_show("b","Other","M2","q-b2",NULL);assert(s.view==HOME && wakes==1 && notices==1);+ assert(ui_question_show("b","Other","M2","q-b2",NULL) && s.view==HOME && wakes==1 && notices==1 && !read_now);+ // The pane on the face already shows its question: still filed, but read at once, no wake, no beep.+ wakes=0;notices=0;face_agent="b";+ assert(!ui_question_show("b","Other","M2","q-b3",NULL) && wakes==0 && notices==1 && read_now==1);+ face_agent="";// The ESP32 compiler's -O0 restrict analysis sees the enclosing global s,// not the disjoint options/answer fields. Exercise every selected subset// at their real capacities and prove that no neighboring state changes.diff --git a/devices/harness-device/firmware/test/test_touch_ui.py b/devices/harness-device/firmware/test/test_touch_ui.pyindex 71ab1a04f..741184234 100644--- a/devices/harness-device/firmware/test/test_touch_ui.py+++ b/devices/harness-device/firmware/test/test_touch_ui.py@@ -47,6 +47,7 @@ code = r'''code += defines('CABLE_READ_TOKEN_MAX','ID_MAX','CABLE_NAME_MAX','SWARM_ID_MAX','SWARMS_MAX','CABLE_MAX_AGENTS','MAX_PROJECTS')code += defines('NOTICES','QUESTION_MAX','OPTION_MAX','PANE_MEMORY_MAX','UI_FONT','Q_ROWS','DRAFT_ROWS',source=source)code += defines('FACE_CX', source=source)+code += '#define NOTICE_TTL_MS 21600000u\n#define ERROR_VIEW_MS 8000u\nstatic void ui_cable_toast(const char *message) { (void)message; }\n'if '#define PANE_RESULT_BYTES ' in source:code += defines('PANE_RESULT_BYTES', source=source)code += face_geometry(source)@@ -62,7 +63,7 @@ static struct {int pattern_mask, pattern_len, view, voice_return, offset, active, count, pressed, hit_count;int draft_drag, tab_drag, start_x, start_y, last_x, last_y, tab_count, machine_count, model_count, notice_count, pet_pose;uint32_t touch_started, coast_until, character_activity, pet_until, nap_until, last_celebration;- uint32_t notice_sequence, voice_retry_until;+ uint32_t notice_sequence, voice_retry_until, error_until;uint8_t status_phase;unsigned bell_unread;uint32_t notice_ms;@@ -157,7 +158,8 @@ static unsigned changes;static void change(void) { changes++; }static void display_lock(void) {}static void display_unlock(void) {}-static void display_wake(void) {}+static int wakes;+static void display_wake(void) { wakes++; }static bool fake_asleep, present_scene=true;static bool display_is_asleep(void) { return fake_asleep; }static bool audio_client_active(void) { return recording; }@@ -211,13 +213,15 @@ static bool scroll_emit(ht_scroll_phase_t phase, int dy, int velocity, void *ctxcode += function('color')code += function('settings_item') + function('settings_count') + function('hit_contains')code += function('find')+code += 'static void notice_expire(uint32_t now);\n'for name in ['copy', 'recap_preview', 'notice_unread', 'notice_was_read', 'notice_forget_read', 'notice_flush_reads', 'notice_mark_read', 'habitat_scene_receipt', 'habitat_scene_presented', 'pane_memory', 'pane_memory_apply', 'dismiss_result', 'activity_text', 'ensure', 'input_cancel', 'view', 'notice_open', 'workspace_index', 'tabs_open', 'workspace_failed', 'tab_request', 'tabs_sync', 'ui_scroll_reportable', 'focus_skin', 'focus_face_for', 'focus_chord', 'focus_put', 'focus_span', 'focus_take', 'focus_rows', 'ui_rows', 'ui_can_display', 'ui_wrap', 'text_in', 'control', 'home_footer', 'footer_control', 'text', 'center', 'render_brand', 'heading', 'question_view', 'question_rows', 'question_move', 'question_text', 'render_question', 'render_choices', 'render_answer_review', 'question_answer', 'send_answer', 'make_action', 'character_mood', 'voice_status', 'home_caption_rotates', 'home_caption_tick', 'status_animated', 'status_speed', 'status_wake_ms', 'surface_tick', 'command_face', 'render_workspace_preview', 'question_prompt', 'focus_bell', 'render_home', 'render_voice', 'render_selection', 'render_form', 'draft_move', 'render_draft', 'render_draft_options', 'ui_swarms_replace', 'ui_workspace_applied', 'ui_land_after_reload']:code += function(name)code += function('render_settings') + function('ui_visit_state')code += function('ui_project_known') + function('ui_focus_project') + function('ui_apply_pending_focus')code += function('focus_centred') + function('focus_header') + function('focus_clipped') + function('tabs_move') + function('tab_name') + function('tab_split') + function('tab_fade') + function('tab_neighbour') + function('focus_carousel') + function('tab_label') + function('render_focus_tabs') + function('pane_label') + function('render_focus_panes') + function('render_agents') + function('render_tabs') + function('page_controls') + function('render_notice') + function('css_line') + function('inbox_line') + function('inbox_page') + function('render_focus_inbox') + function('render_list')-for name in ['notice_remove', 'notice_sync_view', 'notice_selection', 'notice_restore_selection', 'notice_add', 'ui_notify_task_done', 'ui_notif_seen', 'ui_notif_read', 'ui_notif_replace', 'ui_notif_open', 'ui_question_close', 'ui_answer_receipt']:+for name in ['notice_remove', 'notice_sync_view', 'notice_selection', 'notice_restore_selection', 'notice_add', 'notice_expire', 'on_face', 'notice_read_now', 'ui_notify_summary', 'ui_turn_error', 'ui_notif_seen', 'ui_notif_read', 'ui_notif_replace', 'ui_notif_open', 'ui_question_close', 'ui_answer_receipt']:code += function(name)+code += '#define ui_notify_task_done(a,b,c,d) ui_notify_summary(a,b,c,d,"alert",false,false)\n'for name in ['event', 'ui_project_emit', 'ui_project_restore_event', 'ui_project_clear_event', 'ui_project_set_name', 'ui_project_remove', 'ui_project_clear_all', 'ui_project_apply_order']:code += function(name)visit_actions=source.split(' case A_LATEST:',1)[1].split(' case A_TABS:',1)[0]@@ -1220,6 +1224,62 @@ static void notification_read_checks(const char *dir) {}assert(!starts && !question_sends && !desktop_opens);puts("Notification read: post-DMA only, sleep/lock, stale/identical replacements, read/open idempotence, questions, hidden empty bell, reconnect snapshots and bounded receipt history PASS");++ // NOTIFICATION TIERS: only an alert beeps, wakes and celebrates; a list entry is a drawer row and+ // nothing else; silent leaves no row. The pane on the face never beeps or wakes and its row is read.+ reset(); fake_ms=5000; wakes=0;+ assert(ui_notify_summary("b","B","M2","Built.","alert",false,false) && s.notice_count==1 && wakes==1 && s.pet_pose==3);+ reset(); fake_ms=5000; wakes=0;+ assert(!ui_notify_summary("b","B","M2","Built.","list",true,false) && s.notice_count==1 && !wakes && !s.pet_pose);+ reset(); fake_ms=5000; wakes=0; fake_asleep=true;+ assert(!ui_notify_summary("b","B","M2","Built.","list",true,false) && s.notice_count==1 && !wakes && fake_asleep);+ reset(); fake_ms=5000; wakes=0;+ assert(!ui_notify_summary("b","B","M2","Built.","silent",false,true) && !s.notice_count && !wakes && !s.pet_pose);+ // An old daemon sends no tier: quiet is a list entry (it used to beep), silent is silent, neither is an alert.+ reset(); fake_ms=5000; wakes=0;+ assert(!ui_notify_summary("b","B","M2","x",NULL,true,false) && s.notice_count==1 && !wakes);+ assert(!ui_notify_summary("c","C","M2","x",NULL,false,true) && s.notice_count==1);+ assert(!ui_notify_summary("c","C","M2","x",NULL,true,true) && s.notice_count==1);+ assert(!ui_notify_summary("c","C","M2","x","bogus",true,false) && s.notice_count==2);+ assert(ui_notify_summary("d","D","M2","x",NULL,false,false) && s.notice_count==3 && wakes==1);+ // One row per agent: the newest wins.+ assert(ui_notify_summary("d","D","M2","newer","alert",false,false) && s.notice_count==3 && !strcmp(s.notice[0].summary,"newer"));+ // On the face: no beep, no wake, no celebration, and the row is read at once.+ reset(); fake_ms=5000; wakes=0;+ assert(!ui_notify_summary("a","A","M2","Done.","alert",false,false) && !wakes && !s.pet_pose);+ assert(s.notice_count==1 && s.notice[0].read_on_dial && !notice_unread(NULL));+ // Rows expire 6 h after receipt, across the millisecond wrap too, but a question never does.+ for (int w = 0; w < 2; w++) {+ reset(); fake_ms = w ? UINT32_MAX - 1000 : 1000;+ ui_notify_summary("b","B","M2","Old.","list",false,false);+ cable_notif_t pinned={.agent_id="q",.name="Q",.summary="Which?",.question=true};+ ui_notif_replace(&pinned,1); ui_notify_summary("b","B","M2","Old.","list",false,false);+ assert(s.notice_count==2);+ uint32_t t0 = fake_ms;+ fake_ms = t0 + 21599999u; surface_tick(fake_ms); assert(s.notice_count==2);+ fake_ms = t0 + 21600000u; surface_tick(fake_ms); assert(s.notice_count==1 && s.notice[0].question);+ }+ // A failed turn: the full-screen error clears itself after 8 s; the drawer row stays.+ reset(); fake_ms=9000; wakes=0;+ assert(ui_turn_error("b","The build crashed.") && s.view==MESSAGE && wakes==1);+ assert(s.notice_count==1 && s.notice[0].failed && !s.notice[0].read_on_dial);+ fake_ms=16999; surface_tick(fake_ms); assert(s.view==MESSAGE);+ fake_ms=17000; surface_tick(fake_ms); assert(s.view==HOME && s.notice_count==1);+ reset(); fake_ms=9000; wakes=0;+ assert(!ui_turn_error("a","The build crashed.") && s.view==MESSAGE && !wakes && s.notice[0].read_on_dial);+ // The person's own question is never covered: the row is filed, the screen stays.+ reset(); fake_ms=9000; s.view=QUESTION; wakes=0;+ assert(ui_turn_error("b","The build crashed.") && s.view==QUESTION && !s.error_until && s.notice_count==1 && s.notice[0].failed);+ s.view=CHOICE; ui_turn_error("c","Also broke."); assert(s.view==CHOICE);+ s.view=ANSWER_REVIEW; ui_turn_error("d","Also broke."); assert(s.view==ANSWER_REVIEW);+ // A different message replacing the error view must not inherit its 8 s timer.+ reset(); fake_ms=9000; ui_turn_error("b","The build crashed.");+ fake_ms=14000; view(MESSAGE); fake_ms=17000; surface_tick(fake_ms); assert(s.view==MESSAGE);+ // An empty failure still says something.+ reset(); fake_ms=9000; ui_turn_error("b","");+ assert(!strcmp(s.notice[0].summary,"The turn failed") && !strcmp(s.message,"The turn failed"));+ ui_turn_error("c",NULL); assert(!strcmp(s.message,"The turn failed"));+ puts("Notification tiers: alert/list/silent, old-daemon flags, face, one row per agent, 6 h expiry and 8 s error PASS");reset();}diff --git a/devices/harness-device/firmware/test/test_voice_ui.py b/devices/harness-device/firmware/test/test_voice_ui.pyindex 331dda286..3c2dafe97 100644--- a/devices/harness-device/firmware/test/test_voice_ui.py+++ b/devices/harness-device/firmware/test/test_voice_ui.py@@ -58,6 +58,7 @@ static ht_tab_carousel_t tab_carousel;static struct {bool quick_open, coasting, ready, connected, loading, nap, voice_open, voice_start_pending, voice_waiting, voice_carry, voice_review, voice_review_preview, voice_draft_append, voice_search, touch_down, touch_cancelled;int pet_pose, view, voice_return, offset, pressed, active, pane_pos;+ uint32_t error_until;uint32_t pet_until, nap_until, voice_retry_until, voice_started, voice_wait_until, voice_generation, voice_question_revision, voice_draft_revision;int voice_question_index;char title[80], message[256], voice_target[64], voice_engine[12], pending_focus[64], pending_machine[64], opening_notice[48];diff --git a/devices/harness-pro/docs/cable.md b/devices/harness-pro/docs/cable.mdindex dc757e602..34eb49dbd 100644--- a/devices/harness-pro/docs/cable.md+++ b/devices/harness-pro/docs/cable.md@@ -112,7 +112,7 @@ separately), every `speech.*` and the speech PCM frame (`0x05`), `models`, `noti`question.state`, `answer.receipt`, `draft.state`, `voice.draft`, `voice.question`, `voice.search`, `voice.form`,`selection.state`, `carry.state`, `form.state`, `visit.state`, `metrics.state` (and `metrics.get`),`player.overview`, `player.context` (parsed in the shared firmware but unused by Pod), `machine.selected`,-`machine.error`, `toast`, and the notification fields of `summary` (`silent`, `quiet`, `name`, `machine`).+`machine.error`, `toast`, and the notification fields of `summary` (`silent`, `quiet`, `name`, `machine`), though it reads `tier` (below).The Pro does use: `welcome`, `ping`, `agents.*`, `agent.updated`, `machines.*`, `swarms`, `focus`,`turn.started/activity/done/error`, `summary`, `question`, `question.close`, `player.library`, `voice.transcript`,`voice.error`; and sends `hello`, `machines.list`, `agents.list`, `player.library.get`, `agent.open`, `scroll`,@@ -156,3 +156,10 @@ firmware transfer, which has its own resend). The daemon answers with a full snaframe for each question still open. It does not replay recent `summary` history (the attach push does); a lost`summary` is not repaired by a resync. The welcome of a Pro lists `resync` in `features`; a Pro whose welcome does not (an older daemon) sends the old`swarms.list` and `agents.list` instead. A welcome without `seq` turns the gap check off for that session.++## `summary.tier`++`summary` carries `tier`: `"alert"` (beep, wake, toast, Notices entry), `"list"` (Notices entry only: no beep,+wake or toast) or `"silent"` (the card updates, nothing else). The host still sends the older flags beside it+for firmware that predates `tier`: `alert` sets neither, `list` sets `quiet: true`, `silent` sets `silent: true`.+`question` and `turn.error` carry no `tier`; treat both as `alert`.diff --git a/devices/harness-pro/firmware/main/app/pod_glue.c b/devices/harness-pro/firmware/main/app/pod_glue.cindex 71c1a2428..37b85dfe7 100644--- a/devices/harness-pro/firmware/main/app/pod_glue.c+++ b/devices/harness-pro/firmware/main/app/pod_glue.c@@ -760,28 +760,42 @@ bool pod_ui_start(pod_ui_t *u, uint32_t now_ms)// ---- notifications ------------------------------------------------------------------------------------------bool pod_ui_notify(pod_ui_t *u, const char *agent_id, bool awake, uint32_t now_ms)+bool pod_ui_notify(pod_ui_t *u, const char *agent_id, pod_tier_t tier, bool awake, uint32_t now_ms)+{+ return pod_ui_notify_text(u, agent_id, tier, NULL, false, awake, now_ms);+}++bool pod_ui_notify_text(pod_ui_t *u, const char *agent_id, pod_tier_t tier, const char *text, bool question, bool awake, uint32_t now_ms){pod_model_clock(&u->model, now_ms);const pod_agent_t *a = pod_model_find(&u->model, agent_id);- if (!a) return false;+ if (!a || tier == POD_TIER_SILENT) return false;const pod_frame_t *t = top(u);const bool looking = awake && t && (t->view == POD_V_AGENT || t->view == POD_V_RECAP) && !strcmp(t->agent, a->id);- char text[POD_UNREAD_TEXT];- size_t pos = 0;- text[0] = 0;- for (int i = 0; i < a->recap_lines && pos + 1 < sizeof text; i++) { // the recap's sentences, joined- const char *l = a->recap + a->line_at[i];- if (!*l) continue;- int n = snprintf(text + pos, sizeof text - pos, "%s%s", pos ? " " : "", l);- if (n < 0) break;- pos += (size_t)n < sizeof text - pos ? (size_t)n : sizeof text - pos - 1;- }- pod_utf8_trim(text);- pod_model_unread_add(&u->model, a->id, a->name, text, (int32_t)pod_agent_secs(a, now_ms), now_ms);- // The toast: none over the update, nor over the bubble that says the same. It shows only over a room, never for- // the agent it is (looking or not: its recap is already there), and not over Home, Notices or Talk; a toast raised for the next notice replaces this one.- if (!pod_ui_talking(u) && !u->ota && !looking) {+ char joined[POD_UNREAD_TEXT];+ if (!text) {+ size_t pos = 0;+ joined[0] = 0;+ for (int i = 0; i < a->recap_lines && pos + 1 < sizeof joined; i++) { // the recap's sentences, joined+ const char *l = a->recap + a->line_at[i];+ if (!*l) continue;+ int n = snprintf(joined + pos, sizeof joined - pos, "%s%s", pos ? " " : "", l);+ if (n < 0) break;+ pos += (size_t)n < sizeof joined - pos ? (size_t)n : sizeof joined - pos - 1;+ }+ pod_utf8_trim(joined);+ text = joined;+ }+ if (question) pod_model_unread_ask(&u->model, a->id, a->name, text, now_ms);+ else pod_model_unread_add(&u->model, a->id, a->name, text, (int32_t)pod_agent_secs(a, now_ms), now_ms);+ u->dirty = true;+ if (looking) { // its own room is on screen: shown in place, read at once, no sound, no wake, no toast+ pod_model_unread_read(&u->model, a->id);+ return false;+ }+ // The toast (alert only): none over the update, nor over the bubble that says the same. It shows only over a room, never for+ // the agent it is, and not over Home, Notices or Talk; a toast raised for the next notice replaces this one.+ if (tier == POD_TIER_ALERT && !pod_ui_talking(u) && !u->ota) {const bool room = t && (t->view == POD_V_AGENT || t->view == POD_V_RECAP);if (room && strcmp(t->agent, a->id)) {pod_copy_str(u->ban_agent, sizeof u->ban_agent, a->id);@@ -789,8 +803,7 @@ bool pod_ui_notify(pod_ui_t *u, const char *agent_id, bool awake, uint32_t now_mu->ban_on = true;}}- u->dirty = true;- return true;+ return tier == POD_TIER_ALERT;}void pod_ui_notif_begin(pod_ui_t *u) { pod_model_unread_clear(&u->model); }diff --git a/devices/harness-pro/firmware/main/app/pod_glue.h b/devices/harness-pro/firmware/main/app/pod_glue.hindex 7e456e34e..05207651c 100644--- a/devices/harness-pro/firmware/main/app/pod_glue.h+++ b/devices/harness-pro/firmware/main/app/pod_glue.h@@ -161,14 +161,19 @@ void pod_ui_ota(pod_ui_t *, const char *from, const char *to, int pct, bool restbool pod_ui_updating(const pod_ui_t *);// ---- notifications -----// A live summary ended a turn: file an unread entry for the agent (its recap, name, elapsed) and show the toast for-// POD_TOAST_MS over a room (a newer one replaces it; none while TALK is on top; a tap opens Notices, a swipe up dismisses). False,-// and nothing filed, when the agent is not on the roster. The caller beeps only on true.+// A live summary ended a turn: file an unread entry for the agent (its recap, name, elapsed; one per agent, the newest) and, for an+// alert, show the toast for POD_TOAST_MS over a room (a newer one replaces it; none while TALK is on top; a tap opens Notices, a+// swipe up dismisses). Nothing is filed when the agent is not on the roster.#define POD_BANNER_SWIPE_PX 40// `awake`: the glass is lit. A dark one is not looking, even when it rests on that agent's screen.// When the current toast started (it shows for POD_TOAST_MS); the toast draw reads it for its timer line.uint32_t pod_ui_banner_shown_ms(const pod_ui_t *);-bool pod_ui_notify(pod_ui_t *, const char *agent_id, bool awake, uint32_t now_ms);+// `tier` (alert / list / silent): silent files nothing; list files the entry only; alert also toasts. If the agent's own room is on+// screen (and the glass is lit) any tier is read at once there. Returns true only when the caller must wake the glass and beep:+// an alert, not on that agent's own screen. `text` NULL = the agent's recap; `question`: the entry is a question's (it goes when the+// question closes).+bool pod_ui_notify_text(pod_ui_t *, const char *agent_id, pod_tier_t tier, const char *text, bool question, bool awake, uint32_t now_ms);+bool pod_ui_notify(pod_ui_t *, const char *agent_id, pod_tier_t tier, bool awake, uint32_t now_ms);// notif.replace: begin (clears the list), one row per item, end. The toast is not shown for these.void pod_ui_notif_begin(pod_ui_t *);void pod_ui_notif_row(pod_ui_t *, const char *agent_id, const char *name, const char *token, const char *summary, uint32_t now_ms);diff --git a/devices/harness-pro/firmware/main/app/pro_app.c b/devices/harness-pro/firmware/main/app/pro_app.cindex 565b72146..42cd6dbe2 100644--- a/devices/harness-pro/firmware/main/app/pro_app.c+++ b/devices/harness-pro/firmware/main/app/pro_app.c@@ -58,6 +58,10 @@ static EXT_RAM_BSS_ATTR pod_roster_row_t s_rows[POD_AGENTS_MAX]; // not on thestatic EXT_RAM_BSS_ATTR struct { char id[ID_MAX], machine_id[ID_MAX]; } s_info[POD_AGENTS_MAX]; // the roster's machine idsstatic EXT_RAM_BSS_ATTR char s_busy[POD_AGENTS_MAX][ID_MAX]; // agents in a live turn ("" = free slot)static EXT_RAM_BSS_ATTR char s_quest[POD_AGENTS_MAX][ID_MAX]; // agents with an open question+// Agents whose open question already woke the glass, and a hash of its prompt. A link drop does not clear it: the daemon+// re-sends the open question after the relink and that must not beep again. A close (answered, withdrawn) clears it.+static EXT_RAM_BSS_ATTR char s_alerted[POD_AGENTS_MAX][ID_MAX];+static uint32_t s_alerted_h[POD_AGENTS_MAX];static EXT_RAM_BSS_ATTR cable_machine_t s_mach[CABLE_MAX_MACHINES];static int s_mach_n;@@ -67,7 +71,10 @@ static bool s_started, s_linked, s_dirty;static pod_out_t s_fxq[FX_MAX];static int s_fxn;-static bool s_beepq; // a new notification landed: beep once after the lock is released+static bool s_beepq; // an alert landed and the last beep is old enough: beep once after the lock is released+static bool s_wakeq; // an alert landed: light a dark glass after the lock is released+static bool s_beep_set;+static uint32_t s_beep_ms; // when the last beep was queued (POD_BEEP_COALESCE_MS)// The library sweep's request state. The walk itself is the glue's (pod_ui_sweep_*).static int s_sweep_offset; // the offset the running sweep asks for next@@ -120,6 +127,20 @@ static void voice_begin_effect(const char *agent);static void voice_end_effect(void);static void send_library(uint32_t request, int offset);+// An alert for someone else's screen (the caller holds the lock): wake the glass, and beep unless one was queued in the last+// POD_BEEP_COALESCE_MS. Quiet over the update: the Inbox has it.+static void alert_locked(void)+{+ if (pod_ui_updating(&s_pod)) return;+ s_wakeq = true;+ const uint32_t now = ms();+ if (!s_beep_set || (int32_t)(now - s_beep_ms) >= POD_BEEP_COALESCE_MS) {+ s_beep_set = true;+ s_beep_ms = now;+ s_beepq = true;+ }+}+static void perform(const pod_out_t *o){switch (o->fx) {@@ -144,17 +165,15 @@ static void leave(void)const int lib_offset = s_libq.offset;const uint32_t lib_request = s_libq.request;s_libq.on = false;- const bool beep = s_beepq;- s_beepq = false;+ const bool beep = s_beepq, wake = s_wakeq;+ s_beepq = s_wakeq = false;pod_read_out_t reads[POD_READS_MAX];const int read_n = pod_ui_take_reads(&s_pod, reads, POD_READS_MAX); // entries read on the Pod: tell the hostpro_app_unlock();for (int i = 0; i < n; i++) perform(&q[i]);for (int i = 0; i < read_n; i++) pro_cable_send_notif_read(reads[i].agent, reads[i].token);- if (beep) { // a new notification: light a dark glass so its banner is seen, and chime unless muted- pro_app_wake();- if (!pro_settings_muted() && !atomic_load(&s_updating)) audio_beep();- }+ if (wake) pro_app_wake(); // an alert: light a dark glass so its banner is seen+ if (beep && !pro_settings_muted() && !atomic_load(&s_updating)) audio_beep(); // and chime, unless mutedif (lib) send_library(lib_request, lib_offset);}@@ -450,6 +469,10 @@ static void turn_locked(const char *id, const char *kind, const char *text, int} else if (!strcmp(kind, "done") || !strcmp(kind, "error")) {set_remove(s_busy, id);settle(pod_ui_turn(&s_pod, id, kind, "", 0, now));+ if (!strcmp(kind, "error")) { // a failure is always an alert, whatever the daemon's tiers say+ if (pod_ui_notify_text(&s_pod, id, POD_TIER_ALERT, text && text[0] ? text : "The turn failed", false, !pro_app_asleep(), now)) alert_locked();+ change();+ }}}@@ -469,7 +492,7 @@ void pro_app_turn_stats(const char *id, int tests_passed, int tests_failed, intleave();}-void pro_app_summary(const char *id, const char *text, const char *recap, const char *full, bool restore, bool notify)+void pro_app_summary(const char *id, const char *text, const char *recap, const char *full, bool restore, pod_tier_t tier){if (!id_ok(id)) return;pro_app_lock();@@ -482,8 +505,8 @@ void pro_app_summary(const char *id, const char *text, const char *recap, constconst bool has_text = text && text[0] && strcmp(text, "done");if ((recap && recap[0]) || has_text) settle(pod_ui_recap(&s_pod, id, recap && recap[0] ? recap : text, restore));if (full && full[0]) settle(pod_ui_recap(&s_pod, id, full, restore)); // the long recap wins last (R6)- if (notify && !restore && pod_ui_notify(&s_pod, id, !pro_app_asleep(), now)) { // news: an unread entry, the banner, one beep- s_beepq = !pod_ui_updating(&s_pod); // quiet over the update: the Inbox has it+ if (!restore && tier != POD_TIER_SILENT) { // news: an entry; an alert also toasts, wakes and beeps+ if (pod_ui_notify(&s_pod, id, tier, !pro_app_asleep(), now)) alert_locked();change();}}@@ -511,11 +534,24 @@ void pro_app_notif_seen(const char *id, const char *token)leave();}-void pro_app_question(const char *id, const char *text)+void pro_app_question(const char *id, const char *request, const char *text){if (!id_ok(id)) return;pro_app_lock();- if (s_linked && held(id) && set_add(s_quest, id)) settle(pod_ui_question(&s_pod, id, text && text[0] ? text : "Needs your answer"));+ if (s_linked && held(id) && set_add(s_quest, id)) {+ const char *q = text && text[0] ? text : "Needs your answer";+ settle(pod_ui_question(&s_pod, id, q));+ uint32_t h = 2166136261u; // FNV-1a of the request id and the prompt: a lost close must not mute the next one+ for (const char *c = request ? request : ""; *c; c++) h = (h ^ (uint8_t)*c) * 16777619u;+ h = (h ^ 0u) * 16777619u;+ for (const char *c = q; *c; c++) h = (h ^ (uint8_t)*c) * 16777619u;+ int a = set_find(s_alerted, id);+ const bool again = a >= 0 && s_alerted_h[a] == h; // filed already, re-sent after a relink: no second beep+ if (!again && set_add(s_alerted, id)) { a = set_find(s_alerted, id); s_alerted_h[a] = h; }+ // A question is an alert; filed again after a relink it is the same one, and only the row returns.+ if (pod_ui_notify_text(&s_pod, id, POD_TIER_ALERT, q, true, !pro_app_asleep(), ms()) && !again) alert_locked();+ change();+ }leave();}@@ -524,6 +560,7 @@ void pro_app_question_close(const char *id)if (!id_ok(id)) return;pro_app_lock();set_remove(s_quest, id);+ set_remove(s_alerted, id);settle(pod_ui_question_close(&s_pod, id));leave();}@@ -1037,11 +1074,12 @@ void pro_app_test_reset(void)memset(s_info, 0, sizeof s_info);memset(s_busy, 0, sizeof s_busy);memset(s_quest, 0, sizeof s_quest);+ memset(s_alerted, 0, sizeof s_alerted);s_mach_n = 0;s_linked = false;s_dirty = true;s_fxn = 0;- s_beepq = false;+ s_beepq = s_wakeq = s_beep_set = false;s_sqn = 0;s_libq.on = false;s_sweep_offset = 0;diff --git a/devices/harness-pro/firmware/main/cable/cable_types.h b/devices/harness-pro/firmware/main/cable/cable_types.hindex 4227de2ac..c0bc51c8d 100644--- a/devices/harness-pro/firmware/main/cable/cable_types.h+++ b/devices/harness-pro/firmware/main/cable/cable_types.h@@ -43,6 +43,12 @@ typedef struct {cable_swarm_member_meta_t meta[SWARMS_MAX][SWARM_MEMBERS_MAX];} cable_swarm_members_t;+/*+ * How loud a finished turn is (the summary frame's `tier`): alert = beep, wake, toast and an entry in Notices; list = the+ * entry only; silent = nothing new (the pet and the card still update). A question and a failed turn are always alerts.+ */+typedef enum { POD_TIER_ALERT, POD_TIER_LIST, POD_TIER_SILENT } pod_tier_t;+/** ONE TILE OF THE SELECTED TAB'S GRID, exactly where the window put it: a unit rectangle in THOUSANDTHS of the* grid. `agent_id` is empty for a tile this device cannot drive (a shell, a viewer); it still holds its place.diff --git a/devices/harness-pro/firmware/main/cable/pro_cable.c b/devices/harness-pro/firmware/main/cable/pro_cable.cindex 4d2f32636..6654cc400 100644--- a/devices/harness-pro/firmware/main/cable/pro_cable.c+++ b/devices/harness-pro/firmware/main/cable/pro_cable.c@@ -600,13 +600,23 @@ static void handle_turn_stats(const char *id, const cJSON *p)static bool flag(const cJSON *p, const char *key) { return cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(p, key)); }-// restore is history filled back in, quiet is "the desktop already shows this agent", silent is a sub-agent's turn: the-// recap is applied for all three, but none is news (no entry, no banner, no beep). Absent flags are false.+// The recap is always applied; how loud the end is comes from `tier` (alert / list / silent). restore is history filled back+// in: never news. A summary with no (or an unknown) tier is from an older daemon: quiet ("the desktop already shows this agent")+// and silent (a sub-agent's turn) drop the entry as before, anything else is an alert. Absent flags are false.+static pod_tier_t tier_of(const cJSON *p)+{+ if (flag(p, "restore")) return POD_TIER_SILENT;+ const char *tier = str_of(p, "tier");+ if (tier && !strcmp(tier, "alert")) return POD_TIER_ALERT;+ if (tier && !strcmp(tier, "list")) return POD_TIER_LIST;+ if (tier && !strcmp(tier, "silent")) return POD_TIER_SILENT;+ return flag(p, "quiet") || flag(p, "silent") ? POD_TIER_SILENT : POD_TIER_ALERT;+}+static void handle_summary(const char *id, const cJSON *p){- const bool restore = flag(p, "restore");pro_app_summary(id, cut_of(p, "text", s_text, sizeof s_text), cut_of(p, "recap", s_recap, sizeof s_recap),- cut_of(p, "full", s_full, sizeof s_full), restore, !restore && !flag(p, "quiet") && !flag(p, "silent"));+ cut_of(p, "full", s_full, sizeof s_full), flag(p, "restore"), tier_of(p));}// The fixed field the daemon sizes a readToken by: [A-Za-z0-9_-]{1,63}. Anything else is not a token.@@ -659,11 +669,12 @@ static void handle_notif_seen(const cJSON *p)static void handle_question(const char *id, const cJSON *p){- if (!str_of(p, "id")) return; // the request this question belongs to+ const char *request = str_of(p, "id"); // the request this question belongs to+ if (!request) return;const cJSON *questions = cJSON_GetObjectItemCaseSensitive(p, "questions");const char *prompt = str_of(cJSON_GetArrayItem(questions, 0), "q");copy_cut(s_text, PRO_QUESTION_BYTES, prompt ? prompt : "Needs your answer");- pro_app_question(id, s_text);+ pro_app_question(id, request, s_text);}static void handle_question_close(const char *id, const cJSON *p)@@ -891,7 +902,11 @@ static void handle_message(const cJSON *root)}if (!strcmp(t, "turn.activity")) { handle_turn_activity(agent_id, p); return; }if (!strcmp(t, "turn.done")) { pro_app_turn(agent_id, "done", "", 0); return; }- if (!strcmp(t, "turn.error")) { pro_app_turn(agent_id, "error", "", 0); return; }+ if (!strcmp(t, "turn.error")) {+ const char *message = cut_of(p, "message", s_text, sizeof s_text);+ pro_app_turn(agent_id, "error", message ? message : "", 0);+ return;+ }if (!strcmp(t, "turn.stats")) { handle_turn_stats(agent_id, p); return; }if (!strcmp(t, "summary")) { handle_summary(agent_id, p); return; }if (!strcmp(t, "question")) { handle_question(agent_id, p); return; }diff --git a/devices/harness-pro/firmware/main/pod/pod_model.c b/devices/harness-pro/firmware/main/pod/pod_model.cindex 2711c698e..e5c4f6b07 100644--- a/devices/harness-pro/firmware/main/pod/pod_model.c+++ b/devices/harness-pro/firmware/main/pod/pod_model.c@@ -41,10 +41,14 @@ void pod_model_random(uint32_t (*rnd)(void)) { s_random = rnd; }// The model's own idea of "now": the newest now_ms any feed or the renderer has shown it. It only moves forward// (by signed difference, so it survives the uint32 wrap), and lets every reader apply the same stale rule.+static void unread_expire(pod_model_t *m);+static int unread_idx(const pod_model_t *m, const char *agent);+static void unread_drop(pod_model_t *m, int i);void pod_model_clock(pod_model_t *m, uint32_t now_ms) {if (!m->clock_set || (int32_t)(now_ms - m->clock_ms) > 0) {m->clock_ms = now_ms;m->clock_set = true;+ unread_expire(m); // every tick that moves the clock}}@@ -265,7 +269,7 @@ static void push_step(pod_agent_t *a, const char *old, uint32_t now_ms) {if (a->step_total >= 0 && a->step_total < INT16_MAX) a->step_total++;}-static void set_state(pod_agent_t *a, pod_state_t s, uint32_t now_ms);+static void set_state(pod_model_t *m, pod_agent_t *a, pod_state_t s, uint32_t now_ms);void pod_model_library_row(pod_model_t *m, const char *id, const char *name, const char *engine, const char *machine,const char *status, int32_t age_s, uint32_t now_ms) {@@ -296,7 +300,7 @@ void pod_model_library_row(pod_model_t *m, const char *id, const char *name, conif (before != agent_sig(a, true)) m->revision++;if (event_ok(a, now_ms) && status && sweep_applies(a, st)) {uint64_t was = agent_sig(a, false); // a fresh stamp alone is not a visible change- set_state(a, st, now_ms);+ set_state(m, a, st, now_ms);if (was != agent_sig(a, false)) m->revision++;}}@@ -445,9 +449,15 @@ static pod_agent_t *fresh_agent(pod_model_t *m, const char *id, uint32_t now_ms)return &m->agents[i];}-static void set_state(pod_agent_t *a, pod_state_t s, uint32_t now_ms) {+static void set_state(pod_model_t *m, pod_agent_t *a, pod_state_t s, uint32_t now_ms) {if (s == POD_WORKING && a->state != POD_WORKING) a->since_ms = now_ms;- if (s != POD_ASKING) a->question[0] = 0;+ if (s != POD_ASKING) {+ a->question[0] = 0;+ if (a->state == POD_ASKING) { // the question is over, however: its toast entry is stale+ int u = unread_idx(m, a->id);+ if (u >= 0 && m->unread[u].ask) unread_drop(m, u);+ }+ }if (s == POD_WORKING && a->state != POD_WORKING && a->state != POD_ASKING) { // a new turn without a turn.starteda->failed = false;a->step_total = -1;@@ -472,7 +482,7 @@ void pod_model_library_status(pod_model_t *m, const char *id, const char *statuselse s = POD_IDLE; // idle, failed, paused, offline, anything newif (!sweep_applies(a, s)) return;uint64_t before = agent_sig(a, true);- set_state(a, s, now_ms);+ set_state(m, a, s, now_ms);if (before != agent_sig(a, true)) m->revision++;}@@ -483,7 +493,7 @@ void pod_model_turn(pod_model_t *m, const char *id, const char *kind, const charconst bool was_busy = a->state == POD_WORKING || a->state == POD_ASKING;a->sent = false; // the daemon speaks for the turn nowif (!strcmp(kind, "started")) {- set_state(a, POD_WORKING, now_ms);+ set_state(m, a, POD_WORKING, now_ms);a->since_ms = now_ms;a->elapsed_s = 0;a->activity[0] = 0;@@ -495,7 +505,7 @@ void pod_model_turn(pod_model_t *m, const char *id, const char *kind, const chara->tests_passed = a->tests_failed = a->commits = a->tokens_in = a->tokens_out = -1;} else if (!strcmp(kind, "verb")) {if (a->state == POD_ASKING) return;- set_state(a, POD_WORKING, now_ms);+ set_state(m, a, POD_WORKING, now_ms);// Same rule as the sentence: an empty read says nothing. The word keeps its text, not its dots.if (text && *text) {char w[POD_VERB_BYTES + 8];@@ -510,7 +520,7 @@ void pod_model_turn(pod_model_t *m, const char *id, const char *kind, const char}} else if (!strcmp(kind, "activity")) {if (a->state == POD_ASKING) return; // only turn.started or question.close ends a question- set_state(a, POD_WORKING, now_ms);+ set_state(m, a, POD_WORKING, now_ms);// An empty read says nothing: the daemon sends turn.activity with no text when the terminal shows no footer// (every ~3 s, and right after each turn.started heartbeat), and a missing reading is not "no activity". Only// a text replaces the line; a new turn (started) or a state change away from working is what clears it.@@ -526,11 +536,11 @@ void pod_model_turn(pod_model_t *m, const char *id, const char *kind, const char// A tool the turn just started ("Read · pod_model.c"): the newest grey line. A turn of tool calls and no// prose had nothing else to show, and the body stayed empty through all of it.if (a->state == POD_ASKING) return;- if (text && *text) { set_state(a, POD_WORKING, now_ms); push_step(a, text, now_ms); }+ if (text && *text) { set_state(m, a, POD_WORKING, now_ms); push_step(a, text, now_ms); }} else if (!strcmp(kind, "done")) {- set_state(a, POD_DONE, now_ms);+ set_state(m, a, POD_DONE, now_ms);} else if (!strcmp(kind, "error")) {- set_state(a, POD_IDLE, now_ms);+ set_state(m, a, POD_IDLE, now_ms);a->failed = true;}// A task's clock: only an event inside a turn. A stray done for an idle agent (the daemon's focus read, a replay)@@ -576,6 +586,8 @@ void pod_model_question_close(pod_model_t *m, const char *id) {if (i < 0 || m->agents[i].state != POD_ASKING) return;m->agents[i].state = POD_WORKING;m->agents[i].question[0] = 0;+ int u = unread_idx(m, id);+ if (u >= 0 && m->unread[u].ask) unread_drop(m, u); // answered: its toast entry is stalem->revision++;}@@ -661,6 +673,9 @@ void pod_model_recap(pod_model_t *m, const char *id, const char *recap, bool resvoid pod_model_link(pod_model_t *m, bool up) {if (m->linked == up) return;m->linked = up;+ if (!up) // a drop forgets every open question (pro_app clears them): the daemon re-sends what is still owed+ for (int i = m->unread_count - 1; i >= 0; i--)+ if (m->unread[i].ask) unread_drop(m, i);m->revision++;}@@ -670,7 +685,7 @@ void pod_model_sent(pod_model_t *m, const char *id, uint32_t now_ms) {if (i < 0) return;pod_agent_t *a = &m->agents[i];uint64_t before = agent_sig(a, true);- if (a->state != POD_WORKING) { set_state(a, POD_WORKING, now_ms); a->elapsed_s = 0; }+ if (a->state != POD_WORKING) { set_state(m, a, POD_WORKING, now_ms); a->elapsed_s = 0; }a->sent = true;a->sent_ms = now_ms;if (before != agent_sig(a, true)) m->revision++;@@ -756,6 +771,12 @@ static void unread_drop(pod_model_t *m, int i) {m->revision++;}+// An entry older than POD_UNREAD_TTL_MS since receipt goes; the signed difference survives the uint32 wrap.+static void unread_expire(pod_model_t *m) {+ for (int i = m->unread_count - 1; i >= 0; i--)+ if ((int32_t)(m->clock_ms - m->unread[i].at_ms) >= (int32_t)POD_UNREAD_TTL_MS) unread_drop(m, i);+}+void pod_model_unread_add(pod_model_t *m, const char *agent, const char *name, const char *text, int32_t elapsed_s, uint32_t now_ms) {if (!agent || !*agent || strnlen(agent, ID_MAX) >= ID_MAX) return;pod_model_clock(m, now_ms);@@ -776,6 +797,12 @@ void pod_model_unread_add(pod_model_t *m, const char *agent, const char *name, cm->revision++;}+void pod_model_unread_ask(pod_model_t *m, const char *agent, const char *name, const char *text, uint32_t now_ms) {+ pod_model_unread_add(m, agent, name, text, -1, now_ms);+ int i = unread_idx(m, agent);+ if (i >= 0) m->unread[i].ask = true;+}+int pod_notice_count(const pod_model_t *m) {int n = 0;for (int i = 0; i < m->agent_count; i++) n += pod_model_eff(m, &m->agents[i]) == POD_ASKING;diff --git a/devices/harness-pro/firmware/main/pod/pod_model.h b/devices/harness-pro/firmware/main/pod/pod_model.hindex f1150ea14..a64414421 100644--- a/devices/harness-pro/firmware/main/pod/pod_model.h+++ b/devices/harness-pro/firmware/main/pod/pod_model.h@@ -86,9 +86,12 @@ typedef struct {#define POD_UNREAD_MAX 16#define POD_UNREAD_TEXT 240#define POD_TOKEN_MAX 64+#define POD_UNREAD_TTL_MS (6u * 3600u * 1000u) // an entry lives 6 h from receipt (the device's monotonic ms, uint32-wrap safe)+#define POD_BEEP_COALESCE_MS 30000 // at most one beep per this longtypedef enum { POD_UNREAD_FINISHED, POD_UNREAD_FAILED } pod_unread_kind_t;typedef struct {char agent[ID_MAX], name[CABLE_NAME_MAX], token[POD_TOKEN_MAX], text[POD_UNREAD_TEXT];+ bool ask; // filed by a question (not a finished turn): it goes when the question closespod_unread_kind_t kind; // FAILED when the agent's last turn ended in an erroruint32_t at_ms;int32_t elapsed_s; // the turn's length, -1 unknown@@ -195,5 +198,7 @@ bool pod_model_unread_read(pod_model_t *, const char *agent);const pod_unread_t *pod_model_unread_find(const pod_model_t *, const char *agent);// How many notices Pets lists (the Notices screen and Home's Notices card): the asking agents, then the unread entries of agents that are not asking.int pod_notice_count(const pod_model_t *);+// The entry of a question that was just asked (the toast needs one): like pod_model_unread_add, marked `ask`.+void pod_model_unread_ask(pod_model_t *, const char *agent, const char *name, const char *text, uint32_t now_ms);// Take the queued notif.read frames (at most max); returns the count.int pod_model_take_reads(pod_model_t *, pod_read_out_t out[], int max);diff --git a/devices/harness-pro/firmware/main/pro_app_api.h b/devices/harness-pro/firmware/main/pro_app_api.hindex 869e82550..38563cc33 100644--- a/devices/harness-pro/firmware/main/pro_app_api.h+++ b/devices/harness-pro/firmware/main/pro_app_api.h@@ -57,14 +57,16 @@ void pro_app_context(const char *id, const char *machine, const char *project, c// "step" text = one tool card (non-empty, <= 120 B), elapsed_s -1// "done" / "error" text "", elapsed_s 0// `turn.activity` is delivered as verb, then activity, then step, each only when its field is present.+// kind "error": `text` is the failure message (may be ""); the failed turn is filed as an alert.void pro_app_turn(const char *id, const char *kind, const char *text, int elapsed_s);// turn.stats, once before turn.done: each count is 0..1000000, or -1 when the message left it out.void pro_app_turn_stats(const char *id, int tests_passed, int tests_failed, int commits, int tokens_in, int tokens_out);// `text` and `recap` are NULL when absent, `full` is NULL from a daemon without recap=long-v1.-// `notify`: a live turn's end that is news here (not `restore`, not `quiet`, not `silent`): file an unread entry, show the-// banner and beep. The recap itself is applied either way.-void pro_app_summary(const char *id, const char *text, const char *recap, const char *full, bool restore, bool notify);+// `tier`: how loud a live turn's end is (see pod_tier_t; a `restore` is never news, whatever it says): alert files an unread+// entry, shows the banner and beeps (one beep per POD_BEEP_COALESCE_MS), list only files the entry, silent files nothing.+// The recap itself is applied either way.+void pro_app_summary(const char *id, const char *text, const char *recap, const char *full, bool restore, pod_tier_t tier);// ---- notifications ----// notif.replace: the whole unread list (the daemon sends it on greeting; at most 8 items, one per agent). Strings are never@@ -74,7 +76,8 @@ void pro_app_notif_replace(const pro_notif_row_t *rows, int n);// notif.seen: read elsewhere. token is NULL without one.void pro_app_notif_seen(const char *id, const char *token);-void pro_app_question(const char *id, const char *text);+// request is the question's request id: with the prompt it tells a re-sent question from a new one.+void pro_app_question(const char *id, const char *request, const char *text);void pro_app_question_close(const char *id);// The daemon's surface moved to this agent.diff --git a/devices/harness-pro/firmware/test/test_ph_glue.c b/devices/harness-pro/firmware/test/test_ph_glue.cindex 0ad986ffc..b58309637 100644--- a/devices/harness-pro/firmware/test/test_ph_glue.c+++ b/devices/harness-pro/firmware/test/test_ph_glue.c@@ -658,12 +658,12 @@ static void room_agent_gone_lands_home(void) {// Pets: no toast over Home or Notices; the unread entry and the beep (notify's true) stay.static void no_toast_on_home_pets(void) {fresh();- CHECK(pod_ui_notify(&U, "a3", true, 1000)); // on Home+ CHECK(pod_ui_notify(&U, "a3", POD_TIER_ALERT, true, 1000)); // on Homerender(1000);CHECK(!U.frame.banner && !U.ban_on && !find(POD_A_BANNER) && pod_model_unread_find(&U.model, "a3"));fresh();act(POD_A_INBOX, 0); // on Notices- CHECK(pod_ui_notify(&U, "a3", true, 1000));+ CHECK(pod_ui_notify(&U, "a3", POD_TIER_ALERT, true, 1000));render(1000);CHECK(!U.frame.banner && !U.ban_on && !find(POD_A_BANNER) && pod_model_unread_find(&U.model, "a3"));}@@ -988,7 +988,7 @@ static void toast_and_edges(void) {// A toast over a room: the bar's swipe down still opens Notices, but a contact on the toast belongs to the toast (below).fresh();to_agent(0, 0);- CHECK(pod_ui_notify(&U, "a3", true, 1000));+ CHECK(pod_ui_notify(&U, "a3", POD_TIER_ALERT, true, 1000));render(1000);CHECK(U.ban_on && U.frame.banner);t_(true, 360, 190, 1100); t_(true, 360, 240, 1140); t_(false, 360, 300, 1180); // under the toast: a drag on the room@@ -1001,7 +1001,7 @@ static void toast_shows_and_expires(void) {fresh();calm();to_agent(0, 2); // a3's Recap: a still room- CHECK(pod_ui_notify(&U, "a1", true, 1000)); // the beep still plays+ CHECK(pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000)); // the beep still playsCHECK(U.ban_on && U.ban_until == 6000 && pod_ui_banner_shown_ms(&U) == 1000);render(1000);CHECK(U.frame.banner && hits_of_banner() == 1);@@ -1016,18 +1016,18 @@ static void toast_shows_and_expires(void) {fresh();calm();to_agent(0, 2);- pod_ui_notify(&U, "a1", true, 1000);+ pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000);render(1000);for (uint32_t t = 1000; t < 6000; t += 5) CHECK(pod_ui_wake_ms(&U, t) <= 66);// a newer notice replaces it: 5 s from then- CHECK(pod_ui_notify(&U, "a2", true, 3000));+ CHECK(pod_ui_notify(&U, "a2", POD_TIER_ALERT, true, 3000));CHECK(!strcmp(U.ban_agent, "a2") && U.ban_until == 8000 && pod_ui_banner_shown_ms(&U) == 3000);}static void toast_tap_opens_notices(void) {fresh();calm();to_agent(0, 2);- pod_ui_notify(&U, "a1", true, 1000);+ pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000);render(1000);const int depth = U.nav.depth;pod_out_t o = tap_(360, 80, 1100);@@ -1039,7 +1039,7 @@ static void toast_tap_opens_notices(void) {fresh();calm();to_agent(0, 2);- pod_ui_notify(&U, "a1", true, 1000);+ pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000);render(1000);o = tap_(360, 300, 1100);CHECK(o.fx == POD_FX_VOICE_BEGIN && !strcmp(o.agent, "a3") && top()->view == POD_V_TALK);@@ -1048,7 +1048,7 @@ static void toast_swipe_up_dismisses(void) {fresh();calm();to_agent(0, 2);- pod_ui_notify(&U, "a1", true, 1000);+ pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000);render(1000);const int depth = U.nav.depth;CHECK(!U.talk_armed);@@ -1061,7 +1061,7 @@ static void toast_swipe_up_dismisses(void) {fresh();calm();to_agent(0, 2);- pod_ui_notify(&U, "a1", true, 1000);+ pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000);render(1000);t_(true, 360, 40, 1100); t_(true, 360, 90, 1140); t_(false, 360, 170, 1180);CHECK(U.nav.depth == 3 && top()->view == POD_V_RECAP && U.ban_on);@@ -1071,8 +1071,8 @@ static void toast_not_here(void) {fresh();calm();to_agent(0, 2);- CHECK(pod_ui_notify(&U, "a3", true, 1000) && !U.ban_on);- CHECK(pod_ui_notify(&U, "a3", false, 1100) && !U.ban_on);+ CHECK(!pod_ui_notify(&U, "a3", POD_TIER_ALERT, true, 1000) && !U.ban_on);+ CHECK(pod_ui_notify(&U, "a3", POD_TIER_ALERT, false, 1100) && !U.ban_on);CHECK(pod_model_unread_find(&U.model, "a3"));// a room over Notices (opened from a notice) shows toasts for the others// not over Talk: recording or sending@@ -1080,7 +1080,7 @@ static void toast_not_here(void) {to_agent(0, 0);act(POD_A_TALK, 0);CHECK(top()->view == POD_V_TALK);- CHECK(pod_ui_notify(&U, "a3", true, 1000) && !U.ban_on);+ CHECK(pod_ui_notify(&U, "a3", POD_TIER_ALERT, true, 1000) && !U.ban_on);render(1000);CHECK(!U.frame.banner);// not over the update@@ -1088,7 +1088,7 @@ static void toast_not_here(void) {calm();to_agent(0, 2);pod_ui_ota(&U, "0.1.1", "0.1.2", 10, false);- CHECK(pod_ui_notify(&U, "a1", true, 1000) && !U.ban_on);+ CHECK(pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000) && !U.ban_on);pod_ui_ota(&U, NULL, NULL, -1, false);render(1100);CHECK(!U.frame.banner && pod_model_unread_find(&U.model, "a1"));@@ -1096,7 +1096,7 @@ static void toast_not_here(void) {fresh();calm();to_agent(0, 2);- pod_ui_notify(&U, "a1", true, 1000);+ pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000);render(1000);CHECK(U.frame.banner);act(POD_A_INBOX, 0);@@ -1106,7 +1106,7 @@ static void toast_not_here(void) {fresh();calm();to_agent(0, 2);- pod_ui_notify(&U, "a1", true, 1000);+ pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000);act(POD_A_PREV, 0); // a3 -> a2act(POD_A_PREV, 0); // a2 -> a1render(1100);@@ -1154,7 +1154,7 @@ static void home_notices_come_and_go(void) {CHECK(top()->scroll == 1 && pod_tabs_pages_of(&U.nav, &U.model) == 2);render(1100);CHECK(find(POD_A_ENTER_TAB) && !strcmp(find(POD_A_ENTER_TAB)->id, "s2"));- CHECK(pod_ui_notify(&U, "a3", true, 1200));+ CHECK(pod_ui_notify(&U, "a3", POD_TIER_ALERT, true, 1200));CHECK(top()->scroll == 1 && pod_tabs_pages_of(&U.nav, &U.model) == 3);render(1300);CHECK(find(POD_A_ENTER_TAB) && !strcmp(find(POD_A_ENTER_TAB)->id, "s2"));@@ -1313,7 +1313,7 @@ static void toast_cap_only_when_drawn(void) {fresh();calm();to_agent(0, 2); // a3's Recap: a still room- CHECK(pod_ui_notify(&U, "a1", true, 1000));+ CHECK(pod_ui_notify(&U, "a1", POD_TIER_ALERT, true, 1000));render(1000);CHECK(U.ban_on && U.frame.banner);for (uint32_t t = 1000; t < 2000; t += 7) CHECK(pod_ui_wake_ms(&U, t) <= 66);@@ -1451,12 +1451,18 @@ static void home_page(void) {CHECK(tap_(h->x + h->w / 2, h->y + h->h / 2, 1400).fx == POD_FX_AGENT_OPEN && !strcmp(top()->agent, "a3"));}-// A notice for the agent already on screen still adds its unread entry (the finished bubble shows).+// A notice for the agent already on screen is shown in place: no beep or wake (false), no toast, and its entry is read at once.+// Dark (not awake), the same screen is not looked at: the entry stays and the glass is to be lit.static void notify_while_looking(void) {fresh();to_agent(0, 2); // a3, Recap- CHECK(pod_ui_notify(&U, "a3", true, 1000));+ CHECK(!pod_ui_notify(&U, "a3", POD_TIER_ALERT, true, 1000));+ CHECK(pod_model_unread_find(&U.model, "a3") == NULL && !U.ban_on);+ CHECK(pod_ui_notify(&U, "a3", POD_TIER_ALERT, false, 1100));CHECK(pod_model_unread_find(&U.model, "a3") != NULL);+ // list: filed, never a beep (false) nor a toast; silent: nothing filed.+ CHECK(!pod_ui_notify(&U, "a1", POD_TIER_LIST, true, 1200) && pod_model_unread_find(&U.model, "a1") && !U.ban_on);+ CHECK(!pod_ui_notify(&U, "a2", POD_TIER_SILENT, true, 1300) && !pod_model_unread_find(&U.model, "a2"));}// One swipe is one page, in the list's order: Notices, Working, Build, Docs.diff --git a/devices/harness-pro/firmware/test/test_pod_model.c b/devices/harness-pro/firmware/test/test_pod_model.cindex 6bea5f96a..4df3a8206 100644--- a/devices/harness-pro/firmware/test/test_pod_model.c+++ b/devices/harness-pro/firmware/test/test_pod_model.c@@ -864,6 +864,44 @@ static void pod_model_test_offline_members(void) {pod_model_agents_end(&M);}+// Entries live 6 h from receipt, by a signed difference, so they survive the uint32 wrap of the device clock.+static void pod_model_test_unread_expiry(void) {+ fresh();+ pod_model_unread_add(&M, "a1", "Alpha", "first", 1, 1000);+ pod_model_clock(&M, 1000 + POD_UNREAD_TTL_MS - 1); // 5 h 59 m 59.999 s+ CHECK(M.unread_count == 1);+ pod_model_clock(&M, 1000 + POD_UNREAD_TTL_MS);+ CHECK(M.unread_count == 0);+ // Across the wrap: received 1 s before it, the clock a little past 6 h later.+ fresh();+ pod_model_unread_add(&M, "a1", "Alpha", "first", 1, 0xFFFFFC00u);+ pod_model_unread_add(&M, "a2", "Beta", "second", 1, 0xFFFFFC00u + 3600000u); // 1 h later, past the wrap+ pod_model_clock(&M, 0xFFFFFC00u + POD_UNREAD_TTL_MS - 1);+ CHECK(M.unread_count == 2);+ pod_model_clock(&M, 0xFFFFFC00u + POD_UNREAD_TTL_MS);+ CHECK(M.unread_count == 1 && !strcmp(M.unread[0].agent, "a2"));+ // A newer entry of the same agent restarts its clock; an asking agent's entry goes when its question closes.+ fresh();+ pod_model_unread_add(&M, "a1", "Alpha", "first", 1, 1000);+ pod_model_unread_add(&M, "a1", "Alpha", "again", 1, 5000);+ CHECK(M.unread_count == 1);+ pod_model_clock(&M, 1000 + POD_UNREAD_TTL_MS);+ CHECK(M.unread_count == 1);+ pod_model_clock(&M, 5000 + POD_UNREAD_TTL_MS);+ CHECK(M.unread_count == 0);+ fresh();+ pod_model_unread_add(&M, "a1", "Alpha", "a finished one", 1, 100);+ pod_model_question(&M, "a1", "Which?");+ pod_model_unread_ask(&M, "a1", "Alpha", "Which?", 200);+ CHECK(M.unread_count == 1 && M.unread[0].ask && !strcmp(M.unread[0].text, "Which?"));+ pod_model_question_close(&M, "a1");+ CHECK(M.unread_count == 0);+ pod_model_unread_add(&M, "a1", "Alpha", "a finished one", 1, 300); // not a question's: it stays+ pod_model_question(&M, "a1", "Which?");+ pod_model_question_close(&M, "a1");+ CHECK(M.unread_count == 1);+}+static void pod_model_test_unread(void) {fresh();CHECK(M.unread_count == 0);@@ -1104,6 +1142,7 @@ int main(void) {pod_model_test_recent();pod_model_test_offline_members();pod_model_test_unread();+ pod_model_test_unread_expiry();pod_model_test_console_data();pod_model_test_step_total_and_fresh();printf("Pod model: PASS (%d checks)\n", checks);diff --git a/devices/harness-pro/firmware/test/test_pro_app.py b/devices/harness-pro/firmware/test/test_pro_app.pyindex d8185d3d3..b98fd4bf9 100644--- a/devices/harness-pro/firmware/test/test_pro_app.py+++ b/devices/harness-pro/firmware/test/test_pro_app.py@@ -909,9 +909,9 @@ static void *cable_task(void *arg) {pro_app_turn("a1", "verb", "Reading...", -1);pro_app_turn("a1", "activity", "Reading files", 3);pro_app_turn("a1", "step", "Read - pod_model.c", -1);- pro_app_question("a3", "Which branch?");+ pro_app_question("a3", "r1", "Which branch?");pro_app_question_close("a3");- pro_app_summary("a2", "Fixed the parser.", "Fixed the parser. Added two tests.", "Fixed the parser. Added two tests. Then more.", false, false);+ pro_app_summary("a2", "Fixed the parser.", "Fixed the parser. Added two tests.", "Fixed the parser. Added two tests. Then more.", false, POD_TIER_SILENT);pro_app_focus("a4");pro_app_turn("a1", "done", "", 0);pro_app_swarms(NULL, 0, NULL, NULL, NULL, 0);@@ -1484,25 +1484,25 @@ static void pro_app_test_summary_and_question(void) {now = 3000;pro_app_turn("a1", "started", "", 0);// A live summary ends the turn; `full` wins over `recap`.- pro_app_summary("a1", "short", "the recap", "the long recap", false, false);+ pro_app_summary("a1", "short", "the recap", "the long recap", false, POD_TIER_SILENT);CHECK(agent("a1")->state == POD_DONE && strstr(agent("a1")->recap, "the long recap") && !strstr(agent("a1")->recap, "the recap\n"));// A restore summary is history: no end of turn.pro_app_turn("a2", "started", "", 0);- pro_app_summary("a2", "old text", NULL, NULL, true, false);+ pro_app_summary("a2", "old text", NULL, NULL, true, POD_TIER_SILENT);CHECK(agent("a2")->state == POD_WORKING);// "done" is not a text- pro_app_summary("a3", "done", NULL, NULL, false, false);+ pro_app_summary("a3", "done", NULL, NULL, false, POD_TIER_SILENT);CHECK(agent("a3")->recap[0] == 0);// Questions: held while open, closed by the daemon or by a new turn.- pro_app_question("a1", "Which branch?");+ pro_app_question("a1", "r1", "Which branch?");CHECK(pro_app_question_open("a1") && agent("a1")->state == POD_ASKING);pro_app_question_close("a1");CHECK(!pro_app_question_open("a1"));- pro_app_question("a1", NULL);+ pro_app_question("a1", "r1", NULL);CHECK(pro_app_question_open("a1") && !strcmp(agent("a1")->question, "Needs your answer"));pro_app_turn("a1", "started", "", 0);CHECK(!pro_app_question_open("a1"));- pro_app_question("zz", "ghost?");+ pro_app_question("zz", "r1", "ghost?");CHECK(!pro_app_question_open("zz"));}@@ -1574,7 +1574,7 @@ static void pro_app_test_voice_gate(void) {CHECK(!strcmp(pro_app_voice_block_reason("a3"), "Link this computer in Harness."));CHECK(!strcmp(pro_app_voice_block_reason("a4"), "Choose an agent pane."));CHECK(pro_app_voice_block_reason("nobody") == NULL); // unknown: allowed- pro_app_question("a1", "Which?");+ pro_app_question("a1", "r1", "Which?");CHECK(!strcmp(pro_app_voice_block_reason("a1"), "Answer its question first."));pro_app_question_close("a1");CHECK(pro_app_voice_block_reason("a1") == NULL);@@ -1609,7 +1609,7 @@ static void pro_app_test_voice_paths(void) {CHECK(top() == POD_V_AGENT && !pod_ui_talking(&U) && U.notice_on && !strcmp(U.notice, "Can't talk right now"));// A gate refusal never reaches the recorderV.refuse = false;- pro_app_question("a1", "Which?");+ pro_app_question("a1", "r1", "Which?");render();CHECK(hit(POD_A_TALK, 0) == NULL); // no screen draws a Talk button; the gate still meets a stale hittap_stale_talk();@@ -1769,10 +1769,10 @@ static void side_button_discards_hands_free(void) {static void question_needs_the_link(void) {setup();pro_app_link(false, NULL);- pro_app_question("a1", "Which one?");+ pro_app_question("a1", "r1", "Which one?");CHECK(!pro_app_question_open("a1"));pro_app_link(true, "mac");- pro_app_question("a1", "Which one?");+ pro_app_question("a1", "r1", "Which one?");CHECK(pro_app_question_open("a1"));}@@ -1796,7 +1796,7 @@ static void notif_room(void) {static void notify_banner_beep_and_expiry(void) {notif_room();// A plain live summary: an unread entry, the toast, one beep.- pro_app_summary("a3", "t", "Shipped the thing. Tests pass.", NULL, false, true);+ pro_app_summary("a3", "t", "Shipped the thing. Tests pass.", NULL, false, POD_TIER_ALERT);CHECK(BEEPS == 1 && U.model.unread_count == 1 && !strcmp(U.model.unread[0].agent, "a3"));CHECK(pod_ui_take_changed(&U));render();@@ -1814,53 +1814,172 @@ static void notify_banner_beep_and_expiry(void) {CHECK(banner() == NULL && U.model.unread_count == 1); // it stays unread in the Inbox// A newer one replaces the shown one, and moves to the top of the list.now = 20000;- pro_app_summary("a2", "t", "Renamed the module.", NULL, false, true);+ pro_app_summary("a2", "t", "Renamed the module.", NULL, false, POD_TIER_ALERT);render();- CHECK(BEEPS == 2 && U.model.unread_count == 2 && !strcmp(U.model.unread[0].agent, "a2") && banner() && !strcmp(banner()->id, "a2"));+ CHECK(BEEPS == 1 && U.model.unread_count == 2 && !strcmp(U.model.unread[0].agent, "a2") && banner() && !strcmp(banner()->id, "a2")); // 15 s after the beep: coalescednow = 22000;- pro_app_summary("a3", "t", "And again.", NULL, false, true);+ pro_app_summary("a3", "t", "And again.", NULL, false, POD_TIER_ALERT);render();- CHECK(BEEPS == 3 && U.model.unread_count == 2 && !strcmp(banner()->id, "a3") && !strcmp(U.model.unread[0].agent, "a3"));+ CHECK(BEEPS == 1 && U.model.unread_count == 2 && !strcmp(banner()->id, "a3") && !strcmp(U.model.unread[0].agent, "a3"));// Muted: the entry and the toast come, the beep does not.MUTED = true;- now = 30000;- pro_app_summary("a2", "t", "Muted one.", NULL, false, true);- CHECK(BEEPS == 3 && U.model.unread_count == 2);+ now = 40000;+ pro_app_summary("a2", "t", "Muted one.", NULL, false, POD_TIER_ALERT);+ CHECK(BEEPS == 1 && U.model.unread_count == 2);MUTED = false;// quiet / silent / restore (notify false): no entry, no beep, no toast; a restore also leaves the turn state alone.notif_room();now = 6000;- pro_app_summary("a3", "t", "quiet", NULL, false, false);- pro_app_summary("a3", "t", "restored", NULL, true, false);+ pro_app_summary("a3", "t", "quiet", NULL, false, POD_TIER_SILENT);+ pro_app_summary("a3", "t", "restored", NULL, true, POD_TIER_SILENT);CHECK(BEEPS == 0 && U.model.unread_count == 0);render();CHECK(banner() == NULL);// A restore that claims to notify still does not (the cable never sends that; the app does not trust it).- pro_app_summary("a3", "t", "restored", NULL, true, true);+ pro_app_summary("a3", "t", "restored", NULL, true, POD_TIER_ALERT);CHECK(BEEPS == 0 && U.model.unread_count == 0);// An agent the roster does not hold: nothing.- pro_app_summary("zz", "t", "ghost", NULL, false, true);+ pro_app_summary("zz", "t", "ghost", NULL, false, POD_TIER_ALERT);CHECK(BEEPS == 0 && U.model.unread_count == 0);- // Awake on that agent's own screen: it beeps and the entry is filed all the same (the recap on screen reads it), but no toast- // covers the room that says the same. Dark on it: news, and the glass lights.+ // Awake on that agent's own screen: no beep, no wake, the entry is read at once. Dark on it: news, and the glass lights.notif_setup();now = 40000;pod_ui_focus(&U, "a3", now);CHECK(top() == POD_V_AGENT || top() == POD_V_RECAP);- pro_app_summary("a3", "t", "Looked at.", NULL, false, true);+ pro_app_summary("a3", "t", "Looked at.", NULL, false, POD_TIER_ALERT);render();- CHECK(BEEPS == 1 && banner() == NULL && U.model.unread_count == 0); // its recap is on screen: read at once+ CHECK(BEEPS == 0 && banner() == NULL && U.model.unread_count == 0); // its recap is on screen: no beep, read at oncepro_app_sleep();CHECK(pro_app_asleep());- pro_app_summary("a3", "t", "In the dark.", NULL, false, true);- CHECK(BEEPS == 2 && U.model.unread_count == 1 && !pro_app_asleep());+ pro_app_summary("a3", "t", "In the dark.", NULL, false, POD_TIER_ALERT);+ CHECK(BEEPS == 1 && U.model.unread_count == 1 && !pro_app_asleep());+}++// The tiers: alert = entry + toast + beep + wake; list = entry only; silent = nothing. One beep per 30 s; one entry per agent.+static void notify_tiers(void) {+ notif_room(); // a1's room, now = 5300+ pro_app_summary("a3", "t", "Listed.", NULL, false, POD_TIER_LIST);+ render();+ CHECK(BEEPS == 0 && U.model.unread_count == 1 && banner() == NULL && !U.ban_on);+ pro_app_summary("a2", "t", "Silent.", NULL, false, POD_TIER_SILENT);+ CHECK(BEEPS == 0 && U.model.unread_count == 1 && !pod_model_unread_find(&U.model, "a2"));+ // A newer entry of the same agent replaces the older one.+ pro_app_summary("a3", "t", "Listed again.", NULL, false, POD_TIER_LIST);+ CHECK(U.model.unread_count == 1 && !strcmp(U.model.unread[0].text, "Listed again."));+ // An asleep device receiving a list entry stays asleep; an alert wakes it.+ pro_app_sleep();+ pro_app_summary("a2", "t", "Dark list.", NULL, false, POD_TIER_LIST);+ CHECK(pro_app_asleep() && BEEPS == 0 && U.model.unread_count == 2);+ pro_app_summary("a2", "t", "Dark alert.", NULL, false, POD_TIER_ALERT);+ CHECK(!pro_app_asleep() && BEEPS == 1 && U.model.unread_count == 2);+ // Alerts 10 s apart beep once; 31 s after the beep, again. A coalesced alert still wakes and toasts.+ now += 10000;+ pro_app_sleep();+ pro_app_summary("a3", "t", "Second.", NULL, false, POD_TIER_ALERT);+ render();+ CHECK(BEEPS == 1 && !pro_app_asleep() && banner() && !strcmp(banner()->id, "a3"));+ now += 21000; // 31 s after the first beep+ pro_app_summary("a2", "t", "Third.", NULL, false, POD_TIER_ALERT);+ CHECK(BEEPS == 2);+}++// A question is an alert; a failed turn files a failed entry as an alert.+static void notify_question_and_error(void) {+ notif_room(); // a1's room, now = 5300+ pro_app_question("a3", "r1", "Which branch?");+ render();+ CHECK(BEEPS == 1 && banner() && !strcmp(banner()->id, "a3") && pod_model_unread_find(&U.model, "a3"));+ now += 10000;+ pro_app_question("a2", "r1", "Which file?");+ CHECK(BEEPS == 1); // coalesced+ pro_app_question_close("a3");+ pro_app_question_close("a2");+ CHECK(U.model.unread_count == 0); // answered: its entry goes+ // Asleep: the question wakes the glass.+ pro_app_sleep();+ now += 40000;+ pro_app_question("a3", "r1", "Again?");+ CHECK(!pro_app_asleep() && BEEPS == 2);+ // Its own room: no beep, nothing filed.+ pro_app_question_close("a3");+ notif_setup();+ pod_ui_focus(&U, "a3", now);+ pro_app_question("a3", "r1", "Here?");+ CHECK(BEEPS == 0 && U.model.unread_count == 0);+ // turn.error: a failed entry, an alert.+ notif_room();+ pro_app_turn("a3", "error", "Build broke", 0);+ render();+ const pod_unread_t *e = pod_model_unread_find(&U.model, "a3");+ CHECK(BEEPS == 1 && e && e->kind == POD_UNREAD_FAILED && !strcmp(e->text, "Build broke") && banner());+}++// The daemon re-sends an open question after a link drop: the row returns, but the glass does not wake or beep again.+static void notify_question_resent_after_relink_is_quiet(void) {+ notif_room();+ pro_app_question("a3", "r1", "Which branch?");+ CHECK(BEEPS == 1);+ pro_app_link(false, NULL);+ pro_app_link(true, "mac");+ pro_app_sleep();+ now += 40000; // past the beep coalescing, so only the repeat check can silence it+ pro_app_question("a3", "r1", "Which branch?");+ CHECK(pro_app_question_open("a3") && pod_model_unread_find(&U.model, "a3") && BEEPS == 1 && pro_app_asleep());+ pro_app_question("a3", "r2", "A different one?"); // another prompt is news+ CHECK(BEEPS == 2 && !pro_app_asleep());+ pro_app_question_close("a3");+ now += 40000;+ pro_app_question("a3", "r3", "A different one?"); // answered, then asked again: news+ CHECK(BEEPS == 3);+}++// The same prompt under a new request is a new question, even when the close of the last one was lost (Claude+// Code's approvals all read "Do you want to proceed?").+static void notify_question_same_prompt_new_request_beeps(void) {+ notif_room();+ pro_app_question("a3", "r1", "Do you want to proceed?");+ CHECK(BEEPS == 1);+ pro_app_link(false, NULL); // the close of r1 is lost with the link+ pro_app_link(true, "mac");+ now += 40000;+ pro_app_question("a3", "r2", "Do you want to proceed?");+ CHECK(BEEPS == 2);+}++// A question's entry goes whenever the question ends: a new turn, a finished turn, a link drop.+static void notify_question_entry_ends_with_question(void) {+ notif_room();+ pro_app_question("a3", "r1", "Which branch?");+ CHECK(pod_model_unread_find(&U.model, "a3"));+ pro_app_turn("a3", "started", "Working", 0);+ CHECK(!pod_model_unread_find(&U.model, "a3"));+ pro_app_question("a2", "r1", "Which file?");+ CHECK(pod_model_unread_find(&U.model, "a2"));+ pro_app_summary("a2", "t", "Done.", NULL, false, POD_TIER_SILENT);+ CHECK(!pod_model_unread_find(&U.model, "a2")); // a silent end files nothing, and the question's entry is gone+ pro_app_question("a3", "r1", "Again?");+ CHECK(pod_model_unread_find(&U.model, "a3"));+ pro_app_link(false, NULL);+ CHECK(!pod_model_unread_find(&U.model, "a3"));+ pro_app_link(true, "mac");+ CHECK(!pod_model_unread_find(&U.model, "a3"));+}++// Entries expire after 6 h, measured from receipt on the render clock.+static void notify_entries_expire(void) {+ notif_room();+ pro_app_summary("a3", "t", "Old.", NULL, false, POD_TIER_LIST);+ now += POD_UNREAD_TTL_MS - 1; render();+ CHECK(U.model.unread_count == 1);+ now += 1; render();+ CHECK(U.model.unread_count == 0);}static void notify_tap_opens_and_swipe_dismisses(void) {notif_room();// A tap on the toast opens Notices, which lists the entry.now = 6000;- pro_app_summary("a3", "t", "Shipped the thing. Tests pass.", NULL, false, true);+ pro_app_summary("a3", "t", "Shipped the thing. Tests pass.", NULL, false, POD_TIER_ALERT);render();const pod_hit_t *b = banner();CHECK(b);@@ -1871,7 +1990,7 @@ static void notify_tap_opens_and_swipe_dismisses(void) {// A swipe up dismisses; the entry stays unread and nothing opens.notif_room();now = 7000;- pro_app_summary("a3", "t", "Again.", NULL, false, true);+ pro_app_summary("a3", "t", "Again.", NULL, false, POD_TIER_ALERT);render();b = banner();CHECK(b);@@ -1884,7 +2003,7 @@ static void notify_tap_opens_and_swipe_dismisses(void) {CHECK(up.fx == POD_FX_NONE && banner() == NULL && U.model.unread_count == 1 && top() == POD_V_AGENT);// A drag down or sideways on the toast is neither a tap nor a dismissal.now = 8000;- pro_app_summary("a2", "t", "Third.", NULL, false, true);+ pro_app_summary("a2", "t", "Third.", NULL, false, POD_TIER_ALERT);render();b = banner();cx = b->x + b->w / 2; cy = b->y + b->h / 2;@@ -1899,7 +2018,7 @@ static void notify_never_over_talk(void) {expect(tap(POD_A_TALK, 0), POD_FX_VOICE_BEGIN, "a1");CHECK(pod_ui_talking(&U));now = 6000;- pro_app_summary("a3", "t", "Done while talking.", NULL, false, true);+ pro_app_summary("a3", "t", "Done while talking.", NULL, false, POD_TIER_ALERT);render();CHECK(banner() == NULL && U.model.unread_count == 1); // in the Inbox; no toast over a recordingnow = 7000; render();@@ -1911,7 +2030,7 @@ static void notify_never_over_talk(void) {// No cable: no toast.notif_room();now = 6000;- pro_app_summary("a3", "t", "x", NULL, false, true);+ pro_app_summary("a3", "t", "x", NULL, false, POD_TIER_ALERT);pro_app_link(false, NULL);render();CHECK(banner() == NULL);@@ -2107,18 +2226,18 @@ static void ota_notifications_quiet(void) {const int depth = U.nav.depth;fw_update_ui_begin("0.1.2", "0.1.3");now += 100;- pro_app_summary("a3", "t", "Shipped the thing.", NULL, false, true);+ pro_app_summary("a3", "t", "Shipped the thing.", NULL, false, POD_TIER_ALERT);CHECK(BEEPS == 0 && U.model.unread_count == 1 && !U.ban_on); // in Notices, no beep, no toastrender();CHECK(banner() == NULL && !U.frame.banner);- pro_app_summary("a1", "t", "Another.", NULL, false, true);+ pro_app_summary("a2", "t", "Another.", NULL, false, POD_TIER_ALERT);CHECK(BEEPS == 0 && U.model.unread_count == 2);ota_end();CHECK(U.nav.depth == depth);now += 100; render();CHECK(banner() == NULL); // Notices has them; the toast never came// Back to normal afterwards.- pro_app_summary("a2", "t", "After.", NULL, false, true);+ pro_app_summary("a2", "t", "After.", NULL, false, POD_TIER_ALERT);CHECK(BEEPS == 1 && U.ban_on);}@@ -2252,7 +2371,7 @@ int main(int argc, char **argv) {{"pro_app_test_voice_paths", pro_app_test_voice_paths}, {"pro_app_test_touch_rules", pro_app_test_touch_rules},{"pro_app_test_roster_and_swarms", pro_app_test_roster_and_swarms}, {"side_button", side_button}, {"side_button_console", side_button_console}, {"question_needs_the_link", question_needs_the_link},{"notify_banner_beep_and_expiry", notify_banner_beep_and_expiry}, {"notify_tap_opens_and_swipe_dismisses", notify_tap_opens_and_swipe_dismisses},- {"notify_never_over_talk", notify_never_over_talk}, {"notify_replace_seen_and_read", notify_replace_seen_and_read},+ {"notify_never_over_talk", notify_never_over_talk}, {"notify_tiers", notify_tiers}, {"notify_question_and_error", notify_question_and_error}, {"notify_entries_expire", notify_entries_expire}, {"notify_question_entry_ends_with_question", notify_question_entry_ends_with_question}, {"notify_question_resent_after_relink_is_quiet", notify_question_resent_after_relink_is_quiet}, {"notify_question_same_prompt_new_request_beeps", notify_question_same_prompt_new_request_beeps}, {"notify_replace_seen_and_read", notify_replace_seen_and_read},{"ota_screen_and_touch", ota_screen_and_touch}, {"voice_refused_while_updating", voice_refused_while_updating},{"update_gate", update_gate}, {"ota_failed_returns", ota_failed_returns}, {"ota_keeps_awake", ota_keeps_awake},{"ota_notifications_quiet", ota_notifications_quiet}, {"updated_notice", updated_notice},diff --git a/devices/harness-pro/firmware/test/test_pro_cable.c b/devices/harness-pro/firmware/test/test_pro_cable.cindex 57675e90f..903adb6ac 100644--- a/devices/harness-pro/firmware/test/test_pro_cable.c+++ b/devices/harness-pro/firmware/test/test_pro_cable.c@@ -92,9 +92,9 @@ void pro_app_turn_stats(const char *id, int passed, int failed, int commits, int{ev_t *e = add(EV_STATS, id); e->n1 = passed; e->n2 = failed; e->n3 = commits; e->n4 = tokens_in; e->n5 = tokens_out;}-void pro_app_summary(const char *id, const char *text, const char *recap, const char *full, bool restore, bool notify)+void pro_app_summary(const char *id, const char *text, const char *recap, const char *full, bool restore, pod_tier_t tier){- ev_t *e = add(EV_SUMMARY, id); put(e->a, text); put(e->b, recap); put(e->c, full); e->n1 = restore; e->n2 = notify;+ ev_t *e = add(EV_SUMMARY, id); put(e->a, text); put(e->b, recap); put(e->c, full); e->n1 = restore; e->n2 = tier;}void pro_app_notif_replace(const pro_notif_row_t *rows, int n){@@ -106,7 +106,7 @@ void pro_app_notif_seen(const char *id, const char *token){ev_t *e = add(EV_NSEEN, id); put(e->a, token ? token : "(none)");}-void pro_app_question(const char *id, const char *text) { put(add(EV_QUESTION, id)->a, text); }+void pro_app_question(const char *id, const char *request, const char *text) { (void)request; put(add(EV_QUESTION, id)->a, text); }void pro_app_question_close(const char *id) { add(EV_QCLOSE, id); }void pro_app_focus(const char *id) { add(EV_FOCUS, id); }void pro_app_voice_result(int kind, const char *text) { ev_t *e = add(EV_VOICE, NULL); e->n1 = kind; put(e->a, text); }@@ -800,13 +800,30 @@ static void test_notifications(void)welcome();reset();feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"recap\":\"r\"}");- CHECK(nev == 1 && evs[0].kind == EV_SUMMARY && evs[0].n1 == 0 && evs[0].n2 == 1); // plain: notify+ CHECK(nev == 1 && evs[0].kind == EV_SUMMARY && evs[0].n1 == 0 && evs[0].n2 == POD_TIER_ALERT); // plain, no tier (an old daemon): an alertreset();feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"quiet\":true}");feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"silent\":true}");feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"restore\":true}");feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"quiet\":false,\"silent\":false,\"restore\":false}");- CHECK(nev == 4 && evs[0].n2 == 0 && evs[1].n2 == 0 && evs[2].n2 == 0 && evs[2].n1 == 1 && evs[3].n2 == 1);+ CHECK(nev == 4 && evs[0].n2 == POD_TIER_SILENT && evs[1].n2 == POD_TIER_SILENT && evs[2].n2 == POD_TIER_SILENT && evs[2].n1 == 1 &&+ evs[3].n2 == POD_TIER_ALERT);++ // tier: it wins over the old flags (a new daemon sends quiet with list, silent with silent); an unknown one is no tier.+ reset();+ feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"tier\":\"alert\"}");+ feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"tier\":\"list\",\"quiet\":true}");+ feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"tier\":\"silent\",\"silent\":true}");+ feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"tier\":\"list\",\"restore\":true}");+ feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"tier\":\"loud\",\"quiet\":true}");+ feed("{\"t\":\"summary\",\"agentId\":\"a\",\"text\":\"t\",\"tier\":7}");+ CHECK(nev == 6 && evs[0].n2 == POD_TIER_ALERT && evs[1].n2 == POD_TIER_LIST && evs[2].n2 == POD_TIER_SILENT &&+ evs[3].n2 == POD_TIER_SILENT && evs[3].n1 == 1 && evs[4].n2 == POD_TIER_SILENT && evs[5].n2 == POD_TIER_ALERT);++ // turn.error carries its message to the app (the failed entry's text).+ reset();+ feed("{\"t\":\"turn.error\",\"agentId\":\"a\",\"message\":\"Build broke\"}");+ CHECK(nev == 1 && evs[0].kind == EV_TURN && !strcmp(evs[0].a, "error") && !strcmp(evs[0].b, "Build broke"));// notif.replace: every valid item, in order; duplicates pass through (the model drops them); a bad token is blanked.reset();diff --git a/devices/harness-pro/firmware/test/test_pro_voice_gate.py b/devices/harness-pro/firmware/test/test_pro_voice_gate.pyindex c67f88c23..f95b3f55b 100644--- a/devices/harness-pro/firmware/test/test_pro_voice_gate.py+++ b/devices/harness-pro/firmware/test/test_pro_voice_gate.py@@ -272,7 +272,7 @@ static void booting(void) { // no machines.end yet: the gate does not wait for}static void question_agent_says_why(void) {situation(); to_agent(1);- pro_app_question("a2", "Which one?");+ pro_app_question("a2", "r1", "Which one?");render();CHECK(!hit(POD_A_TALK, 0));press_stale();diff --git a/docs/superpowers/plans/2026-10-19-device-notify-tiers.md b/docs/superpowers/plans/2026-10-19-device-notify-tiers.mdnew file mode 100644index 000000000..83d206e86--- /dev/null+++ b/docs/superpowers/plans/2026-10-19-device-notify-tiers.md@@ -0,0 +1,202 @@+# Device Notification Tiers Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** The round dial and the Pro notify only when it is worth it:+- every finished turn gets a tier (`alert`, `list` or `silent`);+- rules decide the clear cases;+- Jev decides finished turns on agents nobody is looking at;+- both firmwares act on the tier.++**Architecture:**+- **The tier.** A new pure module `cli/src/lib/notifyTier.ts` decides it: synchronous rules, then Jev with a 1 s budget, then a fallback rule. The decision is logged.+- **The wire.** `devices.ts` calls it for every `summary`. `cableSession.summary` sends `tier`, plus `quiet` and `silent` for older firmware.+- **The firmwares.** Each one maps the tier to sound, wake, toast and list entry. Each also applies the device-side rules: the agent is on screen, a 30 s beep coalesce, one entry per agent, a 6 h expiry.++**Tech Stack:** TypeScript (vitest) for the daemon; C firmware for the round dial (ESP32-S3, `devices/harness-device/firmware`) and the Pro (ESP32-P4, `devices/harness-pro/firmware`) with host tests.++**Spec:** `docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md`++## Global Constraints++- **Tiers:**+ - `alert` = beep, wake, toast and entry;+ - `list` = entry only;+ - `silent` = nothing but the pet and card update.+- **Rules:**+ - A question or a failure is `alert`.+ - A sub-agent, replayed, restored or empty turn is `silent`.+ - An agent on screen is `silent` (`alreadyOnScreen()` on the desktop; on the device, its own room or face).+ - Everything else goes to Jev.+- **Fallback** (Jev unavailable, more than 1 s, no key, no credits): `list` if the turn ran 120 s or more, else `silent`.+- **Jev:**+ - `createJevDecide` from `cli/src/lib/jev/jevClient.ts`, model `typesafe/jev-1.13`.+ - One `choice` question named `tier`, with options `alert`, `list` and `silent`.+ - The recap is cut to 600 chars or fewer.+ - `HARNESS_NOTIFY_SMART=0` disables Jev.+- **Log line:** `notify · <agent> · <tier> · <by> · <detail> · <ms>ms`, where `by` is `rule:<name>`, `jev` or `fallback:<reason>`.+- **Wire:**+ - `summary` gains `tier`.+ - `alert` sends neither `quiet` nor `silent`.+ - `list` sends `quiet: true`.+ - `silent` sends `silent: true`.+- **Devices:**+ - at most one beep per 30 s per device;+ - one list entry per agent (the newest);+ - entries expire after 6 h;+ - the round dial's error view auto-dismisses after 8 s.+- **Compatibility:**+ - A summary with no `tier` (an old daemon) behaves as it does today on both firmwares.+ - Old firmware keeps working through `quiet` and `silent`.+- No file under `devices/harness-pro/firmware` except `.md` may contain `harness-device` (Pro tree isolation).+- Commit only when the owner asks.++## Review Focus++1. **A burst of 5 agents finishing within 30 s.** Expected: at most one beep per device, five entries (Jev permitting), and one Jev call each with no queue pile-up. Test in Task 1 (concurrency) and Tasks 3–4 (coalesce).+2. **Jev slow or failing while the person waits for a question.** Questions and failures never wait for Jev (rules come first) and are never later than today. Test in Task 1.+3. **An agent finishes again while its previous `list` entry is unread.** Expected: still one entry for that agent, now the newest; the count does not double. Tests in Tasks 3–4.+4. **A device that was asleep (screen off) receives a `list` tier.** Expected: the screen stays off and nothing beeps; the entry is there on the next wake. Tests in Tasks 3–4.+5. **A device whose clock is unknown or wraps when checking the 6 h expiry.** Expiry uses the device's monotonic ms since boot, measured from receipt, and the uint32 wrap is safe (compare by signed difference). Tests in Tasks 3–4.++---++### Task 1: `notifyTier.ts`, the decision++**Files:**+- Create: `cli/src/lib/notifyTier.ts`, `cli/src/lib/notifyTier.spec.ts`++**Interfaces:**+- Produces:++```ts+export type Tier = 'alert' | 'list' | 'silent'+export interface TierInput {+ agent: string; engine: string; recap: string;+ durationS: number | null; // null: unknown start+ stats: { testsPassed?: number; testsFailed?: number; commits?: number };+ subagent: boolean; onScreen: boolean; failed: boolean;+}+export interface TierDecision { tier: Tier; by: string; detail: string; ms: number }+export function createTierDecider(opts: { jev: JevDecide | null; now?: () => number; log: (line: string) => void; budgetMs?: number /* 1000 */ }):+ (input: TierInput) => Promise<TierDecision>+```++- The decider keeps the 30-minute `recent` counts (alerts and lists) itself.++`failed` is true when the turn's summary reports a failed turn; `turn.error` frames bypass the decider and are alerts on the devices.++- [ ] **Step 1: Write the failing tests in `notifyTier.spec.ts` (vitest)**++```ts+it('failed → alert by rule, Jev never asked') // jev mock not called+it('subagent → silent; onScreen → silent; empty recap → silent')+it('otherwise asks Jev once with recap ≤ 600 chars and recent counts; returns its choice')+it('Jev throws JevUnavailable / exceeds 1000 ms → fallback: durationS ≥ 120 → list, else silent; unknown duration → silent')+it('jev null (HARNESS_NOTIFY_SMART=0) → fallback without calling anything')+it('logs exactly one line per decision: "notify · <agent> · <tier> · <by> · …"')+it('recent counts: 3 alerts within 30 min are passed as alerts_30m=3; older ones drop out')+it('5 concurrent decisions resolve independently within the budget (no serial queue)')+```++- [ ] **Step 2: Run them.** `cd cli && npx vitest run src/lib/notifyTier.spec.ts` should FAIL (the module is missing).+- [ ] **Step 3: Implement it.**+ - The Jev `state` is `{agent, engine, recap, duration_s, work:{tests_passed, tests_failed, commits}, recent:{alerts_30m, lists_30m}}`.+ - The question is `{ tier: { type:'choice', instructions, criteria:{alert, list, silent} } }`, with the spec's criteria copy.+ - Race the call against an `AbortController` timeout of `budgetMs`.+- [ ] **Step 4: Run them.** PASS.++---++### Task 2: Wire the tier into the daemon++**Files:**+- Modify:+ - `cli/src/services/devices.ts`: `startDevices` (line 78) gains `jev` via `DevicesDeps`; the summary dispatch (~285) calls the decider; the `done` branch stashes the turn's duration and stats for the summary that follows.+ - Where `startDevices` is called (`cli/src/harnessd/services.ts`): pass `createJevDecide({ backend: (m,p,b) => core.account.backend(m,p,b) })` the way `defaultRouter` does, or `null` when `process.env.HARNESS_NOTIFY_SMART === '0'`.+ - `cli/src/cable/cableSession.ts` `summary()` (~2826): replace the boolean pair with `tier: Tier`. Send `tier` plus `quiet` (for `list`) or `silent` (for `silent`). Update its callers.+ - `cli/src/cable/cableHost.ts` (~903-948): a `turn.error` stays as is; the devices treat it as `alert`.+ - `devices/harness-pro/docs/cable.md`, and the round dial's cable doc if there is one: document `tier`.+- Test: `cli/src/cable/cableSession.spec.ts` and `cli/src/services/devices.spec.ts` (create it if it does not exist).++**Interfaces:**+- Consumes `createTierDecider` (Task 1).+- Produces the wire `summary` frame: `{ t:'summary', …, tier, quiet?, silent? }`.++- [ ] **Step 1: Write the failing tests.**+ - session: `summary(tier:'list')` sends `tier:'list', quiet:true`; `'silent'` sends `silent:true`; `'alert'` sends neither.+ - devices:+ - a summary for an agent on screen sends `silent` and Jev is not called;+ - a subagent summary sends `silent`;+ - otherwise Jev's tier is sent;+ - the duration comes from the stashed `done`.+- [ ] **Step 2: Run** `npx vitest run src/cable src/services/devices`. Expected: FAIL.+- [ ] **Step 3: Implement it.**+- [ ] **Step 4: Run** `npx vitest run src/cable src/services src/lib/notifyTier.spec.ts` and `npm run typecheck` (or the repo's tsc command). Expected: PASS.++---++### Task 3: The Pro acts on the tier++**Files:**+- Modify:+ - `devices/harness-pro/firmware/main/cable/pro_cable.c:600-605`: parse `tier` (absent means today's behaviour).+ - `main/app/pod_glue.c:763-794` (`pod_ui_notify` takes a tier).+ - `main/app/pro_app.c:147-157,485-487`: beep and wake only for `alert`, coalesced to one beep per 30 s.+ - `main/pod/pod_model.c` and `.h`: one unread entry per agent (replace the older one); expire entries older than 6 h on each model tick, using `received_ms` and a signed difference.+- Test: `test/test_pro_cable.c`, `test/test_pod_model.c`, `test/test_pro_app.py`.++**Interfaces:**+- Consumes the wire `tier` (Task 2).+- Produces `void pod_ui_notify(pod_ui_t *u, const char *agent_id, pod_tier_t tier, …)` with `typedef enum { POD_TIER_ALERT, POD_TIER_LIST, POD_TIER_SILENT } pod_tier_t;`, and `#define POD_BEEP_COALESCE_MS 30000`, `#define POD_UNREAD_TTL_MS (6u * 3600u * 1000u)`.++- [ ] **Step 1: Write the failing tests.**+ - `list`: an entry, no beep, no wake, no toast. `alert`: entry, beep, wake, toast. `silent`: no entry.+ - A missing `tier` keeps today's behaviour, including `quiet` dropping the entry.+ - Two alerts 10 s apart beep once; 31 s apart, twice.+ - The same agent's second entry replaces the first, so the count stays 1.+ - An entry expires at 6 h and survives at 5 h 59 m, with a uint32 wrap case.+ - Asleep plus `list`: the screen stays off.+ - With that agent's room on screen: no beep or wake, and the entry is read at once.+ - A `question` frame is an alert: beep (coalesced), wake, and a toast in another agent's room. Today it is silent.+ - `turn.error` files a failed entry as an alert.+- [ ] **Step 2: Run** `bash test/run.sh`. Expected: FAIL.+- [ ] **Step 3: Implement it.**+- [ ] **Step 4: Run** `bash test/run.sh`, `bash test/golden.sh --check` and `python3 test/test_tree_isolation.py`. Expected: PASS. Re-record golden only if a Notices screen fixture changed, and say which.++---++### Task 4: The round dial acts on the tier++**Files:**+- Modify:+ - `devices/harness-device/firmware/main/cable_client.c:1287-1420`: parse `tier`; no beep unless `alert` (fixing the beep on `quiet` at :1322); beep coalescing of 30 s.+ - `main/ui/habitat/ui_habitat.c`:+ - `ui_notify_task_done` (4189-4205): `list` gets a drawer row with no wake and no celebration;+ - the drawer keeps one row per agent (as today) and expires rows at 6 h;+ - `ui_show_error` auto-dismisses after 8 s and keeps a drawer row.+ - If the agent is on the face: no beep or wake, and the row is read.+- Test: the round dial's test suite (`devices/harness-device/firmware/test/run.sh`; extend `test_audio_notify.py` and the habitat tests it runs).++**Interfaces:**+- Consumes the wire `tier` (Task 2).++- [ ] **Step 1: Write failing tests mirroring Task 3's list**, plus:+ - `quiet:true` with no `tier` no longer beeps (the bug fix);+ - the error view is gone after 8 s while its row stays;+ - a `question` beeps (coalesced) as well as filing its pinned row and waking, as it does today.+- [ ] **Step 2: Run** `bash devices/harness-device/firmware/test/run.sh`. Expected: FAIL.+- [ ] **Step 3: Implement it.**+- [ ] **Step 4: Run it again, plus the round dial's golden/screen checks if `run.sh` has them.** Expected: PASS.++---++### Task 5: Measure on the owner's machine++- [ ] **Step 1: Record the baseline.** Before installing, count one working day from the current logs: device beeps (`audio_cap: beep` per device) and desktop done notifications.+- [ ] **Step 2: Install.** Run the CLI from this branch as the daemon (per the CLI README's dev install), flash a Pro with `scripts/flash.sh`, and flash a round dial with its flash procedure (dev version `0.0.99`).+- [ ] **Step 3: After a working day,** count the `notify ·` lines per tier, the beeps per device, and the share decided by `jev` versus `fallback`.+- [ ] **Step 4: Check the success criteria.**+ - Beeps fall by 60% or more.+ - Every question and failure is `alert`, checked by grepping the log for `rule:question` and `rule:failed`.+ - Report to the owner, with a sample of Jev's `alert`/`list`/`silent` calls so its judgement can be reviewed.diff --git a/docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md b/docs/superpowers/specs/2026-10-19-device-notify-tiers-design.mdnew file mode 100644index 000000000..bdfe6d718--- /dev/null+++ b/docs/superpowers/specs/2026-10-19-device-notify-tiers-design.md@@ -0,0 +1,126 @@+# Device notifications: fewer, and each one worth it++Date: 2026-10-19. Status: the direction was approved in brainstorming (a hybrid of rules and Jev). This spec is waiting for review.++## Problem++The owner says notifications on the round dial and on the Pro are "too many". What was measured on one machine:++**One finished turn on an agent you are not watching triggers all of this:**+- Desktop: banner, sound and system notification.+- Round: beep, screen wake, celebration pose, drawer row and bell count.+- Pro: beep, wake, toast and Inbox entry.++**Volume:**+- About 2/3 of the live round-dial summaries (101/150) were for the agent the person was looking at on the desktop. The round dial still beeps for these, even when the daemon marks them `quiet` (`cable_client.c:1322`).+- There is no time-based limit. The busiest day logged 51 beeps, 10 of them in one hour. The desktop logged 29 "done" notifications today, 11 of them in one hour.++**What the person cares about:**+- Every finished turn is treated as equal news: a 5-second fix and a 40-minute build that passed 640 tests get the same treatment.+- The person mostly wants to know two things: that an agent needs them (a question or a failure), and that substantial work is done.++## Goal++A device notifies only when it is worth it, under one policy decided once in the daemon for both devices:+- An **alert** interrupts: sound, wake and toast.+- A **list** entry waits quietly in Notices or the drawer.+- Everything else changes only the pet's state.++## Decision: rules first, Jev for the grey zone++Every live `summary`, question and failure gets one **tier**:++| Event | Decided by | Tier |+|---|---|---|+| The agent asks a question | rule | `alert` |+| The turn failed (`turn.error`, or a summary of a failed turn) | rule | `alert` |+| A sub-agent's turn, a replayed or restored turn, or an empty result | rule | `silent` (as today) |+| The agent is on screen (`alreadyOnScreen()` on the desktop, or open on the device itself) | rule | `silent` |+| **A finished turn on an agent not on screen** | **Jev** | `alert` / `list` / `silent` |+| Jev unavailable, more than 1 s late, or no key/credits | fallback rule | `list` if the turn ran 120 s or more, else `silent` |++### The Jev question++Jev is `typesafe/jev-1.13` through `cli/src/lib/jev/jevClient.ts` `createJevDecide`, Harness-paid through the backend, the same way the ⌘B router uses it.++- **State sent:**++ ```json+ { "agent": "<name>", "engine": "codex",+ "recap": "<the turn's recap, ≤ 600 chars>",+ "duration_s": 312,+ "work": { "tests_passed": 640, "tests_failed": 0, "commits": 1 }, // the turn stats the daemon already reads (cable/turnStats.ts)+ "recent": { "alerts_30m": 2, "lists_30m": 5 } }+ ```++- **One choice question,** `tier`, with these criteria (the exact copy lives in code next to the question):+ - `alert`: a substantial result the person would want to know about now, such as a long task finished, a build or deploy done, or a requested deliverable ready. It is less likely when `alerts_30m` is already high.+ - `list`: real progress worth a glance later, such as a small feature or a fix with edits.+ - `silent`: chatter, such as an acknowledgement, a short answer, a no-op, or a step inside a longer job.+- **Logging.** The daemon logs each decision as `notify · <agent> · <tier> · jev p=<probabilities> · <ms>`, or `· rule <name>` / `· fallback <reason>`, so any call can be checked afterwards.+- **Privacy.** Only the recap excerpt (≤ 600 chars) and the counts leave the machine, never the transcript. The environment variable `HARNESS_NOTIFY_SMART=0` turns Jev off, so the fallback rule decides (the daemon has no settings store for this).++## Wire++- `summary` gains `tier: "alert" | "list" | "silent"`.+- `quiet` and `silent` are still sent, so firmware that predates `tier` degrades sensibly:+ - `alert` sets neither;+ - `list` sets `quiet`;+ - `silent` sets `silent`.+- `question` and `turn.error` stay as they are; both devices treat them as `alert`.++## Devices (both the round dial and the Pro)++| Tier | Sound | Wake screen | Toast or banner | Notices / drawer |+|---|---|---|---|---|+| `alert` | one beep (at most one per 30 s per device: a burst of finishes beeps once) | yes | yes (Pro: unless that agent's room is shown) | entry |+| `list` | none | no | no | entry |+| `silent` | none | no | no | none (the pet and the card still update) |++**Device-side rules:**+- If the agent's own room (Pro) or face (round dial) is on screen, any tier is shown in place: no sound, no wake, and the entry is read at once.+- The list keeps **one entry per agent**, the newest. Entries **expire after 6 hours**. The Pro's limit of 16 and the round's 24 still cap the list.+- **Round dial fixes:**+ - honour `quiet` and `list` (no beep; `cable_client.c:1322`);+ - skip the celebration pose for `list`;+ - auto-dismiss the `turn.error` full-screen message after 8 s, keeping its row in the drawer.+- **Pro fix:** a `list` entry goes into Notices with no beep, no wake and no toast. Today `quiet` drops the entry entirely (`pro_cable.c:600-605`).++## Out of scope++- The desktop's own banners and sounds. They keep today's behaviour; making them use the tier is a follow-up.+- Device "Do Not Disturb" hours.+- A device settings screen.+- Per-agent mute.++## Success criteria++- **Measured volume:** over a normal working day on the owner's machine, device beeps fall by 60% or more compared with the same day pattern before the change. The daemon counts tiers per day in its log.+- **Nothing important is missed:** every question and every failure is an `alert`; tests pin both rules.+- **Fallback:** with Jev unavailable, tiers come from the fallback rule and nothing errors.+- **Old firmware:** it keeps working with a new daemon, through `quiet` and `silent`. New firmware keeps working with an old daemon, which sends no `tier` and is treated as today.++## Code map++**Daemon:**+- `cli/src/lib/agentNotifications.ts`: the tier decision. Rules stay synchronous; Jev runs with a 1 s budget.+- `cli/src/lib/commander.ts:773-781`.+- `cli/src/services/devices.ts:265-291` (`alreadyOnScreen`).+- `cli/src/cable/cableSession.ts` `summary` (the `tier` field).+- `cli/src/lib/jev/jevClient.ts` (reused).++**Round dial:**+- `devices/harness-device/firmware/main/cable_client.c:1287-1420`.+- `main/ui/habitat/ui_habitat.c` (`ui_notify_task_done`, the drawer and its expiry, the error view).++**Pro:**+- `devices/harness-pro/firmware/main/cable/pro_cable.c:600-605`.+- `main/app/pod_glue.c:763-794`.+- `main/app/pro_app.c` (beep and wake).+- `main/pod/pod_model.c` (one entry per agent, expiry).++## Risks++- **Jev judges wrong.** The rules guarantee questions and failures, so the only failure mode is a finished turn landing in the wrong tier. The decision log makes that visible, and the criteria copy can be tuned without firmware.+- **Latency.** The summary is held for up to 1 s waiting for Jev. A summary is not time-critical; the pet's state still changes at once.+- **Cost.** About 30 decisions a day at about $0.0002 each is negligible. It is paid by Harness, as the owner chose for the router (2026-10-11).