Skip to content

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.

fix(device): the dial's pill and the window's badge count the same things

0xdiego25477a7e2b27ec
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 8f28dd5df..0af203014 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -381,6 +381,17 @@ export class DaemonCableHost implements CableHost {
this.swarms = swarms
}
+ /** What the window still has unread, newest first. Empty until a window says otherwise. */
+ private unread: Array<{ agentId: string; machineId: string; question: boolean; text: string }> = []
+
+ setUnread(items: Array<{ agentId: string; machineId: string; question: boolean; text: string }>): void {
+ this.unread = items
+ }
+
+ listUnread(): Array<{ agentId: string; machineId: string; question: boolean; text: string }> {
+ return this.unread
+ }
+
listSwarms(): { selected: string; swarms: CableSwarm[] } {
const app = this.swarms
if (!app) return { selected: '', swarms: [] }
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index e45506afd..ddec36807 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -83,6 +83,7 @@ function makeHost(over: Partial<CableHost> = {}) {
selectedMachine: () => 'mac-local',
selectMachine: async () => ({ ok: true as const }),
listSwarms: () => ({ selected: '', swarms: [] }),
+ listUnread: () => [],
selectSwarm: vi.fn(),
appName: () => 'harness',
voiceLang: () => 'en',
@@ -136,7 +137,11 @@ describe('cable session', () => {
// Machines FIRST: the dial paints its machine name from this list, so an agent list that lands
// ahead of it shows a nameless placeholder for a frame. Swarms next, for the same reason: the line
// naming the tab is drawn on the tile the agent list is about to build.
- ['welcome', 'machines.begin', 'machine', 'machines.end', 'swarms', 'agents.begin', 'agent', 'agent', 'agents.end'],
+ //
+ // `notif.replace` LAST, and that order is the point too: it names agents, and a drawer row for one
+ // the carousel does not hold yet has nothing to draw itself against. A dial that has just greeted
+ // us is the one moment its drawer is known to be empty — its rows live in RAM.
+ ['welcome', 'machines.begin', 'machine', 'machines.end', 'swarms', 'agents.begin', 'agent', 'agent', 'agents.end', 'notif.replace'],
)
const welcome = port.sent[0]
expect(welcome).toMatchObject({ t: 'welcome', app: 'harness', machine: { name: 'MacBook Pro' } })
@@ -189,7 +194,11 @@ describe('cable session', () => {
// Machines FIRST: the dial paints its machine name from this list, so an agent list that lands
// ahead of it shows a nameless placeholder for a frame. Swarms next, for the same reason: the line
// naming the tab is drawn on the tile the agent list is about to build.
- ['welcome', 'machines.begin', 'machine', 'machines.end', 'swarms', 'agents.begin', 'agent', 'agent', 'agents.end'],
+ //
+ // `notif.replace` LAST, and that order is the point too: it names agents, and a drawer row for one
+ // the carousel does not hold yet has nothing to draw itself against. A dial that has just greeted
+ // us is the one moment its drawer is known to be empty — its rows live in RAM.
+ ['welcome', 'machines.begin', 'machine', 'machines.end', 'swarms', 'agents.begin', 'agent', 'agent', 'agents.end', 'notif.replace'],
)
await session.stop()
})
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index faeec60c3..165b325ed 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -282,6 +282,8 @@ export interface CableHost {
listModels(agentId: string): Promise<string[]>
/** One agent's last turn summaries, newest first — what a reattached dial needs to redraw its tiles. */
recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string }>>
+ /** What the window still has unread, newest first — replayed to a dial that has just attached. */
+ listUnread(): Array<{ agentId: string; machineId: string; question: boolean; text: string }>
/**
* The image to offer a dial running `runningVersion`, or null for "nothing to do" — which covers a
* dial that is current, a dev build that must not be touched, and an unreachable manifest.
@@ -1261,6 +1263,9 @@ export class CableSession {
this.restoring = false
}
await this.pushRestores()
+ // …and the drawer, which is the one thing a dial that has just greeted us is KNOWN to have lost:
+ // its rows live in RAM. Last, because it names agents the pushes above put on the carousel.
+ await this.replaceNotifications(this.host.listUnread())
}
// ── swarms ────────────────────────────────────────────────────────────────────────────────────────
@@ -1407,9 +1412,63 @@ export class CableSession {
private whoIs(agentId: string): { name: string; engine: string; machine: string } {
return this.host.describe(agentId) ?? { name: '', engine: '', machine: '' }
}
+ /**
+ * Replace the dial's whole drawer with what the window still has unread.
+ *
+ * Sent once per attach, because that is the one moment the dial is known to have nothing: its rows
+ * live in RAM and an OTA, a replug or a flash takes them. Measured on a flash: a turn ended at
+ * 17:46:19, the dial came back at 17:46:26, a question arrived at 17:46:28 — and the pill read 1
+ * against the window's 2 from then on, with nothing to bring them back together.
+ *
+ * The window sends ids and kinds; the name, machine and recap are filled in HERE, from what this
+ * daemon already knows, so those never have a second source that can disagree.
+ */
+ async replaceNotifications(
+ items: Array<{ agentId: string; machineId: string; question: boolean; text: string }>,
+ ): Promise<void> {
+ const rows = await Promise.all(items.slice(0, 8).map(async (item) => {
+ const who = this.whoIs(item.agentId)
+ // A QUESTION BRINGS ITS OWN WORDS; a finished turn takes the recap this daemon summarised. The
+ // dial cannot supply either after a reboot, and a row with neither renders as the word its type
+ // used to assume — "done", on a question nobody has answered.
+ let summary = item.text
+ if (!item.question && !summary) {
+ try { summary = (await this.host.recentSummaries(item.agentId))[0]?.recap ?? '' } catch { summary = '' }
+ }
+ return { agentId: item.agentId, name: who.name, machine: who.machine, summary, question: item.question }
+ }))
+ await this.send({ t: 'notif.replace', items: rows })
+ }
+
+ /**
+ * A harness the window has now looked at — drop its drawer row on the dial.
+ *
+ * The dial's own gesture is a tap, which already reaches the window as
+ * `agent.open`. This is the other direction, and without it the two counts
+ * separate the moment somebody switches to the tab a notification was about.
+ *
+ * Fire and forget, like every other card: a dial that predates the message
+ * counts it as unknown and drops it, which is the behaviour it has today.
+ */
+ async agentSeen(agentId: string): Promise<void> {
+ if (!agentId) return
+ await this.send({ t: 'notif.seen', agentId })
+ }
async turnError(agentId: string, message: string): Promise<void> {
await this.send({ t: 'turn.error', agentId, message })
}
+ /**
+ * An agent stopped to ask.
+ *
+ * NO `quiet` HERE, and the reason is that a question is a job rather than news. A summary's `quiet`
+ * asks "is somebody looking at this right now" and that is the whole of what a finished turn needed.
+ * A question outlives the glance: it is answered or it is not, and until it is answered it is still
+ * owed (owner, 2026-09-24).
+ *
+ * Asking it anyway was self-defeating besides. Showing a question asks the window to bring that agent
+ * forward, so by the time anyone could answer "is it on screen" the answer was yes — every question
+ * came through quiet, no row was ever recorded, and looking away later left nothing behind.
+ */
async question(agentId: string, id: string, questions: unknown): Promise<void> {
await this.send({ t: 'question', agentId, ...this.whoIs(agentId), id, questions })
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index e051fb827..95ce70943 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1900,6 +1900,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// and skipping the recap here would leave them permanently blank.
/** Agents with a tile open in the desktop window right now. Empty when no window is attached. */
let openPaneAgents = new Set<string>()
+ /** Whether the window those tiles belong to is actually in front. See onAppPanes. */
+ let appWindowForeground = true
+ /**
+ * Is this agent already in front of somebody at this desk?
+ *
+ * Both halves are needed and neither alone is enough: a tile on the tab says WHERE it is, the window
+ * being in front says whether anyone can see it. The dial used to be told the first half only, so it
+ * stayed quiet about a turn that finished while the window sat behind a browser — which is the one
+ * case a notification exists for — and the window, which checks both (`_visibleOnTab`), spoke up.
+ * Two screens, two answers, from one tab.
+ */
+ const alreadyOnScreen = (agentId: string): boolean =>
+ appWindowForeground && openPaneAgents.has(agentId)
const cableWatchingLocal = (): boolean => cableRef?.isConnected === true
const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || backend.autonomousDeviceConnected()
@@ -2528,6 +2541,25 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return summarizeTurnText(text, signal, userMessage, session?.engine ?? 'claude', gateway, previousRecap)
},
}
+ /**
+ * A turn that belongs to a SUB-AGENT: an Orchestrator specialist, or its Director while specialists
+ * are still out.
+ *
+ * Hoisted out of the commander's options because the dial is no longer the only screen that has to
+ * know. The cable learns it as `silent` on the summary card; the window learns it as `subagent` on
+ * `turn_ended` (see emitSessionEvents). One rule, asked twice — the two surfaces used to disagree
+ * here, and a four-specialist project put ONE row on the dial and FIVE marks in the window.
+ *
+ * ⚠️ The commander ORs this with its own `abandoned` state — a held turn released because a
+ * sub-agent went silent — which lives inside it and is not reachable from here. That case is rare
+ * (a killed or crashed sub-agent) and costs the window one extra mark, not five.
+ */
+ const isSubagentSession = (sessionId: string): boolean => {
+ const agentId = registry.bySession(sessionId)?.agentId
+ if (!agentId) return false
+ const role = backend.orchestratorRoleOf(agentId)
+ return role?.role === 'worker' || (role?.role === 'director' && role.busy)
+ }
const mirror = new CommanderMirror({
send: (frame) => backend.sendCommander(frame),
sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicator
@@ -2540,12 +2572,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,
// An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not
// announced: the person asked to hear from the main agent once, not from every sub-agent.
- isSubagent: (sessionId) => {
- const agentId = registry.bySession(sessionId)?.agentId
- if (!agentId) return false
- const role = backend.orchestratorRoleOf(agentId)
- return role?.role === 'worker' || (role?.role === 'director' && role.busy)
- },
+ isSubagent: isSubagentSession,
// A claude sub-agent still at work is one whose transcript is still growing:
// `<session>/subagents/agent-<id>.jsonl` beside the parent's (the same file enrichSubagentStats
// reads). Written in the last SUBAGENT_IDLE_MS = alive; the held turn end waits for it.
@@ -2687,6 +2714,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// skips these; every other consumer ignores an unknown field. Measured before this existed: one
// agent credited with 42 turns in a single second, all re-reads.
if (event.type === 'turn_started' && (opts?.resumed || opts?.replay)) frame.replay = true
+ // WHOSE turn ended, in the clear beside `agentId`, for the same reason `replay` is: the payload
+ // is E2EE and the window has to read this without opening it.
+ //
+ // The dial has always been told (`silent` on the summary card) and the window never was, so the
+ // two screens counted different things: an Orchestrator project of four specialists put ONE row
+ // on the dial and FIVE marks in the window. Same predicate for both now — see isSubagentSession.
+ // An older client ignores an unknown field, which is the behaviour it has today.
+ if (event.type === 'turn_ended' && isSubagentSession(sessionId)) frame.subagent = true
backend.send(frame)
if (event.type === 'turn_started') {
turnStartedAt.set(sessionId, Date.now())
@@ -3856,6 +3891,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
autonomousDeviceService?.appFocus(machineId, agentId, connId)
},
onAppFocus: (machineId, agentId) => { void cableRef?.followApp(machineId, agentId) },
+ // Everything the window still has unread. Held rather than acted on: the dial is handed it when a
+ // cable attaches, which is the one moment its own drawer is known to be empty.
+ onAppUnread: (items) => { cableHostRef?.setUnread(items); void cableRef?.replaceNotifications(items) },
+ // The window looked at a harness, so the dial's drawer row for it is stale.
+ // The dial's own tap already reaches the window (`agent.open`); this is the
+ // return leg, and the pair is what keeps the badge and the pill equal.
+ onAgentSeen: (agentId) => { void cableRef?.agentSeen(agentId) },
// Agents the window has a tile for. A finished turn on one of these is
// already in front of the person, so the dial updates its tile in silence
// rather than beeping about something being looked at.
@@ -3871,7 +3913,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
void cableRef?.syncSwarms()
void cableRef?.syncAgents()
},
- onAppPanes: (agentIds) => {
+ onAppPanes: (agentIds, foreground) => {
// ORDER matters here, not just membership. The dial's carousel is built
// around these — tiles first, in tile order — so the thumb walks the same
// grid the eyes are on. `openPaneAgents` below only ever asks "is this
@@ -3885,6 +3927,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const deskChanged = agentIds.length !== appPaneAgents.length
|| agentIds.some((id, at) => id !== appPaneAgents[at])
appPaneAgents = agentIds
+ // A tile behind a browser is not a tile anybody is looking at. The roster
+ // does not change when the window loses focus, so without this the dial
+ // went quiet about work nobody could see — the one case the notification
+ // is for — while the window, which does check, spoke up. `openPaneAgents`
+ // below is what `quiet` is read from, so emptying it is how both screens
+ // come to the same answer.
+ appWindowForeground = foreground
cableHostRef?.setDesk(agentIds)
const next = new Set(agentIds)
// Logged on CHANGE only. It fires on every pane add, close and reconnect,
@@ -5822,7 +5871,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// 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.
- void cable.summary(event.agentId, event.recap || event.text, event.text, openPaneAgents.has(event.agentId), event.subagent)
+ void cable.summary(event.agentId, event.recap || event.text, event.text, alreadyOnScreen(event.agentId), event.subagent)
}
else void cable.turnError(event.agentId, event.text)
}
@@ -5849,7 +5898,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// turn was a sub-agent's (decided on its own machine). The tile still
// updates — the recap is what it draws — only the beep and the drawer
// entry are withheld.
- void cable.summary(event.agentId, event.recap || event.text, event.text, openPaneAgents.has(event.agentId), event.subagent === true)
+ void cable.summary(event.agentId, event.recap || event.text, event.text, alreadyOnScreen(event.agentId), event.subagent === true)
}
else void cable.turnError(event.agentId, event.text)
})
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 5d7db8ea4..a660f434e 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -191,6 +191,40 @@ describe('local CLI WebSocket', () => {
await vi.waitFor(() => expect(rosters).toEqual([['a1', 'a2'], []]))
})
+ it('says whether the window those tiles belong to is actually in front', async () => {
+ // The roster alone cannot answer it: every pane keeps its place on the tab
+ // while the window sits behind a browser. Without this the dial stayed quiet
+ // about work nobody could see, which is the one case it exists for.
+ const backend = new FakeBackend()
+ const seen: Array<{ ids: string[]; foreground: boolean }> = []
+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
+ local = attachLocalWsServer(server, {
+ machineId,
+ backend,
+ onAppPanes: (ids, foreground) => seen.push({ ids, foreground }),
+ })
+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
+ const url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`
+
+ const ws = new WebSocket(url)
+ await onceOpen(ws)
+ const connected = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))
+ await connected
+
+ ws.send(JSON.stringify({ type: 'app_panes', payload: { agentIds: ['a1'], foreground: true } }))
+ ws.send(JSON.stringify({ type: 'app_panes', payload: { agentIds: ['a1'], foreground: false } }))
+ // A window that predates the field only ever sent this list while it was up,
+ // so absence reads as in front — the behaviour it has today.
+ ws.send(JSON.stringify({ type: 'app_panes', payload: { agentIds: ['a1'] } }))
+ await vi.waitFor(() => expect(seen).toHaveLength(3))
+ expect(seen.map((row) => row.foreground)).toEqual([true, false, true])
+
+ ws.close()
+ // No window at all is not a window in front.
+ await vi.waitFor(() => expect(seen[3]).toEqual({ ids: [], foreground: false }))
+ })
+
it('takes the window\'s swarms, drops what is not a swarm, and forgets them on close', async () => {
const backend = new FakeBackend()
const seen: unknown[] = []
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 9913cde1f..617e2034e 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -58,7 +58,11 @@ export interface LocalWsServerOptions {
onDevicePrepareOpened?: (operationId: string, agentId: string) => void
onAppFocus?: (machineId: string, agentId: string) => void
/** Every agent the window currently has a tile for, across all its machines. */
- onAppPanes?: (agentIds: string[]) => void
+ onAppPanes?: (agentIds: string[], foreground: boolean) => void
+ /** The window has looked at this harness — see the `agent_seen` case below. */
+ onAgentSeen?: (agentId: string) => void
+ /** Everything the window still has unread, newest first — see the `app_unread` case below. */
+ onAppUnread?: (items: Array<{ agentId: string; machineId: string; question: boolean; text: string }>) => void
/**
* The window's swarms — its named groups of agents, one of them on screen. The whole list each time,
* and `null` when the window goes away, so the daemon never keeps describing tabs nobody can see.
@@ -377,10 +381,56 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
// whether a finished turn is already in front of the person.
if (!isBinary && options.onAppPanes) {
if (parsed?.type === 'app_panes') {
- const raw = (parsed.payload as Record<string, unknown> | undefined)?.agentIds
+ const payload = parsed.payload as Record<string, unknown> | undefined
+ const raw = payload?.agentIds
const ids = Array.isArray(raw) ? raw.filter((id): id is string => typeof id === 'string' && id !== '') : []
+ // Absent from a window that predates the field. TRUE then, which is
+ // what every such window meant: it only ever sent this list while it
+ // was up, and reading absence as "behind something" would start
+ // announcing work that is in plain sight.
+ const foreground = payload?.foreground !== false
sentPanes = true
- options.onAppPanes(ids)
+ options.onAppPanes(ids, foreground)
+ return
+ }
+ }
+ // THE WINDOW LOOKED AT A HARNESS. Consumed here like `app_focus` and the
+ // roster above — it describes a pair of eyes at this desk, not anything
+ // the machine could act on, so it never goes on the wire.
+ //
+ // The dial takes a notification away when a row is TAPPED; the window
+ // takes it away when the tab holding that harness comes to the front.
+ // Two gestures, and each has to reach the other screen or the badge and
+ // the pill part company the first time either is used. This is the half
+ // the window owns; the dial's half already travels as `agent.open`.
+ if (!isBinary && options.onAgentSeen) {
+ if (parsed?.type === 'agent_seen') {
+ const agentId = (parsed.payload as Record<string, unknown> | undefined)?.agentId
+ if (typeof agentId === 'string' && agentId) options.onAgentSeen(agentId)
+ return
+ }
+ }
+ // EVERYTHING THE WINDOW STILL HAS UNREAD. Consumed here like the roster and the focus — it
+ // describes a screen at this desk, never anything a machine could act on.
+ //
+ // The dial keeps its drawer in RAM and loses it to any reboot, while this window does not.
+ // Held here so a cable attaching later can be handed the list without a round trip to a window
+ // that may be busy.
+ if (!isBinary && options.onAppUnread) {
+ if (parsed?.type === 'app_unread') {
+ const raw = (parsed.payload as Record<string, unknown> | undefined)?.items
+ const items = Array.isArray(raw)
+ ? raw.flatMap((row) => {
+ const item = row as Record<string, unknown> | null
+ const agentId = item?.agentId
+ const machineId = item?.machineId
+ const text = typeof item?.text === 'string' ? item.text : ''
+ return typeof agentId === 'string' && agentId && typeof machineId === 'string'
+ ? [{ agentId, machineId, question: item?.question === true, text }]
+ : []
+ })
+ : []
+ options.onAppUnread(items)
return
}
}
@@ -517,7 +567,7 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
// A window that went away has no tiles open. Left standing, the roster
// would keep silencing the dial for agents nobody can see any more —
// exactly backwards, and permanently.
- if (sentPanes) options.onAppPanes?.([])
+ if (sentPanes) options.onAppPanes?.([], false)
if (sentSwarms) options.onAppSwarms?.(null)
if (relay) { relay.detach(); relay = null }
else if (selected) void options.backend.unregisterLocalClient(connId)
diff --git a/desktop/lib/notify/agent_alerts.dart b/desktop/lib/notify/agent_alerts.dart
index 14676cc12..542ace6b1 100644
--- a/desktop/lib/notify/agent_alerts.dart
+++ b/desktop/lib/notify/agent_alerts.dart
@@ -151,6 +151,14 @@ class AgentAlerts extends ChangeNotifier {
/// until somebody goes looking. Somebody who turned the noisy halves off still
/// wants the window to be able to say which agent moved while they were away.
class AgentUnread extends ChangeNotifier {
+ /// As many agents as the dial's drawer holds rows (`NOTIF_MAX`), and dropped
+ /// the same way: oldest first.
+ ///
+ /// A window with no ceiling and a dial with one are two different numbers the
+ /// moment a ninth agent has news, whatever else agrees. Dart's map keeps
+ /// insertion order, and [mark] re-inserts, so the first key is the oldest.
+ static const capacity = 8;
+
final _unread = <String, AlertKind>{};
static String keyFor(String machineId, String agentId) =>
@@ -163,6 +171,22 @@ class AgentUnread extends ChangeNotifier {
bool get isEmpty => _unread.isEmpty;
+ /// Every mark, NEWEST FIRST — the order the dial's drawer keeps.
+ ///
+ /// The key is `machineId/agentId`; [keyFor] made it and this is the one place
+ /// that has to take it apart, so the split lives here rather than at the call
+ /// site. A machine id never contains a slash (it is hex or a uuid).
+ List<({String machineId, String agentId, AlertKind kind})> get newestFirst =>
+ [
+ for (final key in _unread.keys.toList().reversed)
+ if (key.indexOf('/') > 0)
+ (
+ machineId: key.substring(0, key.indexOf('/')),
+ agentId: key.substring(key.indexOf('/') + 1),
+ kind: _unread[key]!,
+ ),
+ ];
+
/// What this agent's mark says, or null when it has none.
AlertKind? kindFor(String machineId, String agentId) =>
_unread[keyFor(machineId, agentId)];
@@ -173,7 +197,16 @@ class AgentUnread extends ChangeNotifier {
void mark(String machineId, String agentId, AlertKind kind) {
final key = keyFor(machineId, agentId);
if (_unread[key] == kind) return;
- _unread[key] = kind;
+ // Re-inserted, not updated in place: an agent that moved is the newest
+ // again, which is what makes the first key the oldest for the eviction
+ // below. `notif_push` on the dial does exactly this — it lifts an existing
+ // row out before putting it back on top.
+ _unread
+ ..remove(key)
+ ..[key] = kind;
+ while (_unread.length > capacity) {
+ _unread.remove(_unread.keys.first);
+ }
notifyListeners();
}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 2c5582267..e70ba7a0e 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -266,7 +266,20 @@ class _SwarmScreenState extends State<SwarmScreen>
app.agentUnread.addListener(_unreadChanged);
// Coming back to the window puts the tab in front of the person again, and
// nothing in the app necessarily changes when that happens — so it is told.
- _lifecycle = AppLifecycleListener(onResume: app.seeWatchedAgents);
+ //
+ // The daemon is told too, on the way out as well as the way back: it decides
+ // from `app_panes` whether a finished turn is already on screen, and that
+ // roster does not change when the window slips behind a browser. Without
+ // the second half the dial went quiet the first time this window lost focus
+ // and stayed quiet until a pane happened to change.
+ _lifecycle = AppLifecycleListener(
+ onResume: () {
+ app.seeWatchedAgents();
+ app.announceWindowForeground();
+ },
+ onHide: app.announceWindowForeground,
+ onInactive: app.announceWindowForeground,
+ );
app.addListener(_syncToolbarNotices);
_toolbarNotices.addListener(_toolbarNoticesChanged);
_onboarding.addListener(_onboardingChanged);
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index ffed4a391..87afdb6ef 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1701,6 +1701,12 @@ class AppNotifier extends ChangeNotifier {
// closing a tab, a restored layout, a reveal. Listening here catches all of
// them, and a clear that finds nothing to clear notifies nobody.
addListener(seeWatchedAgents);
+ // The dial is told the whole list whenever it changes, so a cable attaching
+ // later is handed it without asking. See [_announceUnreadToDial].
+ //
+ // `this.` because the constructor's own parameter of the same name is in
+ // scope here and is the nullable one.
+ this.agentUnread.addListener(_announceUnreadToDial);
}
/// Through the local CLI in a desktop build; straight to the backend, signed, in a viewer.
@@ -2079,6 +2085,7 @@ class AppNotifier extends ChangeNotifier {
// the dial goes back to beeping about tiles in plain sight until the
// next time a pane happens to change.
_announceOpenPanesToDial();
+ _announceUnreadToDial();
// ...nor which tile this window is looking at. The daemon repeats that to the dial after every
// list push, which is what keeps the two screens from drifting apart — but it can only repeat
// something it has been told, and until now the first telling waited for the focus to CHANGE.
@@ -2169,6 +2176,54 @@ class AppNotifier extends ChangeNotifier {
/// The dial belongs to whichever daemon owns the cable, and only a complete
/// roster lets that one judge; the others store a list they never use, which
/// costs nothing and saves the window from having to know which is which.
+ /// THE WHOLE UNREAD LIST, for a dial that has just lost its own.
+ ///
+ /// The dial keeps its drawer in RAM, so a reboot — an OTA, a replug, a flash —
+ /// wipes it while this window still holds every mark. Measured: a turn ended
+ /// at 17:46:19, the dial came back at 17:46:26, a question arrived at
+ /// 17:46:28, and the two screens then read 2 and 1 forever.
+ ///
+ /// Sent on every change rather than asked for: the daemon holds the latest and
+ /// can hand it over the moment a cable attaches, without a round trip to a
+ /// window that may be busy. Ids and kinds only — the daemon already knows each
+ /// agent's name, machine and last recap, and re-deriving them here would be a
+ /// second place for them to be wrong.
+ void _announceUnreadToDial() {
+ final pool = _pool;
+ if (pool == null) return;
+ final items = [
+ for (final mark in agentUnread.newestFirst)
+ {
+ 'agentId': mark.agentId,
+ 'machineId': mark.machineId,
+ 'question': mark.kind == AlertKind.needsYou,
+ // A QUESTION'S OWN WORDS, because nobody else has them. The daemon
+ // fills in the recap for a finished turn from what it summarised, but
+ // an open question lives here — in `blockedAgents` — and a dial that
+ // rebooted has no memory of having asked it. Without this its drawer
+ // row arrives blank and falls back to the word the row type used to
+ // assume: "done", on a question nobody has answered.
+ if (mark.kind == AlertKind.needsYou)
+ 'text':
+ machineStates[mark.machineId]
+ ?.blockedAgents[mark.agentId]
+ ?.prompt ??
+ '',
+ },
+ ];
+ for (final machineId in pool.machineIds) {
+ pool[machineId]
+ ?.sendTerminalFrame('app_unread', {'items': items})
+ .catchError((_) => false)
+ .ignore();
+ }
+ }
+
+ /// Re-send the tile roster because the WINDOW moved, not because the tiles
+ /// did. Public so the lifecycle listener can say so; the roster itself is
+ /// unchanged and the `foreground` flag riding with it is the point.
+ void announceWindowForeground() => _announceOpenPanesToDial();
+
void _announceOpenPanesToDial() {
final pool = _pool;
if (pool == null) return;
@@ -2220,7 +2275,23 @@ class AppNotifier extends ChangeNotifier {
if (connection == null) continue;
unawaited(
connection
- .sendTerminalFrame('app_panes', {'agentIds': agentIds})
+ .sendTerminalFrame('app_panes', {
+ 'agentIds': agentIds,
+ // WHETHER THESE TILES ARE ACTUALLY IN FRONT OF ANYBODY.
+ //
+ // The daemon decides from this list whether a finished turn is
+ // already on screen, and the list alone cannot say: every pane
+ // keeps its place on the tab while this window sits behind a
+ // browser. The dial therefore stayed quiet about work nobody
+ // could see, which is the one case the notification exists for —
+ // and this window, which DOES check (see `_visibleOnTab`), spoke
+ // up. Two screens, two answers, from the same tab.
+ //
+ // Sent with the roster rather than on its own so the pair can
+ // never be read half-updated. An older daemon ignores it and
+ // behaves as it does today.
+ 'foreground': lifecycle() == AppLifecycleState.resumed,
+ })
.catchError((_) => false),
);
unawaited(
@@ -6277,7 +6348,56 @@ class AppNotifier extends ChangeNotifier {
/// routes, which are many and would each have to remember.
void seeWatchedAgents() {
for (final w in watchedAgents()) {
- agentUnread.clear(w.machineId, w.agentId);
+ // A QUESTION IS NOT CLEARED BY BEING LOOKED AT. Everything else here is
+ // news — an agent finished, and seeing it is the whole of what was owed.
+ // A blocked agent is a job: it is still waiting on a person however many
+ // times its tab came to the front, and a badge that stopped counting it
+ // would be saying the work was done because somebody glanced at it. It
+ // goes when the question is ANSWERED (`commander_question_close`).
+ if (agentUnread.kindFor(w.machineId, w.agentId) != AlertKind.done) {
+ continue;
+ }
+ _forgetUnread(w.machineId, w.agentId);
+ }
+ }
+
+ /// Drop this harness's mark and tell the daemon, so the dial drops its drawer
+ /// row for it too. Silent when there was no mark.
+ void _forgetUnread(String machineId, String agentId) {
+ if (agentUnread.kindFor(machineId, agentId) == null) return;
+ agentUnread.clear(machineId, agentId);
+ _announceAgentSeen(machineId, agentId);
+ }
+
+ /// Tell the daemon this harness has been looked at, so the dial drops its
+ /// drawer row for it.
+ ///
+ /// The two screens take a notification away on different gestures — a tap on
+ /// the dial, a tab coming to the front here — and each has to reach the other
+ /// or the two numbers part company the first time either is used. The dial's
+ /// half already travels: a tap sends `agent.open`, which brings the harness
+ /// forward here, and the sweep above clears it as anything else would.
+ ///
+ /// Guarded by the caller on "there was a mark", so an ordinary tab switch
+ /// does not put a frame on every socket.
+ void _announceAgentSeen(String machineId, String agentId) {
+ // No transport at all — a window still booting, or a plain `test()` with no
+ // live pool. `_conn` asserts one exists rather than answering null, which
+ // is right for the paths that cannot proceed without it and wrong for a
+ // diagnostic aside like this one.
+ if (_pool == null && connectionForTest == null) return;
+ // Through `_conn`, the resolver everything else on this socket uses — it
+ // refuses a shared harness, which this window has no business reporting on
+ // anyway, by throwing rather than by returning null.
+ try {
+ unawaited(
+ _conn(machineId)
+ .sendTerminalFrame('agent_seen', {'agentId': agentId})
+ .catchError((_) => false),
+ );
+ } on StateError {
+ // A view-only harness. Nothing to tell the dial about something this
+ // window does not drive.
}
}
@@ -6304,7 +6424,17 @@ class AppNotifier extends ChangeNotifier {
// Nothing at all for the agent on screen in front of you. A sound, a banner
// and a count are three ways of saying "look over here", and all three are
// noise about the pane you are already in.
- if (_isBeingWatched(machine.machine.machineId, agentId)) return;
+ //
+ // A QUESTION IS THE EXCEPTION, and it is the same exception the sweep makes
+ // (see [seeWatchedAgents]): it is a job rather than news, so it is owed
+ // until it is ANSWERED and being looked at is not an answer. Skipping it
+ // here would also have been self-defeating — a question asks the window to
+ // bring its agent forward, so "already on screen" was true by construction
+ // and the mark was never raised at all (owner, 2026-09-24).
+ if (kind != AlertKind.needsYou &&
+ _isBeingWatched(machine.machine.machineId, agentId)) {
+ return;
+ }
final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
// Before the banner and outside its switch: the mark is what the window can
// still say when somebody has turned the interrupting halves off.
@@ -6351,8 +6481,14 @@ class AppNotifier extends ChangeNotifier {
/// The person has gone to this agent — by clicking its row, its banner, or
/// anything else that puts it in front of them. Whatever it was carrying has
/// been seen.
- void markAgentSeen(String machineId, String agentId) =>
- agentUnread.clear(machineId, agentId);
+ /// This harness has been gone to — from a banner, from the dial, from a row.
+ ///
+ /// Same rule as the sweep: arriving at a blocked harness is not answering it,
+ /// so its mark stays. See [seeWatchedAgents].
+ void markAgentSeen(String machineId, String agentId) {
+ if (agentUnread.kindFor(machineId, agentId) != AlertKind.done) return;
+ _forgetUnread(machineId, agentId);
+ }
/// Whatever tile is now in front of the person has been seen.
///
@@ -10891,13 +11027,46 @@ class AppNotifier extends ChangeNotifier {
final requestId = payload['requestId'];
if (agentId != null) {
final open = machine.blockedAgents[agentId];
- // Only if it is the one being closed: a stale close must not wipe the
- // question that replaced it when a dialog advanced to its next page.
- if (open != null &&
- (requestId is! String ||
- requestId.isEmpty ||
- open.requestId == requestId)) {
+ // A stale close must not wipe the question that REPLACED it when a
+ // dialog advanced to its next page. That is the only thing the id
+ // guards, so it is asked as its own question and nothing else hangs
+ // off it.
+ final supersededByANewerQuestion =
+ open != null &&
+ requestId is String &&
+ requestId.isNotEmpty &&
+ open.requestId != requestId;
+ if (!supersededByANewerQuestion) {
machine.blockedAgents.remove(agentId);
+ // A question stops being unread when it is ANSWERED, wherever that
+ // happened — here, in the pane by hand, on the dial, in another
+ // window. Being looked at is not enough: the badge counts what is
+ // still waiting on a person.
+ //
+ // ⚠️ NOT nested inside "the dialog is still open". It was, and the
+ // mark then outlived its own question: answering makes the turn end
+ // too, `_cancelTurnActivity` clears `blockedAgents` on the way past,
+ // and whichever of the two frames lands first decides whether this
+ // runs at all. The close is the authoritative word that the question
+ // is answered; the dialog bookkeeping is a separate thing that may
+ // already have been tidied.
+ //
+ // WHATEVER THE MARK IS, not only a question's.
+ //
+ // Answering ENDS THE TURN for these engines — measured, one
+ // millisecond apart and the turn first:
+ //
+ // 18:04:58.534 [turn] 395050e8 ended · 65175ms
+ // 18:04:58.535 [question] 395050e8 answered elsewhere · closing
+ //
+ // so the `done` that lands with every answer overwrote the question
+ // mark and the badge never went down. Reading it as news is wrong on
+ // its face: a turn that ended in the same breath as your own answer
+ // is not something that happened while you were away.
+ //
+ // A close means somebody just dealt with this agent. Anything unread
+ // for it at that moment is about the work they were standing over.
+ _forgetUnread(machine.machine.machineId, agentId);
}
}
break;
@@ -10932,7 +11101,14 @@ class AppNotifier extends ChangeNotifier {
case 'turn_ended':
final agentId = _eventAgentId(machine, event, payload);
if (agentId != null) {
- _raiseAlert(machine, agentId, AlertKind.done);
+ // A SUB-AGENT'S turn end is not news — an Orchestrator specialist, or
+ // its Director while specialists are still out. The dial has always
+ // known (`silent` on its summary card) and this window never did, so a
+ // project of four specialists put one row on the dial and five marks
+ // here. Same predicate now, asked on the daemon: `isSubagentSession`.
+ if (event['subagent'] != true) {
+ _raiseAlert(machine, agentId, AlertKind.done);
+ }
_cancelTurnActivity(machine.machine.machineId, agentId);
} else {
final sessionId = _eventSessionId(event, payload);
diff --git a/desktop/lib/ws/ws_pool.dart b/desktop/lib/ws/ws_pool.dart
index f1ee6b991..6798266a3 100644
--- a/desktop/lib/ws/ws_pool.dart
+++ b/desktop/lib/ws/ws_pool.dart
@@ -101,6 +101,10 @@ class WsPool {
}
WsConn? operator [](String machineId) => _conns[machineId];
+
+ /// The machines this pool holds a socket for. A snapshot, so a caller can send
+ /// on each without a concurrent connect mutating what it is walking.
+ List<String> get machineIds => _conns.keys.toList(growable: false);
bool has(String machineId) => _conns.containsKey(machineId);
Future<void> closeMachine(String machineId) async {
diff --git a/desktop/test/agent_unread_test.dart b/desktop/test/agent_unread_test.dart
index 8c1a87cce..6a72a7cf1 100644
--- a/desktop/test/agent_unread_test.dart
+++ b/desktop/test/agent_unread_test.dart
@@ -73,4 +73,41 @@ void main() {
unread.mark('m1', 'a1', AlertKind.done);
expect(rebuilds, 1);
});
+
+ // ── Parity with the dial ───────────────────────────────────────────────────
+ // The badge here and the pill there count the same finished turns, so this
+ // store holds as many agents as the dial's drawer holds rows, and lets go of
+ // them the same way.
+
+ group('as many as the dial holds', () {
+ test('at most as many agents as the dial has rows', () {
+ for (var i = 0; i < AgentUnread.capacity + 3; i++) {
+ unread.mark('m1', 'a$i', AlertKind.done);
+ }
+
+ expect(unread.count, AgentUnread.capacity);
+ expect(unread.kindFor('m1', 'a0'), isNull, reason: 'the oldest went');
+ expect(unread.kindFor('m1', 'a2'), isNull);
+ expect(unread.kindFor('m1', 'a3'), isNotNull, reason: 'the rest stayed');
+ });
+
+ test('a mark touched again is the newest, and outlives an older one', () {
+ // `notif_push` lifts an existing row out and puts it back on top; without
+ // that here, an agent that keeps working would be evicted before agents
+ // that have said nothing for an hour.
+ for (var i = 0; i < AgentUnread.capacity; i++) {
+ unread.mark('m1', 'a$i', AlertKind.done);
+ }
+ unread.mark('m1', 'a0', AlertKind.needsYou); // the oldest speaks again
+ unread.mark('m1', 'fresh', AlertKind.done); // …and one more arrives
+
+ expect(
+ unread.kindFor('m1', 'a0'),
+ AlertKind.needsYou,
+ reason: 'it was touched, so it is no longer the oldest',
+ );
+ expect(unread.kindFor('m1', 'a1'), isNull, reason: 'a1 was');
+ expect(unread.count, AgentUnread.capacity);
+ });
+ });
}
diff --git a/desktop/test/notification_parity_test.dart b/desktop/test/notification_parity_test.dart
new file mode 100644
index 000000000..37daf4143
--- /dev/null
+++ b/desktop/test/notification_parity_test.dart
@@ -0,0 +1,258 @@
+// THE BADGE HERE AND THE PILL ON THE DIAL SHOW THE SAME NUMBER.
+//
+// Not a style rule — the two used to disagree in three separate places, and a
+// person looking at both saw "2" on the dial and "6" in the window with no way
+// to tell which was lying. Each group below pins one of the three.
+//
+// The daemon is the decider for all three: it already told the cable, and now
+// it tells this window on the same events, so neither side re-derives a rule
+// the other one owns (`isSubagentSession`, `alreadyOnScreen`, `deviceIsWatching`
+// in cli/src/cli.ts).
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/notify/alert_sounds.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+/// Records the frames this window puts on a machine's socket.
+class _Conn extends WsConn {
+ _Conn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final sent = <({String type, Map<String, dynamic> payload})>[];
+
+ @override
+ Future<bool> sendTerminalFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ sent.add((type: type, payload: payload));
+ return true;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late AppNotifier app;
+
+ setUp(() {
+ app = createApp()
+ // Nothing is on screen: `_visibleOnTab` reads the real lifecycle, and a
+ // test with no window would otherwise have every agent count as watched.
+ ..watchedAgents = () => const [];
+ });
+ tearDown(() => app.dispose());
+
+ Future<void> turnEnded(String agentId, {bool? subagent}) =>
+ app.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'agentId': agentId,
+ if (subagent != null) 'subagent': subagent,
+ 'payload': <String, dynamic>{},
+ });
+
+ Future<void> question(String agentId) => app.handleEventForTest('m', {
+ 'type': 'commander_question',
+ 'agentId': agentId,
+ 'payload': <String, dynamic>{
+ 'requestId': 'req-$agentId',
+ 'questions': [
+ {
+ 'key': 'k',
+ 'q': 'Which one?',
+ 'options': ['a', 'b'],
+ },
+ ],
+ },
+ });
+
+ Future<void> answered(String agentId) => app.handleEventForTest('m', {
+ 'type': 'commander_question_close',
+ 'agentId': agentId,
+ 'payload': <String, dynamic>{'requestId': 'req-$agentId'},
+ });
+
+ group('a sub-agent is not news on either screen', () {
+ test('an ordinary turn end is counted', () async {
+ await turnEnded('a1');
+ expect(app.agentUnread.count, 1);
+ });
+
+ test('a sub-agent turn end is not', () async {
+ await turnEnded('a1', subagent: true);
+ expect(app.agentUnread.count, 0);
+ expect(app.agentUnread.kindFor('m', 'a1'), isNull);
+ });
+
+ test('an Orchestrator project rings once, not once per specialist', () async {
+ // Four specialists and a Director that is still busy: the dial draws ONE
+ // row, for the wrap-up. This used to be five marks here.
+ for (final worker in ['w1', 'w2', 'w3', 'w4']) {
+ await turnEnded(worker, subagent: true);
+ }
+ await turnEnded('director', subagent: true); // still busy
+ expect(app.agentUnread.count, 0);
+
+ await turnEnded('director'); // the wrap-up
+ expect(app.agentUnread.count, 1);
+ });
+
+ test('a daemon that does not say is a daemon that did not know', () async {
+ // Absent field, not false: every build before this one sent nothing, and
+ // reading absence as "sub-agent" would swallow every turn they report.
+ await turnEnded('a1');
+ expect(app.agentUnread.count, 1);
+ });
+ });
+
+ group('a question is counted until it is answered', () {
+ test('it counts, device or no device', () async {
+ // A blocked agent is waiting on a person whatever else is on the desk.
+ await question('a1');
+ expect(app.agentUnread.count, 1);
+ expect(app.agentUnread.kindFor('m', 'a1'), AlertKind.needsYou);
+ });
+
+ test('being looked at is not being answered', () async {
+ // The mark for a finished turn goes when its tab comes to the front —
+ // there is nothing left to do. A question is not like that: it is still
+ // waiting however many times somebody glanced at it.
+ await question('a1');
+ app.watchedAgents = () => [(machineId: 'm', agentId: 'a1')];
+ app.seeWatchedAgents();
+
+ expect(app.agentUnread.count, 1, reason: 'still waiting on a person');
+ });
+
+ test('it counts even while its own agent is on screen', () async {
+ // Showing a question asks the window to bring that agent forward, so "already
+ // on screen" is true by construction — a skip here meant the mark was never
+ // raised at all, and looking away later left nothing behind.
+ app.watchedAgents = () => [(machineId: 'm', agentId: 'a1')];
+ await question('a1');
+
+ expect(app.agentUnread.count, 1);
+ expect(app.agentUnread.kindFor('m', 'a1'), AlertKind.needsYou);
+ });
+
+ test('a finished turn on screen is still silent', () async {
+ // The exception is the QUESTION, not the rule: news about a pane you are
+ // looking at is still noise about the pane you are looking at.
+ app.watchedAgents = () => [(machineId: 'm', agentId: 'a1')];
+ await turnEnded('a1');
+
+ expect(app.agentUnread.count, 0);
+ });
+
+ test('answering it takes the mark away', () async {
+ await question('a1');
+ await answered('a1');
+
+ expect(app.agentUnread.count, 0);
+ expect(app.agentUnread.kindFor('m', 'a1'), isNull);
+ });
+
+ test('answering clears it even when the turn ended first', () async {
+ // Answering makes the turn end too, and the two frames race. `turn_ended`
+ // runs `_cancelTurnActivity`, which clears `blockedAgents` on the way
+ // past — so a close that arrives second finds no open dialog. The mark is
+ // the close's to take either way; hanging it off the dialog bookkeeping
+ // left it stranded whenever that order came up.
+ await question('a1');
+ expect(app.agentUnread.count, 1);
+
+ await turnEnded('a1'); // the turn closes first…
+ await answered('a1'); // …and the close lands after
+
+ expect(app.agentUnread.count, 0, reason: 'answered is answered');
+ });
+
+ test('answering clears it when the close arrives first', () async {
+ await question('a1');
+ await answered('a1');
+ expect(app.agentUnread.count, 0);
+ });
+
+ test('a stale close does not wipe the question that replaced it', () async {
+ // A dialog advancing to its next page closes one request and opens the
+ // next; the close for the old one must not take the new one with it.
+ await question('a1');
+ await app.handleEventForTest('m', {
+ 'type': 'commander_question_close',
+ 'agentId': 'a1',
+ 'payload': <String, dynamic>{'requestId': 'some-older-request'},
+ });
+
+ expect(app.agentUnread.count, 1);
+ });
+
+ test('the turn that ends WITH the answer is not news', () async {
+ // Measured on the real thing: answering ends the turn, and the two frames
+ // land a millisecond apart with the turn first. So `done` overwrites the
+ // question mark and the badge never goes down — while the person is
+ // standing right over that agent, having just answered it.
+ await question('a1');
+ await turnEnded('a1');
+ expect(app.agentUnread.kindFor('m', 'a1'), AlertKind.done);
+
+ await answered('a1');
+ expect(app.agentUnread.count, 0);
+ });
+ });
+
+ // The `foreground` flag on the roster is asserted where it is READ, in
+ // cli/src/localWsServer.spec.ts: true, false and absent all have to mean
+ // something, and the roster itself goes out through the pool rather than
+ // through `_conn`, which a fake connection cannot stand in for.
+ group('what this window tells the daemon', () {
+ late _Conn conn;
+ late AppNotifier wired;
+
+ setUp(() {
+ conn = _Conn();
+ wired = createApp(connectionForTest: (_) => conn)
+ ..watchedAgents = () => const [];
+ });
+ tearDown(() => wired.dispose());
+
+ test(
+ 'looking at a marked harness is announced, so the dial drops its row',
+ () async {
+ await wired.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'agentId': 'a1',
+ 'payload': <String, dynamic>{},
+ });
+ expect(wired.agentUnread.count, 1);
+
+ wired.markAgentSeen('m', 'a1');
+ await Future<void>.delayed(Duration.zero);
+
+ expect(wired.agentUnread.count, 0);
+ expect(
+ conn.sent.where((f) => f.type == 'agent_seen').map((f) => f.payload),
+ [
+ {'agentId': 'a1'},
+ ],
+ );
+ },
+ );
+
+ test('a harness with nothing unread is not announced', () async {
+ // An ordinary tab switch must not put a frame on every socket.
+ wired.markAgentSeen('m', 'a1');
+ await Future<void>.delayed(Duration.zero);
+
+ expect(conn.sent.where((f) => f.type == 'agent_seen'), isEmpty);
+ });
+ });
+}
diff --git a/desktop/test/pending_question_test.dart b/desktop/test/pending_question_test.dart
index 625613a2c..65ad0be91 100644
--- a/desktop/test/pending_question_test.dart
+++ b/desktop/test/pending_question_test.dart
@@ -50,7 +50,10 @@ class _Silent extends WsConn {
);
@override
- Future<bool> sendTerminalFrame(String type, Map<String, dynamic> payload) async => true;
+ Future<bool> sendTerminalFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async => true;
@override
Future<Map<String, dynamic>> request(
@@ -280,11 +283,7 @@ void main() {
final notifier = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
- alerts: AlertSounds(
- store: store(),
- channel: channel,
- now: () => clock,
- ),
+ alerts: AlertSounds(store: store(), channel: channel, now: () => clock),
// Injected, and switched on. Left to the default this would read the app's own global
// store — the real file-backed one — so the banner assertions would pass or fail on a
// preference belonging to whoever ran the suite, and silently stop testing anything the
@@ -306,21 +305,24 @@ void main() {
expect(played, [AlertKind.needsYou.sound]);
});
- test('the daemon re-announcing the SAME question is not heard again', () async {
- // Every reconnect re-sends every open question, and attaching to a turn that is already
- // mid-dialog does too. A window that beeped at those would sound an alarm whenever the
- // network hiccuped — for a question the person has been looking at for ten minutes.
- final app = wired();
- addTearDown(app.dispose);
- await app.handleMachineEventForTest('m1', asked());
- // Well past the rate limiter, so silence here is the guard's doing and nothing else.
- clock = clock.add(const Duration(minutes: 5));
- await app.handleMachineEventForTest('m1', asked());
- clock = clock.add(const Duration(minutes: 5));
- await app.handleMachineEventForTest('m1', asked());
- await Future<void>.delayed(Duration.zero);
- expect(played, [AlertKind.needsYou.sound]);
- });
+ test(
+ 'the daemon re-announcing the SAME question is not heard again',
+ () async {
+ // Every reconnect re-sends every open question, and attaching to a turn that is already
+ // mid-dialog does too. A window that beeped at those would sound an alarm whenever the
+ // network hiccuped — for a question the person has been looking at for ten minutes.
+ final app = wired();
+ addTearDown(app.dispose);
+ await app.handleMachineEventForTest('m1', asked());
+ // Well past the rate limiter, so silence here is the guard's doing and nothing else.
+ clock = clock.add(const Duration(minutes: 5));
+ await app.handleMachineEventForTest('m1', asked());
+ clock = clock.add(const Duration(minutes: 5));
+ await app.handleMachineEventForTest('m1', asked());
+ await Future<void>.delayed(Duration.zero);
+ expect(played, [AlertKind.needsYou.sound]);
+ },
+ );
test('a DIFFERENT question from the same agent is heard', () async {
final app = wired();
@@ -348,34 +350,40 @@ void main() {
expect(played, [AlertKind.done.sound]);
});
- test('a finished turn also raises a banner, named after the agent', () async {
- final app = wired();
- addTearDown(app.dispose);
- app.machineStates['m1']!.agents = [
- const Agent(id: 'a1', name: 'Respond to greeting', engine: 'codex'),
- ];
- await app.handleMachineEventForTest('m1', {
- 'type': 'turn_ended',
- 'agentId': 'a1',
- 'payload': {'agentId': 'a1'},
- });
- final raised = app.agentAlerts.alerts;
- expect(raised, hasLength(1));
- // The agent's own NAME. A banner naming a uuid tells nobody which pane to look at.
- expect(raised.single.title, 'Respond to greeting');
- expect(raised.single.kind, AlertKind.done);
- expect(raised.single.agentId, 'a1');
- });
+ test(
+ 'a finished turn also raises a banner, named after the agent',
+ () async {
+ final app = wired();
+ addTearDown(app.dispose);
+ app.machineStates['m1']!.agents = [
+ const Agent(id: 'a1', name: 'Respond to greeting', engine: 'codex'),
+ ];
+ await app.handleMachineEventForTest('m1', {
+ 'type': 'turn_ended',
+ 'agentId': 'a1',
+ 'payload': {'agentId': 'a1'},
+ });
+ final raised = app.agentAlerts.alerts;
+ expect(raised, hasLength(1));
+ // The agent's own NAME. A banner naming a uuid tells nobody which pane to look at.
+ expect(raised.single.title, 'Respond to greeting');
+ expect(raised.single.kind, AlertKind.done);
+ expect(raised.single.agentId, 'a1');
+ },
+ );
- test('a question raises a banner too, and a re-announced one does not', () async {
- final app = wired();
- addTearDown(app.dispose);
- await app.handleMachineEventForTest('m1', asked());
- clock = clock.add(const Duration(minutes: 5));
- await app.handleMachineEventForTest('m1', asked());
- expect(app.agentAlerts.alerts, hasLength(1));
- expect(app.agentAlerts.alerts.single.kind, AlertKind.needsYou);
- });
+ test(
+ 'a question raises a banner too, and a re-announced one does not',
+ () async {
+ final app = wired();
+ addTearDown(app.dispose);
+ await app.handleMachineEventForTest('m1', asked());
+ clock = clock.add(const Duration(minutes: 5));
+ await app.handleMachineEventForTest('m1', asked());
+ expect(app.agentAlerts.alerts, hasLength(1));
+ expect(app.agentAlerts.alerts.single.kind, AlertKind.needsYou);
+ },
+ );
test('both moments mark the harness unread, whatever the switches say', () async {
// The mark is not an interruption — it sits still until somebody goes looking — so it is
@@ -385,9 +393,7 @@ void main() {
config: AppConfig.dev,
authSession: AuthSession(),
alerts: AlertSounds(store: store(on: false), channel: channel),
- agentAlerts: AgentAlerts(
- store: ScreenAlertStore(storage: _Memory()),
- ),
+ agentAlerts: AgentAlerts(store: ScreenAlertStore(storage: _Memory())),
);
addTearDown(app.dispose);
app.machines = [_machine];
@@ -404,8 +410,17 @@ void main() {
await app.handleMachineEventForTest('m1', asked());
expect(app.agentUnread.kindFor('m1', 'a1'), AlertKind.needsYou);
- // And going to it is what makes it read.
+ // Going to a BLOCKED harness is not answering it, so the mark stays: the
+ // badge counts what is still waiting on a person (owner, 2026-09-24).
app.markAgentSeen('m1', 'a1');
+ expect(app.agentUnread.count, 1);
+
+ // Answering is what makes it read, wherever that happened.
+ await app.handleMachineEventForTest('m1', {
+ 'type': 'commander_question_close',
+ 'agentId': 'a1',
+ 'payload': {'requestId': asked()['payload']['requestId']},
+ });
expect(app.agentUnread.count, 0);
});
@@ -473,14 +488,15 @@ void main() {
.setMockMethodCallHandler(channel, null);
});
- TerminalSession session(String machineId, String agentId) => TerminalSession(
- machineId: machineId,
- agentId: agentId,
- agentName: agentId,
- engineId: 'codex',
- send: (_, _) async => true,
- sendBinary: (_) async => true,
- );
+ TerminalSession session(String machineId, String agentId) =>
+ TerminalSession(
+ machineId: machineId,
+ agentId: agentId,
+ agentName: agentId,
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ );
/// The scenario, built with REAL tabs: A, B, C on tab X; D, E on tab Y; tab X in front.
///
@@ -520,12 +536,15 @@ void main() {
return (app: app, x: x, y: y);
}
- Future<void> finish(AppNotifier a, String agentId, {String machineId = 'm1'}) =>
- a.handleMachineEventForTest(machineId, {
- 'type': 'turn_ended',
- 'agentId': agentId,
- 'payload': {'agentId': agentId},
- });
+ Future<void> finish(
+ AppNotifier a,
+ String agentId, {
+ String machineId = 'm1',
+ }) => a.handleMachineEventForTest(machineId, {
+ 'type': 'turn_ended',
+ 'agentId': agentId,
+ 'payload': {'agentId': agentId},
+ });
test('harnesses on the tab in front of you finish silently; one on another tab does not', () async {
final t = fiveHarnesses();
@@ -550,35 +569,52 @@ void main() {
expect(played, [AlertKind.done.sound]);
});
- test('a question on the visible tab is silent too; one on another tab is not', () async {
+ test('a question counts wherever it is — the visible tab included', () async {
+ // The opposite of a finished turn, and deliberately. News about a pane in
+ // front of you is noise; a question is a JOB, owed until it is answered,
+ // and being looked at is not an answer (owner, 2026-09-24).
+ //
+ // Skipping it here was also self-defeating: a question asks the window to
+ // bring its agent forward, so "already on screen" was true by the time
+ // anyone could ask — the mark was never raised at all, and looking away
+ // afterwards left nothing behind.
final t = fiveHarnesses();
addTearDown(t.app.dispose);
await t.app.handleMachineEventForTest('m1', asked(agentId: 'C'));
- expect(t.app.agentUnread.count, 0);
+ expect(t.app.agentUnread.kindFor('m1', 'C'), AlertKind.needsYou);
await t.app.handleMachineEventForTest(
'm1',
asked(agentId: 'E', requestId: 'q_e'),
);
expect(t.app.agentUnread.kindFor('m1', 'E'), AlertKind.needsYou);
- });
-
- test('switching to the tab clears the marks of every harness on it', () async {
- final t = fiveHarnesses();
- addTearDown(t.app.dispose);
- await finish(t.app, 'D');
- await t.app.handleMachineEventForTest(
- 'm1',
- asked(agentId: 'E', requestId: 'q_e'),
- );
expect(t.app.agentUnread.count, 2);
-
- // Tab Y comes to the front. D and E are on screen now, so neither mark is true any more —
- // with no pane clicked, no row, no banner.
- t.app.selectSwarm(t.y, attachPending: false);
- expect(t.app.agentUnread.count, 0);
});
+ test(
+ 'switching to the tab clears what FINISHED on it, not what is waiting',
+ () async {
+ final t = fiveHarnesses();
+ addTearDown(t.app.dispose);
+ await finish(t.app, 'D');
+ await t.app.handleMachineEventForTest(
+ 'm1',
+ asked(agentId: 'E', requestId: 'q_e'),
+ );
+ expect(t.app.agentUnread.count, 2);
+
+ // Tab Y comes to the front. D and E are both on screen now — with no pane clicked, no row,
+ // no banner — and that is the whole of what D was owed: it finished, and it has been seen.
+ //
+ // E has not. A question is a job, not news: it is still waiting on a person however many
+ // times its tab came to the front, and it goes when it is ANSWERED (owner, 2026-09-24).
+ t.app.selectSwarm(t.y, attachPending: false);
+ expect(t.app.agentUnread.count, 1);
+ expect(t.app.agentUnread.kindFor('m1', 'D'), isNull);
+ expect(t.app.agentUnread.kindFor('m1', 'E'), AlertKind.needsYou);
+ },
+ );
+
test('switching away does not clear the tab being left', () async {
final t = fiveHarnesses();
addTearDown(t.app.dispose);
@@ -600,21 +636,35 @@ void main() {
expect(t.app.agentUnread.kindFor('m1', 'A'), AlertKind.done);
});
- test('coming back to the window clears the marks on the tab in front of you', () async {
- var state = AppLifecycleState.inactive;
- final t = fiveHarnesses();
- addTearDown(t.app.dispose);
- t.app.lifecycle = () => state;
- await finish(t.app, 'A'); // on the front tab, but nobody is looking at the window
- await finish(t.app, 'D'); // on the other tab
- expect(t.app.agentUnread.count, 2);
-
- // The screen's lifecycle listener calls this on resume.
- state = AppLifecycleState.resumed;
- t.app.seeWatchedAgents();
- expect(t.app.agentUnread.kindFor('m1', 'A'), isNull, reason: 'A is on screen again');
- expect(t.app.agentUnread.kindFor('m1', 'D'), AlertKind.done, reason: 'D still is not');
- });
+ test(
+ 'coming back to the window clears the marks on the tab in front of you',
+ () async {
+ var state = AppLifecycleState.inactive;
+ final t = fiveHarnesses();
+ addTearDown(t.app.dispose);
+ t.app.lifecycle = () => state;
+ await finish(
+ t.app,
+ 'A',
+ ); // on the front tab, but nobody is looking at the window
+ await finish(t.app, 'D'); // on the other tab
+ expect(t.app.agentUnread.count, 2);
+
+ // The screen's lifecycle listener calls this on resume.
+ state = AppLifecycleState.resumed;
+ t.app.seeWatchedAgents();
+ expect(
+ t.app.agentUnread.kindFor('m1', 'A'),
+ isNull,
+ reason: 'A is on screen again',
+ );
+ expect(
+ t.app.agentUnread.kindFor('m1', 'D'),
+ AlertKind.done,
+ reason: 'D still is not',
+ );
+ },
+ );
test('the same agent id on another machine is not on this tab', () async {
// Visibility is the machine AND the agent. Matching on the id alone would silence a harness
@@ -636,10 +686,11 @@ void main() {
test('the visible set is the whole front tab, not the focused pane', () {
final t = fiveHarnesses();
addTearDown(t.app.dispose);
- expect(
- t.app.visibleOnTabForTest().map((w) => w.agentId).toSet(),
- {'A', 'B', 'C'},
- );
+ expect(t.app.visibleOnTabForTest().map((w) => w.agentId).toSet(), {
+ 'A',
+ 'B',
+ 'C',
+ });
});
});
}
diff --git a/devices/harness-device/firmware/main/cable_client.c b/devices/harness-device/firmware/main/cable_client.c
index 94676f2e1..c659a94e5 100644
--- a/devices/harness-device/firmware/main/cable_client.c
+++ b/devices/harness-device/firmware/main/cable_client.c
@@ -718,6 +718,34 @@ static void handle_message(const cJSON *root)
}
return;
}
+ // The WINDOW looked at this agent — its drawer row here is stale. The tap's half of this pair
+ // already goes the other way (cable_client_send_open); without the return leg the pill and the
+ // window's badge stop agreeing the first time somebody switches to the tab a card was about.
+ // The window's whole unread list, replayed because this dial has just attached and its drawer is
+ // empty — see ui_notif_replace.
+ if (strcmp(t, "notif.replace") == 0) {
+ static cable_notif_t rows[8]; // static: too much for the reader task's stack
+ int n = 0;
+ const cJSON *it = NULL;
+ cJSON_ArrayForEach(it, cJSON_GetObjectItemCaseSensitive(p, "items")) {
+ if (n >= (int)(sizeof(rows) / sizeof(rows[0]))) break;
+ const char *aid = str_of(it, "agentId");
+ if (!aid || !aid[0]) continue;
+ memset(&rows[n], 0, sizeof(rows[n]));
+ snprintf(rows[n].agent_id, sizeof(rows[n].agent_id), "%s", aid);
+ snprintf(rows[n].name, sizeof(rows[n].name), "%s", str_of(it, "name") ? str_of(it, "name") : "");
+ snprintf(rows[n].machine, sizeof(rows[n].machine), "%s", str_of(it, "machine") ? str_of(it, "machine") : "");
+ snprintf(rows[n].summary, sizeof(rows[n].summary), "%s", str_of(it, "summary") ? str_of(it, "summary") : "");
+ rows[n].question = bool_of(it, "question");
+ n++;
+ }
+ ui_notif_replace(rows, n);
+ return;
+ }
+ if (strcmp(t, "notif.seen") == 0) {
+ if (agent_id) ui_notif_seen(agent_id);
+ return;
+ }
if (strcmp(t, "turn.error") == 0) {
if (agent_id) ui_project_emit(agent_id, "", "done", "", NULL);
ui_cable_toast(str_of(p, "message"));
diff --git a/devices/harness-device/firmware/main/cable_client.h b/devices/harness-device/firmware/main/cable_client.h
index 17391d6c4..afb9c4997 100644
--- a/devices/harness-device/firmware/main/cable_client.h
+++ b/devices/harness-device/firmware/main/cable_client.h
@@ -161,6 +161,16 @@ typedef struct {
int panes;
} cable_swarm_t;
+// One row of the window's unread list, as `notif.replace` carries it. `summary` is the last recap for
+// a finished turn and empty for a question — the dial kept that question's own text from when it asked.
+typedef struct {
+ char agent_id[ID_MAX];
+ char name[NAME_MAX];
+ char machine[NAME_MAX];
+ char summary[100];
+ bool question;
+} cable_notif_t;
+
// The user tapped a swarm. Not answered — see above.
void cable_client_select_swarm(const char *swarm_id);
// Re-ask for the list (a screen that just opened wants it fresh).
diff --git a/devices/harness-device/firmware/main/ui/ui_screens.c b/devices/harness-device/firmware/main/ui/ui_screens.c
index 5bcf17950..7db93c774 100644
--- a/devices/harness-device/firmware/main/ui/ui_screens.c
+++ b/devices/harness-device/firmware/main/ui/ui_screens.c
@@ -208,7 +208,11 @@ static uint32_t s_voice_route_ms; // lv_tick when the upload finished (routing
#define NOTIF_DEBUG_SEED 0 // set 1 to seed fake notifications at boot for testing the drawer redesign
// `machine` is the DISPLAY name (kept even if the machine is renamed later); `machine_id` is what a tap needs
// to switch back to the machine the notification came from.
-typedef struct { char proj_id[48]; char name[44]; char summary[100]; char machine[40]; char machine_id[40]; uint32_t ms; bool unread, used; } notif_t;
+// `question` separates the two kinds of news a row can be, because they are taken away by different
+// things: a finished turn goes when somebody looks at it, a question goes when it is ANSWERED. One row
+// per agent either way, newest wins — so a question that arrives over a finished turn replaces it, and
+// answering that question must not also throw away a finish that has since replaced IT.
+typedef struct { char proj_id[48]; char name[44]; char summary[100]; char machine[40]; char machine_id[40]; uint32_t ms; bool unread, used, question; } notif_t;
static EXT_RAM_BSS_ATTR notif_t s_notif[NOTIF_MAX]; // newest at index 0; opening marks read, tapping a row removes that one
static lv_obj_t *s_notif_pill; // top-mid "🔔 N" count badge (projects screen, when N>0)
static lv_obj_t *s_notif_pill_lbl; // the "N" label inside the pill
@@ -404,6 +408,13 @@ static void agent_actions_apply(void); // show/hide the per-agent Voice cluste
static void machine_toast(const char *msg); // a short centred line over the face (defined with the machine picker)
static void build_agent_actions(void); // build that cluster once on scr_projects (defined below)
static void notif_badge_apply(void); // show/hide the top unread pill (defined below)
+// Give the face back when the window moves to a DIFFERENT agent — see ui_focus_project. Defined with
+// the question screen, which owns the state it reads.
+static void q_leave_if_other_agent(const char *project_id);
+// Put an unanswered question back on the face — what tapping its notification should land on.
+static bool q_reopen(const char *project_id);
+// Does this agent have an unanswered question waiting? Its notification row is what remembers.
+static bool notif_is_question(const char *proj_id);
static void notif_bg_tap(lv_event_t *e); // tap the drawer's empty area → close (defined below)
static void machine_switch_to(int i); // select machine i + enter its carousel (defined with the picker)
static int utf8_clip(const char *s, int max); // clip to <=max bytes on a codepoint boundary (defined below)
@@ -1050,6 +1061,21 @@ static void busy_compose(proj_t *p)
int64_t sec = (esp_timer_get_time() - p->busy_since) / 1000000LL;
if (sec < 0) sec = 0;
char el[24]; fmt_elapsed(sec, el, sizeof(el));
+ // AN AGENT WITH AN UNANSWERED QUESTION IS NOT WORKING. Its turn is open — which is why the tile is
+ // in the busy state at all — but it is open BECAUSE it is waiting on a person, and "Cooking… 4m"
+ // over a question nobody has answered reads as progress that is not happening (owner, 2026-09-24).
+ //
+ // Read off the notification row rather than off `s_q`: that row is this agent's question whether or
+ // not the question screen is the one on the face right now, and it goes when the question is
+ // answered — which is exactly when this line should go back to a verb.
+ if (notif_is_question(p->id)) {
+ // NO ELAPSED HERE. `busy_since` is stamped when a `processing` frame says the turn (re)started,
+ // and an agent that leaves this tab is removed from the model and re-added when it comes back —
+ // so the clock restarts on a turn that has been standing still, which is the opposite of what a
+ // number beside "waiting" would be read as.
+ lv_label_set_text(p->busy_verb, "Waiting for you");
+ return;
+ }
lv_label_set_text_fmt(p->busy_verb, "%s\xE2\x80\xA6 %s", GERUNDS[(sec / 6) % N_GERUNDS], el); // Cooking… 34s
}
@@ -5787,6 +5813,17 @@ void ui_focus_project(const char *project_id)
return;
}
pending_focus_clear(); // this one landed; nothing older can still be wanted
+ // A question the person has not answered must not pin the face here — see the helper.
+ q_leave_if_other_agent(project_id);
+ // …and the other direction: coming BACK to an agent that is still waiting on an answer shows the
+ // answer screen, not the tile behind it. "Waiting for you" on a tile says what the state is; the
+ // question says what to do about it, and being asked to go there and then shown the waiting room
+ // is a step nobody asked for (owner, 2026-09-24).
+ //
+ // A FOCUS ONLY, never a swipe. `tile_changed` is the dial's own gesture and it deliberately does
+ // not do this: a blocked agent you could not swipe past without being handed its question is a
+ // carousel with a hole in it.
+ if (notif_is_question(project_id)) q_reopen(project_id); // takes the lock itself; recursive
if (i >= 0) {
carousel_goto(col_for_ring_near(carousel_col(), ring_of_agent(i)), LV_ANIM_OFF); // nearest column showing agent i
s_active_idx = i;
@@ -5921,6 +5958,19 @@ static void notif_badge_apply(void)
{
if (!s_notif_pill) return;
int n = notif_count();
+ // THE NUMBER, IN THE LOG, WHENEVER IT MOVES.
+ //
+ // This count has to equal the window's badge, and for as long as it lived only on the glass the
+ // only way to check that was to hold the two side by side — which is how a question row being
+ // dropped by a carousel settle went unnoticed through four attempts at the wrong fix. Printed on
+ // CHANGE only: this runs on every settle, every screen change and every wake.
+ static int last = -1;
+ if (n != last) {
+ last = n;
+ int q = 0;
+ for (int k = 0; k < NOTIF_MAX; k++) if (s_notif[k].used && s_notif[k].unread && s_notif[k].question) q++;
+ ESP_LOGI(TAG, "notif: %d unread (%d question, %d done)", n, q, n - q);
+ }
// The Overview has its own bell on the lower arc, with the count as a badge; the top-edge pill is
// for the agent tiles, which have no seat for one.
bool show = n > 0 && !display_is_asleep() && lv_screen_active() == scr_projects
@@ -5936,8 +5986,17 @@ static void notif_badge_apply(void)
static void notif_ud_free(lv_event_t *e) { free(lv_obj_get_user_data(lv_event_get_target(e))); }
// What a drawer row needs on tap: which agent. The daemon routes the `open` to its machine.
typedef struct { char proj[48]; } notif_ref_t;
-// Remove ONE project's notification from the queue (compact the tail up). Caller holds the lock.
-static void notif_remove(const char *proj_id)
+// Remove ONE project's notification from the queue (compact the tail up).
+// Remove this project's row only when it is the KIND the caller means — a question, or a finished turn.
+//
+// One row per agent, newest wins, so the two kinds share a slot and each is taken away by a different
+// thing: a finish goes when somebody looks at it, a question goes when it is answered. An agent that
+// asked and then finished carries the finish, and answering that old question must not throw it away.
+// Caller holds the lock.
+// EVERY row this agent has, whatever kind. Exactly one caller — the close, which means somebody just
+// answered this agent — and named so it cannot be reached for by accident: an any-kind remove is what
+// let a carousel settle throw away an unanswered question, four fixes running. Caller holds the lock.
+static void notif_forget_agent(const char *proj_id)
{
for (int k = 0; k < NOTIF_MAX; k++) {
if (s_notif[k].used && strcmp(s_notif[k].proj_id, proj_id) == 0) {
@@ -5947,6 +6006,26 @@ static void notif_remove(const char *proj_id)
}
}
}
+
+static void notif_remove_matching(const char *proj_id, bool question)
+{
+ for (int k = 0; k < NOTIF_MAX; k++) {
+ if (s_notif[k].used && strcmp(s_notif[k].proj_id, proj_id) == 0) {
+ if (s_notif[k].question != question) return;
+ for (int j = k; j < NOTIF_MAX - 1; j++) s_notif[j] = s_notif[j + 1];
+ s_notif[NOTIF_MAX - 1].used = false;
+ return;
+ }
+ }
+}
+// Is the row this project has a question? False when it has none.
+static bool notif_is_question(const char *proj_id)
+{
+ for (int k = 0; k < NOTIF_MAX; k++) {
+ if (s_notif[k].used && strcmp(s_notif[k].proj_id, proj_id) == 0) return s_notif[k].question;
+ }
+ return false;
+}
// Tap a row → remove ONLY that notification (Model B: the rest are kept), then ask the window to open that
// agent — see notif_row_tap.
// Focus an agent AND open its detail reader — where a notification tap should land. Same text source as
@@ -5979,7 +6058,12 @@ static void notif_row_tap(lv_event_t *e)
const notif_ref_t *ref = (const notif_ref_t *)lv_obj_get_user_data(lv_event_get_target(e));
char id[48]; // copy before close frees the rows
snprintf(id, sizeof id, "%s", ref ? ref->proj : "");
- if (id[0]) notif_remove(id);
+ // A QUESTION'S ROW SURVIVES ITS OWN TAP. Tapping is how you go and answer it, and going is not
+ // answering — the row goes on `question.close` and nowhere else (owner, 2026-09-24). Removing it
+ // here took the pill down by one while the window still counted it, and landed the person on a
+ // tile reading "Working…", which is what an agent waiting on an answer honestly is.
+ const bool question = id[0] && notif_is_question(id);
+ if (id[0] && !question) notif_remove_matching(id, false);
ui_notif_close();
// THE OPEN NAMES THE NOTIFICATION'S AGENT, whether or not the dial holds it. The dial has the window's
@@ -5991,6 +6075,10 @@ static void notif_row_tap(lv_event_t *e)
if (id[0]) {
s_notif_open_pending = false;
cable_client_send_open(id, NULL);
+ // The question itself, not the tile behind it: that tile says "Working…", because the turn is
+ // still open — it is the answer it is waiting on. Falls through when the dial no longer holds
+ // the question (a reboot, or another one took its place), and then the tile is all there is.
+ if (question && q_reopen(id)) return;
open_agent_detail(id); // held until the list arrives when the agent is off this tab
return;
}
@@ -6087,7 +6175,12 @@ static void notif_rebuild(void)
lv_obj_set_width(sm, lv_pct(100));
lv_label_set_long_mode(sm, LV_LABEL_LONG_WRAP);
// Recap is already ≤15 words from the backend; clip generously as a safety net + "…".
- const char *full = n->summary[0] ? n->summary : "done";
+ //
+ // THE FALLBACK IS PER KIND. It was the bare word "done" for every row, which is true of a
+ // finished turn and a lie about a question — and a question row restored after a reboot has no
+ // text of its own to show, so the lie is exactly what you got (owner, 2026-09-24). The window
+ // sends the question's own words now; this is what stands in if even those are missing.
+ const char *full = n->summary[0] ? n->summary : n->question ? "Waiting for you" : "done";
char snip[128]; int plen = utf8_clip(full, 100);
if (plen > (int)sizeof(snip) - 4) plen = (int)sizeof(snip) - 4;
memcpy(snip, full, plen);
@@ -6329,9 +6422,11 @@ void ui_notif_swipe_up(void)
// Push a done notification for project i (dedupe by id → refresh + move to top). Caller holds the lock.
// `i` is the agent's tile, or -1 when the dial does not hold it — then the frame's `name`, `machine` and
// `recap` are all the row has, and they are enough.
-static void notif_push(const char *proj_id, int i, const char *name, const char *machine, const char *recap)
+static void notif_push(const char *proj_id, int i, const char *name, const char *machine, const char *recap,
+ bool question)
{
notif_t rec = {0};
+ rec.question = question;
snprintf(rec.proj_id, sizeof rec.proj_id, "%s", proj_id);
const char *nm = (i >= 0 && s_proj[i].name[0]) ? s_proj[i].name : (name && name[0]) ? name : proj_id; // MODEL, not the widget
snprintf(rec.name, sizeof rec.name, "%s", nm);
@@ -6373,7 +6468,7 @@ void ui_notify_task_done(const char *project_id, const char *name, const char *m
bool viewing = i >= 0 && !display_is_asleep() && !s_settings_active && !s_machines_active && !s_overview_active && !s_notif_open && s_active_idx == i;
if (!viewing) {
bool was_asleep = display_is_asleep();
- notif_push(project_id, i, name, machine, recap); // record it so the drawer/badge has the entry
+ notif_push(project_id, i, name, machine, recap, false); // record it so the drawer/badge has the entry
if (was_asleep) {
// Woke from an off screen → open the notification list directly. ui_notif_open only opens
// over the projects carousel, so land there first.
@@ -6388,6 +6483,49 @@ void ui_notify_task_done(const char *project_id, const char *name, const char *m
display_unlock();
}
+void ui_notif_replace(const cable_notif_t *rows, int count)
+{
+ display_lock();
+ if (count < 0) count = 0;
+ if (count > NOTIF_MAX) count = NOTIF_MAX;
+ memset(s_notif, 0, sizeof(s_notif));
+ for (int k = 0; k < count; k++) {
+ notif_t *r = &s_notif[k];
+ snprintf(r->proj_id, sizeof r->proj_id, "%s", rows[k].agent_id);
+ // The tile's OWN name when it has one: the carousel is built by the time this lands, and a row
+ // naming the agent differently from the tile beside it reads as two different agents.
+ int i = find_proj(rows[k].agent_id);
+ const char *nm = (i >= 0 && s_proj[i].name[0]) ? s_proj[i].name : rows[k].name;
+ snprintf(r->name, sizeof r->name, "%s", nm);
+ snprintf(r->summary, sizeof r->summary, "%s", rows[k].summary);
+ snprintf(r->machine, sizeof r->machine, "%s", rows[k].machine);
+ if (i >= 0 && s_proj[i].machine_id[0]) snprintf(r->machine_id, sizeof r->machine_id, "%s", s_proj[i].machine_id);
+ // NOT the time it was raised — the window sends no clock and this device's ticks mean nothing
+ // to it. "now" is the honest reading of a row whose age this dial never saw.
+ r->ms = lv_tick_get();
+ r->question = rows[k].question;
+ r->unread = true;
+ r->used = true;
+ }
+ notif_badge_apply();
+ if (s_notif_open) notif_rebuild();
+ display_unlock();
+}
+
+void ui_notif_seen(const char *project_id)
+{
+ if (!project_id || !project_id[0]) return;
+ display_lock();
+ // FINISHES ONLY. The window sends this when a harness it had marked comes into view, and looking
+ // at a blocked agent is not answering it — so a question's row stays until `question.close`.
+ notif_remove_matching(project_id, false);
+ notif_badge_apply();
+ // The drawer may be open on the very row that just went. Rebuilt rather than left holding a
+ // widget whose record is gone — notif_rebuild reads s_notif, and it is the only thing that does.
+ if (s_notif_open) notif_rebuild();
+ display_unlock();
+}
+
// Multi-attach: a BACKGROUND machine (one the device isn't rendering) finished a turn. Its project tile isn't
// loaded, so build the notification entry straight from the machineId + optional recap. `summary` is NULL when
@@ -7300,6 +7438,43 @@ static void q_leave(const char *why)
// The user backed out. The agent's turn stays waiting; they can answer later or stop it with BOOT.
static void q_cancel(void) { q_leave("dismissed"); }
+// THE QUESTION SCREEN IS NOT A TRAP. It owns the whole face, and ui_focus_project only ever moved the
+// carousel UNDERNEATH it — so somebody who switched tab or agent in the window watched the dial sit on
+// a question they had not answered, with no way out but answering it or the BOOT button.
+//
+// A focus naming ANOTHER agent is the window saying the person is looking elsewhere, so the face
+// follows. Not an answer and not a dismissal: the question keeps its row behind the bell, and that row
+// goes when it is ANSWERED (owner, 2026-09-24) — see ui_question_close.
+//
+// A focus naming the question's OWN agent is left alone, and that is not a rare case: showing a
+// question asks the window to bring that agent forward (the `open` at the end of ui_question_show), and
+// the focus coming back would otherwise close the question a beat after it appeared.
+// Put a question the person walked away from back on the face.
+//
+// `q_leave` only lowers `active` — the shaped questions and their options stay in `s_q` — so an
+// unanswered one can be returned to exactly as it was. False when this dial no longer holds THAT
+// question: a reboot cleared it, or another agent's took the slot.
+static bool q_reopen(const char *project_id)
+{
+ if (!project_id || !project_id[0]) return false;
+ bool ok = false;
+ display_lock();
+ if (s_q.n_q > 0 && strcmp(s_q.project, project_id) == 0) {
+ if (!s_q.active) { s_q.active = true; s_q.idx = 0; q_render(); }
+ lv_screen_load(scr_question);
+ ok = true;
+ }
+ display_unlock();
+ return ok;
+}
+
+static void q_leave_if_other_agent(const char *project_id)
+{
+ if (!s_q.active || !project_id) return;
+ if (strcmp(s_q.project, project_id) == 0) return;
+ q_leave("the window moved on");
+}
+
void ui_question_close(const char *project_id, const char *request_id)
{
display_lock();
@@ -7310,6 +7485,21 @@ void ui_question_close(const char *project_id, const char *request_id)
&& (!request_id || !request_id[0] || strcmp(s_q.request_id, request_id) == 0)) {
q_leave("answered elsewhere");
}
+ // THE AGENT'S ROW GOES, whatever kind it is, and whether or not that question was still the one on
+ // the face.
+ //
+ // Answering ENDS THE TURN for these engines — measured, a millisecond apart and the turn first:
+ //
+ // 18:04:58.534 [turn] 395050e8 ended · 65175ms
+ // 18:04:58.535 [question] 395050e8 answered elsewhere · closing
+ //
+ // so the finish lands on top of the question's row and the pill never goes down. A turn that ended
+ // in the same breath as the answer is not something that happened while anybody was away: a close
+ // means somebody just dealt with this agent, and anything unread for it then is the work they were
+ // standing over. The window follows the same rule (see `commander_question_close` there).
+ notif_forget_agent(project_id);
+ notif_badge_apply();
+ if (s_notif_open) notif_rebuild();
display_unlock();
}
@@ -7325,8 +7515,22 @@ static void clear_removed_project_transients_locked(const char *project_id, bool
update_stop_btn();
}
if (s_q.active && strcmp(s_q.project, project_id) == 0) {
- memset(&s_q, 0, sizeof(s_q));
+ // GIVE THE FACE BACK, BUT KEEP THE QUESTION.
+ //
+ // "Removed" here is not "deleted". The dial holds ONE TAB, and this runs from the reconcile in
+ // refresh_projects for every agent that is not on the tab the window just pushed — which is
+ // routine, and happens the moment somebody switches tabs. This used to `memset` the whole of
+ // `s_q`, so a question that was merely off-tab for a second became unanswerable and its
+ // notification could no longer be returned to: tapping the row fell through to the tile, which
+ // says "Waiting for you" now but said "Cooking…" then (owner, 2026-09-24).
+ //
+ // The content stays, so q_reopen can put it back; the row behind the bell stays, because the
+ // question is still unanswered. Only the face is handed over.
+ s_q.active = false;
if (lv_screen_active() == scr_question) lv_screen_load(scr_projects);
+ // SAID OUT LOUD. This was the one way off the question screen that left no line at all, and
+ // from a capture it was indistinguishable from the screen vanishing on its own.
+ ESP_LOGI(TAG, "question set aside — %s left this tab (req=%s)", project_id, s_q.request_id);
}
}
@@ -7404,6 +7608,16 @@ void ui_question_show(const char *project_id, const char *agent_name, const char
if (s_q.n_q == 0) { display_unlock(); return; }
s_q.active = true;
s_q.idx = 0;
+ // A BLOCKED AGENT IS ALWAYS COUNTED, and stays counted until the question is ANSWERED — not until
+ // somebody looks at it (owner, 2026-09-24). The face is taken over either way; this is the row
+ // behind the bell, so the pill here and the badge in the window say the same number.
+ //
+ // Unconditional, unlike a summary's `quiet`. It was gated on that for a day and the gate never
+ // opened: showing a question asks the window to bring its agent forward, so the agent was on screen
+ // by construction, every question came through quiet, and no row was ever written. Looking away
+ // afterwards then left nothing at all — a question owed and nothing anywhere saying so.
+ notif_push(project_id, find_proj(project_id), agent_name, machine, s_q.q[0].text, true);
+ notif_badge_apply();
ESP_LOGI(TAG, "question shown (req=%s n=%d multi=%d opts=%d)", s_q.request_id, s_q.n_q, s_q.q[0].multi, s_q.q[0].n_options);
if (display_is_asleep()) display_wake();
q_render();
@@ -8190,10 +8404,17 @@ static void tile_changed(lv_event_t *e)
apply_active_from_col(); // active/settings from the centered ring position
update_content_window(); // materialize the newly-active tile ± window, free the rest
rebuild_page_dots(); // move the green sparkle to the newly-centered page
- // Swiping onto an agent's tile = the user saw it → drop that agent's notification (if any).
+ // Landing on an agent's tile = the user saw it → drop that agent's FINISHED-turn notification.
+ //
+ // NOT ITS QUESTION. A question is owed until it is answered, and arriving at the agent is not
+ // answering it (owner, 2026-09-24) — the same rule the window's sweep follows and the same one
+ // ui_notif_seen follows. This line took any row at all, and because every route back to an agent
+ // ends in a carousel settle it was the thing undoing all of it: focus away and back and the
+ // question was gone from the pill, gone from busy_compose, and the tile said "Cooking…" over a
+ // turn that was standing still waiting for an answer.
if (!s_settings_active && !s_machines_active && !s_overview_active &&
s_active_idx >= 0 && s_active_idx < s_proj_count && s_proj[s_active_idx].id[0]) {
- notif_remove(s_proj[s_active_idx].id);
+ notif_remove_matching(s_proj[s_active_idx].id, false);
}
update_stop_btn(); // STOP follows the newly-visible tile's processing state (hidden on settings)
voice_btn_apply_visibility();
diff --git a/devices/harness-device/firmware/main/ui/ui_screens.h b/devices/harness-device/firmware/main/ui/ui_screens.h
index 39a6cd396..719887597 100644
--- a/devices/harness-device/firmware/main/ui/ui_screens.h
+++ b/devices/harness-device/firmware/main/ui/ui_screens.h
@@ -299,6 +299,20 @@ void ui_voice_quota_exceeded(void);
// `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);
+// 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
+// front over there — and each has to reach the other or the pill and the badge stop agreeing the
+// first time either is used. The tap's half already travels (cable_client_send_open); this is the
+// return leg. No-op when no row names this agent. Safe from the reader task.
+void ui_notif_seen(const char *project_id);
+// Replace the WHOLE drawer with what the window still has unread, newest first.
+//
+// Sent once per attach, because that is the one moment this dial is known to have nothing: the rows
+// live in RAM and an OTA, a replug or a flash takes them while the window keeps every mark. Without
+// it the two screens read different numbers from that moment on, with nothing to bring them back.
+// Safe from the reader task.
+void ui_notif_replace(const cable_notif_t *rows, int count);
// Append a commander event to a project's tile as a readable text card (keeps the last 2).
// kind: "say" | "act" | "ask" | "done" | "error". session_id is the dbSessionId for voice resume.
// `recap` (optional, may be NULL): a short headline shown on the tile at a glance; `text` is the
@@ -331,6 +345,9 @@ void ui_project_set_agents(const char *project_id, const struct cJSON *agents);
// Show the question screen: tap an option row to answer (single/multi-select). Tap-only — there is no
// voice answer. `questions` is the cJSON array from the `commander_question` frame; copied out
// synchronously, so the caller may free the JSON right after this returns.
+// 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);
// 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.