Skip to content

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.

feat(ack): the host consumes phone read-acks; stale asks can't mute new ones

enes17e4e21c76fe
diff --git a/src/core/ack-sweep.test.ts b/src/core/ack-sweep.test.ts
new file mode 100644
index 000000000..358970a36
--- /dev/null
+++ b/src/core/ack-sweep.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect } from 'vitest'
+import { sweepAckDir, createAckSweeper, type AckSweepFsLike } from './ack-sweep'
+
+/**
+ * In-memory fs double for the sweeper. `dir` is a flat map of name → content; `mtime` advances on
+ * every mutation so `createAckSweeper`'s dir-mtime gate can be exercised. `rm` records deletions.
+ */
+function fakeFs(initial: Record<string, string>) {
+ const files = new Map(Object.entries(initial))
+ let mtimeMs = 1
+ const readErrors = new Set<string>()
+ const fs: AckSweepFsLike = {
+ readdirSync: (_dir) => [...files.keys()],
+ readFileSync: (p, _e) => {
+ const name = p.split('/').pop() as string
+ if (readErrors.has(name)) throw new Error('EACCES')
+ if (!files.has(name)) throw new Error('ENOENT')
+ return files.get(name) as string
+ },
+ statSync: (_p) => ({ mtimeMs }),
+ rmSync: (p, _o) => {
+ const name = p.split('/').pop() as string
+ if (files.delete(name)) mtimeMs++
+ }
+ }
+ return {
+ fs,
+ files,
+ setMtime: (n: number) => (mtimeMs = n),
+ getMtime: () => mtimeMs,
+ failRead: (name: string) => readErrors.add(name),
+ clearReadError: (name: string) => readErrors.delete(name),
+ add: (name: string, content: string) => {
+ files.set(name, content)
+ mtimeMs++
+ }
+ }
+}
+
+const DIR = '/home/u/.nodeterm/acks'
+
+describe('sweepAckDir — consume + resolve + delete', () => {
+ it('acks each node, clears its unread, and deletes the file', () => {
+ const f = fakeFs({ 'nt-a.seen': 'evt-1', 'nt-b.seen': 'evt-2' })
+ const acked: string[] = []
+ const cleared: string[] = []
+ const consumed = sweepAckDir(DIR, f.fs, {
+ ackDone: (id) => acked.push(id),
+ onUnreadClear: (id) => cleared.push(id)
+ })
+ expect(consumed.sort()).toEqual(['nt-a', 'nt-b'])
+ expect(acked.sort()).toEqual(['nt-a', 'nt-b'])
+ expect(cleared.sort()).toEqual(['nt-a', 'nt-b'])
+ // Files are consumed exactly once — nothing left on disk.
+ expect(f.files.size).toBe(0)
+ })
+
+ it('tolerates junk: ignores non-.seen files and empty-name entries', () => {
+ const f = fakeFs({
+ 'nt-a.seen': 'evt-1',
+ 'README.txt': 'not an ack',
+ '.seen': 'empty node id',
+ 'nt-b.other': 'wrong ext'
+ })
+ const acked: string[] = []
+ const consumed = sweepAckDir(DIR, f.fs, {
+ ackDone: (id) => acked.push(id),
+ onUnreadClear: () => {}
+ })
+ expect(consumed).toEqual(['nt-a'])
+ expect(acked).toEqual(['nt-a'])
+ // Only the consumed .seen is deleted; junk is left untouched.
+ expect([...f.files.keys()].sort()).toEqual(['.seen', 'README.txt', 'nt-b.other'])
+ })
+
+ it('skips an unreadable (mid-write) .seen and retries it next pass', () => {
+ const f = fakeFs({ 'nt-a.seen': 'evt-1', 'nt-b.seen': 'evt-2' })
+ f.failRead('nt-a.seen')
+ const acked: string[] = []
+ const first = sweepAckDir(DIR, f.fs, { ackDone: (id) => acked.push(id), onUnreadClear: () => {} })
+ expect(first).toEqual(['nt-b']) // a was unreadable this pass, skipped (still on disk)
+ expect(f.files.has('nt-a.seen')).toBe(true)
+ // The write finishes (file readable) — next pass consumes it.
+ f.clearReadError('nt-a.seen')
+ const second = sweepAckDir(DIR, f.fs, { ackDone: (id) => acked.push(id), onUnreadClear: () => {} })
+ expect(second).toEqual(['nt-a'])
+ expect(acked.sort()).toEqual(['nt-a', 'nt-b'])
+ expect(f.files.size).toBe(0)
+ })
+
+ it('a missing directory yields nothing (fail-open)', () => {
+ const fs: AckSweepFsLike = {
+ readdirSync: () => {
+ throw new Error('ENOENT')
+ },
+ readFileSync: () => '',
+ statSync: () => ({ mtimeMs: 1 }),
+ rmSync: () => {}
+ }
+ expect(sweepAckDir(DIR, fs, { ackDone: () => {}, onUnreadClear: () => {} })).toEqual([])
+ })
+
+ it('a throwing ackDone still clears unread and deletes the file (never re-ack loop)', () => {
+ const f = fakeFs({ 'nt-a.seen': 'evt-1' })
+ const cleared: string[] = []
+ const consumed = sweepAckDir(DIR, f.fs, {
+ ackDone: () => {
+ throw new Error('boom')
+ },
+ onUnreadClear: (id) => cleared.push(id)
+ })
+ expect(consumed).toEqual(['nt-a'])
+ expect(cleared).toEqual(['nt-a'])
+ expect(f.files.size).toBe(0)
+ })
+})
+
+describe('createAckSweeper — dir-mtime gate + no re-ack loop', () => {
+ it('consumes on the first drop, then does NOT re-process until a new drop lands', () => {
+ const f = fakeFs({ 'nt-a.seen': 'evt-1' })
+ const acked: string[] = []
+ const cleared: string[] = []
+ const sweeper = createAckSweeper({
+ dir: DIR,
+ fs: f.fs,
+ handlers: { ackDone: (id) => acked.push(id), onUnreadClear: (id) => cleared.push(id) }
+ })
+ // First sweep: dir mtime (1) differs from the initial -1 → scan + consume.
+ expect(sweeper.sweep()).toEqual(['nt-a'])
+ expect(acked).toEqual(['nt-a'])
+ // Second sweep with no new drop: mtime unchanged since our post-delete capture → skipped,
+ // so the ack does NOT fire again (no re-ack loop).
+ expect(sweeper.sweep()).toEqual([])
+ expect(acked).toEqual(['nt-a'])
+ // A new ack from the phone bumps the dir mtime → next sweep picks it up.
+ f.add('nt-b.seen', 'evt-2')
+ expect(sweeper.sweep()).toEqual(['nt-b'])
+ expect(acked.sort()).toEqual(['nt-a', 'nt-b'])
+ expect(cleared.sort()).toEqual(['nt-a', 'nt-b'])
+ })
+
+ it('start()/stop() are idempotent and drive sweeps on the interval', () => {
+ const f = fakeFs({})
+ const acked: string[] = []
+ const sweeper = createAckSweeper({
+ dir: DIR,
+ fs: f.fs,
+ intervalMs: 10,
+ handlers: { ackDone: (id) => acked.push(id), onUnreadClear: () => {} }
+ })
+ sweeper.start()
+ sweeper.start() // idempotent — no second timer
+ sweeper.stop()
+ expect(acked).toEqual([])
+ })
+})
diff --git a/src/core/ack-sweep.ts b/src/core/ack-sweep.ts
new file mode 100644
index 000000000..54710689c
--- /dev/null
+++ b/src/core/ack-sweep.ts
@@ -0,0 +1,174 @@
+// Host-side consumer of the phone's read-acks (spec: cross-surface read sync).
+//
+// The desktop→phone direction (a desktop/browser READ of a finished session → `ackDone` → mirror
+// resolve + live-update dismiss) already exists. This module is the phone→host direction: the phone,
+// which can write files on the session host as the user, drops a read-ack at
+// `~/.nodeterm/acks/<nodeId>.seen` (content = the acked inbox event id, atomic write, umask 077). The
+// mirror-owning process sweeps that directory and, for each ack:
+// - calls `ackDone(nodeId)` — resolves the node's done inbox event(s) + fires the end seam so
+// OTHER phones / the phone's own activities sync (same path the desktop-side read uses);
+// - clears the DESKTOP renderer's unread flag for that node (the missing piece the owner hit),
+// via an injected broadcast — WITHOUT re-acking (the renderer's clearUnread must not loop back
+// into another ackDone; see `onUnreadClear` at the call site, which threads an `external` flag);
+// - deletes the `.seen` file so it is consumed exactly once.
+//
+// Pure + electron-free (`src/core`): all fs access is behind an injectable seam so it is unit-testable
+// and boots from either shell. Tolerant of junk/partial files (a phone mid-write, or an unrelated file
+// in the dir, must never break the scan) — mirrors push-grants.ts.
+
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+
+/** The slice of `fs` the sweeper needs — injectable so tests drive it without touching disk. */
+export interface AckSweepFsLike {
+ readdirSync(dir: string): string[]
+ readFileSync(p: string, enc: 'utf8'): string
+ statSync(p: string): { mtimeMs: number }
+ rmSync(p: string, opts: { force: boolean }): void
+}
+
+const nodeFs: AckSweepFsLike = {
+ readdirSync: (d) => fs.readdirSync(d),
+ readFileSync: (p, e) => fs.readFileSync(p, e),
+ statSync: (p) => fs.statSync(p),
+ rmSync: (p, o) => fs.rmSync(p, o)
+}
+
+/** `~/.nodeterm/acks` — where the phone drops `<nodeId>.seen` files. */
+export function defaultAckDir(): string {
+ return path.join(os.homedir(), '.nodeterm', 'acks')
+}
+
+const ACK_EXT = '.seen'
+
+export interface AckSweepHandlers {
+ /** Resolve the node's done inbox event(s) + fire the end seam (the core mirror's `ackDone`). */
+ ackDone(nodeId: string): void
+ /** Drop the renderer's unread flag for the node. MUST NOT re-ack (external, non-looping clear). */
+ onUnreadClear(nodeId: string): void
+}
+
+/**
+ * One pass over `dir`: for each `<nodeId>.seen` file, run `ackDone` + `onUnreadClear`, then delete
+ * the file. Returns the node ids it consumed. Tolerant at every step: a missing dir, an
+ * unreadable/unstattable file, or an odd name are skipped silently (a half-written file simply
+ * isn't consumed until it is complete, and re-appears next pass). The file content (the acked event
+ * id) is read only to confirm the file is fully written; `ackDone(nodeId)` resolves the node's
+ * newest unresolved done regardless (a stray/duplicate ack is an idempotent no-op in the mirror).
+ * Pure apart from the injected handlers + the delete.
+ */
+export function sweepAckDir(dir: string, fsi: AckSweepFsLike, handlers: AckSweepHandlers): string[] {
+ let names: string[]
+ try {
+ names = fsi.readdirSync(dir)
+ } catch {
+ // No dir yet (the common case: the phone hasn't acked anything) — nothing to consume.
+ return []
+ }
+ const consumed: string[] = []
+ for (const name of names) {
+ if (!name.endsWith(ACK_EXT)) continue
+ const nodeId = name.slice(0, -ACK_EXT.length)
+ if (!nodeId) continue
+ const full = path.join(dir, name)
+ // Read the content as a completeness gate: an unreadable file (transient / mid-write) is skipped
+ // and retried next pass. The value itself (the event id) is informational — see the docblock.
+ try {
+ fsi.readFileSync(full, 'utf8')
+ } catch {
+ continue
+ }
+ // A handler must never break the sweep (or leave the file un-consumed): ack + clear, then delete.
+ try {
+ handlers.ackDone(nodeId)
+ } catch {
+ // ackDone is best-effort; keep going so the file is still deleted + unread still cleared.
+ }
+ try {
+ handlers.onUnreadClear(nodeId)
+ } catch {
+ // ignore
+ }
+ try {
+ fsi.rmSync(full, { force: true })
+ } catch {
+ // Couldn't delete (rare): re-processing next pass is harmless — ackDone/clearUnread are both
+ // idempotent no-ops once the node has no unresolved done / no unread.
+ }
+ consumed.push(nodeId)
+ }
+ return consumed
+}
+
+export interface AckSweeperOpts {
+ /** Directory holding `<nodeId>.seen` files. Defaults to `~/.nodeterm/acks`. */
+ dir?: string
+ /** Injectable fs (tests). Defaults to node `fs`. */
+ fs?: AckSweepFsLike
+ /** Injectable clock (tests). Defaults to `Date.now`. */
+ now?: () => number
+ /** Sweep interval for `start()`. Defaults to 15s (a cheap dir-mtime check gates the readdir). */
+ intervalMs?: number
+ handlers: AckSweepHandlers
+}
+
+export interface AckSweeper {
+ /** Sweep once, gated by a cheap dir-mtime check (skips the readdir when nothing changed since the
+ * last sweep). Returns the node ids consumed this pass. */
+ sweep(): string[]
+ /** Begin sweeping on the interval. Idempotent. */
+ start(): void
+ /** Stop the interval. */
+ stop(): void
+}
+
+/**
+ * A self-scheduling ack sweeper for the mirror-owning process. `sweep()` re-reads the directory only
+ * when its mtime changed since the last pass (a `.seen` added, or our own delete) — the cheap gate the
+ * spec calls for, matching push-grants. Fails open: any fs error yields "nothing consumed", never a
+ * throw. `start()`/`stop()` drive it on a 15s interval (the desktop shell drives its own combined
+ * local+remote cadence, so it uses `sweep()` directly; the server shell just calls `start()`).
+ */
+export function createAckSweeper(opts: AckSweeperOpts): AckSweeper {
+ const dir = opts.dir ?? defaultAckDir()
+ const fsi = opts.fs ?? nodeFs
+ const intervalMs = opts.intervalMs ?? 15_000
+ let dirMtime = -1
+ let timer: NodeJS.Timeout | null = null
+
+ function dirMtimeMs(): number {
+ try {
+ return fsi.statSync(dir).mtimeMs
+ } catch {
+ return -1 // no dir / stat error → treated as "unchanged from initial"
+ }
+ }
+
+ function sweep(): string[] {
+ const dm = dirMtimeMs()
+ // Cheap gate: nothing changed since the last sweep → skip the readdir. On the very first pass
+ // (dirMtime === -1) this also skips when the dir doesn't exist yet (dm === -1), which is correct
+ // — there is nothing to consume. A first `.seen` drop moves the mtime off -1 and triggers a scan.
+ if (dm === dirMtime) return []
+ const consumed = sweepAckDir(dir, fsi, opts.handlers)
+ // Our deletes moved the mtime again — re-capture so the next tick re-scans only on a NEW drop.
+ dirMtime = dirMtimeMs()
+ return consumed
+ }
+
+ return {
+ sweep,
+ start() {
+ if (timer) return
+ timer = setInterval(sweep, intervalMs)
+ timer.unref?.()
+ },
+ stop() {
+ if (timer) {
+ clearInterval(timer)
+ timer = null
+ }
+ }
+ }
+}
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 8d2ffeb5a..90e53e566 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -28,12 +28,14 @@ import {
extractQuestionMultiSelect,
onNodeStateChange,
onNodeNowChange,
+ onInboxActionable,
_resetForTest,
_snapshot,
_inboxSnapshot,
DONE_HOLDOFF_MS,
EXPIRE_MS,
STASH_MAX_AGE_MS,
+ QUESTION_DEDUP_WINDOW_MS,
INBOX_EVENTS_CAP,
type MirrorEntry,
type MirrorFile,
@@ -428,6 +430,59 @@ describe('inbox event production (via recordAgentEvent)', () => {
expect(_inboxSnapshot().events[0].resolved).toBe(true)
})
+ // Task 3: the title-dedup must be BOUNDED so a lingering unresolved same-title ask (e.g. a generic
+ // "Waiting for input" restored across a restart) can't muzzle a genuinely NEW same-title ask forever.
+ describe('bounded title-dedup window (QUESTION_DEDUP_WINDOW_MS)', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ _resetForTest()
+ })
+ afterEach(() => {
+ _resetForTest()
+ vi.useRealTimers()
+ })
+
+ it('dedups a same-generic-title re-assert INSIDE the window (no duplicate)', () => {
+ vi.setSystemTime(0)
+ recordAgentEvent(ev({ state: 'waiting' })) // generic title "Waiting for input"
+ expect(_inboxSnapshot().events).toHaveLength(1)
+ // Re-assert well within the window (node still waiting) → deduped.
+ vi.setSystemTime(QUESTION_DEDUP_WINDOW_MS - 1000)
+ recordAgentEvent(ev({ state: 'waiting' }))
+ const ib = _inboxSnapshot()
+ expect(ib.events).toHaveLength(1)
+ expect(ib.events[0].resolved).toBeUndefined()
+ })
+
+ it('supersedes a STALE unresolved same-title ask and fires the new one (the restart false-suppression fix)', () => {
+ vi.setSystemTime(0)
+ recordAgentEvent(ev({ state: 'waiting' })) // event 0, title "Waiting for input", unresolved
+ // Node stays waiting; the ask lingers unanswered past the dedup window (models an unresolved
+ // event surviving a restart, its node never re-passing the state-leave resolve).
+ vi.setSystemTime(QUESTION_DEDUP_WINDOW_MS + 1)
+ recordAgentEvent(ev({ state: 'waiting' })) // same generic title, but the old dup is now stale
+ const ib = _inboxSnapshot()
+ expect(ib.events).toHaveLength(2)
+ // The stale one is superseded (resolved) so it stops muzzling; the new ask is live.
+ expect(ib.events[0].resolved).toBe(true)
+ expect(ib.events[1].title).toBe('Waiting for input')
+ expect(ib.events[1].resolved).toBeUndefined()
+ })
+
+ it('the superseding new ask fires the actionable seam (a genuinely new question is not lost)', () => {
+ const fired: string[] = []
+ const off = onInboxActionable((e) => fired.push(e.id))
+ vi.setSystemTime(0)
+ recordAgentEvent(ev({ state: 'waiting' }))
+ vi.setSystemTime(QUESTION_DEDUP_WINDOW_MS + 1)
+ recordAgentEvent(ev({ state: 'waiting' }))
+ off()
+ // Two distinct actionable events — the stale one did NOT swallow the new ask.
+ expect(fired).toHaveLength(2)
+ expect(new Set(fired).size).toBe(2)
+ })
+ })
+
it('session reset also resolves a pending question', () => {
recordAgentEvent(ev({ state: 'waiting', lastMessage: 'Pick one' }))
recordAgentEvent(ev({ kind: 'session', sessionPhase: 'end' }))
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index ceb1082c2..a8e63f880 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -209,6 +209,13 @@ export const INBOX_QUESTION_OPTIONS_MAX = 4
export const INBOX_OPTION_LABEL_MAX = 60
// Live-update `message` headline cap (needs-you / done event title).
export const LIVE_MESSAGE_MAX = 120
+// Bound on the approval/question TITLE-dedup (see produceInboxFromState). A live ask re-asserts
+// within seconds, so only an unresolved same-title event YOUNGER than this suppresses a re-assert.
+// An OLDER lingering same-title event — e.g. an unresolved generic-title "Waiting for input"
+// restored across a restart (loadPersisted keeps unresolved events verbatim), whose node never
+// re-passed the state-leave `resolveUnresolvedFor` — must NOT muzzle a genuinely NEW ask forever:
+// it is SUPERSEDED (resolved) and the new ask fires.
+export const QUESTION_DEDUP_WINDOW_MS = 10 * 60_000
export interface InboxEvent {
/** Monotonic per writer: `${ts}-${seq}`. */
@@ -1080,9 +1087,17 @@ function produceInboxFromState(
...(pendingId ? { pendingId } : {})
})
}
- // Dedup a re-asserted SAME ask (title match) — but always return the classification below so
- // the broadcast enrichment is consistent across the re-assert.
- if (newestUnresolved(inboxEvents, nodeId)?.title !== title) {
+ // Dedup a re-asserted SAME ask (title match) — BOUNDED (QUESTION_DEDUP_WINDOW_MS): only an
+ // unresolved same-title event still inside the window suppresses. A stale lingering same-title one
+ // (restored across a restart, or a long-abandoned turn) is SUPERSEDED — marked resolved so it
+ // stops muzzling — and the new ask fires. A different-title unresolved event never suppresses (a
+ // genuinely new ask) and is left untouched (it may still be pending). Always return the
+ // classification below so the broadcast enrichment stays consistent across the re-assert.
+ const dup = newestUnresolved(inboxEvents, nodeId)
+ const sameTitle = !!dup && dup.title === title
+ const freshDup = sameTitle && dup ? now - dup.ts < QUESTION_DEDUP_WINDOW_MS : false
+ if (!freshDup) {
+ if (sameTitle && dup) dup.resolved = true // supersede the stale same-title card
pushInboxEvent({
...baseEvent,
kind,
diff --git a/src/main/index.ts b/src/main/index.ts
index 452b9a2a4..5439d3479 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -43,6 +43,7 @@ import {
type MirrorSettings
} from '../core/agent-status-mirror'
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
+import { createAckSweeper } from '../core/ack-sweep'
import { getDeviceId } from '../core/device-id'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
@@ -1088,6 +1089,37 @@ app.whenReady().then(async () => {
corePlatform.handle(IPC.agentAckDone, (nodeId: string) => {
ackDone(nodeId)
})
+ // Phone→host read-acks (this feature, the other direction): the phone drops
+ // `~/.nodeterm/acks/<nodeId>.seen` on the SESSION host when it READS a finished session. For each
+ // ack: `ackDone` (mirror resolves the done event → phone Inbox archives it + the paired phone's
+ // DONE Live Activity dismisses) AND `agent:unread-clear` so the desktop renderer drops the node's
+ // unread flag WITHOUT re-acking (external clear — the ack already happened phone-side; a re-ack
+ // would loop). ONE 15s cadence drives BOTH: the LOCAL fs sweep (cheap dir-mtime gate) for
+ // local-project nodes, and a REMOTE sweep of each connected SSH project's host over its
+ // ControlMaster (a Mac→SSH node's acks land on the REMOTE fs, invisible to the local sweep).
+ // sshProjectManager is created below; the tick resolves it lazily.
+ const ackSweeper = createAckSweeper({
+ handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }
+ })
+ let remoteAckSweepBusy = false
+ const ackSweepTimer = setInterval(() => {
+ ackSweeper.sweep()
+ if (remoteAckSweepBusy || !sshProjectManager) return
+ remoteAckSweepBusy = true
+ void sshProjectManager
+ .sweepRemoteAcks()
+ .then((ids) => {
+ for (const id of ids) {
+ ackDone(id)
+ sendToMain(IPC.agentUnreadClear, id)
+ }
+ })
+ .catch(() => {})
+ .finally(() => {
+ remoteAckSweepBusy = false
+ })
+ }, 15_000)
+ ackSweepTimer.unref?.()
// Sweep stale request/answer files (~/.nodeterm/pending) on boot + hourly — orphans from killed
// sessions that never got an answer. Local only; a remote host runs its own sweep if it hosts
// nodeterm, else the files age out harmlessly.
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 05114aaa2..144a2cf1b 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -575,6 +575,46 @@ export class SshProjectManager {
.catch(() => {})
}
+ /**
+ * Sweep phone read-acks on the connected hosts (spec: cross-surface read sync). The phone drops
+ * `~/.nodeterm/acks/<nodeId>.seen` on the host it can reach; for a Mac→SSH node that host is the
+ * REMOTE one, so the desktop must consume them over the ControlMaster — the local-fs sweep never
+ * sees them. One command per connected HOST (deduped by host key, since projects sharing a host
+ * share `$HOME/.nodeterm/acks`) atomically lists + deletes each `.seen` and prints its nodeId; the
+ * returned ids are fed the SAME `ackDone` + unread-clear path a local ack takes. Best-effort — a
+ * disconnected/failed project simply contributes nothing. The command is fully literal (no
+ * interpolation), and the returned nodeIds are used only as in-memory map keys (never a path), so
+ * a compromised host can at worst clear an unread badge / resolve a done card it can guess.
+ */
+ async sweepRemoteAcks(): Promise<string[]> {
+ // List then delete each `~/.nodeterm/acks/*.seen`, printing the basename (nodeId). The `break` on
+ // a non-existent first match handles the no-glob case (the pattern stays literal when nothing
+ // matches). Absent dir ⇒ exit 0 (nothing swept).
+ const cmd =
+ 'd="$HOME/.nodeterm/acks"; [ -d "$d" ] || exit 0; ' +
+ 'for f in "$d"/*.seen; do [ -e "$f" ] || break; ' +
+ 'printf "%s\\n" "$(basename "$f" .seen)"; rm -f "$f"; done'
+ const seenHosts = new Set<string>()
+ const out: string[] = []
+ for (const c of this.conns.values()) {
+ const hk = sshHostKey(c.conn)
+ if (seenHosts.has(hk)) continue
+ seenHosts.add(hk)
+ try {
+ const { code, stdout } = await this.r.run(childArgs(c.conn, c.controlPath, cmd))
+ if (code === 0 && stdout) {
+ for (const line of stdout.split('\n')) {
+ const id = line.trim()
+ if (id) out.push(id)
+ }
+ }
+ } catch {
+ // best-effort per host — a failed sweep just leaves the acks for the next tick
+ }
+ }
+ return out
+ }
+
/**
* Deterministic hook-reply approvals (docs/hook-reply-approvals.md): write the one-line answer
* file for a held REMOTE permission hook, on the project's host over its ControlMaster (atomic
diff --git a/src/preload/index.ts b/src/preload/index.ts
index e66c6a1c0..92e082689 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -504,6 +504,11 @@ const api: NodeTerminalApi = {
ackDone: (nodeId) => {
void ipcRenderer.invoke(IPC.agentAckDone, nodeId)
},
+ onUnreadClear: (listener) => {
+ const handler = (_e: unknown, nodeId: string) => listener(nodeId)
+ ipcRenderer.on(IPC.agentUnreadClear, handler)
+ return () => ipcRenderer.removeListener(IPC.agentUnreadClear, handler)
+ },
onAgentStatus: (listener) => {
const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)
ipcRenderer.on(IPC.agentStatus, handler)
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 0b69c0e2a..18e503160 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -115,6 +115,7 @@ export function buildStubApi(): Omit<
| 'dialog'
| 'onAgentStatus'
| 'onSubagentActivity'
+ | 'onUnreadClear'
| 'answerPermission'
| 'ackDone'
// Real over the bridge (IPC.appUserDataDir): the worktree dialog's default path is derived from
@@ -332,6 +333,7 @@ export function buildStubApi(): Omit<
| 'dialog'
| 'onAgentStatus'
| 'onSubagentActivity'
+ | 'onUnreadClear'
| 'answerPermission'
| 'ackDone'
| 'userDataDir'
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index eda58c0d8..37e9bf8e1 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -415,9 +415,14 @@ export function buildFilesApi(
*/
export function buildAgentApi(
client: RpcClient
-): Pick<NodeTerminalApi, 'onAgentStatus' | 'onSubagentActivity' | 'answerPermission' | 'ackDone'> {
+): Pick<
+ NodeTerminalApi,
+ 'onAgentStatus' | 'onSubagentActivity' | 'onUnreadClear' | 'answerPermission' | 'ackDone'
+> {
return {
onAgentStatus: (listener) => client.subscribe(IPC.agentStatus, listener as Listener),
+ // Host swept a phone read-ack → drop this browser canvas's unread flag (external clear, no re-ack).
+ onUnreadClear: (listener) => client.subscribe(IPC.agentUnreadClear, listener as Listener),
onSubagentActivity: (listener) =>
client.subscribe(IPC.agentSubagentActivity, listener as Listener),
// Deterministic hook-reply approvals: a real request over the bridge — the Server Edition runs
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 5d227c7b6..d695fc230 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -5208,6 +5208,15 @@ export function Canvas() {
[]
)
+ // Phone→host read-ack: the host swept a `~/.nodeterm/acks/<nodeId>.seen` (the phone READ this
+ // node's finished session), so drop the node's unread flag here too. `external: true` so this
+ // clear does NOT re-ack — the ack already happened on the phone side; a re-ack would loop
+ // host→renderer→ackDone. See core/ack-sweep.ts.
+ useEffect(
+ () => api.onUnreadClear((nodeId) => useAgentStatus.getState().clearUnread(nodeId, { external: true })),
+ []
+ )
+
// Agent lifecycle, reported by each agent's own hooks via the main-process hook server
// (`main/agents/hook-server.ts`) and mapped to the shared 4-state model by the per-agent
// normalizers (`shared/agents/normalize.ts`): working / waiting / blocked / done. On a turn
diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.ts
index a3a6d65b6..8e62ff135 100644
--- a/src/renderer/state/agentStatus.test.ts
+++ b/src/renderer/state/agentStatus.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
useAgentStatus,
+ createAgentStatusSession,
inferInterruptAfterSettle,
DONE_HOLDOFF_MS,
STALE_WORKING_MS
@@ -106,3 +107,38 @@ describe('interrupt inference (Esc/Ctrl-C with no final hook)', () => {
expect(useAgentStatus.getState().byId[id].state).toBe('done')
})
})
+
+describe('clearUnread — cross-surface ack vs. external (host-driven) clear', () => {
+ it('a normal clear of a done+unread node ACKs the read (dismisses the phone activity)', () => {
+ const acked: string[] = []
+ const { store } = createAgentStatusSession(undefined, (id) => acked.push(id))
+ const id = 'nt-1'
+ store.getState().setState(id, 'done', 'claude')
+ store.getState().markUnread(id)
+ store.getState().clearUnread(id)
+ expect(store.getState().byId[id].unread).toBe(false)
+ expect(acked).toEqual(['nt-1'])
+ })
+
+ it('an EXTERNAL clear (driven by a swept phone read-ack) does NOT re-ack — no loop', () => {
+ const acked: string[] = []
+ const { store } = createAgentStatusSession(undefined, (id) => acked.push(id))
+ const id = 'nt-2'
+ store.getState().setState(id, 'done', 'claude')
+ store.getState().markUnread(id)
+ store.getState().clearUnread(id, { external: true })
+ expect(store.getState().byId[id].unread).toBe(false)
+ // The ack already happened phone-side; re-acking here would loop host→renderer→ackDone.
+ expect(acked).toEqual([])
+ })
+
+ it('a non-done unread clear never acks (regardless of the external flag)', () => {
+ const acked: string[] = []
+ const { store } = createAgentStatusSession(undefined, (id) => acked.push(id))
+ const id = 'nt-3'
+ store.getState().setState(id, 'working', 'claude')
+ store.getState().markUnread(id)
+ store.getState().clearUnread(id)
+ expect(acked).toEqual([])
+ })
+})
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index c52629b35..b2a6c21c3 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -89,7 +89,13 @@ export interface AgentStatusStore {
setSession(id: string, session: string): void
setSessionId(id: string, sessionId: string): void
markUnread(id: string): void
- clearUnread(id: string): void
+ /**
+ * Drop a node's unread flag. By default a clear of a FINISHED (done) node also ACKs the read
+ * cross-surface (dismisses the paired phone's DONE Live Activity via the mirror's `ackDone`).
+ * Pass `{ external: true }` for a clear that was ITSELF driven by a phone read-ack the host swept
+ * (`agent:unread-clear`): it must NOT re-ack, or host→renderer→ackDone would loop.
+ */
+ clearUnread(id: string, opts?: { external?: boolean }): void
/** Start (active=true, resets) or stop a /loop, /schedule or /cron indicator. */
setLoop(
id: string,
@@ -296,7 +302,7 @@ export function createAgentStatusSession(
return { byId }
}),
- clearUnread: (id) =>
+ clearUnread: (id, opts) =>
set((s) => {
const prev = s.byId[id]
if (!prev?.unread) return s
@@ -305,7 +311,9 @@ export function createAgentStatusSession(
// on the node's LATEST state being `done` — a working-state focus (unread from an earlier
// turn while a new turn is now live) must not ack. Fire-and-forget; the mirror no-ops when
// there is no unresolved done event, so a stray call is harmless + idempotent.
- if (prev.state === 'done') ackDone?.(id)
+ // SUPPRESSED for an `external` clear — one the host drove FROM a phone read-ack it swept
+ // (`agent:unread-clear`): re-acking here would loop host→renderer→ackDone straight back.
+ if (prev.state === 'done' && !opts?.external) ackDone?.(id)
const byId = { ...s.byId, [id]: { ...prev, unread: false } }
save(byId)
return { byId }
diff --git a/src/server/index.ts b/src/server/index.ts
index 0e242f02e..a9f0d26fa 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -39,6 +39,7 @@ import {
} from '../core/agent-status-mirror'
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
+import { createAckSweeper } from '../core/ack-sweep'
import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
@@ -282,6 +283,17 @@ export async function startServer(
platform.handle(IPC.agentAckDone, (nodeId: string) => {
ackDone(nodeId)
})
+ // Phone→host read-acks: the phone drops `~/.nodeterm/acks/<nodeId>.seen` on this host when it READS
+ // a finished session. Sweep it (15s cadence, cheap dir-mtime gate) and for each ack: `ackDone`
+ // (mirror resolve + phone Live-Activity dismiss) + broadcast `agent:unread-clear` so the browser
+ // canvas drops the node's unread flag WITHOUT re-acking. Local fs only — the Server Edition has no
+ // SSH projects (v1); a host it hosts writes its own acks here. See core/ack-sweep.ts.
+ createAckSweeper({
+ handlers: {
+ ackDone,
+ onUnreadClear: (nodeId) => platform.broadcast(IPC.agentUnreadClear, nodeId)
+ }
+ }).start()
// Sweep stale ~/.nodeterm/pending files on boot + hourly (orphans from killed sessions).
startPendingSweep(os.homedir())
// Phone push via SSH-possession GRANTS (spec: nodeterm-server/docs/specs/2026-07-21-push-grants.md).
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index f1fe04e3d..35141fd4a 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -43,6 +43,11 @@ export const IPC = {
* node's done inbox event(s) + dismisses the paired phone's lingering DONE Live Activity. Arg:
* `nodeId: string`. Fire-and-forget. See agent-status-mirror `ackDone`. */
agentAckDone: 'agent:ack-done',
+ /** main/server → renderer: drop the unread flag for a node because the phone READ its finished
+ * session (a `~/.nodeterm/acks/<nodeId>.seen` the host swept). Arg: `nodeId: string`. The
+ * renderer clears unread WITHOUT re-acking (external clear — see agentStatus.clearUnread's
+ * `external` opt). See core/ack-sweep.ts. */
+ agentUnreadClear: 'agent:unread-clear',
agentSubagentActivity: 'agent:subagent-activity',
agentControl: 'agent:control',
agentControlResult: 'agent:control-result',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 7b75830d6..22048b185 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1630,6 +1630,11 @@ export interface NodeTerminalApi {
* paired phone dismisses its lingering DONE Live Activity. Fire-and-forget; no-op if the node has
* no unresolved done event. */
ackDone(nodeId: string): void
+ /** Fires when the host swept a phone read-ack (`~/.nodeterm/acks/<nodeId>.seen`) for a finished
+ * session: the renderer should drop the node's unread flag WITHOUT re-acking (call
+ * `clearUnread(id, { external: true })`, so it does not loop back into `ackDone`). Arg is the
+ * node id. Returns unsubscribe. See core/ack-sweep.ts. */
+ onUnreadClear(listener: (nodeId: string) => void): () => void
/** Fires on each normalized agent hook event (working/done/waiting/subagent/…). Returns unsubscribe. */
onAgentStatus(listener: (e: NormalizedAgentEvent) => void): () => void
/** Fires with live subagent transcript chunks while a subagent runs. Returns unsubscribe. */