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(agent-status): mirror each SSH project's agent status onto its host

enesb7a24b83627e
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 6c19acfb7..732179c8d 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -6,6 +6,8 @@ import type { NormalizedAgentEvent } from '@shared/agents/normalize'
import {
reduceEntry,
buildFile,
+ filterMirrorForNodes,
+ onMirrorFlush,
recordAgentEvent,
clearNode,
flush,
@@ -14,7 +16,8 @@ import {
_snapshot,
DONE_HOLDOFF_MS,
EXPIRE_MS,
- type MirrorEntry
+ type MirrorEntry,
+ type MirrorFile
} from './agent-status-mirror'
// Minimal event factory — only the fields the reducer reads.
@@ -172,4 +175,51 @@ describe('recordAgentEvent + atomic write', () => {
const doc = JSON.parse(fs.readFileSync(file, 'utf-8'))
expect(Object.keys(doc.nodes)).toEqual(['b'])
})
+
+ it('onMirrorFlush delivers the built doc on every flush; unsubscribe stops it', async () => {
+ const seen: MirrorFile[] = []
+ const off = onMirrorFlush((doc) => seen.push(doc))
+ recordAgentEvent(ev({ nodeId: 'n1', state: 'working' }))
+ await flush()
+ expect(seen).toHaveLength(1)
+ expect(seen[0].nodes.n1.state).toBe('working')
+ off()
+ recordAgentEvent(ev({ nodeId: 'n1', state: 'done' }))
+ await flush()
+ expect(seen).toHaveLength(1)
+ })
+
+ it('onMirrorFlush still fires when the local disk write fails', async () => {
+ initAgentStatusMirror(path.join(dir, 'no-such-dir', 'x', 'agent-status.json'))
+ const seen: MirrorFile[] = []
+ onMirrorFlush((doc) => seen.push(doc))
+ recordAgentEvent(ev({ nodeId: 'n1', state: 'working' }))
+ await flush()
+ expect(seen).toHaveLength(1)
+ })
+})
+
+describe('filterMirrorForNodes', () => {
+ it('keeps only the given node ids, preserving header fields', () => {
+ const doc: MirrorFile = {
+ v: 1,
+ updatedAt: 99,
+ nodes: {
+ a: { state: 'working', updatedAt: 1 },
+ b: { state: 'done', updatedAt: 2 },
+ c: { updatedAt: 3 }
+ }
+ }
+ const out = filterMirrorForNodes(doc, new Set(['b', 'c', 'ghost']))
+ expect(out.v).toBe(1)
+ expect(out.updatedAt).toBe(99)
+ expect(Object.keys(out.nodes).sort()).toEqual(['b', 'c'])
+ expect(out.nodes.b.state).toBe('done')
+ })
+
+ it('does not mutate the input doc', () => {
+ const doc: MirrorFile = { v: 1, updatedAt: 1, nodes: { a: { updatedAt: 1 } } }
+ filterMirrorForNodes(doc, new Set())
+ expect(Object.keys(doc.nodes)).toEqual(['a'])
+ })
})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 8a8f19d7d..fd49f5f9b 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -91,6 +91,17 @@ export function reduceEntry(
return next
}
+/**
+ * Restrict a mirror doc to the given node ids. Pure. Used by the SSH-host status push: each
+ * connected host receives ONLY its own project's nodes — the full mirror would leak other
+ * projects' node/session ids to every host the user is connected to.
+ */
+export function filterMirrorForNodes(doc: MirrorFile, nodeIds: ReadonlySet<string>): MirrorFile {
+ const nodes: MirrorFile['nodes'] = {}
+ for (const [id, e] of Object.entries(doc.nodes)) if (nodeIds.has(id)) nodes[id] = e
+ return { v: doc.v, updatedAt: doc.updatedAt, nodes }
+}
+
/** Prune expired entries and shape the on-disk file. Pure; `now` injected for testability. */
export function buildFile(
nodes: Record<string, MirrorEntry>,
@@ -113,6 +124,17 @@ const state = new Map<string, MirrorEntry>()
let targetFile: string | null = null
let writeTimer: NodeJS.Timeout | null = null
let writeSeq = 0
+const flushListeners = new Set<(doc: MirrorFile) => void>()
+
+/**
+ * Subscribe to every flush's built doc (fires even when the local disk write fails — the doc is
+ * the product, the file is one consumer of it). Returns an unsubscribe. Feeds the SSH-host
+ * status push, which mirrors each connected project's slice of this doc onto its host.
+ */
+export function onMirrorFlush(cb: (doc: MirrorFile) => void): () => void {
+ flushListeners.add(cb)
+ return () => flushListeners.delete(cb)
+}
/**
* Point the mirror at its file. Called once from main on launch; the path defaults to
@@ -162,6 +184,13 @@ export async function flush(): Promise<void> {
const doc = buildFile(Object.fromEntries(state), now)
// Also drop expired entries from memory so the map itself can't grow without bound.
for (const [id, e] of state) if (now - e.updatedAt > EXPIRE_MS) state.delete(id)
+ for (const cb of flushListeners) {
+ try {
+ cb(doc)
+ } catch {
+ // A listener must never break the local write (or its sibling listeners).
+ }
+ }
const tmp = `${file}.${process.pid}.${++writeSeq}.tmp`
try {
await fs.promises.writeFile(tmp, JSON.stringify(doc), { mode: 0o600 })
@@ -173,12 +202,13 @@ export async function flush(): Promise<void> {
// ---- Test helpers --------------------------------------------------------------------------
-/** Reset all module state (in-memory map + config). Test-only. */
+/** Reset all module state (in-memory map + config + listeners). Test-only. */
export function _resetForTest(): void {
state.clear()
targetFile = null
if (writeTimer) clearTimeout(writeTimer)
writeTimer = null
+ flushListeners.clear()
}
/** Snapshot the in-memory map. Test-only. */
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 140e2875c..cf50cd044 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -359,6 +359,13 @@ export class WorkspaceStore {
return (this.index?.entries ?? []).filter((e) => e.ssh).map((e) => e.id)
}
+ /** Node ids of an ssh project's cached file — the slice of the agent-status mirror its host
+ * receives (see remote-status-push.ts). Empty when the project isn't an ssh entry. */
+ sshProjectNodeIds(projectId: string): Set<string> {
+ const e = this.index?.entries.find((x) => x.id === projectId && x.ssh)
+ return new Set((e?.cache?.nodes ?? []).map((n) => n.id))
+ }
+
/** A throttled trailing mirror write was acked but later dropped (connection died inside the
* throttle window): re-owe it so the next save retries. Wired from makeRemoteWorkspaceIO. */
markUnmirrored(projectId: string): void {
diff --git a/src/main/index.ts b/src/main/index.ts
index 81853194b..af703c3e0 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -17,7 +17,13 @@ import { initUpdater } from './updater'
import { fetchCheck } from '../core/check'
import { hookServer } from '../core/agents/hook-server'
import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose } from './main-window'
-import { initAgentStatusMirror, recordAgentEvent } from '../core/agent-status-mirror'
+import {
+ initAgentStatusMirror,
+ onMirrorFlush,
+ flush as flushAgentStatusMirror,
+ recordAgentEvent
+} from '../core/agent-status-mirror'
+import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
import { retainUntilDismissed } from './notifications'
import { installManagedAgentHooks } from '../core/agents/hooks'
@@ -614,6 +620,18 @@ app.whenReady().then(async () => {
})
// Mirror live agent status to <userData>/agent-status.json for the external mobile host agent.
initAgentStatusMirror()
+ // And push each connected SSH project's slice of it onto its host
+ // (`~/.nodeterm/agent-status-<projectId>.json`): hook events tunnel from the host to THIS
+ // process, so that file is the only agent-status source a phone browsing the host directly
+ // can read. sshProjectManager is created below — the closures look it up per call.
+ initRemoteStatusPush({
+ onFlush: onMirrorFlush,
+ flush: flushAgentStatusMirror,
+ sshProjectIds: () => workspaceStore.sshProjectIds(),
+ nodeIdsFor: (projectId) => workspaceStore.sshProjectNodeIds(projectId),
+ push: (projectId, json) =>
+ sshProjectManager ? sshProjectManager.pushAgentStatus(projectId, json) : Promise.resolve()
+ })
// Canvas sync: the same reflector the Server Edition boots. With a single window clientIds()
// returns one id, so on the desktop today it is a no-op — wired for parity (and for the
// relay-host / multi-window futures), not because Electron needs it right now.
diff --git a/src/main/remote-ssh/remote-status-push.test.ts b/src/main/remote-ssh/remote-status-push.test.ts
new file mode 100644
index 000000000..8f165fd92
--- /dev/null
+++ b/src/main/remote-ssh/remote-status-push.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import type { MirrorFile } from '../../core/agent-status-mirror'
+import { initRemoteStatusPush } from './remote-status-push'
+
+function doc(updatedAt: number, ids: string[]): MirrorFile {
+ const nodes: MirrorFile['nodes'] = {}
+ for (const id of ids) nodes[id] = { state: 'working', updatedAt }
+ return { v: 1, updatedAt, nodes }
+}
+
+describe('initRemoteStatusPush', () => {
+ let flushCb: ((d: MirrorFile) => void) | null
+ let pushes: Array<{ id: string; json: string }>
+ let disposer: { dispose: () => void } | null
+
+ const deps = (over: Partial<Parameters<typeof initRemoteStatusPush>[0]> = {}) => ({
+ onFlush: (cb: (d: MirrorFile) => void) => {
+ flushCb = cb
+ return () => {
+ flushCb = null
+ }
+ },
+ flush: vi.fn(async () => flushCb?.(doc(Date.now(), ['a1']))),
+ sshProjectIds: () => ['p1'],
+ nodeIdsFor: () => new Set(['a1']),
+ push: async (id: string, json: string) => {
+ pushes.push({ id, json })
+ },
+ heartbeatMs: 0,
+ ...over
+ })
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ flushCb = null
+ pushes = []
+ disposer = null
+ })
+
+ afterEach(() => {
+ disposer?.dispose()
+ vi.useRealTimers()
+ })
+
+ it('pushes each project its own filtered slice on flush', () => {
+ disposer = initRemoteStatusPush(
+ deps({
+ sshProjectIds: () => ['p1', 'p2'],
+ nodeIdsFor: (id) => new Set(id === 'p1' ? ['a1'] : ['b1'])
+ })
+ )
+ flushCb!(doc(1000, ['a1', 'b1', 'other']))
+ expect(pushes).toHaveLength(2)
+ const p1 = JSON.parse(pushes.find((p) => p.id === 'p1')!.json)
+ expect(Object.keys(p1.nodes)).toEqual(['a1'])
+ const p2 = JSON.parse(pushes.find((p) => p.id === 'p2')!.json)
+ expect(Object.keys(p2.nodes)).toEqual(['b1'])
+ })
+
+ it('throttles a burst into leading + one trailing push with the LATEST doc', () => {
+ disposer = initRemoteStatusPush(deps({ throttleMs: 2000 }))
+ flushCb!(doc(1, ['a1']))
+ flushCb!(doc(2, ['a1']))
+ flushCb!(doc(3, ['a1']))
+ expect(pushes).toHaveLength(1)
+ expect(JSON.parse(pushes[0].json).updatedAt).toBe(1)
+ vi.advanceTimersByTime(2000)
+ expect(pushes).toHaveLength(2)
+ expect(JSON.parse(pushes[1].json).updatedAt).toBe(3)
+ })
+
+ it('a quiet window ends the throttle without a redundant trailing push', () => {
+ disposer = initRemoteStatusPush(deps({ throttleMs: 2000 }))
+ flushCb!(doc(1, ['a1']))
+ vi.advanceTimersByTime(2000)
+ expect(pushes).toHaveLength(1)
+ // Next flush after the window pushes immediately again (leading edge restored).
+ flushCb!(doc(9, ['a1']))
+ expect(pushes).toHaveLength(2)
+ })
+
+ it('heartbeat triggers mirror flushes on the interval', () => {
+ const d = deps({ heartbeatMs: 60_000 })
+ disposer = initRemoteStatusPush(d)
+ expect(d.flush).not.toHaveBeenCalled()
+ vi.advanceTimersByTime(60_000)
+ expect(d.flush).toHaveBeenCalledTimes(1)
+ vi.advanceTimersByTime(120_000)
+ expect(d.flush).toHaveBeenCalledTimes(3)
+ })
+
+ it('dispose unsubscribes and stops timers', () => {
+ const d = deps({ heartbeatMs: 60_000, throttleMs: 2000 })
+ disposer = initRemoteStatusPush(d)
+ flushCb?.(doc(1, ['a1']))
+ disposer.dispose()
+ disposer = null
+ expect(flushCb).toBeNull()
+ vi.advanceTimersByTime(300_000)
+ expect(d.flush).not.toHaveBeenCalled()
+ expect(pushes).toHaveLength(1)
+ })
+})
diff --git a/src/main/remote-ssh/remote-status-push.ts b/src/main/remote-ssh/remote-status-push.ts
new file mode 100644
index 000000000..baa4ceab9
--- /dev/null
+++ b/src/main/remote-ssh/remote-status-push.ts
@@ -0,0 +1,80 @@
+import type { MirrorFile } from '../../core/agent-status-mirror'
+import { filterMirrorForNodes } from '../../core/agent-status-mirror'
+
+/**
+ * Pushes each connected SSH project's slice of the agent-status mirror onto its host, where the
+ * mobile companion reads it (`~/.nodeterm/agent-status-<projectId>.json`). This file is the ONLY
+ * status source that exists on an SSH host: hook events tunnel from the host to the desktop's
+ * loopback hook server, so without this push a phone browsing the host directly sees live tmux
+ * sessions but no agent states.
+ *
+ * Electron-free and dependency-injected so the throttle/heartbeat behavior is unit-testable;
+ * index.ts wires the real mirror, workspace store and SshProjectManager in.
+ */
+
+/** Floor between two pushes to one project — a busy turn flushes the mirror every ~300 ms. */
+export const STATUS_PUSH_THROTTLE_MS = 2_000
+/**
+ * The mirror only flushes on agent events, so a pushed file's `updatedAt` goes stale the moment
+ * the desktop disconnects or quits — indistinguishable from an idle-but-connected desktop. The
+ * heartbeat re-flushes (fresh `updatedAt`) so the phone can treat a stale file as "no data".
+ */
+export const STATUS_HEARTBEAT_MS = 60_000
+
+interface Deps {
+ /** Subscribe to mirror flushes (agent-status-mirror's onMirrorFlush). Returns unsubscribe. */
+ onFlush: (cb: (doc: MirrorFile) => void) => () => void
+ /** Trigger a mirror flush — the heartbeat rides the normal flush path so listeners fire. */
+ flush: () => Promise<void>
+ /** SSH project ids of the workspace index (pushAgentStatus no-ops for unconnected ones). */
+ sshProjectIds: () => string[]
+ /** Node ids belonging to one project — its slice of the mirror. */
+ nodeIdsFor: (projectId: string) => ReadonlySet<string>
+ /** Write one project's slice to its host. Best-effort (failures only stale the phone). */
+ push: (projectId: string, json: string) => Promise<void>
+ throttleMs?: number
+ /** 0 disables the heartbeat (tests drive flushes explicitly). */
+ heartbeatMs?: number
+}
+
+export function initRemoteStatusPush(deps: Deps): { dispose: () => void } {
+ const throttleMs = deps.throttleMs ?? STATUS_PUSH_THROTTLE_MS
+ let latest: MirrorFile | null = null
+ const timers = new Map<string, NodeJS.Timeout>()
+ const dirty = new Set<string>()
+
+ const pushProject = (id: string): void => {
+ if (!latest) return
+ const slice = filterMirrorForNodes(latest, deps.nodeIdsFor(id))
+ void deps.push(id, JSON.stringify(slice))
+ const t = setTimeout(() => {
+ timers.delete(id)
+ // A flush landed inside the window → trailing push so the final state always ships.
+ if (dirty.delete(id)) pushProject(id)
+ }, throttleMs)
+ t.unref?.()
+ timers.set(id, t)
+ }
+
+ const off = deps.onFlush((doc) => {
+ latest = doc
+ for (const id of deps.sshProjectIds()) {
+ if (timers.has(id)) dirty.add(id)
+ else pushProject(id)
+ }
+ })
+
+ const heartbeatMs = deps.heartbeatMs ?? STATUS_HEARTBEAT_MS
+ const hb = heartbeatMs > 0 ? setInterval(() => void deps.flush(), heartbeatMs) : null
+ hb?.unref?.()
+
+ return {
+ dispose: (): void => {
+ off()
+ if (hb) clearInterval(hb)
+ for (const t of timers.values()) clearTimeout(t)
+ timers.clear()
+ dirty.clear()
+ }
+ }
+}
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 80e5f2775..18a852add 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -160,6 +160,9 @@ export class SshProjectManager {
private remoteHooks: RemoteHooks
/** Per-manager counter mixed into each upload token so concurrent drops never collide. */
private uploadSeq = 0
+ /** Projects whose agent-status mirror was actually pushed — gates the disconnect cleanup so a
+ * transient folder-picker browse (never pushed) doesn't pay an extra rm round-trip. */
+ private statusPushed = new Set<string>()
constructor(private r: Runners) {
this.remoteHooks = new RemoteHooks({ run: r.run })
}
@@ -428,6 +431,40 @@ export class SshProjectManager {
return this.conns.get(projectId)?.remoteHome
}
+ /** Remote path of this project's pushed agent-status mirror (`~`-relative when the remote
+ * home never resolved — the shell expands it in the commands below). */
+ private statusFilePath(projectId: string, c: Conn): string {
+ const dir = c.remoteHome ? `${c.remoteHome}/.nodeterm` : '~/.nodeterm'
+ return `${dir}/agent-status-${projectId}.json`
+ }
+
+ /**
+ * Mirror this project's slice of the agent-status doc onto its host as
+ * `~/.nodeterm/agent-status-<projectId>.json` (atomic tmp+mv, 0600 via umask). This is the
+ * ONLY status source that exists on an SSH host — hook events tunnel from the host to the
+ * desktop's loopback hook server — so it's what the mobile companion reads when it browses
+ * the host directly. No-ops when the project isn't connected; best-effort otherwise (a failed
+ * write only means stale/absent badges on the phone).
+ */
+ async pushAgentStatus(projectId: string, json: string): Promise<void> {
+ const c = this.conns.get(projectId)
+ if (!c) return
+ const file = this.statusFilePath(projectId, c)
+ const q = quoteRemotePath(file)
+ const qTmp = quoteRemotePath(`${file}.tmp`)
+ this.statusPushed.add(projectId)
+ await this.r
+ .run(
+ childArgs(
+ c.conn,
+ c.controlPath,
+ `umask 077; mkdir -p ${quoteRemotePath(file.slice(0, file.lastIndexOf('/')))} && cat > ${qTmp} && mv -f ${qTmp} ${q}`
+ ),
+ json
+ )
+ .catch(() => {})
+ }
+
/**
* The resolved remote `$HOME` for the project owning this `controlPath`, if known. The hook
* raw-listener only has the node's `{ controlPath, conn }` (from `sshRemoteForNode`), so it
@@ -560,6 +597,15 @@ export class SshProjectManager {
async disconnect(projectId: string): Promise<void> {
const c = this.conns.get(projectId)
if (!c) return
+ // Remove the pushed agent-status mirror while the master is still alive: a file left behind
+ // would freeze the phone's badges at the last event (the heartbeat that lets the phone detect
+ // staleness dies with this connection). Best-effort.
+ if (this.statusPushed.delete(projectId)) {
+ const f = this.statusFilePath(projectId, c)
+ await this.r
+ .run(childArgs(c.conn, c.controlPath, `rm -f ${quoteRemotePath(f)} ${quoteRemotePath(`${f}.tmp`)}`))
+ .catch(() => {})
+ }
// Cancel the reverse hook tunnel (over the still-live master) BEFORE tearing the master down.
await this.remoteHooks.teardown(projectId, c.conn, c.controlPath)
void this.r.run(exitMasterArgs(c.conn, c.controlPath))