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(push): question options + Live Activity update stream

enesa7415bc39db0
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index f7e665aa5..8c6c796e9 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -19,6 +19,9 @@ import {
buildMirrorUsage,
toolActivity,
firstLine,
+ extractQuestionOptions,
+ onNodeStateChange,
+ onNodeNowChange,
_resetForTest,
_snapshot,
_inboxSnapshot,
@@ -27,7 +30,9 @@ import {
INBOX_EVENTS_CAP,
type MirrorEntry,
type MirrorFile,
- type MirrorUsage
+ type MirrorUsage,
+ type NodeStateChange,
+ type NodeNowChange
} from './agent-status-mirror'
// Minimal event factory — only the fields the reducer reads.
@@ -315,6 +320,20 @@ describe('inbox event production (via recordAgentEvent)', () => {
expect(ib.events[1].title).toBe('Approve rm -rf /tmp/x')
})
+ it('carries the deterministic-approval pendingId onto the approval event (and omits it when absent)', () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write', pendingId: 'n1-123-9' }))
+ const withId = _inboxSnapshot().events[0]
+ expect(withId.kind).toBe('approval')
+ expect(withId.pendingId).toBe('n1-123-9')
+
+ // A different node whose hook did NOT arm the wait (no pendingId) → the field is omitted.
+ recordAgentEvent(ev({ nodeId: 'other', state: 'blocked', lastMessage: 'Approve?' }))
+ const noId = _inboxSnapshot().events.find((e) => e.nodeId === 'other')!
+ expect(noId.kind).toBe('approval')
+ expect('pendingId' in noId).toBe(false)
+ })
+
it('titles blocked/waiting from lastMessage first line, with fallbacks', () => {
recordAgentEvent(ev({ nodeId: 'a', state: 'blocked' }))
recordAgentEvent(ev({ nodeId: 'b', state: 'waiting' }))
@@ -448,6 +467,165 @@ describe('activity mapping (toolActivity + recordRawToolEvent)', () => {
})
})
+// ---- interactive-push-live-activities -------------------------------------------------------
+
+describe('question options (AskUserQuestion)', () => {
+ beforeEach(() => _resetForTest())
+ afterEach(() => _resetForTest())
+
+ const q1 = (opts: unknown[]) => ({ questions: [{ options: opts }] })
+
+ it('extracts ≤4 labels clipped to 60, first question only, fail-open on bad shape', () => {
+ expect(extractQuestionOptions(q1([{ label: 'Dark' }, { label: 'Light' }]))).toEqual(['Dark', 'Light'])
+ // clips each label to 60
+ const long = 'x'.repeat(100)
+ expect(extractQuestionOptions(q1([{ label: long }]))![0]).toBe('x'.repeat(59) + '…')
+ // caps at 4
+ expect(extractQuestionOptions(q1([1, 2, 3, 4, 5].map((n) => ({ label: `o${n}` })))))
+ .toEqual(['o1', 'o2', 'o3', 'o4'])
+ // only the FIRST question's options
+ expect(
+ extractQuestionOptions({ questions: [{ options: [{ label: 'A' }] }, { options: [{ label: 'B' }] }] })
+ ).toEqual(['A'])
+ // fail-open on every shape mismatch
+ expect(extractQuestionOptions(undefined)).toBeUndefined()
+ expect(extractQuestionOptions({})).toBeUndefined()
+ expect(extractQuestionOptions({ questions: [] })).toBeUndefined()
+ expect(extractQuestionOptions(q1([]))).toBeUndefined()
+ expect(extractQuestionOptions(q1([{ nope: 1 }]))).toBeUndefined()
+ expect(extractQuestionOptions({ questions: 'x' } as unknown as Record<string, unknown>)).toBeUndefined()
+ })
+
+ it('stashes options on the raw AskUserQuestion hook and attaches them to the next question', () => {
+ recordRawToolEvent('n1', {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'AskUserQuestion',
+ tool_input: q1([{ label: 'Dark' }, { label: 'Light' }, { label: 'System' }])
+ })
+ recordAgentEvent(ev({ nodeId: 'n1', state: 'waiting', lastMessage: 'Pick a theme' }))
+ const q = _inboxSnapshot().events.find((e) => e.nodeId === 'n1' && e.kind === 'question')!
+ expect(q.options).toEqual(['Dark', 'Light', 'System'])
+ })
+
+ it('a plain question (no AskUserQuestion) carries no options', () => {
+ recordAgentEvent(ev({ nodeId: 'n2', state: 'waiting', lastMessage: 'Which file?' }))
+ expect(_inboxSnapshot().events.find((e) => e.nodeId === 'n2')!.options).toBeUndefined()
+ })
+
+ it('approvals never carry options even when a stash exists', () => {
+ recordRawToolEvent('n3', {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'AskUserQuestion',
+ tool_input: q1([{ label: 'A' }])
+ })
+ recordAgentEvent(ev({ nodeId: 'n3', state: 'blocked', lastMessage: 'Approve?' }))
+ const e = _inboxSnapshot().events.find((x) => x.nodeId === 'n3')!
+ expect(e.kind).toBe('approval')
+ expect(e.options).toBeUndefined()
+ })
+
+ it('clears the stash when the node leaves waiting (no reuse on a later question)', () => {
+ recordRawToolEvent('n4', {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'AskUserQuestion',
+ tool_input: q1([{ label: 'A' }])
+ })
+ recordAgentEvent(ev({ nodeId: 'n4', state: 'waiting', lastMessage: 'Q1' }))
+ recordAgentEvent(ev({ nodeId: 'n4', state: 'working' })) // leaves waiting → clears stash
+ recordAgentEvent(ev({ nodeId: 'n4', state: 'waiting', lastMessage: 'Q2' }))
+ const qs = _inboxSnapshot().events.filter((e) => e.nodeId === 'n4' && e.kind === 'question')
+ expect(qs[qs.length - 1].options).toBeUndefined()
+ })
+
+ it('clears the stash on a new turn', () => {
+ recordRawToolEvent('n5', {
+ hook_event_name: 'PreToolUse',
+ tool_name: 'AskUserQuestion',
+ tool_input: q1([{ label: 'A' }])
+ })
+ recordAgentEvent(ev({ nodeId: 'n5', state: 'working', newTurn: true })) // new turn clears
+ recordAgentEvent(ev({ nodeId: 'n5', state: 'waiting', lastMessage: 'Q' }))
+ expect(_inboxSnapshot().events.find((e) => e.nodeId === 'n5' && e.kind === 'question')!.options).toBeUndefined()
+ })
+})
+
+describe('onNodeStateChange seam', () => {
+ beforeEach(() => _resetForTest())
+ afterEach(() => _resetForTest())
+
+ it('fires start on working, needsYou on blocked/waiting, end on done — with the mapped messages', () => {
+ const seen: NodeStateChange[] = []
+ onNodeStateChange((c) => seen.push(c))
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write' }))
+ recordAgentEvent(ev({ state: 'working' })) // resume — an edge back into working
+ recordAgentEvent(ev({ state: 'done', lastMessage: 'Wrapped up.' }))
+ expect(seen.map((c) => [c.event, c.state])).toEqual([
+ ['start', 'working'],
+ ['update', 'needsYou'],
+ ['start', 'working'],
+ ['end', 'done']
+ ])
+ expect(seen[1].message).toBe('Approve write')
+ expect(seen[3].message).toBe('Finished')
+ })
+
+ it('maps waiting to needsYou and titles interrupted done "Stopped"', () => {
+ const seen: NodeStateChange[] = []
+ onNodeStateChange((c) => seen.push(c))
+ recordAgentEvent(ev({ nodeId: 'q', state: 'waiting', lastMessage: 'Which one?' }))
+ recordAgentEvent(ev({ nodeId: 'q', state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ nodeId: 'q', state: 'done', interrupted: true }))
+ expect(seen.find((c) => c.state === 'needsYou')!.message).toBe('Which one?')
+ expect(seen.find((c) => c.state === 'done')!.message).toBe('Stopped')
+ })
+
+ it('does not refire start for a same-state working tick, nor needsYou for a re-asserted blocked', () => {
+ const seen: NodeStateChange[] = []
+ onNodeStateChange((c) => seen.push(c))
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'working' })) // tool tick
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'A' }))
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'A' })) // re-assert
+ expect(seen.filter((c) => c.event === 'start')).toHaveLength(1)
+ expect(seen.filter((c) => c.state === 'needsYou')).toHaveLength(1)
+ })
+
+ it('does not fire a start for a held-off late working (done-holdoff)', () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'done' }))
+ const seen: NodeStateChange[] = []
+ onNodeStateChange((c) => seen.push(c))
+ // A late, non-newTurn working within DONE_HOLDOFF_MS is held off by reduceEntry → no start.
+ recordAgentEvent(ev({ state: 'working' }))
+ expect(seen.filter((c) => c.event === 'start')).toHaveLength(0)
+ })
+})
+
+describe('onNodeNowChange seam', () => {
+ beforeEach(() => _resetForTest())
+ afterEach(() => _resetForTest())
+
+ it('fires on an activity change and on a context change', () => {
+ const seen: NodeNowChange[] = []
+ onNodeNowChange((c) => seen.push(c))
+ recordRawToolEvent('n1', { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'ls' } })
+ recordContextUsage('n1', 55)
+ expect(seen).toHaveLength(2)
+ expect(seen[0]).toMatchObject({ nodeId: 'n1', activity: 'Running ls' })
+ expect(seen[1]).toMatchObject({ nodeId: 'n1', contextPercent: 55 })
+ })
+
+ it('fires with activity undefined when a Stop clears the line', () => {
+ const seen: NodeNowChange[] = []
+ recordRawToolEvent('n2', { hook_event_name: 'PreToolUse', tool_name: 'Read', tool_input: { file_path: 'a.ts' } })
+ onNodeNowChange((c) => seen.push(c))
+ recordRawToolEvent('n2', { hook_event_name: 'Stop' })
+ expect(seen).toHaveLength(1)
+ expect(seen[0].activity).toBeUndefined()
+ })
+})
+
describe('buildMirrorUsage', () => {
it('maps snapshots to accounts, system first, with defensive limit fields + labels', () => {
const snap = [
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 3f0546a45..5e871f71e 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -185,6 +185,12 @@ export const INBOX_EVENTS_CAP = 50
export const INBOX_TITLE_MAX = 120
export const INBOX_DETAIL_MAX = 240
export const INBOX_ACTIVITY_MAX = 80
+// Question options (spec: interactive-push-live-activities): first question only, ≤4 choices,
+// each label clipped to 60 chars.
+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
export interface InboxEvent {
/** Monotonic per writer: `${ts}-${seq}`. */
@@ -202,6 +208,15 @@ export interface InboxEvent {
interrupted?: boolean
/** approval/question: the node has since left blocked/waiting (moves to the phone's archive). */
resolved?: boolean
+ /** question only: the AskUserQuestion choices (first question, ≤4 labels, each ≤60 chars) so the
+ * phone can render numbered chips / notification actions. Absent for approvals + plain questions
+ * (spec: interactive-push-live-activities). */
+ options?: string[]
+ /** approval only: the deterministic hook-reply ticket (docs/hook-reply-approvals.md). Present when
+ * the managed permission hook is holding open for an answer — the phone/canvas write
+ * `~/.nodeterm/pending/<pendingId>.answer` to answer it. Rides the mirror to the phone; dropped
+ * from the push-notify body (the phone re-reads the mirror before acting). Absent = legacy prompt. */
+ pendingId?: string
}
export interface InboxNodeNow {
/** ≤80 chars — "Editing foo.ts", "Running npm test", "Reading bar.ts". */
@@ -428,6 +443,102 @@ export function onInboxActionable(cb: (e: InboxEvent) => void): () => void {
return () => inboxActionableListeners.delete(cb)
}
+// ---- Live-update seams (spec: interactive-push-live-activities) -----------------------------
+// Two narrow side-channels feed the desktop live-update push stream (src/core/push-notify.ts
+// `createLiveUpdatePush`). Neither changes the feed or any disk write.
+// - `onNodeStateChange` fires on the MAIN-state EDGES a Live Activity cares about: working start,
+// the edge INTO waiting/blocked (mapped to 'needsYou'), and the edge into done — post the same
+// done-holdoff / newTurn gating as the badge, so a held-off working never fires a spurious start.
+// - `onNodeNowChange` fires when a node's live activity line or context% changes (from
+// recordRawToolEvent / recordContextUsage); the sender coalesces these ≥20s per node.
+
+/** A main-state edge worth a Live Activity update. `state` is the phone-facing bucket
+ * (waiting/blocked collapse to 'needsYou'); `message` is the event headline for needs-you/done. */
+export interface NodeStateChange {
+ nodeId: string
+ agentId?: string
+ sessionId?: string
+ event: 'start' | 'update' | 'end'
+ state: 'working' | 'needsYou' | 'done'
+ /** needs-you / done headline, ≤120 chars. Absent for a plain 'start'. */
+ message?: string
+ ts: number
+}
+
+/** A per-node "what it's doing now" change (activity line and/or context%). */
+export interface NodeNowChange {
+ nodeId: string
+ activity?: string
+ contextPercent?: number
+ ts: number
+}
+
+const nodeStateChangeListeners = new Set<(c: NodeStateChange) => void>()
+const nodeNowChangeListeners = new Set<(c: NodeNowChange) => void>()
+
+/** Subscribe to main-state edges (working start / needsYou / done). Returns an unsubscribe. */
+export function onNodeStateChange(cb: (c: NodeStateChange) => void): () => void {
+ nodeStateChangeListeners.add(cb)
+ return () => nodeStateChangeListeners.delete(cb)
+}
+
+/** Subscribe to per-node activity/context% changes. Returns an unsubscribe. */
+export function onNodeNowChange(cb: (c: NodeNowChange) => void): () => void {
+ nodeNowChangeListeners.add(cb)
+ return () => nodeNowChangeListeners.delete(cb)
+}
+
+function fireNodeStateChange(c: NodeStateChange): void {
+ for (const cb of nodeStateChangeListeners) {
+ try {
+ cb(c)
+ } catch {
+ // A subscriber must never break production (or its siblings).
+ }
+ }
+}
+
+function fireNodeNowChange(c: NodeNowChange): void {
+ for (const cb of nodeNowChangeListeners) {
+ try {
+ cb(c)
+ } catch {
+ // A subscriber must never break production (or its siblings).
+ }
+ }
+}
+
+// Per-node stash of the pending AskUserQuestion option labels, set from the raw-hook seam and
+// attached to the next `question` InboxEvent for that node (cleared on state-leave / new turn /
+// session boundary).
+const pendingOptions = new Map<string, string[]>()
+
+/**
+ * Extract question option labels from an AskUserQuestion `tool_input` (first question only, v1):
+ * `questions[0].options[].label`, each clipped to 60 chars, ≤4 labels. Pure. FAIL-OPEN — any shape
+ * mismatch (missing/empty arrays, non-string labels) yields `undefined`.
+ */
+export function extractQuestionOptions(
+ toolInput: Record<string, unknown> | undefined
+): string[] | undefined {
+ try {
+ const questions = (toolInput as { questions?: unknown })?.questions
+ if (!Array.isArray(questions) || questions.length === 0) return undefined
+ const options = (questions[0] as { options?: unknown })?.options
+ if (!Array.isArray(options)) return undefined
+ const labels: string[] = []
+ for (const o of options) {
+ const label = (o as { label?: unknown })?.label
+ if (typeof label !== 'string' || !label) continue
+ labels.push(clip(label, INBOX_OPTION_LABEL_MAX))
+ if (labels.length >= INBOX_QUESTION_OPTIONS_MAX) break
+ }
+ return labels.length > 0 ? labels : undefined
+ } catch {
+ return undefined
+ }
+}
+
function pushInboxEvent(e: Omit<InboxEvent, 'id'>): void {
const id = `${e.ts}-${++inboxSeq}`
const full: InboxEvent = { id, ...e }
@@ -545,31 +656,56 @@ function produceInboxFromState(
nextState: AgentState | undefined,
now: number
): void {
+ // Clear any stashed question options on a new turn or session boundary — a stale option set must
+ // never attach to a later, unrelated question. (State-leave clearing is handled below.)
+ if (ev.kind === 'session' || (ev.kind === 'state' && ev.state === 'working' && ev.newTurn)) {
+ pendingOptions.delete(nodeId)
+ }
// Leaving blocked/waiting (any newer, different state — incl. a session reset to idle) resolves
// that node's pending approval/question cards; they move to the phone's archive.
if ((prevState === 'blocked' || prevState === 'waiting') && nextState !== prevState) {
resolveUnresolvedFor(nodeId)
+ pendingOptions.delete(nodeId)
}
const baseEvent = { ts: now, nodeId, agentId: ev.agentId, sessionId: ev.sessionId }
+ const stateBase = { nodeId, agentId: ev.agentId, sessionId: ev.sessionId, ts: now }
+ // Working START edge (fresh turn / session open): a Live Activity begins here. reduceEntry's
+ // done-holdoff means a held-off late working keeps `nextState === 'done'`, so it never reaches
+ // here — no spurious 'start'.
+ if (nextState === 'working' && prevState !== 'working') {
+ fireNodeStateChange({ ...stateBase, event: 'start', state: 'working' })
+ }
// approval/question dedup is TITLE-based (not edge-based): a re-asserted blocked with the SAME
// ask is a no-op, but a genuinely different ask still lands — so the guard can't be a plain
// "same-state, skip". `done` alone is edge-guarded (one per turn).
if (nextState === 'blocked') {
const title = firstLine(ev.lastMessage, INBOX_TITLE_MAX) || 'Needs approval'
+ // needsYou live-update on the EDGE into blocked (a re-assert keeps the same activity live).
+ if (prevState !== 'blocked') {
+ fireNodeStateChange({ ...stateBase, event: 'update', state: 'needsYou', message: clip(title, LIVE_MESSAGE_MAX) })
+ }
if (newestUnresolved(inboxEvents, nodeId)?.title === title) return
- pushInboxEvent({ ...baseEvent, kind: 'approval', title })
+ // Carry the deterministic-approval ticket (present only when the wait-branch of the managed
+ // hook ran) so the phone can answer the held hook. See docs/hook-reply-approvals.md.
+ pushInboxEvent({ ...baseEvent, kind: 'approval', title, ...(ev.pendingId ? { pendingId: ev.pendingId } : {}) })
} else if (nextState === 'waiting') {
const title = firstLine(ev.lastMessage, INBOX_TITLE_MAX) || 'Waiting for input'
+ if (prevState !== 'waiting') {
+ fireNodeStateChange({ ...stateBase, event: 'update', state: 'needsYou', message: clip(title, LIVE_MESSAGE_MAX) })
+ }
+ const options = pendingOptions.get(nodeId)
if (newestUnresolved(inboxEvents, nodeId)?.title === title) return
- pushInboxEvent({ ...baseEvent, kind: 'question', title })
+ pushInboxEvent({ ...baseEvent, kind: 'question', title, ...(options ? { options } : {}) })
} else if (nextState === 'done' && prevState !== 'done') {
// The turn ended: emit one `done` on the edge into done (reduceEntry's holdoff keeps a late
// working from re-entering, and the normalizer collapses an Esc-spam into one done).
const detail = firstLine(ev.lastMessage, INBOX_DETAIL_MAX) || undefined
+ const title = ev.interrupted ? 'Stopped' : 'Finished'
+ fireNodeStateChange({ ...stateBase, event: 'end', state: 'done', message: title })
pushInboxEvent({
...baseEvent,
kind: 'done',
- title: ev.interrupted ? 'Stopped' : 'Finished',
+ title,
...(detail ? { detail } : {}),
...(ev.interrupted ? { interrupted: true } : {})
})
@@ -602,15 +738,25 @@ export function recordRawToolEvent(nodeId: string, payload: Record<string, unkno
payload.tool_input && typeof payload.tool_input === 'object'
? (payload.tool_input as Record<string, unknown>)
: undefined
+ // AskUserQuestion: stash the choice labels so the next `question` InboxEvent + push carry them
+ // (spec: interactive-push-live-activities). Fail-open — a shape mismatch leaves no stash.
+ if (toolName === 'AskUserQuestion') {
+ const opts = extractQuestionOptions(toolInput)
+ if (opts) pendingOptions.set(nodeId, opts)
+ }
const activity = toolActivity(toolName, toolInput)
const cur = inboxNodes.get(nodeId)
if (cur?.activity === activity && cur?.tool === toolName) return // no change
inboxNodes.set(nodeId, { activity, tool: toolName, contextPercent: cur?.contextPercent, updatedAt: now })
+ fireNodeNowChange({ nodeId, activity, contextPercent: cur?.contextPercent, ts: now })
scheduleWrite()
} else if (hook === 'Stop' || hook === 'SessionEnd') {
const before = inboxNodes.get(nodeId)?.activity
clearActivity(nodeId, now)
- if (before !== undefined) scheduleWrite()
+ if (before !== undefined) {
+ fireNodeNowChange({ nodeId, activity: undefined, contextPercent: inboxNodes.get(nodeId)?.contextPercent, ts: now })
+ scheduleWrite()
+ }
}
}
@@ -623,7 +769,9 @@ export function recordContextUsage(nodeId: string, percent: number): void {
const clamped = Math.min(100, Math.max(0, percent))
const cur = inboxNodes.get(nodeId)
if (cur?.contextPercent === clamped) return
- inboxNodes.set(nodeId, { activity: cur?.activity, tool: cur?.tool, contextPercent: clamped, updatedAt: Date.now() })
+ const now = Date.now()
+ inboxNodes.set(nodeId, { activity: cur?.activity, tool: cur?.tool, contextPercent: clamped, updatedAt: now })
+ fireNodeNowChange({ nodeId, activity: cur?.activity, contextPercent: clamped, ts: now })
scheduleWrite()
}
@@ -635,6 +783,7 @@ export function recordContextUsage(nodeId: string, percent: number): void {
export function clearNode(nodeId: string): void {
let changed = state.delete(nodeId)
if (inboxNodes.delete(nodeId)) changed = true
+ pendingOptions.delete(nodeId)
// History stays; unresolved cards for a gone node can never be answered → archive them.
for (const e of inboxEvents) {
if (e.nodeId === nodeId && !e.resolved && (e.kind === 'approval' || e.kind === 'question')) {
@@ -697,6 +846,9 @@ export function _resetForTest(): void {
inboxNodes.clear()
inboxSeq = 0
inboxActionableListeners.clear()
+ nodeStateChangeListeners.clear()
+ nodeNowChangeListeners.clear()
+ pendingOptions.clear()
}
/** Snapshot the in-memory map. Test-only. */
diff --git a/src/core/push-notify.test.ts b/src/core/push-notify.test.ts
index c94ef6cf4..8f018492c 100644
--- a/src/core/push-notify.test.ts
+++ b/src/core/push-notify.test.ts
@@ -3,15 +3,37 @@ import fs from 'fs'
import os from 'os'
import path from 'path'
import type { NormalizedAgentEvent } from '@shared/agents/normalize'
-import { createPushNotify, type PushNotifyDeps, type PushHostIdentity } from './push-notify'
+import {
+ createPushNotify,
+ createLiveUpdatePush,
+ type PushNotifyDeps,
+ type PushHostIdentity,
+ type LiveUpdateDeps
+} from './push-notify'
import {
onInboxActionable,
recordAgentEvent,
initAgentStatusMirror,
_resetForTest,
- type InboxEvent
+ type InboxEvent,
+ type NodeStateChange,
+ type NodeNowChange
} from './agent-status-mirror'
+/** A generic manual event source standing in for the mirror subscribe seams. */
+function emitter<T>(): { subscribe: (cb: (e: T) => void) => () => void; emit: (e: T) => void } {
+ const cbs = new Set<(e: T) => void>()
+ return {
+ subscribe: (cb) => {
+ cbs.add(cb)
+ return () => cbs.delete(cb)
+ },
+ emit: (e) => {
+ for (const cb of cbs) cb(e)
+ }
+ }
+}
+
// ---- helpers -------------------------------------------------------------------------------
/** A manual actionable-event source standing in for `onInboxActionable`. */
@@ -195,7 +217,10 @@ describe('createPushNotify', () => {
title: 'Approve write to /etc/hosts',
detail: 'Edit needs sudo',
ts: 1789,
- resolved: false
+ resolved: false,
+ // Deterministic-approval ticket rides the mirror to the phone but MUST NOT ride the push
+ // body (the phone re-reads the mirror before acting). See docs/hook-reply-approvals.md.
+ pendingId: 'node-9-1789-42'
})
)
await vi.advanceTimersByTimeAsync(2000)
@@ -217,6 +242,7 @@ describe('createPushNotify', () => {
// The internal InboxEvent fields do not leak into the payload.
expect(body.events[0]).not.toHaveProperty('id')
expect(body.events[0]).not.toHaveProperty('resolved')
+ expect(body.events[0]).not.toHaveProperty('pendingId')
h.stop()
})
@@ -400,6 +426,26 @@ describe('createPushNotify', () => {
})
})
+ describe('question options pass-through', () => {
+ it('passes question options into the notify payload', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
+ em.emit(iev({ nodeId: 'a', kind: 'question', title: 'Pick a theme', options: ['Dark', 'Light', 'System'] }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(bodyOf().events[0].options).toEqual(['Dark', 'Light', 'System'])
+ h.stop()
+ })
+
+ it('omits options when the event has none', async () => {
+ const em = makeEmitter()
+ const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
+ em.emit(iev({ nodeId: 'a', kind: 'approval', title: 'Approve' }))
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(bodyOf().events[0]).not.toHaveProperty('options')
+ h.stop()
+ })
+ })
+
it('stop() unsubscribes so later events are ignored', async () => {
const em = makeEmitter()
const h = createPushNotify(baseDeps({ subscribe: em.subscribe }))
@@ -409,3 +455,197 @@ describe('createPushNotify', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
})
+
+// ---- live-update stream --------------------------------------------------------------------
+
+describe('createLiveUpdatePush', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ fetchMock = vi.fn().mockResolvedValue({ ok: true })
+ clock = 0
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ function liveDeps(over: Partial<LiveUpdateDeps> = {}): LiveUpdateDeps {
+ return {
+ subscribeStateChange: () => () => {},
+ subscribeNowChange: () => () => {},
+ getHostIdentity: () => IDENTITY,
+ mobilePushEnabled: () => true,
+ mobileLiveActivities: () => true,
+ isPackaged: () => true,
+ getNodeTitle: () => undefined,
+ env: {},
+ fetchImpl: fetchMock as unknown as typeof fetch,
+ now: () => clock,
+ batchWindowMs: 1000,
+ coalesceMs: 20000,
+ ...over
+ }
+ }
+
+ function liveBodyOf(callIndex = 0): {
+ hostDeviceId: string
+ hostPublicKeyB64: string
+ hostLabel: string
+ updates: Array<Record<string, unknown>>
+ } {
+ return JSON.parse(fetchMock.mock.calls[callIndex][1].body)
+ }
+
+ function wire(over: Partial<LiveUpdateDeps> = {}): {
+ h: ReturnType<typeof createLiveUpdatePush>
+ st: ReturnType<typeof emitter<NodeStateChange>>
+ nw: ReturnType<typeof emitter<NodeNowChange>>
+ } {
+ const st = emitter<NodeStateChange>()
+ const nw = emitter<NodeNowChange>()
+ const h = createLiveUpdatePush(
+ liveDeps({ subscribeStateChange: st.subscribe, subscribeNowChange: nw.subscribe, ...over })
+ )
+ return { h, st, nw }
+ }
+
+ it('posts a state edge within the batch window (immediate)', async () => {
+ const { h, st } = wire()
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ expect(fetchMock).not.toHaveBeenCalled() // still batching
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchMock.mock.calls[0]
+ expect(url).toBe('https://api.nodeterm.dev/v1/push/live-update')
+ expect(init.method).toBe('POST')
+ expect(liveBodyOf().updates[0]).toMatchObject({ nodeId: 'a', event: 'start', state: 'working' })
+ h.stop()
+ })
+
+ it('emits the contract payload shape (host identity + trimmed update fields)', async () => {
+ const { h, st } = wire({ getNodeTitle: () => 'api-server' })
+ st.emit({ nodeId: 'node-1', agentId: 'claude', event: 'update', state: 'needsYou', message: 'Approve write', ts: 42 })
+ await vi.advanceTimersByTimeAsync(1000)
+ const body = liveBodyOf()
+ expect(body.hostDeviceId).toBe('host-device-1')
+ expect(body.hostPublicKeyB64).toBe('PUBKEYB64==')
+ expect(body.hostLabel).toBe('niova')
+ expect(body.updates[0]).toEqual({
+ nodeId: 'node-1',
+ nodeTitle: 'api-server',
+ agentId: 'claude',
+ event: 'update',
+ state: 'needsYou',
+ message: 'Approve write',
+ ts: 42
+ })
+ h.stop()
+ })
+
+ it('sends a now-update immediately on the leading edge, then COALESCES ticks to ≥20s/node', async () => {
+ const { h, nw } = wire()
+ // Leading edge (no prior send) → sent.
+ clock = 0
+ nw.emit({ nodeId: 'a', activity: 'Editing a.ts', contextPercent: 10, ts: 0 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(liveBodyOf(0).updates[0]).toMatchObject({
+ event: 'update',
+ state: 'working',
+ activity: 'Editing a.ts',
+ contextPercent: 10
+ })
+ // A second tick 5s later is inside the 20s window → coalesced (NOT sent yet).
+ clock = 5000
+ nw.emit({ nodeId: 'a', activity: 'Editing b.ts', ts: 5000 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ // At the window edge the coalesced LATEST flushes.
+ clock = 20000
+ await vi.advanceTimersByTimeAsync(20000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(liveBodyOf(1).updates[0].activity).toBe('Editing b.ts')
+ h.stop()
+ })
+
+ it('a state edge is NOT subject to the now-coalesce window', async () => {
+ const { h, st, nw } = wire()
+ clock = 0
+ nw.emit({ nodeId: 'a', activity: 'x', ts: 0 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ // A state edge on the same node 2s later still posts immediately (no 20s wait).
+ clock = 2000
+ st.emit({ nodeId: 'a', event: 'end', state: 'done', message: 'Finished', ts: 2000 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(liveBodyOf(1).updates[0]).toMatchObject({ event: 'end', state: 'done' })
+ h.stop()
+ })
+
+ it('caps at 20 updates per POST and sends the remainder next', async () => {
+ const { h, st } = wire()
+ for (let i = 0; i < 25; i++) st.emit({ nodeId: `n${i}`, event: 'start', state: 'working', ts: i })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(liveBodyOf(0).updates).toHaveLength(20)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(liveBodyOf(1).updates).toHaveLength(5)
+ h.stop()
+ })
+
+ it('honors NODETERM_API_BASE override', async () => {
+ const { h, st } = wire({ env: { NODETERM_API_BASE: 'http://localhost:9999' } })
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock.mock.calls[0][0]).toBe('http://localhost:9999/v1/push/live-update')
+ h.stop()
+ })
+
+ it('drops on network error without throwing', async () => {
+ fetchMock.mockRejectedValue(new Error('offline'))
+ const { h, st } = wire()
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ h.stop()
+ })
+
+ describe('inert gates (no POST)', () => {
+ async function expectNoPost(over: Partial<LiveUpdateDeps>): Promise<void> {
+ const { h, st, nw } = wire(over)
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ nw.emit({ nodeId: 'a', activity: 'x', ts: 1 })
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).not.toHaveBeenCalled()
+ h.stop()
+ }
+
+ it('master switch off', async () => {
+ await expectNoPost({ mobilePushEnabled: () => false })
+ })
+ it('live-activities sub-gate off', async () => {
+ await expectNoPost({ mobileLiveActivities: () => false })
+ })
+ it('no relay host identity', async () => {
+ await expectNoPost({ getHostIdentity: () => null })
+ })
+ it('no paired phone', async () => {
+ await expectNoPost({ getHostIdentity: () => ({ ...IDENTITY, hasPairedPhone: false }) })
+ })
+ it('DO_NOT_TRACK', async () => {
+ await expectNoPost({ env: { DO_NOT_TRACK: '1' } })
+ })
+ it('unpackaged without a local API base', async () => {
+ await expectNoPost({ isPackaged: () => false, env: {} })
+ })
+ })
+
+ it('stop() unsubscribes both seams so later events are ignored', async () => {
+ const { h, st, nw } = wire()
+ h.stop()
+ st.emit({ nodeId: 'a', event: 'start', state: 'working', ts: 1 })
+ nw.emit({ nodeId: 'a', activity: 'x', ts: 1 })
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/core/push-notify.ts b/src/core/push-notify.ts
index ac82281d6..fa8dede0e 100644
--- a/src/core/push-notify.ts
+++ b/src/core/push-notify.ts
@@ -12,7 +12,7 @@
// identity + paired-phone registry to feed it — the Server Edition has neither, so it never
// constructs this (a documented, deliberate three-surfaces degrade; see src/server/index.ts).
-import type { InboxEvent } from './agent-status-mirror'
+import type { InboxEvent, NodeStateChange, NodeNowChange } from './agent-status-mirror'
const DEFAULT_API_BASE = 'https://api.nodeterm.dev'
// Batch actionable events landing close together into one POST (≤10 events/call per the contract).
@@ -49,6 +49,10 @@ export interface PushNotifyEvent {
* Optional: the backend renders the alert title as "<Needs you|Completed> — <nodeTitle>" when
* present, and falls back to a generic title when absent. */
nodeTitle?: string
+ /** question only: the AskUserQuestion choices (≤4 labels, each ≤60 chars). The backend renders
+ * them as numbered notification actions + appends them to the body (spec:
+ * interactive-push-live-activities). Absent for approvals + plain questions. */
+ options?: string[]
ts: number
}
@@ -166,6 +170,7 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
nodeId: e.nodeId,
...(e.agentId ? { agentId: e.agentId } : {}),
...(nodeTitle ? { nodeTitle } : {}),
+ ...(e.options && e.options.length > 0 ? { options: e.options } : {}),
ts: e.ts
})
scheduleFlush()
@@ -219,3 +224,243 @@ export function createPushNotify(deps: PushNotifyDeps): PushNotifyHandle {
_flushNow: flush
}
}
+
+// ---- Live-update stream (spec: interactive-push-live-activities) ----------------------------
+// A second, chattier stream to `POST {apiBase}/v1/push/live-update`, feeding iOS Live Activities.
+// Two sources from the mirror:
+// - STATE EDGES (`onNodeStateChange`): working start → event 'start', edge into waiting/blocked →
+// event 'update' state 'needsYou', edge into done → event 'end'. Sent IMMEDIATELY (short batch
+// window only, to coalesce simultaneous edges into one POST + honor the ≤20 cap).
+// - NOW CHANGES (`onNodeNowChange`): activity line / context% ticks, COALESCED to ≥20s per node
+// (event 'update', state 'working' — activity only moves while a turn runs).
+// Same host-identity auth + DNT/packaged/paired-phone guards as notify, plus its own
+// `mobileLiveActivities` sub-gate (both under the `mobilePushEnabled` master).
+
+// Batch window for POSTing accumulated updates — short, so a state edge goes out "immediately".
+const DEFAULT_LIVE_BATCH_WINDOW_MS = 1000
+// Coalesce activity/context ticks to at most one live-update per node per this window.
+const DEFAULT_LIVE_COALESCE_MS = 20_000
+// Backend contract cap: updates[≤20] per call.
+const MAX_UPDATES_PER_CALL = 20
+// Live-activity field caps (Apple content-state stays small).
+const LIVE_ACTIVITY_MAX = 80
+const LIVE_MESSAGE_MAX = 120
+
+/** One entry of the `/v1/push/live-update` `updates[]` array (backend contract). */
+export interface LiveUpdateItem {
+ nodeId: string
+ nodeTitle?: string
+ agentId?: string
+ event: 'start' | 'update' | 'end'
+ state: 'working' | 'needsYou' | 'done'
+ activity?: string
+ contextPercent?: number
+ message?: string
+ ts: number
+}
+
+export interface LiveUpdateDeps {
+ /** Subscribe to main-state edges. In production this is `onNodeStateChange`. */
+ subscribeStateChange: (cb: (c: NodeStateChange) => void) => () => void
+ /** Subscribe to per-node activity/context changes. In production this is `onNodeNowChange`. */
+ subscribeNowChange: (cb: (c: NodeNowChange) => void) => () => void
+ /** The standing relay host identity, or null when none is configured/available. */
+ getHostIdentity: () => PushHostIdentity | null
+ /** The `settings.mobilePushEnabled` master switch. */
+ mobilePushEnabled: () => boolean
+ /** The `settings.mobileLiveActivities` sub-gate (default on). */
+ mobileLiveActivities: () => boolean
+ /** `app.isPackaged` — dev never hits the prod API unless a local base is targeted. */
+ isPackaged: () => boolean
+ /** Resolve a node's human display title. In production this is `workspaceStore.getNodeTitle`. */
+ getNodeTitle?: (nodeId: string) => string | undefined
+ apiBase?: string
+ env?: Record<string, string | undefined>
+ fetchImpl?: typeof fetch
+ now?: () => number
+ batchWindowMs?: number
+ coalesceMs?: number
+}
+
+export interface LiveUpdateHandle {
+ stop(): void
+ _flushNow(): Promise<void>
+}
+
+/**
+ * Wire the live-update push stream. State edges post immediately (within a short batch window);
+ * activity/context ticks coalesce to ≥20s per node. Gated by the master switch, the
+ * `mobileLiveActivities` sub-gate, and the same DNT/packaged/identity/paired-phone guards as
+ * notify. Everything is injected — pure + unit-testable. Drops on any network error (no retry).
+ */
+export function createLiveUpdatePush(deps: LiveUpdateDeps): LiveUpdateHandle {
+ const env = deps.env ?? process.env
+ const apiBase = deps.apiBase ?? env.NODETERM_API_BASE ?? DEFAULT_API_BASE
+ const fetchImpl = deps.fetchImpl ?? fetch
+ const now = deps.now ?? Date.now
+ const batchWindowMs = deps.batchWindowMs ?? DEFAULT_LIVE_BATCH_WINDOW_MS
+ const coalesceMs = deps.coalesceMs ?? DEFAULT_LIVE_COALESCE_MS
+
+ const buffer: LiveUpdateItem[] = []
+ // Per-node coalescing of activity/context ticks.
+ const lastNowSentAt = new Map<string, number>()
+ const pendingNow = new Map<string, NodeNowChange>()
+ let batchTimer: ReturnType<typeof setTimeout> | null = null
+ let coalesceTimer: ReturnType<typeof setTimeout> | null = null
+
+ function allowed(): boolean {
+ if (env.DO_NOT_TRACK || env.NODETERM_TELEMETRY_DISABLED) return false
+ if (!deps.isPackaged() && !env.NODETERM_API_BASE) return false
+ return true
+ }
+
+ function liveIdentity(): PushHostIdentity | null {
+ if (!allowed()) return null
+ if (!deps.mobilePushEnabled()) return null
+ if (!deps.mobileLiveActivities()) return null
+ const id = deps.getHostIdentity()
+ if (!id || !id.hasPairedPhone) return null
+ return id
+ }
+
+ function nodeTitleOf(nodeId: string): string | undefined {
+ try {
+ return deps.getNodeTitle?.(nodeId)?.slice(0, NODE_TITLE_MAX) || undefined
+ } catch {
+ return undefined
+ }
+ }
+
+ function scheduleFlush(): void {
+ if (batchTimer) return
+ batchTimer = setTimeout(() => {
+ batchTimer = null
+ void flush()
+ }, batchWindowMs)
+ batchTimer.unref?.()
+ }
+
+ function onStateChange(c: NodeStateChange): void {
+ if (!liveIdentity()) return
+ const title = nodeTitleOf(c.nodeId)
+ buffer.push({
+ nodeId: c.nodeId,
+ ...(title ? { nodeTitle: title } : {}),
+ ...(c.agentId ? { agentId: c.agentId } : {}),
+ event: c.event,
+ state: c.state,
+ ...(c.message ? { message: c.message.slice(0, LIVE_MESSAGE_MAX) } : {}),
+ ts: c.ts
+ })
+ scheduleFlush()
+ }
+
+ /** Push a coalesced now-update for a node into the buffer. */
+ function emitNow(c: NodeNowChange): void {
+ const title = nodeTitleOf(c.nodeId)
+ buffer.push({
+ nodeId: c.nodeId,
+ ...(title ? { nodeTitle: title } : {}),
+ event: 'update',
+ state: 'working',
+ ...(c.activity ? { activity: c.activity.slice(0, LIVE_ACTIVITY_MAX) } : {}),
+ ...(typeof c.contextPercent === 'number' ? { contextPercent: c.contextPercent } : {}),
+ ts: c.ts
+ })
+ scheduleFlush()
+ }
+
+ function scheduleCoalesceTimer(): void {
+ if (coalesceTimer || pendingNow.size === 0) return
+ // Fire at the soonest node's window edge.
+ const t = now()
+ let soonest = Infinity
+ for (const nodeId of pendingNow.keys()) {
+ const due = (lastNowSentAt.get(nodeId) ?? 0) + coalesceMs
+ if (due < soonest) soonest = due
+ }
+ const delay = Math.max(0, soonest - t)
+ coalesceTimer = setTimeout(() => {
+ coalesceTimer = null
+ const cur = now()
+ for (const [nodeId, change] of [...pendingNow]) {
+ if (cur - (lastNowSentAt.get(nodeId) ?? -Infinity) >= coalesceMs) {
+ pendingNow.delete(nodeId)
+ lastNowSentAt.set(nodeId, cur)
+ emitNow(change)
+ }
+ }
+ scheduleCoalesceTimer()
+ }, delay)
+ coalesceTimer.unref?.()
+ }
+
+ function onNowChange(c: NodeNowChange): void {
+ if (!liveIdentity()) return
+ const t = now()
+ const last = lastNowSentAt.get(c.nodeId) ?? -Infinity
+ if (t - last >= coalesceMs) {
+ // Leading edge: send now.
+ lastNowSentAt.set(c.nodeId, t)
+ pendingNow.delete(c.nodeId)
+ emitNow(c)
+ } else {
+ // Within the window: keep only the latest, flush at the window edge.
+ pendingNow.set(c.nodeId, c)
+ scheduleCoalesceTimer()
+ }
+ }
+
+ async function flush(): Promise<void> {
+ if (buffer.length === 0) return
+ const id = liveIdentity()
+ if (!id) {
+ buffer.length = 0
+ return
+ }
+ const updates = buffer.splice(0, MAX_UPDATES_PER_CALL)
+ if (buffer.length > 0) scheduleFlush()
+
+ const body = {
+ hostDeviceId: id.hostDeviceId,
+ hostPublicKeyB64: id.hostPublicKeyB64,
+ hostLabel: id.hostLabel,
+ updates
+ }
+ const ctrl = new AbortController()
+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
+ try {
+ await fetchImpl(`${apiBase}/v1/push/live-update`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ signal: ctrl.signal
+ })
+ } catch {
+ // Drop on any network error — no retry queue (the phone still polls the mirror).
+ } finally {
+ clearTimeout(timer)
+ }
+ }
+
+ const unsubState = deps.subscribeStateChange(onStateChange)
+ const unsubNow = deps.subscribeNowChange(onNowChange)
+
+ return {
+ stop() {
+ unsubState()
+ unsubNow()
+ if (batchTimer) {
+ clearTimeout(batchTimer)
+ batchTimer = null
+ }
+ if (coalesceTimer) {
+ clearTimeout(coalesceTimer)
+ coalesceTimer = null
+ }
+ buffer.length = 0
+ pendingNow.clear()
+ },
+ _flushNow: flush
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index a12268399..769585a04 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -19,6 +19,7 @@ import { generateCommitMessage, generateGroupName, generateTerminalName } from '
import { initUpdater } from './updater'
import { fetchCheck } from '../core/check'
import { hookServer } from '../core/agents/hook-server'
+import { writePendingAnswerLocal, startPendingSweep, isValidPendingId } from '../core/agents/pending-approvals'
import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose } from './main-window'
import {
initAgentStatusMirror,
@@ -31,9 +32,11 @@ import {
setMirrorUsageProvider,
buildMirrorUsage,
onInboxActionable,
+ onNodeStateChange,
+ onNodeNowChange,
type MirrorSettings
} from '../core/agent-status-mirror'
-import { createPushNotify } from '../core/push-notify'
+import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { getDeviceId } from '../core/device-id'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
@@ -772,6 +775,28 @@ app.whenReady().then(async () => {
// "<Needs you|Completed> — <nodeTitle>" (see workspace-store.getNodeTitle for the freshness note).
getNodeTitle: (nodeId) => workspaceStore.getNodeTitle(nodeId)
})
+ // Desktop → paired-phone Live Activity updates (spec: interactive-push-live-activities). Feeds off
+ // the mirror's state-edge + activity/context seams, throttles activity ticks (≥20s/node), and
+ // POSTs to /v1/push/live-update. Same host identity + paired-phone gate as notify, plus its own
+ // `mobileLiveActivities` sub-gate under the `mobilePushEnabled` master. Inert without a paired
+ // phone — same documented three-surfaces degrade (Server Edition has no standing relay identity).
+ createLiveUpdatePush({
+ subscribeStateChange: onNodeStateChange,
+ subscribeNowChange: onNodeNowChange,
+ getHostIdentity: () =>
+ pushHostKeyB64
+ ? {
+ hostDeviceId: getDeviceId(),
+ hostPublicKeyB64: pushHostKeyB64,
+ hostLabel: hostname(),
+ hasPairedPhone: pushHasPairedPhone
+ }
+ : null,
+ mobilePushEnabled: () => settingsStore.get().mobilePushEnabled !== false,
+ mobileLiveActivities: () => settingsStore.get().mobileLiveActivities !== false,
+ isPackaged: () => app.isPackaged,
+ getNodeTitle: (nodeId) => workspaceStore.getNodeTitle(nodeId)
+ })
// 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
@@ -1003,6 +1028,28 @@ app.whenReady().then(async () => {
sendToMain(IPC.agentStatus, e)
recordAgentEvent(e)
})
+ // Deterministic hook-reply approvals (docs/hook-reply-approvals.md): the canvas Approve/Deny
+ // buttons (and any relay client) answer a held Claude permission hook here. Route by the node's
+ // project: an SSH project's hook runs on the REMOTE host (write over its ControlMaster), a local
+ // project's on THIS machine (write under os.homedir() — the hook uses $HOME, which may differ from
+ // the project cwd). pendingId is validated before it is interpolated into any path/command.
+ corePlatform.handle(
+ IPC.agentAnswerPermission,
+ async (payload: { nodeId: string; pendingId: string; decision: 'allow' | 'deny' }) => {
+ const { nodeId, pendingId, decision } = payload ?? ({} as typeof payload)
+ if (!isValidPendingId(pendingId)) return false
+ if (decision !== 'allow' && decision !== 'deny') return false
+ const sshProjectId = workspaceStore.sshProjectIdForNode(nodeId)
+ if (sshProjectId && sshProjectManager) {
+ return sshProjectManager.writePendingAnswer(sshProjectId, pendingId, decision)
+ }
+ return writePendingAnswerLocal(pendingId, decision, homedir())
+ }
+ )
+ // 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.
+ startPendingSweep(homedir())
// Security: hook POSTs now arrive over the remote reverse tunnel too (SSH Phase 2a), so a
// forged/remote POST could set transcript_path to an arbitrary LOCAL path (e.g. ~/.ssh/id_rsa)
// and have the app read it. The tails read the LOCAL filesystem; legitimate LOCAL transcripts
diff --git a/src/renderer/components/settings/sections/NotificationsSection.tsx b/src/renderer/components/settings/sections/NotificationsSection.tsx
index 4a6a6b473..aa7396b50 100644
--- a/src/renderer/components/settings/sections/NotificationsSection.tsx
+++ b/src/renderer/components/settings/sections/NotificationsSection.tsx
@@ -13,7 +13,7 @@ const ROWS = {
},
mobilePush: {
title: 'Send push notifications to your paired phone',
- keywords: ['push', 'phone', 'mobile', 'apns', 'ios', 'notification', 'approval', 'question', 'done', 'completed', 'needs you']
+ keywords: ['push', 'phone', 'mobile', 'apns', 'ios', 'notification', 'approval', 'question', 'done', 'completed', 'needs you', 'live activity', 'live activities', 'dynamic island', 'lock screen']
}
}
const ENTRIES = Object.values(ROWS)
@@ -23,6 +23,7 @@ export function NotificationsSection({ isActive }: { isActive: boolean }): React
const mobilePushEnabled = useSettings((s) => s.settings.mobilePushEnabled)
const mobilePushNeedsYou = useSettings((s) => s.settings.mobilePushNeedsYou)
const mobilePushDone = useSettings((s) => s.settings.mobilePushDone)
+ const mobileLiveActivities = useSettings((s) => s.settings.mobileLiveActivities)
const update = useSettings((s) => s.update)
// The OS refused our test notification (macOS permission denied). macOS never re-prompts
// once the app's record exists, so the only way back is the System Settings pane.
@@ -110,6 +111,17 @@ export function NotificationsSection({ isActive }: { isActive: boolean }): React
/>
}
/>
+ <FieldRow
+ label="Live Activities"
+ description="Keep a Lock Screen / Dynamic Island activity updated as a session works, needs you, or finishes."
+ control={
+ <Switch
+ checked={mobileLiveActivities}
+ ariaLabel="Live Activities on your phone"
+ onChange={(on) => update({ mobileLiveActivities: on })}
+ />
+ }
+ />
</div>
</SearchableRow>
</SettingsSection>
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e5368c28f..3094365cc 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -668,6 +668,15 @@ export interface Settings {
/** Push when an agent finishes a turn (the `done` kind). Default on. Sub-gate under
* `mobilePushEnabled` (the master switch). Toggle in Settings → Notifications. */
mobilePushDone: boolean
+ /** Stream Live Activity updates (Lock Screen / Dynamic Island) to paired phones as a session's
+ * state + activity + context% change (spec: interactive-push-live-activities). Default on.
+ * Sub-gate under `mobilePushEnabled` (the master switch). Toggle in Settings → Notifications. */
+ mobileLiveActivities: boolean
+ /** Deterministic hook-reply approvals (spec: docs/hook-reply-approvals.md). When on (default),
+ * Claude terminal sessions launch with `NODETERM_PERM_WAIT_SECS` set: the managed permission
+ * hook holds briefly for a phone/canvas Approve/Deny before falling through to the normal
+ * interactive prompt. Off ⇒ the env var is absent ⇒ exact legacy behavior. Claude-only. */
+ hookReplyApprovals: boolean
/** Dictation (desktop/server). Written as a whole object by the renderer. */
speech: SpeechSettings
}
@@ -715,6 +724,10 @@ export const DEFAULT_SETTINGS: Settings = {
mobilePushEnabled: true,
mobilePushNeedsYou: true,
mobilePushDone: true,
+ mobileLiveActivities: true,
+ // Deterministic hook-reply approvals default ON (existing users pick it up on hydrate). Only
+ // affects Claude terminal sessions; off reproduces the pre-feature launch bit-for-bit.
+ hookReplyApprovals: true,
speech: { engine: 'whisper', model: 'tiny', language: 'auto', shortcut: 'Cmd+Alt' },
}
@@ -1594,6 +1607,13 @@ export interface NodeTerminalApi {
openNotificationSettings(): Promise<void>
/** Fires when a notification is clicked, asking the renderer to focus a node. Returns unsubscribe. */
onFocusNode(listener: (nodeId: string) => void): () => void
+ /** Answer a Claude permission request via the deterministic hook-reply channel (spec:
+ * docs/hook-reply-approvals.md). Writes the one-line answer file the held hook is polling
+ * (`~/.nodeterm/pending/<pendingId>.answer`) on the host the agent runs on — the LOCAL fs for a
+ * local project, or the remote host over the project's ControlMaster for an SSH project. Resolves
+ * `true` when the file was written, `false` on any failure (invalid pendingId, unknown node,
+ * unsupported project, fs/exec error). */
+ answerPermission(payload: { nodeId: string; pendingId: string; decision: 'allow' | 'deny' }): Promise<boolean>
/** 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. */