Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(agents): one chime per background fan-out, not one per subagent
enesfe4415615b6b
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 0c685b0ec..205445f2e 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useShallow } from 'zustand/react/shallow'import { playSfx, primeSfx } from '@renderer/lib/sfx'+import { fanoutStillWorking } from '@renderer/lib/completionAlert'import {addEdge,applyEdgeChanges,@@ -11968,10 +11969,19 @@ export function Canvas() {if (e.account) cs.setAccount(e.nodeId, { ...e.account, remote: observationIsRemote(originOf(e.nodeId)) })const agentLabel = agentConfig(e.agentId)?.label ?? 'Agent'// "<folder> — Claude finished" + last assistant message as the body.- const alert = (statusText: string, fallbackBody: string, sound: 'done' | 'needsYou') => {+ const alert = (+ statusText: string,+ fallbackBody: string,+ sound: 'done' | 'needsYou',+ opts?: { quiet?: boolean }+ ) => {// Unread unless the user is actively in this node's terminal (focused window +// this node is the active terminal). So a finish while you're in another terminal,// or with nothing focused, still flags unread.+ //+ // `opts.quiet` reaches this function BELOW this block on purpose (issue #708): it silences+ // the two INTERRUPTS (chime, OS notification) and never the unread record or its ack. See+ // `fanoutStillWorking` — a dot is a different fact from a chime.const watching = document.hasFocus() && cs.activeId === e.nodeIdif (!watching) cs.markUnread(e.nodeId)// Watched it finish? Then it is already read. Nothing marks it unread in this branch, so@@ -11979,6 +11989,9 @@ export function Canvas() {// green blob and the phone's Live Activity would keep glowing for a turn the user sat and// watched end. The mirror no-ops when there is no unresolved done event.else if (sound === 'done') void window.nodeTerminal.ackDone(e.nodeId)+ // Everything from here down is an INTERRUPT, and this is where a quiet alert stops. The+ // unread dot and its ack above are deliberately on the other side of this line.+ if (opts?.quiet) return// Sound first: it is the one alert that also fires while you're in the app but looking at// another node — the case OS notifications deliberately skip.const snd = useSettings.getState().settings@@ -12046,7 +12059,16 @@ export function Canvas() {// a renderer reload. Gating the badge but not the sound/notification would half-enforce// the flag and leave the expensive error — a false completion — fully reachable.cs.bumpLoop(e.nodeId, e.lastMessage) // count loop iterations + summary (no-op if not looping)- alert('finished', `${agentLabel} finished its turn.`, 'done')+ // Issue #708: a turn that ended only because a BACKGROUND SUBAGENT reported back is+ // not the fan-out finishing — the parent is about to be woken again by the next one.+ // Read fresh (not the `an` snapshot taken at listener entry): `clearFinishedForParent`+ // may have run just above. It only drops DONE cards, so the verdict is the same either+ // way, and depending on that is exactly the kind of coupling that rots.+ const fanoutBusy = fanoutStillWorking(+ Object.values(useAgentNodes.getState().byId),+ e.nodeId+ )+ alert('finished', `${agentLabel} finished its turn.`, 'done', { quiet: fanoutBusy })}if (e.state === 'blocked')alert('needs input', `${agentLabel} needs permission to continue.`, 'needsYou')diff --git a/src/renderer/canvas/fanout-chime.test.ts b/src/renderer/canvas/fanout-chime.test.tsnew file mode 100644index 000000000..ec8278505--- /dev/null+++ b/src/renderer/canvas/fanout-chime.test.ts@@ -0,0 +1,66 @@+// The completion alert must go QUIET while the parent still holds working subagent cards, and the+// unread record must stay on the other side of that gate (issue #708).+//+// Canvas.tsx is a ~12k-line monolith and this listener lives inside one of its `useEffect`s — there+// is no harness that can dispatch an `agent:status` event at it (see the note at the top of+// `agent-status-rescue.test.ts`, which pins its sibling invariant the same way). The DECISION is+// pure and behaviourally tested in `renderer/lib/completionAlert.test.ts`; what only the source can+// show is that Canvas asks it, asks it for the right event, and puts the quiet gate BELOW the+// unread write rather than above it.++import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'++const src = fs.readFileSync(path.resolve(__dirname, 'Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')++/** The body of the `alert` closure in the agent-status listener. */+function alertBody(): string {+ const start = src.indexOf('const alert = (')+ expect(start, 'Canvas must still build its alert closure').toBeGreaterThan(-1)+ const end = src.indexOf('const an = useAgentNodes.getState()', start)+ expect(end).toBeGreaterThan(start)+ return src.slice(start, end)+}++describe('Canvas completion alert — background fan-out (issue #708)', () => {+ it('asks the shared predicate rather than re-deriving "still working" inline', () => {+ expect(src).toContain("import { fanoutStillWorking } from '@renderer/lib/completionAlert'")+ // The verdict must be computed from the LIVE store, not from the `an` snapshot taken at+ // listener entry, and it must be handed to the alert as `quiet`.+ expect(src).toMatch(+ /fanoutStillWorking\(\s*Object\.values\(useAgentNodes\.getState\(\)\.byId\),\s*e\.nodeId\s*\)/+ )+ })++ it('gates only the completion alert, never "needs input"', () => {+ // A blocked/waiting agent needs the user NOW, whatever its subagents are doing.+ const done = src.match(/alert\('finished',[^\n]*\)/)+ expect(done, "the 'finished' alert call must still exist").toBeTruthy()+ expect(done![0]).toContain('quiet:')+ for (const m of src.matchAll(/alert\('needs input',[^\n]*\)/g)) {+ expect(m[0]).not.toContain('quiet')+ }+ })++ it('silences the chime and the OS notification but NOT the unread record', () => {+ const body = alertBody()+ const unread = body.indexOf('cs.markUnread(e.nodeId)')+ const ack = body.indexOf('ackDone(e.nodeId)')+ const quiet = body.indexOf('opts?.quiet')+ const sound = body.indexOf('playSfx(')+ const notify = body.indexOf('nodeTerminal.notify(')+ expect(unread).toBeGreaterThan(-1)+ expect(ack).toBeGreaterThan(-1)+ expect(quiet).toBeGreaterThan(-1)+ expect(sound).toBeGreaterThan(-1)+ expect(notify).toBeGreaterThan(-1)+ // Unread + its ack are ABOVE the quiet return; both interrupts are below it.+ expect(unread).toBeLessThan(quiet)+ expect(ack).toBeLessThan(quiet)+ expect(quiet).toBeLessThan(sound)+ expect(quiet).toBeLessThan(notify)+ // And the gate is a hard return, so nothing after it can leak through.+ expect(body).toMatch(/if \(opts\?\.quiet\) return/)+ })+})diff --git a/src/renderer/lib/completionAlert.test.ts b/src/renderer/lib/completionAlert.test.tsnew file mode 100644index 000000000..5f99051da--- /dev/null+++ b/src/renderer/lib/completionAlert.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest'+import { fanoutStillWorking } from './completionAlert'+import { useAgentNodes } from '../state/agentNodes'+import { WORKING_STALE_MS } from '@shared/agents/stale'++const cards = (...cs: { parentNodeId: string; state?: string }[]): typeof cs => cs++describe('fanoutStillWorking — the completion alert’s quiet gate (issue #708)', () => {+ it('is loud with no cards at all — the ordinary agent node must never lose its chime', () => {+ expect(fanoutStillWorking([], 'n1')).toBe(false)+ })++ it('is quiet while this parent still holds a working card', () => {+ expect(fanoutStillWorking(cards({ parentNodeId: 'n1', state: 'working' }), 'n1')).toBe(true)+ })++ it('is loud once every card of this parent is done — the last one lands, the chime fires', () => {+ expect(+ fanoutStillWorking(+ cards(+ { parentNodeId: 'n1', state: 'done' },+ { parentNodeId: 'n1', state: 'done' },+ { parentNodeId: 'n1', state: 'done' }+ ),+ 'n1'+ )+ ).toBe(false)+ })++ it('is quiet with nine done and one still working — the case in the report', () => {+ const nine = Array.from({ length: 9 }, () => ({ parentNodeId: 'n1', state: 'done' }))+ expect(fanoutStillWorking([...nine, { parentNodeId: 'n1', state: 'working' }], 'n1')).toBe(true)+ })++ it('is scoped per parent — another node’s live fan-out never silences this one', () => {+ expect(fanoutStillWorking(cards({ parentNodeId: 'n2', state: 'working' }), 'n1')).toBe(false)+ })++ it('is LOUD for an unknown/absent state — the opposite direction from Eco’s liveSubagents', () => {+ // Eco counts anything not provably `done` as live, because being wrong there kills running+ // work. Being wrong HERE swallows a completion, so only a positive `working` may silence.+ expect(fanoutStillWorking(cards({ parentNodeId: 'n1' }), 'n1')).toBe(false)+ expect(fanoutStillWorking(cards({ parentNodeId: 'n1', state: 'queued' }), 'n1')).toBe(false)+ })+})++describe('the real store feeds it the shape it expects', () => {+ const P = 'parent-708'+ const reset = (): void => useAgentNodes.getState().clearForParent(P)++ it('goes quiet on start() and loud again on finish() — no adapter in between', () => {+ reset()+ const values = (): { parentNodeId: string; state?: string }[] =>+ Object.values(useAgentNodes.getState().byId)++ useAgentNodes.getState().start('t1', { parentNodeId: P })+ useAgentNodes.getState().start('t2', { parentNodeId: P })+ expect(fanoutStillWorking(values(), P)).toBe(true)++ useAgentNodes.getState().finish('t1', {})+ expect(fanoutStillWorking(values(), P)).toBe(true) // t2 still out there++ useAgentNodes.getState().finish('t2', {})+ expect(fanoutStillWorking(values(), P)).toBe(false)+ reset()+ })++ it('the 20-minute stale decay is what bounds a lost subagent end', () => {+ // A subagent whose end never arrives would otherwise silence this node's chimes forever.+ reset()+ useAgentNodes.getState().start('t3', { parentNodeId: P })+ const startedAt = useAgentNodes.getState().byId['t3'].startedAt+ const values = (): { parentNodeId: string; state?: string }[] =>+ Object.values(useAgentNodes.getState().byId)++ useAgentNodes.getState().sweepStaleWorking(startedAt + WORKING_STALE_MS - 1)+ expect(fanoutStillWorking(values(), P)).toBe(true)++ useAgentNodes.getState().sweepStaleWorking(startedAt + WORKING_STALE_MS + 1)+ expect(fanoutStillWorking(values(), P)).toBe(false)+ reset()+ })+})diff --git a/src/renderer/lib/completionAlert.ts b/src/renderer/lib/completionAlert.tsnew file mode 100644index 000000000..fb0a859ae--- /dev/null+++ b/src/renderer/lib/completionAlert.ts@@ -0,0 +1,77 @@+/**+ * Should a parent agent's turn-end alert be QUIET — no chime, no OS notification?+ *+ * Issue #708. Claude launches background subagents async: each one that finishes is announced back+ * to the PARENT as a queued `<task-notification>` prompt, and the parent's handling of that+ * notification is a full turn — `UserPromptSubmit` → … → `Stop`. `Stop` normalizes to+ * `state: 'done'`, and `done` is what fires the completion alert. So a fan-out of ten background+ * agents produces ten `done` events on ONE node, each of them a chime. The reporter's words: "a+ * chime every few seconds :)))".+ *+ * None of those ten is a lie about the turn — the turn really did end. What they are wrong about is+ * the thing the chime MEANS, which is "this node is finished and wants you". A parent still holding+ * subagents in `working` has not finished; it is going to be woken again by the next one.+ *+ * ## What is suppressed, and what is deliberately not+ *+ * The chime and the OS notification only. **`unread` is NOT suppressed** — read the "Unread ++ * notification" bullet in CLAUDE.md: unread is a durable per-node flag, cleared by looking at the+ * node, and it is idempotent, so ten report-backs raise ONE dot rather than ten. It costs the user+ * no interruption and it is the thing that still tells them "something happened here" if the final+ * chime is ever lost. The chime and the banner are interrupts; the dot is a record. Suppressing the+ * record to fix the interrupt would trade a noisy bug for a silent one.+ *+ * ## Why this fires exactly once at the end, with no deferred-alert bookkeeping+ *+ * The LAST subagent's completion writes its `<task-notification>` into the parent transcript, the+ * context tail sniffs it within one poll (`POLL_MS` = 1 s in `core/context-tail.ts`) and emits the+ * synthetic `subagent-end` that marks the card `done`. Only THEN does the parent wake and run the+ * turn whose `Stop` arrives seconds later. By that point no card is `working`, so the alert fires+ * normally. The "one chime when the whole fan-out is done" is therefore the ordinary alert, not a+ * replayed one — there is no debt to remember and no second alert path that could double-chime.+ *+ * ## The direction of the guess is the OPPOSITE of Eco's+ *+ * `buildHibernationCandidates`' `liveSubagents` asks a related question and answers it+ * conservatively the other way: anything that is not provably `done` counts as LIVE, because being+ * wrong there means `/exit`ing a CLI with live background work in it (issue #402). Here being wrong+ * means SWALLOWING a genuine completion, so the conservative direction is to stay loud: only a card+ * this store positively holds in `working` may silence a chime. That is why this is its own+ * predicate rather than a call into the hibernation adapter — same store, opposite failure cost.+ *+ * The store types `state` as `'working' | 'done'`, so on today's data the two spellings agree; the+ * match is written as `=== 'working'` anyway so a future third state (or a card rehydrated from+ * somewhere with a missing field) falls to the loud side by construction.+ *+ * ## The bounded worst case+ *+ * A subagent whose end never arrives (crashed CLI, killed pane, slept machine) pins its card in+ * `working`, and this would then silence that node's completion chimes. It is bounded by the same+ * decay everything else in this store leans on: Canvas's 60 s sweep runs `sweepStaleWorking`, which+ * marks a card `done` after `WORKING_STALE_MS` (20 min). Past that the node chimes again on its+ * next turn end. The alternative — remembering a suppressed alert and replaying it when the last+ * card lands — was considered and rejected: the replay races the parent's own woken turn, so the+ * normal path would chime twice whenever that turn takes longer than the node's 5 s sound cooldown,+ * which is most of the time.+ */++/** One subagent card, narrowed to what this decision reads. */+export interface FanoutCard {+ parentNodeId: string+ state?: string+}++/**+ * Does this parent still hold at least one subagent card in `working`?+ *+ * Pure; `cards` is `Object.values(useAgentNodes.getState().byId)`.+ */+export function fanoutStillWorking(+ cards: Iterable<FanoutCard>,+ parentNodeId: string+): boolean {+ for (const c of cards) {+ if (c.parentNodeId === parentNodeId && c.state === 'working') return true+ }+ return false+}