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(eco): make hibernation phone-compatible — SLEEPING on the mirror, wake on relay attach, phone viewers count as watched

enes2d95c629fec9
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 44f2f34bd..d7476686a 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -17,6 +17,7 @@ import {
flush,
initAgentStatusMirror,
setMirrorSettingsProvider,
+ setNodeHibernated,
setMirrorServerProvider,
setMirrorUsageProvider,
buildMirrorUsage,
@@ -2203,3 +2204,65 @@ describe('inbox event age prune (flush)', () => {
expect(_inboxSnapshot().events[0].resolved).toBeUndefined()
})
})
+
+describe('hibernated flag (Eco × phone — SLEEPING on external readers)', () => {
+ let dir: string
+ let file: string
+
+ beforeEach(() => {
+ _resetForTest()
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-status-hib-'))
+ file = path.join(dir, 'agent-status.json')
+ initAgentStatusMirror(file)
+ })
+ afterEach(() => {
+ _resetForTest()
+ fs.rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('buildFile carries hibernated and EXEMPTS a hibernated entry from expiry', () => {
+ const now = EXPIRE_MS + 100_000
+ const doc = buildFile(
+ {
+ // Hibernation IS hours of idleness — the staleness rule must not erase the flag.
+ sleeping: { agentId: 'claude', hibernated: true, updatedAt: now - EXPIRE_MS - 1 },
+ stale: { state: 'working', updatedAt: now - EXPIRE_MS - 1 }
+ },
+ now
+ )
+ expect(Object.keys(doc.nodes)).toEqual(['sleeping'])
+ expect(doc.nodes.sleeping.hibernated).toBe(true)
+ })
+
+ it('setNodeHibernated sets on an EXISTING entry, creates a minimal one for an unknown id, and clears', async () => {
+ recordAgentEvent(ev({ nodeId: 'known', state: 'done' }))
+ setNodeHibernated('known', true)
+ // Unknown id: a hibernated session is typically one the mirror expired (or one reported at
+ // boot before any hook event of this run) — exactly when the flag matters most.
+ setNodeHibernated('fresh-boot', true)
+ expect(_snapshot().known.hibernated).toBe(true)
+ expect(_snapshot()['fresh-boot'].hibernated).toBe(true)
+ await flush()
+ const doc = JSON.parse(fs.readFileSync(file, 'utf-8'))
+ expect(doc.nodes.known.hibernated).toBe(true)
+ expect(doc.nodes['fresh-boot'].hibernated).toBe(true)
+
+ setNodeHibernated('known', false)
+ expect(_snapshot().known.hibernated).toBeUndefined()
+ await flush()
+ const woken = JSON.parse(fs.readFileSync(file, 'utf-8'))
+ expect('hibernated' in woken.nodes.known).toBe(false)
+ // Clearing an unknown id stays a no-op (no phantom entry minted).
+ setNodeHibernated('never-seen', false)
+ expect(_snapshot()['never-seen']).toBeUndefined()
+ })
+
+ it('the flag survives the SessionEnd reset the /exit itself fires', () => {
+ recordAgentEvent(ev({ nodeId: 'n1', state: 'done', sessionId: 's1' }))
+ setNodeHibernated('n1', true)
+ // Eco types /exit → the CLI's SessionEnd hook resets the node to idle — the flag must ride.
+ recordAgentEvent(ev({ nodeId: 'n1', kind: 'session' }))
+ expect(_snapshot().n1.state).toBeUndefined()
+ expect(_snapshot().n1.hibernated).toBe(true)
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 4601a827e..b0028a32f 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -112,6 +112,19 @@ export interface MirrorEntry {
* describe a state it did not arrive with.
*/
idleInferred?: true
+ /**
+ * Eco hibernation: this node's CLI was `/exit`ed while nobody was looking; its tmux session and
+ * pane live on and the conversation comes back with the provider's `--resume`. The RENDERER owns
+ * the flag (`agentStatus.setHibernated`, persisted in its localStorage) and reports every change
+ * over `agent:hibernated` — the mirror only carries it, so an external reader (the phone) can
+ * render SLEEPING instead of an unexplained idle shell (`setNodeHibernated`). Present = true,
+ * absent = not hibernated — like `restored`/`idleInferred`, so old files keep their shape.
+ *
+ * A hibernated entry is EXEMPT from the expiry sweep: hibernation is precisely "idle for hours",
+ * so the 6 h staleness rule would erase the one durable fact this field exists to carry. The
+ * renderer re-reports its persisted set at boot, and a wake (or `clearNode`) drops the flag.
+ */
+ hibernated?: true
}
/** This host's Server-Edition install metadata (spec: server-update). Written by the installer
@@ -155,6 +168,8 @@ export interface MirrorFile {
sessionId?: string
/** The agent's own session name (see MirrorEntry.name). Absent until resolved. */
name?: string
+ /** Eco hibernation (see MirrorEntry.hibernated). Present = true; absent on old files. */
+ hibernated?: true
updatedAt: number
}
>
@@ -495,7 +510,9 @@ export function buildFile(
): MirrorFile {
const out: MirrorFile = { v: 1, updatedAt: now, nodes: {} }
for (const [id, e] of Object.entries(nodes)) {
- if (now - e.updatedAt > expireMs) continue
+ // A hibernated entry never expires: hibernation IS long idleness, so the staleness rule would
+ // erase exactly the durable fact the flag carries (see MirrorEntry.hibernated).
+ if (now - e.updatedAt > expireMs && !e.hibernated) continue
// Undefined fields drop out of JSON.stringify — an idle node keeps agentId/sessionId
// without a `state` key.
out.nodes[id] = {
@@ -503,6 +520,7 @@ export function buildFile(
agentId: e.agentId,
sessionId: e.sessionId,
...(e.name ? { name: e.name } : {}),
+ ...(e.hibernated ? { hibernated: true as const } : {}),
updatedAt: e.updatedAt
}
}
@@ -1115,12 +1133,16 @@ function loadPersisted(file: string): void {
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
+ // Hibernated entries survive the expiry, as in buildFile: hours of idleness is what the
+ // flag MEANS. (The renderer also re-reports its persisted set at boot — this restore just
+ // keeps the file honest in the window before that report lands.)
+ if (now - updatedAt > EXPIRE_MS && e.hibernated !== true) continue
state.set(id, {
state: e.state,
agentId: e.agentId,
sessionId: e.sessionId,
...(e.name ? { name: e.name } : {}),
+ ...(e.hibernated === true ? { hibernated: true as const } : {}),
updatedAt,
// Marked, and FORCED unverified whatever the file said. `buildFile` writes neither field
// — it is an allowlist, which is what keeps `stateVerified` off disk — but a file this
@@ -1603,6 +1625,29 @@ export function setNodeSessionName(nodeId: string, name: string): boolean {
return true
}
+/**
+ * Record (or clear) a node's Eco hibernation flag — the `agent:hibernated` cast's only writer.
+ * The renderer owns the flag; this is a mirror of it, like `terminalFocused` in main (see
+ * MirrorEntry.hibernated). Unlike `setNodeSessionName`, an UNKNOWN node id creates a minimal
+ * entry: a hibernated session is typically one the mirror has expired (hibernation is hours of
+ * idleness) or one reported at boot before any hook event of this run — exactly when the flag
+ * matters most. Clearing an unknown id stays a no-op.
+ */
+export function setNodeHibernated(nodeId: string, on: boolean): void {
+ if (typeof nodeId !== 'string' || !nodeId || nodeId.length > 128) return
+ const e = state.get(nodeId)
+ if (on) {
+ if (e?.hibernated) return
+ state.set(nodeId, e ? { ...e, hibernated: true } : { updatedAt: Date.now(), hibernated: true })
+ } else {
+ if (!e?.hibernated) return
+ const next = { ...e }
+ delete next.hibernated
+ state.set(nodeId, next)
+ }
+ scheduleWrite()
+}
+
/** A node's published session name (see MirrorEntry.name), or undefined. */
export function nodeSessionName(nodeId: string): string | undefined {
return state.get(nodeId)?.name
diff --git a/src/main/index.ts b/src/main/index.ts
index 5d893be8f..22229d642 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -158,6 +158,7 @@ import {
isEventUnresolved,
type MirrorSettings,
setNodeSessionName,
+ setNodeHibernated,
sessionNameSweepEntries,
nodeState,
nodeSessionName,
@@ -3356,11 +3357,48 @@ app.whenReady().then(async () => {
}
await workspaceStore.removeRemoteNode(nodeId).catch(() => false)
},
+ // Relay-viewer presence (Eco × phone): a COUNT per node id, shared by the interactive host and
+ // every standing-host pool session (several phones can watch at once, and one phone switching
+ // sessions overlaps its old and new streams). Two consumers, both renderer-side:
+ // - `agent:remote-viewers` carries the full watched SET each change, so Eco's `isNodeWatched`
+ // stops hibernating a session someone is watching from a phone (the phone viewer used to be
+ // invisible to every attention predicate — the kanban-modal gap, one surface further out);
+ // - `agent:wake` fires on each attach, so a hibernated node someone just opened on their
+ // phone resumes its CLI — the same nudge contract as `wakeHibernatedNode` (re-reads the
+ // flag, no-ops when not hibernated or not mounted).
+ remoteViewer: (() => {
+ const counts = new Map<string, number>()
+ const toRenderer = (channel: string, payload: unknown): void => {
+ if (!win.isDestroyed()) win.webContents.send(channel, payload)
+ }
+ const broadcast = (): void => toRenderer(IPC.agentRemoteViewers, [...counts.keys()])
+ return {
+ attached(nodeId: string) {
+ counts.set(nodeId, (counts.get(nodeId) ?? 0) + 1)
+ broadcast()
+ toRenderer(IPC.agentWake, nodeId)
+ },
+ detached(nodeId: string) {
+ const n = (counts.get(nodeId) ?? 0) - 1
+ if (n <= 0) counts.delete(nodeId)
+ else counts.set(nodeId, n)
+ broadcast()
+ }
+ }
+ })(),
// Jail roots beyond the active canvas: the phone browses EVERY project (projects.list), so
// its fs/git access spans every local project root — not just the tab the desktop happens
// to have focused (that gap read as "cwd is outside the shared project roots" on the phone).
workspaceRoots: () => workspaceStore.localProjectCwds()
}
+ // The renderer owns the Eco hibernation flag (persisted in ITS localStorage) and main only
+ // mirrors it — same direction as `terminalFocused`. Feeds the agent-status mirror so the phone
+ // renders SLEEPING (and re-fed at renderer boot from the persisted store, so a desktop restart
+ // does not blank the phone's view of a still-hibernated session).
+ ipcMain.on(IPC.agentHibernated, (_e, msg: { nodeId?: unknown; on?: unknown } = {}) => {
+ if (typeof msg?.nodeId !== 'string' || !msg.nodeId) return
+ setNodeHibernated(msg.nodeId, msg.on === true)
+ })
initRemoteHost(win, ptyManager, listProjectsOutput, hostBridge)
// NEW interactive relay host (Stage 4): a connecting peer desktop becomes a first-class
// CorePlatform client of this desktop after mutual SAS approval. Runs BESIDE initRemoteHost (the
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 1dba6085f..9636b2c6a 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -200,7 +200,13 @@ export function createHostHandlers(
// "End session" (`pty.destroy`), reaching the SAME path as the desktop ×
// (`destroySession(…, {everySocket:true})` + node removal). Absent ⇒ `pty.destroy` is not
// served, which is what an un-wired context (and every pre-feature test fake) should say.
- destroyNode?: (nodeId: string) => Promise<void>
+ destroyNode?: (nodeId: string) => Promise<void>,
+ // A relay stream attached to / detached from a node id — "a phone viewer is (no longer) watching
+ // this session". Every stream drop funnels through `dropStream`, so attached/detached calls are
+ // balanced per stream (kill, destroy, PTY exit, closeAll, an attach superseded mid-flight).
+ // The desktop uses it to (a) wake a hibernated node someone just opened on their phone and
+ // (b) keep Eco from hibernating a session a phone is actively watching. Absent ⇒ no tracking.
+ remoteViewer?: { attached(nodeId: string): void; detached(nodeId: string): void }
): HostHandlers {
// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no
// reverse (sessionId -> streamId) index is needed.
@@ -208,7 +214,17 @@ export function createHostHandlers(
let streamCounter = 0
function dropStream(streamId: number): void {
+ const stream = streams.get(streamId)
streams.delete(streamId)
+ // Report AFTER the delete: `detached` may consult the live viewer set via its own bookkeeping,
+ // and a callback that throws must not leave the stream registered.
+ if (stream) {
+ try {
+ remoteViewer?.detached(stream.persistKey)
+ } catch {
+ /* viewer bookkeeping must never break the stream teardown */
+ }
+ }
}
// Build the output/exit sinks for a new stream: pipe PTY output into OP.Output frames (with
@@ -284,6 +300,13 @@ export function createHostHandlers(
// Reserve the stream, then respond so the client can route Input/Resize frames; the snapshot
// + live attach then proceed. Capturing the screen is async (a tmux side-call).
streams.set(streamId, stream)
+ // A phone viewer is now watching this node's session (reported at RESERVE time, balanced by
+ // `dropStream`): the desktop wakes a hibernated node for it and shields it from Eco.
+ try {
+ remoteViewer?.attached(nodeId)
+ } catch {
+ /* viewer bookkeeping must never break the attach */
+ }
// `fresh` — did this attach CREATE the session, or join a live one? It has to be asked BEFORE
// `attachDetached`, whose `tmux new-session -A` creates when the session is gone; afterwards
@@ -615,10 +638,21 @@ export function createHostHandlers(
}
},
closeAll() {
- for (const stream of streams.values()) {
+ // Kill every viewer first (the R4 adjacency the tests pin: `streams.clear()` in the same
+ // synchronous turn), then report the departures — dropStream would interleave callbacks
+ // between kills, and a callback must never widen that window.
+ const closing = [...streams.values()]
+ for (const stream of closing) {
pty.kill(null, stream.sessionId)
}
streams.clear()
+ for (const stream of closing) {
+ try {
+ remoteViewer?.detached(stream.persistKey)
+ } catch {
+ /* viewer bookkeeping must never break the teardown */
+ }
+ }
}
}
}
@@ -805,6 +839,9 @@ export interface HostSessionOptions {
/** Permanently ends a node's session + removes the node (`pty.destroy`). Optional: absent ⇒
* the verb answers with an honest "not served" error. */
destroyNode?: (nodeId: string) => Promise<void>
+ /** Relay-viewer presence per node (attach/detach, balanced per stream) — see createHostHandlers.
+ * Optional: absent ⇒ no tracking. */
+ remoteViewer?: { attached(nodeId: string): void; detached(nodeId: string): void }
/** Extra fs/git jail roots beyond the shared canvas's node cwds — production passes the
* workspace's local project cwds: the phone browses EVERY project over `projects.list`, so a
* canvas-only jail denied whichever project the desktop didn't happen to have focused. */
@@ -926,7 +963,8 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {
opts.getClientId ?? (() => null),
opts.git,
opts.registerNode,
- opts.destroyNode
+ opts.destroyNode,
+ opts.remoteViewer
)
canvasSync = createHostCanvasSync(socket, opts.applyMutation)
unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())
@@ -949,6 +987,9 @@ export interface HostBridgeDeps {
/** The phone's "End session" (`pty.destroy`): destroy the tmux session on every socket it could
* live on + take the node off its project's canvas — the desktop ×'s two steps. */
destroyNode?: (nodeId: string) => Promise<void>
+ /** Relay-viewer presence per node — wakes a hibernated node a phone just opened and shields a
+ * phone-watched session from Eco (see main/index.ts's counter). */
+ remoteViewer?: { attached(nodeId: string): void; detached(nodeId: string): void }
/** Workspace-level jail roots (local project cwds) merged with the canvas node cwds. */
workspaceRoots?: () => string[]
}
@@ -1020,6 +1061,7 @@ export function initRemoteHost(
git: bridge.git,
registerNode: bridge.registerNode,
destroyNode: bridge.destroyNode,
+ remoteViewer: bridge.remoteViewer,
extraRoots: bridge.workspaceRoots,
// Typing attribution: this session's input frames are this phone's keystrokes.
getClientId: () => phone.id(),
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
index 565e507c1..436e7e8e9 100644
--- a/src/main/remote/remote-security.test.ts
+++ b/src/main/remote/remote-security.test.ts
@@ -522,3 +522,65 @@ describe('pty.destroy ends the session through the injected destroyNode', () =>
expect(writeMock).not.toHaveBeenCalled()
})
})
+
+// --- relay-viewer presence (Eco × phone) --------------------------------------
+
+// `remoteViewer` tells the desktop who is WATCHING a session from a phone: `attached` fires at
+// stream-reserve time, and every stream drop — kill, destroy, closeAll — funnels through one
+// `detached`, so the calls stay balanced per stream. The desktop turns this into the
+// `agent:remote-viewers` set (Eco must not /exit a phone-watched session) and the attach edge
+// into an `agent:wake` nudge.
+describe('remoteViewer presence reporting', () => {
+ function viewerFakes() {
+ const events: string[] = []
+ const remoteViewer = {
+ attached: (id: string) => events.push(`+${id}`),
+ detached: (id: string) => events.push(`-${id}`)
+ }
+ return { events, remoteViewer }
+ }
+ const make = (base: ReturnType<typeof makeHostFakes>, rv: { attached(id: string): void; detached(id: string): void }) =>
+ createHostHandlers(
+ base.pty, base.socket, base.fs, () => [], async () => '', () => null,
+ undefined, undefined, undefined, rv
+ )
+
+ it('attach reports the viewer; kill reports the departure — balanced per stream', async () => {
+ const base = makeHostFakes()
+ const { events, remoteViewer } = viewerFakes()
+ const handlers = make(base, remoteViewer)
+ await attachStream(handlers, 'node-a')
+ expect(events).toEqual(['+node-a'])
+ handlers.onRpc({ id: 'k', method: 'pty.kill', params: { streamId: 1 } })
+ expect(events).toEqual(['+node-a', '-node-a'])
+ })
+
+ it('closeAll reports every departure (relay dropped mid-view)', async () => {
+ const base = makeHostFakes()
+ const { events, remoteViewer } = viewerFakes()
+ const handlers = make(base, remoteViewer)
+ await attachStream(handlers, 'node-a')
+ await attachStream(handlers, 'node-b')
+ handlers.closeAll()
+ expect(events.sort()).toEqual(['+node-a', '+node-b', '-node-a', '-node-b'])
+ })
+
+ it('a throwing callback breaks neither the attach nor the teardown', async () => {
+ const base = makeHostFakes()
+ const remoteViewer = {
+ attached: () => {
+ throw new Error('bookkeeping boom')
+ },
+ detached: () => {
+ throw new Error('bookkeeping boom')
+ }
+ }
+ const handlers = make(base, remoteViewer)
+ await attachStream(handlers, 'node-a')
+ // The stream is live despite the throwing callback: input still routes.
+ handlers.onFrame(inputFrame(1, 'echo ok\n'))
+ expect(base.pty.write).toHaveBeenCalledWith(null, 'sess', 'echo ok\n')
+ handlers.onRpc({ id: 'k', method: 'pty.kill', params: { streamId: 1 } })
+ expect(base.responses.at(-1)).toMatchObject({ id: 'k', ok: true })
+ })
+})
diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.ts
index d0303b385..d3737a86d 100644
--- a/src/main/remote/standing-host.ts
+++ b/src/main/remote/standing-host.ts
@@ -336,6 +336,7 @@ export function initStandingHost(
git: bridge.git,
registerNode: bridge.registerNode,
destroyNode: bridge.destroyNode,
+ remoteViewer: bridge.remoteViewer,
extraRoots: bridge.workspaceRoots,
// Typing attribution: this pooled session's input frames are ITS phone's keystrokes.
getClientId: () => pooled.presence.id(),
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b6e285dc4..b0bb4c8c4 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -751,6 +751,17 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.agentStatus, handler)
return () => ipcRenderer.removeListener(IPC.agentStatus, handler)
},
+ reportHibernated: (nodeId, on) => ipcRenderer.send(IPC.agentHibernated, { nodeId, on }),
+ onAgentWake: (listener) => {
+ const handler = (_e: unknown, nodeId: string) => listener(nodeId)
+ ipcRenderer.on(IPC.agentWake, handler)
+ return () => ipcRenderer.removeListener(IPC.agentWake, handler)
+ },
+ onRemoteViewers: (listener) => {
+ const handler = (_e: unknown, nodeIds: string[]) => listener(nodeIds)
+ ipcRenderer.on(IPC.agentRemoteViewers, handler)
+ return () => ipcRenderer.removeListener(IPC.agentRemoteViewers, handler)
+ },
onSubagentActivity: (listener) => {
const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)
ipcRenderer.on(IPC.agentSubagentActivity, handler)
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index c912525c0..4f21b2ae5 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -122,6 +122,9 @@ export function buildStubApi(): Omit<
| 'onUnreadClear'
| 'answerPermission'
| 'ackDone'
+ | 'reportHibernated'
+ | 'onAgentWake'
+ | 'onRemoteViewers'
// Real over the bridge (IPC.appUserDataDir): the worktree dialog's default path is derived from
// it, and a '' stub would propose `/worktrees/…` at the filesystem root.
| 'userDataDir'
@@ -510,6 +513,9 @@ export function buildStubApi(): Omit<
| 'onUnreadClear'
| 'answerPermission'
| 'ackDone'
+ | 'reportHibernated'
+ | 'onAgentWake'
+ | 'onRemoteViewers'
| 'userDataDir'
| 'presence'
| 'speech'
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 695c6e14c..65ef8670a 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -630,10 +630,27 @@ export function buildAgentApi(
client: RpcClient
): Pick<
NodeTerminalApi,
- 'onAgentStatus' | 'onSubagentActivity' | 'onUnreadClear' | 'answerPermission' | 'ackDone'
+ | 'onAgentStatus'
+ | 'onSubagentActivity'
+ | 'onUnreadClear'
+ | 'answerPermission'
+ | 'ackDone'
+ | 'reportHibernated'
+ | 'onAgentWake'
+ | 'onRemoteViewers'
> {
return {
onAgentStatus: (listener) => client.subscribe(IPC.agentStatus, listener as Listener),
+ // REAL forward: the Server Edition writes its own agent-status mirror, and the phone reads it
+ // over its SSH browse path — a browser canvas hibernating a node must reach that file too.
+ reportHibernated: (nodeId, on) => {
+ void client.request(IPC.agentHibernated, { nodeId, on }).catch(() => undefined)
+ },
+ // Deliberate no-op subscriptions, not stubs-by-accident: both signals originate in the phone
+ // RELAY host, which lives only in the desktop main process — the Server Edition serves no
+ // relay, so there is nothing to subscribe to and nothing silently degrades.
+ onAgentWake: () => () => undefined,
+ onRemoteViewers: () => () => undefined,
// 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) =>
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 236cbbf64..f4cb1c745 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -31,6 +31,7 @@ import {
isNodeRemote,
isNodeWatched,
setWatchedNode,
+ setRemotelyViewedNodes,
wakeHibernatedNode
} from '../nodes/TerminalNode'
import { solveFitPadding } from './fit-view'
@@ -4729,6 +4730,38 @@ export function Canvas() {
return () => window.removeEventListener('nodeterm:account-removed', onAccountRemoved)
}, [setNodes, markDirty, deleteNodes])
+ // Eco × phone ("hibernation isn't phone-compatible"). Three wires, all nudges:
+ // - `agent:wake`: a phone viewer just attached over the relay to a node's session — ask the
+ // node to resume its hibernated CLI. Same contract as every other wake asker: the node
+ // re-reads the flag itself, so this is a no-op for a non-hibernated node, and a no-op for an
+ // UNMOUNTED one (inactive project) — the phone then still sees the SLEEPING chip and an
+ // honest shell, never a resume typed into a pane nothing verified.
+ // - `agent:remote-viewers`: the full set of phone-watched node ids, fed into `isNodeWatched`
+ // so the sweep cannot `/exit` a session someone is reading on their phone.
+ // - boot replay: the hibernated flag is persisted in THIS renderer's localStorage, and main's
+ // mirror starts empty every launch — re-report the persisted set once so the phone's
+ // SLEEPING chips survive a desktop restart.
+ useEffect(() => {
+ const unsubWake = window.nodeTerminal.onAgentWake?.((nodeId) => wakeHibernatedNode(nodeId))
+ const unsubViewers = window.nodeTerminal.onRemoteViewers?.((ids) =>
+ setRemotelyViewedNodes(ids)
+ )
+ for (const [id, st] of Object.entries(useAgentStatus.getState().byId)) {
+ if (st?.hibernated) {
+ try {
+ window.nodeTerminal.reportHibernated?.(id, true)
+ } catch {
+ /* mirror side-channel only */
+ }
+ }
+ }
+ return () => {
+ unsubWake?.()
+ unsubViewers?.()
+ setRemotelyViewedNodes([])
+ }
+ }, [])
+
// Cmd/Ctrl+W (forwarded from main) closes the selected node(s) immediately, like the
// node's × button. With nothing selected it falls back to closing the window.
useEffect(() => {
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 4318c8a5d..93ee51531 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -888,6 +888,21 @@ function setNodeOffscreen(nodeId: string, offscreen: boolean): void {
else offscreenNodes.delete(nodeId)
}
+/**
+ * Node ids with a live relay (phone) viewer attached — fed by Canvas from `agent:remote-viewers`
+ * (main sends the full set each change, never a delta, so a dropped event cannot strand a stale
+ * entry). A phone viewer is a THIRD way to be watched, invisible to both of `isNodeWatched`'s
+ * older eyes (the canvas observer and the kanban modal) — before this, Eco could `/exit` a CLI
+ * someone was actively reading on their phone.
+ */
+const remotelyViewedNodes = new Set<string>()
+
+/** Replace the remotely-viewed set (Canvas's `agent:remote-viewers` listener is the one caller). */
+export function setRemotelyViewedNodes(nodeIds: readonly string[]): void {
+ remotelyViewedNodes.clear()
+ for (const id of nodeIds) remotelyViewedNodes.add(id)
+}
+
/**
* "Is the user looking at this session RIGHT NOW?" — the one predicate behind every hibernation
* decision that turns on attention: the sweep's plan, the exit closure's fire-time re-ask, and the
@@ -895,13 +910,16 @@ function setNodeOffscreen(nodeId: string, offscreen: boolean): void {
* three times, and the fire-time copy was missing the modal clause — so a card modal opened
* mid-batch could still have `/exit` typed into it.
*
- * Two ways to be watched, and the second is not visible to any observer: the node is on screen, or
- * its kanban card modal is open (see `watchedNodeId`). Unknown answers WATCHED — a node whose
- * observer has not delivered yet must never be read as "nobody is looking", which is the direction
- * that quits a session out from under someone.
+ * Three ways to be watched, and only the first is visible to any observer: the node is on screen,
+ * its kanban card modal is open (see `watchedNodeId`), or a phone viewer is attached to its
+ * session over the relay (`remotelyViewedNodes`). Unknown answers WATCHED — a node whose observer
+ * has not delivered yet must never be read as "nobody is looking", which is the direction that
+ * quits a session out from under someone.
*/
export function isNodeWatched(nodeId: string): boolean {
- return !offscreenNodes.has(nodeId) || watchedNodeId === nodeId
+ return (
+ !offscreenNodes.has(nodeId) || watchedNodeId === nodeId || remotelyViewedNodes.has(nodeId)
+ )
}
/**
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index 85970d5fa..4435cd7b6 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -454,6 +454,14 @@ export function createAgentStatusSession(
set((s) => {
const prev = s.byId[id] ?? EMPTY
if (!!prev.hibernated === on) return s
+ // The renderer owns this flag; the core only mirrors it (agent-status mirror → SLEEPING on
+ // the phone). Reported on the same edge the store changes, guarded because tests (and any
+ // non-preload context) run this store without a bridge.
+ try {
+ window.nodeTerminal?.reportHibernated?.(id, on)
+ } catch {
+ /* the mirror is a side-channel; a failed report must never break the store */
+ }
// Cleared by dropping the key, not by storing `false`: `save` skips entries that carry
// nothing durable, so a woken node leaves no residue behind in localStorage.
// The recorded pane belongs to THIS hibernation: it goes with the flag, in both
diff --git a/src/server/index.ts b/src/server/index.ts
index 14ba015f3..3c459f0f6 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -73,6 +73,7 @@ import {
type MirrorSettings,
type MirrorServer,
setNodeSessionName,
+ setNodeHibernated,
sessionNameSweepEntries,
nodeSessionName
} from '../core/agent-status-mirror'
@@ -459,6 +460,12 @@ export async function startServer(
platform.handle(IPC.agentAckDone, (nodeId: string) => {
ackDone(nodeId)
})
+ // Eco hibernation report (parity with desktop's ipcMain.on(IPC.agentHibernated)): the browser
+ // renderer owns the flag; the mirror carries it so the phone's SSH browse renders SLEEPING.
+ platform.handle(IPC.agentHibernated, (msg: { nodeId?: unknown; on?: unknown }) => {
+ if (typeof msg?.nodeId !== 'string' || !msg.nodeId) return
+ setNodeHibernated(msg.nodeId, msg.on === true)
+ })
// 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
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 9c7f50b3f..37cf2314b 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -144,6 +144,22 @@ export const IPC = {
* renderer clears unread WITHOUT re-acking (external clear — see agentStatus.clearUnread's
* `external` opt). See core/ack-sweep.ts. */
agentUnreadClear: 'agent:unread-clear',
+ /** Renderer → main/server: a node's Eco hibernation flag changed (the renderer owns the flag —
+ * `agentStatus.setHibernated` — and main only mirrors it, like `terminalFocused`). Arg:
+ * `{ nodeId: string, on: boolean }`. Fire-and-forget cast; feeds the agent-status mirror so the
+ * phone can render SLEEPING, and gives main the `isHibernated` signal the delivery queue's
+ * hibernated leg was recorded as missing (agent-messaging.ts). */
+ agentHibernated: 'agent:hibernated',
+ /** main → renderer: ask the renderer to wake a hibernated node NOW (a phone viewer attached to
+ * its session over the relay). A nudge, never an assertion: the renderer re-reads the flag and
+ * no-ops for a non-hibernated or unmounted node — same contract as `wakeHibernatedNode`. Arg:
+ * `nodeId: string`. */
+ agentWake: 'agent:wake',
+ /** main → renderer: the CURRENT set of node ids with a live relay viewer attached (a phone
+ * watching the session). Arg: `string[]` — the full set each change, so a dropped event cannot
+ * strand a stale entry. Feeds `isNodeWatched`: a session someone is watching from a phone must
+ * not be hibernated out from under them. */
+ agentRemoteViewers: 'agent:remote-viewers',
agentSubagentActivity: 'agent:subagent-activity',
/** macOS Notch HUD (docs/notch-hud.md). main → hud: push the current row array. */
hudRows: 'hud:rows',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 24e8c5f6f..3b375f6ff 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2980,6 +2980,20 @@ export interface NodeTerminalApi {
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
+ /** Report a node's Eco hibernation flag to the core (the renderer owns the flag; the core only
+ * mirrors it into the agent-status file so the phone can render SLEEPING). Fire-and-forget;
+ * called on every `setHibernated` change and replayed for the persisted set at boot. */
+ reportHibernated(nodeId: string, on: boolean): void
+ /** Fires when the core asks this renderer to WAKE a hibernated node NOW (a phone viewer just
+ * attached to its session over the relay). A nudge with `wakeHibernatedNode`'s exact contract:
+ * re-read the flag, no-op when not hibernated or not mounted. Returns unsubscribe.
+ * Desktop-only signal (the relay host lives in the desktop main process); the ws-bridge
+ * subscribes to nothing and returns a no-op unsubscribe. */
+ onAgentWake(listener: (nodeId: string) => void): () => void
+ /** Fires with the CURRENT set of node ids that have a live relay (phone) viewer attached — the
+ * full set each change, never a delta. Feeds `isNodeWatched` so Eco cannot hibernate a session
+ * someone is watching from a phone. Desktop-only signal, like `onAgentWake`. */
+ onRemoteViewers(listener: (nodeIds: string[]) => void): () => void
/** Fires with live subagent transcript chunks while a subagent runs. Returns unsubscribe. */
onSubagentActivity(listener: (e: SubagentActivity) => void): () => void
/** Fires when an agent's `nodeterm` CLI requests a canvas action. Returns unsubscribe. */