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.

fix(mirror): restarts neither re-push done events nor kill tmux sessions

enes6e08a36323e8
diff --git a/scripts/install-server.sh b/scripts/install-server.sh
index c7decb624..a60c3e549 100755
--- a/scripts/install-server.sh
+++ b/scripts/install-server.sh
@@ -218,6 +218,12 @@ Environment=NODETERM_HEADLESS=1
ExecStart=$NODE_BIN $APP_DIR/out/server/main.cjs
Restart=on-failure
RestartSec=5
+# KillMode=process is LOAD-BEARING: the default control-group kill would SIGTERM every
+# process the service ever spawned — including the tmux server holding the user's live
+# agent sessions — so each restart (installer re-run, the nightly auto-update timer)
+# silently killed every session and their resumed turns re-emitted duplicate done
+# notifications. Only the node process dies on restart; tmux and its sessions survive.
+KillMode=process
# Logs go to journald (journalctl); StandardOutput/Error default to journal.
[Install]
diff --git a/src/core/agent-status-mirror.restart.test.ts b/src/core/agent-status-mirror.restart.test.ts
new file mode 100644
index 000000000..377e06fe1
--- /dev/null
+++ b/src/core/agent-status-mirror.restart.test.ts
@@ -0,0 +1,130 @@
+// Restart-survival of the agent-status mirror's dedup (field bug: THREE identical "Finished —
+// <same lastMessage>" APNs pushes, one per Server-Edition restart). The dedup used to live only in
+// memory, so every boot re-armed it and a re-produced `done` re-fired `onInboxActionable` → the
+// push service. These tests SERIALIZE the mirror to a temp file, throw away all module state
+// (fresh process), re-`initAgentStatusMirror` at the same file, and assert that a re-arriving
+// IDENTICAL done/needs-you fires NO new actionable event — while a genuinely new turn still does.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import type { NormalizedAgentEvent } from '@shared/agents/normalize'
+import {
+ recordAgentEvent,
+ recordRawToolEvent,
+ flush,
+ initAgentStatusMirror,
+ onInboxActionable,
+ _resetForTest,
+ _inboxSnapshot,
+ _snapshot,
+ type InboxEvent
+} from './agent-status-mirror'
+
+function ev(partial: Partial<NormalizedAgentEvent>): NormalizedAgentEvent {
+ return { nodeId: 'n1', agentId: 'claude', kind: 'state', ...partial } as NormalizedAgentEvent
+}
+
+let dir: string
+let file: string
+
+beforeEach(() => {
+ _resetForTest()
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-mirror-restart-'))
+ file = path.join(dir, 'agent-status.json')
+})
+
+afterEach(() => {
+ _resetForTest()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+/** Serialize the live mirror to disk, then simulate a full process restart: drop ALL module state
+ * and re-init pointing at the same file (which triggers loadPersisted). */
+async function restart(): Promise<void> {
+ initAgentStatusMirror(file)
+ await flush()
+ _resetForTest()
+ initAgentStatusMirror(file)
+}
+
+/** Collect actionable inbox events fired AFTER this point. */
+function captureActionable(): InboxEvent[] {
+ const got: InboxEvent[] = []
+ onInboxActionable((e) => got.push(e))
+ return got
+}
+
+describe('agent-status mirror — restart survival of the done dedup', () => {
+ it('does NOT re-fire an identical done after a restart (the duplicate-APNs bug)', async () => {
+ initAgentStatusMirror(file)
+ // A turn runs and finishes → one done, one actionable fire (the legit push).
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'done', lastMessage: 'Araştırma tamam.' }))
+
+ await restart()
+
+ // Post-restart the node's main state is restored to `done`…
+ expect(_snapshot().n1?.state).toBe('done')
+
+ const got = captureActionable()
+ // …so the cold-restore's `claude --resume` re-emitting the SAME Stop is a no-op edge.
+ recordAgentEvent(ev({ state: 'done', lastMessage: 'Araştırma tamam.' }))
+ expect(got).toHaveLength(0)
+
+ // And the feed did not grow a duplicate — still exactly one done.
+ const dones = _inboxSnapshot().events.filter((e) => e.kind === 'done')
+ expect(dones).toHaveLength(1)
+ })
+
+ it('STILL fires done for a genuinely new turn after a restart', async () => {
+ initAgentStatusMirror(file)
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'done', lastMessage: 'First answer.' }))
+
+ await restart()
+
+ const got = captureActionable()
+ // A real new turn (UserPromptSubmit → working) re-arms the done edge…
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'done', lastMessage: 'Second answer.' }))
+ // …so this legit finish fires.
+ const dones = got.filter((e) => e.kind === 'done')
+ expect(dones).toHaveLength(1)
+ expect(dones[0].detail).toBe('Second answer.')
+ })
+
+ it('does NOT re-push an identical approval after a restart (needs-you class)', async () => {
+ initAgentStatusMirror(file)
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ // A permission summary stash + the blocked edge → one approval.
+ recordRawToolEvent('n1', {
+ hook_event_name: 'PermissionRequest',
+ tool_name: 'Bash',
+ tool_input: { command: 'rm -rf /tmp/x' }
+ })
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Run command' }))
+
+ await restart()
+
+ const got = captureActionable()
+ // The same still-open approval re-asserting (re-stash + blocked) must not re-fire: the feed's
+ // newestUnresolved title survived the restart.
+ recordRawToolEvent('n1', {
+ hook_event_name: 'PermissionRequest',
+ tool_name: 'Bash',
+ tool_input: { command: 'rm -rf /tmp/x' }
+ })
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Run command' }))
+ expect(got).toHaveLength(0)
+ expect(_inboxSnapshot().events.filter((e) => e.kind === 'approval')).toHaveLength(1)
+ })
+
+ it('is fail-open: a corrupt persisted file leaves memory empty (legacy behavior)', () => {
+ fs.writeFileSync(file, '{ this is not json ')
+ // Must not throw at boot.
+ expect(() => initAgentStatusMirror(file)).not.toThrow()
+ expect(Object.keys(_snapshot())).toHaveLength(0)
+ expect(_inboxSnapshot().events).toHaveLength(0)
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 23838c388..ceb1082c2 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -849,11 +849,92 @@ export function onMirrorFlush(cb: (doc: MirrorFile) => void): () => void {
}
/**
- * Point the mirror at its file. Called once from main on launch; the path defaults to
- * `<userData>/agent-status.json`. Tests pass an explicit path (and thus never touch electron).
+ * Restore the persisted mirror doc into memory WITHOUT firing any seam. This is what makes the
+ * in-memory dedups survive a process RESTART.
+ *
+ * Field bug (owner screenshot): THREE identical "Finished — <same lastMessage>" APNs pushes, one
+ * per Server-Edition restart. Root cause: the mirror kept ALL its dedup in memory only, so every
+ * boot started with an empty `state` map + empty `inboxEvents`. Because the headless service is
+ * `Type=simple` (KillMode=control-group), a `systemctl restart` SIGTERMs the whole cgroup — the
+ * app's tmux server included — so its sessions die; each reconnect then cold-restores the node and
+ * re-launches `claude --resume`, whose completed turn re-emits `Stop` → a `done` carrying the SAME
+ * `last_assistant_message`. With `prevState === undefined` after boot, `produceInboxFromState`'s
+ * done-EDGE guard (`nextState === 'done' && prevState !== 'done'`) always fired, re-producing the
+ * done and re-firing `onInboxActionable` → the duplicate push (and, come the nightly auto-update
+ * timer, a nightly duplicate for every lingering done).
+ *
+ * Restoring `state` so `prevState` survives makes the done-edge guard suppress an identical
+ * re-`done` on its own; restoring `inboxEvents` makes the approval/question title-dedup
+ * (`newestUnresolved`) survive too, closing the same class for needs-you re-pushes. A restored
+ * state is NOT a new event — this NEVER calls a listener, so no push/live-update fires on boot.
+ * Fail-open: a missing / unreadable / corrupt file leaves memory empty, i.e. bit-for-bit legacy
+ * behavior. Stale entries are dropped with the SAME expiry sweep `buildFile`/`flush` apply, so a
+ * "working" from a long-dead session is never resurrected.
+ */
+function loadPersisted(file: string): void {
+ // Only seed empty memory — never clobber a live session (init runs once at boot, but guard so a
+ // stray re-init can't wipe in-flight state).
+ if (state.size > 0 || inboxEvents.length > 0) return
+ let doc: MirrorFile
+ try {
+ doc = JSON.parse(fs.readFileSync(file, 'utf-8')) as MirrorFile
+ } catch {
+ return // missing / unreadable / corrupt → empty (legacy behavior)
+ }
+ if (!doc || typeof doc !== 'object') return
+ const now = Date.now()
+ try {
+ // Main per-node state — apply the same expiry as buildFile so a stale "working" from a crashed
+ // session isn't resurrected past its window. This is what lets `prevState` survive the restart.
+ if (doc.nodes && typeof doc.nodes === 'object') {
+ for (const [id, e] of Object.entries(doc.nodes)) {
+ if (!e || typeof e !== 'object') continue
+ const updatedAt = typeof e.updatedAt === 'number' ? e.updatedAt : 0
+ if (now - updatedAt > EXPIRE_MS) continue
+ state.set(id, { state: e.state, agentId: e.agentId, sessionId: e.sessionId, updatedAt })
+ }
+ }
+ // Inbox feed — restore verbatim (already capped + carries `resolved` flags) so the
+ // approval/question title-dedup and the done-history survive. Ids continue monotonically from
+ // the max trailing `-<n>` seen (they are `${ts}-${seq}`; ts differs after a restart, so a
+ // collision is unlikely, but continuing the seq keeps them clean).
+ if (doc.inbox && Array.isArray(doc.inbox.events)) {
+ let events = doc.inbox.events.filter(
+ (e): e is InboxEvent => !!e && typeof e === 'object' && typeof e.id === 'string'
+ )
+ if (events.length > INBOX_EVENTS_CAP) events = events.slice(events.length - INBOX_EVENTS_CAP)
+ inboxEvents = events
+ let maxSeq = 0
+ for (const e of inboxEvents) {
+ const m = /-(\d+)$/.exec(e.id)
+ if (m) maxSeq = Math.max(maxSeq, Number(m[1]))
+ }
+ inboxSeq = maxSeq
+ }
+ // Per-node "doing now" — restore fresh entries only (same expiry as flush()).
+ if (doc.inbox && doc.inbox.nodes && typeof doc.inbox.nodes === 'object') {
+ for (const [id, n] of Object.entries(doc.inbox.nodes)) {
+ if (!n || typeof n !== 'object') continue
+ const updatedAt = typeof n.updatedAt === 'number' ? n.updatedAt : 0
+ if (now - updatedAt > EXPIRE_MS) continue
+ inboxNodes.set(id, n)
+ }
+ }
+ } catch {
+ // Any shape surprise → keep whatever restored so far (fail-open, never throw at boot).
+ }
+}
+
+/**
+ * Point the mirror at its file and RESTORE its persisted state into memory. Called once from each
+ * shell on launch; the path defaults to `<userData>/agent-status.json`. Tests pass an explicit path
+ * (and thus never touch electron). The restore (see `loadPersisted`) is what makes the in-memory
+ * dedups survive a restart — without it, a re-produced `done` re-fires the push (the duplicate-APNs
+ * field bug).
*/
export function initAgentStatusMirror(filePath?: string): void {
targetFile = filePath ?? path.join(platform().userDataDir, 'agent-status.json')
+ loadPersisted(targetFile)
}
function resolveFile(): string | null {