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(relay): chat.page/status/send and agent.answer for the phone

review8daec3b094a2
diff --git a/CLAUDE.md b/CLAUDE.md
index 237c97112..95542bdcc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5448,6 +5448,24 @@ to the class, and no bare `.react-flow__viewport` rule carries `will-change`).
`POST /v1/relay/host-token` / `/v1/relay/device` must admit deviceId (no-entitlement) mints, and
the relay server may rate-limit free hosts independently — a client-side gate must NOT be
reintroduced to work around a backend refusal (fix the backend policy instead).
+- **The phone's Chat screen verbs** (`chat.page` / `chat.status` / `chat.send` / `agent.answer`,
+ `host-service.ts` `handleChat` → `main/remote/host-chat.ts`, spec + exact error strings in
+ `docs/mobile-chat-view.md` §3.2). Four rules a refactor must not undo: (1) **the phone sends only a
+ node id**; cwd/account/agent/session are resolved from THIS machine's records
+ (`WorkspaceStore.getNodeResolved` + the mirror), and a node with no known session id reads
+ NOTHING rather than claude's cwd-newest fallback (a stranger's session); (2) **the send gate is
+ the renderer's** — `chat.status`/`chat.send` are an IPC round-trip (`host:chat-query` /
+ `host:chat-reply`, sender-checked to the main window) answered from the agent-status store and the
+ ⌘M composer's `chatSendRefusal` at send time plus "no held request", and a renderer that does not
+ answer FAILS CLOSED (status is an error, send is `'refused'`; a late renderer refuses a send past
+ its `startBy`); (3) **text is capped raw (64000) then stripped of ESC + C0/C1** (`\n`/`\t` kept) and
+ rides `pty.sendText` (stdin into tmux, never argv); `'sent'` only for `sendText === true`;
+ (4) **`agent.answer` is the desktop answer path** — `answerHeldPermission` over the SAME
+ `heldPermissionIoFor` (local fs or the SSH ControlMaster) and the in-process structured-ticket
+ gate. The `chat` dependency is OPTIONAL at every hop, so a dropped hop compiles and ships the verbs
+ inert ("not served"); `host-chat-wiring.test.ts` pins the chain at source level. Served only to an
+ approved phone; Team-access relay guests never reach them (`relay-host.ts` serves no phone
+ dialect). Server Edition: N/A (no phone relay; the bridge subscription is inert).
- **A Windows desktop pairs relay-only — no SSH key, and do not "fix" that by writing one.** The
phone's direct-SSH path is POSIX sh + tmux end to end (nodeterm-ios `HostCommands`, `TmuxBinary`,
the typed `tmux new-session -A` attach, workspace paths with no `%APPDATA%` candidate). Windows
diff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.md
index dc3f2ea94..d0f96fbc9 100644
--- a/docs/mobile-chat-view.md
+++ b/docs/mobile-chat-view.md
@@ -69,22 +69,47 @@ ChatStatus { state, held?: {pendingId, toolName, questions?}, hibernated, paused
`version` lets the phone refuse a newer shape honestly.
-### 3.2 Relay producer (desktop, this repo)
-
-New verbs in `host-service.ts` `onRpc`, all behind the existing relay project-scope jail; the phone
-sends **only `nodeId`** (plus paging/answer payload) — cwd, account, agent, transcript path and remote
-routing are resolved host-side from the desktop's own registry (node ids are attacker-controllable;
-never trust phone-supplied paths).
-
-| verb | params | does |
-|---|---|---|
-| `chat.page` | `{nodeId, before?, maxBytes?}` | `readChatPage` (paged, remote-aware, grok unpaged) + `model`/`effort` |
-| `chat.status` | `{nodeId}` | agent state + `held` + shell-owned-pane flags + whether structured answers are supported (revision gate) |
-| `chat.send` | `{nodeId, text}` | desktop send gate (`canSendFromChat` + `agentProcessInPane` + no held request) then `sendText` |
-| `agent.answer` | `{nodeId, pendingId, answer: PermissionAnswer}` | `answerHeldPermission` (pending file is the source of truth; revision gate; no `setMode auto`) |
-
-Limits: page ≤ 5 MB (existing clamp), text ≤ 64K chars, answer ≤ 64K chars. Unknown verb on an older
-desktop → the phone shows "Update nodeterm on your computer".
+### 3.2 Relay producer (desktop, this repo) — implemented
+
+Four verbs in `host-service.ts` `onRpc` (`handleChat`), served to an **approved phone** only (the
+session's approval gate refuses every RPC before approval). They are NOT reachable from a Team-access
+relay guest: `relay-host.ts` serves no phone dialect at all (its `onRpc` is inert), so the
+project-scope jail in `relay-project-scope.ts` never sees them and they widen nothing. The phone
+sends **only `nodeId`** (plus paging / text / answer payload) — cwd, account, agent, session id,
+transcript path and remote routing are resolved host-side from the desktop's own registry
+(`WorkspaceStore.getNodeResolved` + the agent-status mirror; node ids are attacker-controllable, so
+a phone-supplied path is never trusted). Ops: `main/remote/host-chat.ts` (`createHostChat`, wired
+as `hostBridge.chat` in `main/index.ts`, forwarded by both phone hosts).
+
+| verb | params | reply | does |
+|---|---|---|---|
+| `chat.page` | `{nodeId, before?, maxBytes?}` | `{page: ChatPage}` | `readChatTranscript` with the ⌘M panel's own deps (paged ALWAYS — an absent page is the default 256 KB tail; remote-aware; grok unpaged) + `model`/`effort`, `version: 1`. No known session id ⇒ no cwd fallback (it would pick the cwd's newest transcript, possibly another node's) ⇒ `found:false`. |
+| `chat.status` | `{nodeId}` | `{status: ChatStatus}` | the renderer's agent-status entry (`state` null = unknown, `held`, hibernated/paused/dropped/sessionEnded) + `structuredAnswers` = the held ticket is in main's structured-ticket ledger (script revision ≥ 5). |
+| `chat.send` | `{nodeId, text}` | `{result: 'sent' \| 'refused' \| 'pasted-not-submitted'}` | text capped at 64000 UTF-16 units RAW, then ESC + C0/C1 stripped (`\n`, `\t` kept; `sanitizeChatText`); the renderer runs the ⌘M composer's gate at send time (`chatSendRefusal` = `agentProcessInPane` + state ∈ {done, unknown}) plus "no held request", then `pty.sendText`. `'sent'` only for `sendText === true`. |
+| `agent.answer` | `{nodeId, pendingId, answer}` | `{ok: boolean}` | `answerHeldPermission` with the node's own I/O (local fs, or the SSH project's ControlMaster — the same `heldPermissionIoFor` the desktop answer path uses): validated against the pending request file, structured-ticket gated, no `setMode auto`. Success emits the same optimistic "answered" event. |
+
+Refusals are `respond(id, false, {message})`, with these exact strings:
+
+| message | when |
+|---|---|
+| `<verb> is not served on this host.` | a desktop without the ops (pre-feature, or an unwired context) |
+| `Invalid node id.` | `nodeId` missing / not a string / over `REF_MAX_LEN` / contains a C0/C1 control char |
+| `Unknown node.` | the host has no such node (`chat.page`, `chat.status`, `chat.send`) |
+| `Invalid page.` | `before` / `maxBytes` rejected by `normalizeChatPage` (checked before any read) |
+| `Could not read the transcript.` | the page read failed (never an empty page standing in for it) |
+| `The desktop window is not available.` | `chat.status`: the renderer did not answer within 3 s (or there is no window) — never a guessed state |
+| `Text too long.` | `chat.send` raw text over 64000 UTF-16 units |
+| `chat.send requires non-empty text.` | nothing left after stripping control chars and whitespace |
+| `Invalid pending id.` | `agent.answer` `pendingId` fails `isValidPendingId` |
+
+Fail-closed rules: a `chat.send` whose renderer does not START within 3 s is refused unsent (the
+query carries `startBy`; a late renderer refuses rather than typing), a started send gets 15 s to
+report and is `'refused'` past it (the one residual race — the text may still land); a throwing send
+is `'refused'`, a throwing answer is `{ok:false}`. `agent.answer` for an unknown node is `{ok:false}`
+(no I/O touched). Limits: page ≤ 5 MB (existing clamp), chat text ≤ 64000, answer text ≤ 8000
+(`ANSWER_TEXT_MAX_CHARS`, applied by `buildPermissionDecision`). Unknown verb on an older desktop →
+`Unknown method: chat.page` → the phone shows "Update nodeterm on your computer". Server Edition:
+N/A (it serves no phone relay; its bridge subscription is inert).
### 3.3 SSH producer (phone, `nodeterm-ios`)
diff --git a/src/core/agents/answer-permission-parity.test.ts b/src/core/agents/answer-permission-parity.test.ts
index 1bd187af9..33b0dd66a 100644
--- a/src/core/agents/answer-permission-parity.test.ts
+++ b/src/core/agents/answer-permission-parity.test.ts
@@ -26,6 +26,14 @@ describe('answerPermission handler parity', () => {
})
}
it('the desktop reads the held request over SSH for a remote node', () => {
- expect(handler('src/main/index.ts')).toContain('readPendingRequest(sshProjectId, pendingId)')
+ // The I/O choice lives in `heldPermissionIoFor`, shared by this handler and the phone's
+ // `agent.answer` (main/remote/host-chat.ts), so both answer paths reach the same host.
+ expect(handler('src/main/index.ts')).toContain('heldPermissionIoFor(nodeId, pendingId)')
+ const src = readFileSync(resolve(root, 'src/main/index.ts'), 'utf8')
+ const at = src.indexOf('const heldPermissionIoFor =')
+ expect(at).toBeGreaterThan(-1)
+ expect(src.slice(at, at + 800)).toContain('readPendingRequest(sshProjectId, pendingId)')
+ // …and the phone path uses the same function, not a second copy.
+ expect(src).toContain('answerIo: heldPermissionIoFor')
})
})
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 9acb3786b..78aa05f12 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -2284,3 +2284,28 @@ describe('localOnly save (the launch write-ahead barrier)', () => {
expect(calls[0]).toBe('read:ps')
})
})
+
+// The phone Chat verbs resolve a node HOST-side (main/remote/host-chat.ts): the node's cwd must be
+// the ABSOLUTE path the canvas uses, not the portable "./sub" form a local ref's project.json stores
+// — the cwd is what the transcript resolver keys on.
+describe('getNodeResolved — a node with its cwd as the canvas sees it', () => {
+ const termAt = (id: string, cwd: string | undefined) => ({
+ id, kind: 'terminal' as const, position: { x: 0, y: 0 }, size: { width: 1, height: 1 },
+ title: id, color: '#fff', group: null, cwd, agentId: 'claude'
+ })
+ it('resolves a local ref\'s portable cwd against the project root', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: 'p-local', cwd: projRoot, nodes: [termAt('n-sub', path.join(projRoot, 'sub')), termAt('n-root', projRoot)] })]))
+ expect(store.getNodeResolved('n-sub')?.cwd).toBe(path.join(projRoot, 'sub'))
+ expect(store.getNodeResolved('n-root')?.cwd).toBe(projRoot)
+ expect(store.getNodeResolved('n-sub')?.agentId).toBe('claude')
+ // getNode keeps the stored (portable) form — its existing callers are unchanged.
+ expect(store.getNode('n-sub')?.cwd).toBe('./sub')
+ })
+ it('passes inline / absolute cwds through and answers undefined for an unknown node', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ id: 'p-inline', cwd: undefined, nodes: [termAt('n-abs', '/elsewhere')] })]))
+ expect(store.getNodeResolved('n-abs')?.cwd).toBe('/elsewhere')
+ expect(store.getNodeResolved('nope')).toBeUndefined()
+ })
+})
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 37f89d76c..ffd0ee7ca 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1466,6 +1466,23 @@ export class WorkspaceStore {
* `getNodeTitle`, which now delegates here.
*/
getNode(nodeId: string): CanvasNodeState | undefined {
+ return this.findNode(nodeId)?.node
+ }
+
+ /**
+ * `getNode`, with the node's cwd as the CANVAS sees it: a local ref's project.json stores node
+ * cwds portable (`./sub`), and this resolves them against the project root exactly as
+ * `fileToProject` / `persistedCanvases` do. For callers that hand the cwd to a resolver keyed on
+ * the absolute path (the phone Chat verbs' transcript read). `getNode` keeps the stored form so
+ * its existing callers are unchanged.
+ */
+ getNodeResolved(nodeId: string): CanvasNodeState | undefined {
+ const hit = this.findNode(nodeId)
+ if (!hit) return undefined
+ return hit.root ? resolveNodes([hit.node], hit.root)[0] : hit.node
+ }
+
+ private findNode(nodeId: string): { node: CanvasNodeState; root?: string } | undefined {
for (const e of this.index?.entries ?? []) {
let nodes: CanvasNodeState[] | undefined
if (e.project) nodes = e.project.nodes
@@ -1481,7 +1498,8 @@ export class WorkspaceStore {
}
}
const node = nodes?.find((n) => n.id === nodeId)
- if (node) return node
+ // Only a local ref's nodes come off the shared file in portable form.
+ if (node) return { node, root: !e.project && !e.cache && e.cwd ? e.cwd : undefined }
}
return undefined
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 66bdb4b32..35d252d54 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -132,7 +132,7 @@ import {
isValidPendingId,
syntheticAnsweredEvent
} from '../core/agents/pending-approvals'
-import { answerHeldPermission, type HeldPermissionIo } from '../core/agents/permission-decision'
+import { answerHeldPermission, isStructuredTicket, type HeldPermissionIo } from '../core/agents/permission-decision'
import type { AnswerPermissionPayload } from '../shared/agents/permission-answer'
import { setMainWindow, getMainWindow, sendToMain, closeAction, createCrashReloadPolicy } from './main-window'
import {
@@ -185,7 +185,8 @@ import {
sessionNameSweepEntries,
nodeState,
nodeSessionName,
- workingNodes
+ workingNodes,
+ mirrorEntry
} from '../core/agent-status-mirror'
import { paneOwnerProject } from '../core/agents/pane-ownership'
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
@@ -227,7 +228,9 @@ import {
parseLocatedTranscript,
remoteTranscriptRoots
} from '../core/remote-transcript-locate'
-import { registerTranscriptIpc, resolveTranscript } from '../core/transcript-ipc'
+import { readChatTranscript, registerTranscriptIpc, resolveTranscript, type TranscriptIpcDeps } from '../core/transcript-ipc'
+import { createHostChat } from './remote/host-chat'
+import type { ChatSendResult, ChatStatus, HostChatReply } from '../shared/mobile-chat'
import {
createReadRemotePage,
forgetLocatedRef,
@@ -2667,7 +2670,8 @@ app.whenReady().then(async () => {
// Both read channels now live in core (the Server Edition serves the very same handlers); the
// ONE thing this shell adds is the remote leg, which needs a ControlMaster. `null` means "not a
// remote session", which is the signal for core to take its local path.
- registerTranscriptIpc({
+ // Named so the phone Chat verbs (hostBridge.chat) read through the SAME deps as the ⌘M panel.
+ const transcriptIpcDeps: TranscriptIpcDeps = {
pathFor: (sessionId) => contextTail.pathFor(sessionId),
readRemote: async ({ sessionId, cwd, accountId, nodeId }) => {
const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)
@@ -2685,7 +2689,8 @@ app.whenReady().then(async () => {
}),
remoteExists: async ({ sessionId, accountId, nodeId }) =>
sessionId ? await remoteTranscriptPresence(sessionId, accountId, nodeId) : null
- })
+ }
+ registerTranscriptIpc(transcriptIpcDeps)
initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])
corePlatform.handle(IPC.transcriptSearch, (query: string) => searchTranscripts(query))
@@ -2788,20 +2793,24 @@ app.whenReady().then(async () => {
// 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.
+ // The held request's I/O for a node — shared with the phone's `agent.answer` (hostBridge.chat) so
+ // both answer paths reach the SAME host the same way.
+ const heldPermissionIoFor = (nodeId: string, pendingId: string): HeldPermissionIo => {
+ const sshProjectId = workspaceStore.sshProjectIdForNode(nodeId)
+ return sshProjectId && sshProjectManager
+ ? {
+ readPending: () => sshProjectManager!.readPendingRequest(sshProjectId, pendingId),
+ write: (content) => sshProjectManager!.writePendingAnswer(sshProjectId, pendingId, content)
+ }
+ : localHeldPermissionIo(pendingId, homedir())
+ }
corePlatform.handle(IPC.agentAnswerPermission, async (payload: AnswerPermissionPayload) => {
const { nodeId, pendingId } = payload ?? ({} as AnswerPermissionPayload)
if (typeof nodeId !== 'string' || !isValidPendingId(pendingId)) return false
- const sshProjectId = workspaceStore.sshProjectIdForNode(nodeId)
// The ONE answer body both shells share (core/agents/permission-decision.ts): read the held
// request on the host the agent runs on, validate + build the decision there, write it back.
// A structured answer is refused without a readable request; the legacy words are not.
- const io: HeldPermissionIo =
- sshProjectId && sshProjectManager
- ? {
- readPending: () => sshProjectManager!.readPendingRequest(sshProjectId, pendingId),
- write: (content) => sshProjectManager!.writePendingAnswer(sshProjectId, pendingId, content)
- }
- : localHeldPermissionIo(pendingId, homedir())
+ const io = heldPermissionIoFor(nodeId, pendingId)
const res = await answerHeldPermission(pendingId, { decision: payload.decision, answer: payload.answer }, io)
// Optimistic flip: on a successful write, emit the same synthetic "answered" transition the
// held hook's second POST will produce, so the NEEDS YOU badge clears instantly instead of
@@ -4030,6 +4039,67 @@ app.whenReady().then(async () => {
rename: (nodeId: string, title: string) => deliver(IPC.agentRenameNode, { nodeId, title })
}
})(),
+ // The phone's Chat screen (`chat.page` / `chat.status` / `chat.send` / `agent.answer`,
+ // main/remote/host-chat.ts). Everything about the node comes from THIS machine's records: the
+ // workspace store (cwd resolved as the canvas sees it, account, agent) and the status mirror
+ // (the live session id; the node's minted `agentSessionId` covers a restart). The page reads
+ // through the ⌘M panel's own deps, the answer through the desktop answer path's own I/O, and
+ // status / send ask the renderer, which owns the agent-status store and the send gate.
+ chat: createHostChat({
+ lookupNode: (nodeId) => {
+ const node = workspaceStore.getNodeResolved(nodeId)
+ if (!node) return null
+ const m = mirrorEntry(nodeId)
+ return {
+ cwd: node.cwd,
+ // The effective account for READERS (CLAUDE.md "Observed account"): the node's own
+ // binding, else the account its session was observed on.
+ accountId: node.accountId ?? m?.account?.accountId ?? undefined,
+ agentId: node.agentId ?? m?.agentId,
+ sessionId: m?.sessionId ?? node.agentSessionId
+ }
+ },
+ readTranscript: (q, rawPage) => readChatTranscript(q, rawPage, transcriptIpcDeps),
+ answerIo: heldPermissionIoFor,
+ isStructuredTicket,
+ onAnswered: (nodeId, pendingId, decision) => {
+ const ev = syntheticAnsweredEvent(nodeId, pendingId, decision)
+ if (ev) emitAgentStatus(ev)
+ },
+ renderer: (() => {
+ const pending = new Map<string, (reply: HostChatReply) => void>()
+ ipcMain.on(IPC.hostChatReply, (e, reply: HostChatReply) => {
+ // Only the main window answers; a <webview> guest is a webContents in this process too.
+ if (win.isDestroyed() || e.sender !== win.webContents) return
+ const resolve = reply && typeof reply.requestId === 'string' ? pending.get(reply.requestId) : undefined
+ if (!resolve) return
+ pending.delete(reply.requestId)
+ resolve(reply)
+ })
+ const ask = (q: { kind: 'status'; nodeId: string; agentId?: string } | {
+ kind: 'send'; nodeId: string; agentId?: string; text: string; startBy: number
+ }): Promise<HostChatReply | null> => {
+ if (win.isDestroyed()) return Promise.resolve(null)
+ const requestId = randomUUID()
+ // host-chat.ts races this against its own timeout; a reply that never comes leaves only
+ // this entry, dropped here when the race is lost.
+ const answered = new Promise<HostChatReply>((resolve) => pending.set(requestId, resolve))
+ win.webContents.send(IPC.hostChatQuery, { ...q, requestId })
+ const drop = setTimeout(() => pending.delete(requestId), 30_000)
+ return answered.finally(() => clearTimeout(drop))
+ }
+ return {
+ status: async (q: { nodeId: string; agentId?: string }): Promise<Omit<ChatStatus, 'structuredAnswers'> | null> => {
+ const r = await ask({ kind: 'status', ...q })
+ return r && r.kind === 'status' ? r.status : null
+ },
+ send: async (q: { nodeId: string; agentId?: string; text: string; startBy: number }): Promise<ChatSendResult | null> => {
+ const r = await ask({ kind: 'send', ...q })
+ return r && r.kind === 'send' ? r.result : null
+ }
+ }
+ })()
+ }),
// 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).
diff --git a/src/main/remote/host-chat-wiring.test.ts b/src/main/remote/host-chat-wiring.test.ts
new file mode 100644
index 000000000..dc53c52dc
--- /dev/null
+++ b/src/main/remote/host-chat-wiring.test.ts
@@ -0,0 +1,30 @@
+// The phone Chat verbs' `chat` dependency is OPTIONAL at every hop (host-service's handler
+// parameter, HostSessionOptions, HostBridgeDeps), so dropping it anywhere compiles and passes every
+// unit test while every phone gets "chat.page is not served on this host." — the verbs shipped
+// inert. Pinned at source level, the remedy this repo uses for exactly that class of hole
+// (hook-verified-parity.test.ts, codex-identity-record-wiring.test.ts).
+import { describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+
+const read = (rel: string): string => fs.readFileSync(path.join(__dirname, '..', '..', rel), 'utf8').replace(/\r\n/g, '\n')
+
+describe('phone chat verbs are wired end to end', () => {
+ it('main builds the ops and puts them on the shared host bridge', () => {
+ const src = read('main/index.ts')
+ expect(src).toMatch(/\n\s{4}chat: createHostChat\(\{/)
+ // Both phone hosts receive that one bridge.
+ expect(src).toMatch(/initRemoteHost\(win, ptyManager, listProjectsOutput, hostBridge\)/)
+ expect(src).toMatch(/initStandingHost\(.*, hostBridge\)/)
+ })
+ it('both phone hosts forward bridge.chat into the session, and the session into the handlers', () => {
+ expect(read('main/remote/host-service.ts')).toMatch(/chat: bridge\.chat,/)
+ expect(read('main/remote/standing-host.ts')).toMatch(/chat: bridge\.chat,/)
+ expect(read('main/remote/host-service.ts')).toMatch(/opts\.kanban,\n\s*opts\.chat\n\s*\)/)
+ })
+ it('the renderer answers the round-trip', () => {
+ const canvas = read('renderer/canvas/Canvas.tsx')
+ expect(canvas).toMatch(/api\.onHostChatQuery\(/)
+ expect(canvas).toMatch(/api\.sendHostChatReply\(/)
+ })
+})
diff --git a/src/main/remote/host-chat.test.ts b/src/main/remote/host-chat.test.ts
new file mode 100644
index 000000000..a1a91dd9c
--- /dev/null
+++ b/src/main/remote/host-chat.test.ts
@@ -0,0 +1,146 @@
+// The production HostChatOps (host-chat.ts), over injected deps. What these pin:
+// - Every verb resolves the node HOST-side (`lookupNode`); nothing about the node comes from the
+// phone. A node the host does not know is refused (null / 'unknown-node' / false).
+// - `page` always reads PAGED (an absent page is the default tail, never the legacy 5 MB read),
+// stamps `version: 1`, and never lets a node with no session id fall back to the cwd's newest
+// transcript (a stranger's session).
+// - `status` / `send` ask the renderer and FAIL CLOSED: a renderer that does not answer within
+// the timeout is an error for status and a refusal for send — never a guessed state, never
+// "sent".
+// - `answer` runs `answerHeldPermission` with the node's I/O, and reports the answered
+// transition on success only.
+import { describe, expect, it, vi } from 'vitest'
+import { createHostChat, type HostChatDeps } from './host-chat'
+import type { ChatTranscriptResult } from '../../shared/types'
+import type { HeldPermissionIo } from '../../core/agents/permission-decision'
+
+const RESULT: ChatTranscriptResult = { messages: [], found: true, olderCursor: null, unmatchedResults: [], model: 'm' }
+const RSTATUS = { state: 'done' as const, held: null, hibernated: false, paused: false, dropped: false, sessionEnded: false }
+
+function deps(over: Partial<HostChatDeps> = {}): HostChatDeps {
+ return {
+ lookupNode: vi.fn((id: string) =>
+ id === 'n1' ? { cwd: '/srv/app', accountId: 'acc', agentId: 'claude', sessionId: 'sid-1' } : null
+ ),
+ readTranscript: vi.fn(async () => RESULT),
+ answerIo: vi.fn(() => ({ readPending: async () => null, write: async () => true }) as HeldPermissionIo),
+ answerHeld: vi.fn(async () => ({ ok: true, decision: 'allow' as const })),
+ onAnswered: vi.fn(),
+ isStructuredTicket: vi.fn(() => false),
+ renderer: {
+ status: vi.fn(async () => RSTATUS),
+ send: vi.fn(async () => 'sent' as const)
+ },
+ timeoutMs: 20,
+ sendTimeoutMs: 40,
+ now: () => 1000,
+ ...over
+ }
+}
+
+describe('host-chat page', () => {
+ it('resolves the node host-side, reads paged and stamps version 1', async () => {
+ const d = deps()
+ const page = await createHostChat(d).page('n1', { before: 10, maxBytes: 65536 })
+ expect(page).toEqual({ ...RESULT, version: 1 })
+ expect(d.readTranscript).toHaveBeenCalledWith(
+ { sessionId: 'sid-1', cwd: '/srv/app', accountId: 'acc', nodeId: 'n1', agentId: 'claude' },
+ { before: 10, maxBytes: 65536 }
+ )
+ })
+ it('an absent page is the default paged tail, not the legacy read', async () => {
+ const d = deps()
+ await createHostChat(d).page('n1', undefined)
+ expect(d.readTranscript).toHaveBeenCalledWith(expect.anything(), {})
+ })
+ it('a node the host does not know is null (and nothing is read)', async () => {
+ const d = deps()
+ expect(await createHostChat(d).page('nope', {})).toBeNull()
+ expect(d.readTranscript).not.toHaveBeenCalled()
+ })
+ it('no known session id ⇒ no cwd either, so no cwd fallback onto a stranger\'s transcript', async () => {
+ const d = deps({ lookupNode: () => ({ cwd: '/srv/app', agentId: 'claude' }) })
+ await createHostChat(d).page('n1', {})
+ expect(d.readTranscript).toHaveBeenCalledWith(
+ { sessionId: undefined, cwd: undefined, accountId: undefined, nodeId: 'n1', agentId: 'claude' },
+ {}
+ )
+ })
+})
+
+describe('host-chat status', () => {
+ it('asks the renderer with the host\'s agent id and adds structuredAnswers for a held ticket', async () => {
+ const held = { pendingId: 'p-1', toolName: 'ExitPlanMode' }
+ const d = deps({
+ renderer: { status: vi.fn(async () => ({ ...RSTATUS, state: 'waiting' as const, held })), send: vi.fn() },
+ isStructuredTicket: vi.fn((id: string) => id === 'p-1')
+ })
+ const s = await createHostChat(d).status('n1')
+ expect(s).toEqual({ ...RSTATUS, state: 'waiting', held, structuredAnswers: true })
+ expect(d.renderer.status).toHaveBeenCalledWith({ nodeId: 'n1', agentId: 'claude' })
+ })
+ it('structuredAnswers is false with no held request', async () => {
+ const d = deps({ isStructuredTicket: vi.fn(() => true) })
+ expect((await createHostChat(d).status('n1'))?.structuredAnswers).toBe(false)
+ })
+ it('unknown node ⇒ null, renderer never asked', async () => {
+ const d = deps()
+ expect(await createHostChat(d).status('nope')).toBeNull()
+ expect(d.renderer.status).not.toHaveBeenCalled()
+ })
+ it('a renderer that does not answer in time (or has no window) REJECTS — never a guessed state', async () => {
+ const hang = deps({ renderer: { status: () => new Promise(() => {}), send: vi.fn() } })
+ await expect(createHostChat(hang).status('n1')).rejects.toThrow()
+ const gone = deps({ renderer: { status: async () => null, send: vi.fn() } })
+ await expect(createHostChat(gone).status('n1')).rejects.toThrow()
+ })
+})
+
+describe('host-chat send', () => {
+ it('asks the renderer (which owns the send gate) and passes its answer through', async () => {
+ const d = deps()
+ expect(await createHostChat(d).send('n1', 'hello')).toBe('sent')
+ // startBy = now + timeoutMs: the renderer refuses a send it receives after that.
+ expect(d.renderer.send).toHaveBeenCalledWith({ nodeId: 'n1', agentId: 'claude', text: 'hello', startBy: 1020 })
+ })
+ it('unknown node ⇒ unknown-node, renderer never asked', async () => {
+ const d = deps()
+ expect(await createHostChat(d).send('nope', 'hi')).toBe('unknown-node')
+ expect(d.renderer.send).not.toHaveBeenCalled()
+ })
+ it('timeout / no window / a throw ⇒ refused, never sent', async () => {
+ for (const send of [() => new Promise<never>(() => {}), async () => null, async () => { throw new Error('x') }]) {
+ const d = deps({ renderer: { status: vi.fn(), send: send as never } })
+ expect(await createHostChat(d).send('n1', 'hi')).toBe('refused')
+ }
+ })
+})
+
+describe('host-chat answer', () => {
+ it('runs answerHeldPermission with the node\'s I/O and reports the answered transition', async () => {
+ const d = deps()
+ const answer = { kind: 'plan', mode: 'restore' }
+ expect(await createHostChat(d).answer('n1', 'p-1', answer)).toBe(true)
+ expect(d.answerIo).toHaveBeenCalledWith('n1', 'p-1')
+ const io = (d.answerIo as ReturnType<typeof vi.fn>).mock.results[0].value
+ expect(d.answerHeld).toHaveBeenCalledWith('p-1', { answer }, io)
+ expect(d.onAnswered).toHaveBeenCalledWith('n1', 'p-1', 'allow')
+ })
+ it('a refused answer is false and reports nothing', async () => {
+ const d = deps({ answerHeld: vi.fn(async () => ({ ok: false })) })
+ expect(await createHostChat(d).answer('n1', 'p-1', { kind: 'deny' })).toBe(false)
+ expect(d.onAnswered).not.toHaveBeenCalled()
+ })
+ it('an unknown node is false and touches no I/O', async () => {
+ const d = deps()
+ expect(await createHostChat(d).answer('nope', 'p-1', { kind: 'deny' })).toBe(false)
+ expect(d.answerIo).not.toHaveBeenCalled()
+ expect(d.answerHeld).not.toHaveBeenCalled()
+ })
+ it('the real answerHeldPermission refuses a structured answer on a non-capable ticket (no write)', async () => {
+ const write = vi.fn(async () => true)
+ const d = deps({ answerHeld: undefined, answerIo: () => ({ readPending: async () => null, write }) })
+ expect(await createHostChat(d).answer('n1', 'never-seen-ticket', { kind: 'plan', mode: 'restore' })).toBe(false)
+ expect(write).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/remote/host-chat.ts b/src/main/remote/host-chat.ts
new file mode 100644
index 000000000..8efa11ce2
--- /dev/null
+++ b/src/main/remote/host-chat.ts
@@ -0,0 +1,135 @@
+// The production `HostChatOps` behind the phone's Chat screen verbs (docs/mobile-chat-view.md
+// §3.2). Electron-free and dependency-injected so every rule is testable without a window: main
+// wires the real node lookup, transcript reader, answer I/O and renderer bridge.
+//
+// Three rules the shape exists to hold:
+// - The node is resolved HERE, from the host's own registry — never from anything the phone
+// sends. A node the host does not know is refused, not answered with an empty page.
+// - The send gate is the RENDERER's (it owns the agent-status store and `chatSendRefusal`, the
+// same one the ⌘M composer runs), asked at send time. A renderer that does not answer fails
+// CLOSED: status is an error, send is a refusal. A guessed state would let a message be typed
+// into a permission dialog, whose Enter answers it.
+// - An answer goes through `answerHeldPermission` — the one body both shells share — so it is
+// validated against the pending request file on the agent's host and gated on the structured
+// ticket ledger, exactly like the desktop's own answer controls.
+import type { ChatTranscriptResult } from '../../shared/types'
+import type { ChatSendResult, ChatStatus } from '../../shared/mobile-chat'
+import type { ChatReadQuery } from '../../core/transcript-ipc'
+import {
+ answerHeldPermission,
+ type HeldPermissionIo
+} from '../../core/agents/permission-decision'
+import type { HostChatOps } from './host-service'
+
+/** What the host knows about a node, from its own records. */
+export interface HostChatNode {
+ cwd?: string
+ accountId?: string
+ agentId?: string
+ sessionId?: string
+}
+
+export interface HostChatDeps {
+ /** The node from the host's own registry, or null when it has no such node. */
+ lookupNode(nodeId: string): HostChatNode | null
+ /** `readChatTranscript` (core/transcript-ipc.ts) with the shell's deps bound. */
+ readTranscript(q: ChatReadQuery, rawPage: unknown): Promise<ChatTranscriptResult>
+ /** The held-request I/O for this node: local fs, or the SSH project's ControlMaster. */
+ answerIo(nodeId: string, pendingId: string): HeldPermissionIo
+ /** Test seam; defaults to the real `answerHeldPermission`. */
+ answerHeld?: typeof answerHeldPermission
+ /** A successful answer — main emits the same optimistic "answered" transition the desktop's
+ * own answer path does, so every surface's NEEDS YOU clears at once. */
+ onAnswered?(nodeId: string, pendingId: string, decision: 'allow' | 'deny'): void
+ /** The in-process structured-ticket ledger (`isStructuredTicket`). */
+ isStructuredTicket(pendingId: string): boolean
+ /** The renderer query bridge. `null` = no window to ask. */
+ renderer: {
+ status(q: { nodeId: string; agentId?: string }): Promise<Omit<ChatStatus, 'structuredAnswers'> | null>
+ send(q: { nodeId: string; agentId?: string; text: string; startBy: number }): Promise<ChatSendResult | null>
+ }
+ /** How long a status query may take, and how long a send has to START (the renderer refuses a
+ * send it receives after `startBy`), before failing closed. Default 3 s. */
+ timeoutMs?: number
+ /** How long a started send may take to report (a paste over SSH plus the settled-submit wait).
+ * Default 15 s. */
+ sendTimeoutMs?: number
+ /** Clock seam for `startBy`. */
+ now?: () => number
+}
+
+export const HOST_CHAT_RENDERER_TIMEOUT_MS = 3000
+export const HOST_CHAT_SEND_TIMEOUT_MS = 15_000
+
+const TIMED_OUT = Symbol('timed-out')
+
+function withTimeout<T>(p: Promise<T>, ms: number): Promise<T | typeof TIMED_OUT> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const timeout = new Promise<typeof TIMED_OUT>((resolve) => {
+ timer = setTimeout(() => resolve(TIMED_OUT), ms)
+ })
+ return Promise.race([p, timeout]).finally(() => clearTimeout(timer))
+}
+
+export function createHostChat(deps: HostChatDeps): HostChatOps {
+ const timeoutMs = deps.timeoutMs ?? HOST_CHAT_RENDERER_TIMEOUT_MS
+ const sendTimeoutMs = deps.sendTimeoutMs ?? HOST_CHAT_SEND_TIMEOUT_MS
+ const now = deps.now ?? Date.now
+ const answerHeld = deps.answerHeld ?? answerHeldPermission
+ return {
+ async page(nodeId, rawPage) {
+ const node = deps.lookupNode(nodeId)
+ if (!node) return null
+ // No known session id ⇒ no cwd either: claude's resolver would otherwise fall back to the
+ // NEWEST transcript in the cwd, which may be another node's session. Not found is the honest
+ // answer (the ⌘M panel likewise shows the chat only once the session id is known).
+ const q: ChatReadQuery = {
+ sessionId: node.sessionId,
+ cwd: node.sessionId ? node.cwd : undefined,
+ accountId: node.accountId,
+ nodeId,
+ agentId: node.agentId
+ }
+ // Always PAGED: an absent page is the default tail, never the legacy 5 MB read.
+ const result = await deps.readTranscript(q, rawPage ?? {})
+ return { ...result, version: 1 }
+ },
+
+ async status(nodeId) {
+ const node = deps.lookupNode(nodeId)
+ if (!node) return null
+ const answered = await withTimeout(deps.renderer.status({ nodeId, agentId: node.agentId }), timeoutMs)
+ if (answered === TIMED_OUT || answered === null) {
+ throw new Error('The desktop window is not available.')
+ }
+ const structuredAnswers = answered.held ? deps.isStructuredTicket(answered.held.pendingId) : false
+ return { ...answered, structuredAnswers }
+ },
+
+ async send(nodeId, text) {
+ const node = deps.lookupNode(nodeId)
+ if (!node) return 'unknown-node'
+ try {
+ // `startBy`: a renderer that receives this late (a stalled window) refuses rather than
+ // typing a message the phone has already been told was not sent. A send that STARTED in
+ // time gets the longer budget to finish; past it the answer is 'refused' although the text
+ // may still land — the one residual race, bounded by how long a paste can take.
+ const startBy = now() + timeoutMs
+ const result = await withTimeout(
+ deps.renderer.send({ nodeId, agentId: node.agentId, text, startBy }),
+ sendTimeoutMs
+ )
+ return result === TIMED_OUT || result === null ? 'refused' : result
+ } catch {
+ return 'refused'
+ }
+ },
+
+ async answer(nodeId, pendingId, answer) {
+ if (!deps.lookupNode(nodeId)) return false
+ const res = await answerHeld(pendingId, { answer }, deps.answerIo(nodeId, pendingId))
+ if (res.ok && res.decision) deps.onAnswered?.(nodeId, pendingId, res.decision)
+ return res.ok
+ }
+ }
+}
diff --git a/src/main/remote/host-service.chat.test.ts b/src/main/remote/host-service.chat.test.ts
new file mode 100644
index 000000000..d6484425a
--- /dev/null
+++ b/src/main/remote/host-service.chat.test.ts
@@ -0,0 +1,223 @@
+// The phone Chat screen's relay verbs (`chat.page` / `chat.status` / `chat.send` / `agent.answer`),
+// at the RPC envelope. What these pin:
+// - Absent injection ⇒ every verb answers an honest "not served" (a pre-feature host).
+// - The client-sent node id is validated exactly like the node.* verbs (empty / over REF_MAX_LEN
+// / control chars ⇒ refused, the op never invoked). The phone sends ONLY a node id; everything
+// else about the node is resolved host-side, inside the op.
+// - `chat.send`: raw text over 64000 UTF-16 units ⇒ refused; ESC + C0/C1 stripped (\n \t kept)
+// BEFORE the op sees it; nothing left ⇒ refused.
+// - Unknown node ⇒ "Unknown node.", never an empty success.
+// - Happy paths answer `{page}` / `{status}` / `{result}` / `{ok}`.
+import { describe, expect, it, vi } from 'vitest'
+import { REF_MAX_LEN } from '../../shared/presence'
+import { CHAT_SEND_TEXT_MAX, type ChatPage, type ChatStatus } from '../../shared/mobile-chat'
+import {
+ createHostHandlers,
+ type HostChatOps,
+ type HostFsOps,
+ type HostPtyManager,
+ type HostRelaySocket
+} from './host-service'
+
+const PAGE: ChatPage = { version: 1, messages: [], found: true, olderCursor: null, unmatchedResults: [] }
+const STATUS: ChatStatus = {
+ state: 'done',
+ held: null,
+ hibernated: false,
+ paused: false,
+ dropped: false,
+ sessionEnded: false,
+ structuredAnswers: false
+}
+
+function make(chat?: Partial<HostChatOps>, served = true) {
+ const responses: Array<{ id: string; ok: boolean; body: unknown }> = []
+ const socket: HostRelaySocket = {
+ respond: (id, ok, body) => responses.push({ id, ok, body }),
+ sendFrame: () => true
+ }
+ const fs: HostFsOps = {
+ listDir: async () => [],
+ readText: async () => '',
+ readBinary: async () => '',
+ writeText: async () => true
+ }
+ const ops: HostChatOps = {
+ page: vi.fn(async () => PAGE),
+ status: vi.fn(async () => STATUS),
+ send: vi.fn(async () => 'sent' as const),
+ answer: vi.fn(async () => true),
+ ...chat
+ }
+ const handlers = createHostHandlers(
+ {} as HostPtyManager,
+ socket,
+ fs,
+ () => [],
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ served ? ops : undefined
+ )
+ const call = async (method: string, params: unknown) => {
+ handlers.onRpc({ id: 'r1', method, params } as never)
+ await new Promise((r) => setTimeout(r, 0))
+ return responses[responses.length - 1]
+ }
+ return { call, ops, responses }
+}
+
+const VERBS: Array<[string, Record<string, unknown>]> = [
+ ['chat.page', {}],
+ ['chat.status', {}],
+ ['chat.send', { text: 'hi' }],
+ ['agent.answer', { pendingId: 'p-1', answer: { kind: 'deny' } }]
+]
+
+describe('phone chat verbs — not served', () => {
+ it.each(VERBS)('%s answers an honest "not served" when no chat ops are wired', async (method, extra) => {
+ const { call } = make(undefined, false)
+ const r = await call(method, { nodeId: 'n1', ...extra })
+ expect(r).toEqual({ id: 'r1', ok: false, body: { message: `${method} is not served on this host.` } })
+ })
+})
+
+describe('phone chat verbs — node id validation', () => {
+ const bad: unknown[] = [undefined, '', 42, 'x'.repeat(REF_MAX_LEN + 1), 'a\x1bb', 'a\nb', 'a\x9bb']
+ it.each(VERBS)('%s refuses an invalid node id without calling the op', async (method, extra) => {
+ for (const nodeId of bad) {
+ const { call, ops } = make()
+ const r = await call(method, { nodeId, ...extra })
+ expect(r).toEqual({ id: 'r1', ok: false, body: { message: 'Invalid node id.' } })
+ for (const f of Object.values(ops)) expect(f).not.toHaveBeenCalled()
+ }
+ })
+})
+
+describe('chat.page', () => {
+ it('answers {page} and passes only before/maxBytes through', async () => {
+ const { call, ops } = make()
+ const r = await call('chat.page', { nodeId: 'n1', before: 100, maxBytes: 65536, cwd: '/etc', sessionId: 'x' })
+ expect(r).toEqual({ id: 'r1', ok: true, body: { page: PAGE } })
+ expect(ops.page).toHaveBeenCalledWith('n1', { before: 100, maxBytes: 65536 })
+ })
+ it('refuses an invalid page before reading anything', async () => {
+ const { call, ops } = make()
+ const r = await call('chat.page', { nodeId: 'n1', before: -1 })
+ expect(r).toEqual({ id: 'r1', ok: false, body: { message: 'Invalid page.' } })
+ expect(ops.page).not.toHaveBeenCalled()
+ })
+ it('an unknown node is "Unknown node."', async () => {
+ const { call } = make({ page: vi.fn(async () => null) })
+ expect(await call('chat.page', { nodeId: 'n1' })).toEqual({ id: 'r1', ok: false, body: { message: 'Unknown node.' } })
+ })
+ it('a failed read is an error, never an empty page', async () => {
+ const { call } = make({ page: vi.fn(async () => { throw new Error('boom') }) })
+ expect(await call('chat.page', { nodeId: 'n1' })).toEqual({
+ id: 'r1',
+ ok: false,
+ body: { message: 'Could not read the transcript.' }
+ })
+ })
+})
+
+describe('chat.status', () => {
+ it('answers {status}', async () => {
+ const { call } = make()
+ expect(await call('chat.status', { nodeId: 'n1' })).toEqual({ id: 'r1', ok: true, body: { status: STATUS } })
+ })
+ it('unknown node ⇒ "Unknown node."', async () => {
+ const { call } = make({ status: vi.fn(async () => null) })
+ expect(await call('chat.status', { nodeId: 'n1' })).toEqual({ id: 'r1', ok: false, body: { message: 'Unknown node.' } })
+ })
+ it('a desktop window that does not answer is said as such', async () => {
+ const { call } = make({ status: vi.fn(async () => { throw new Error('x') }) })
+ expect(await call('chat.status', { nodeId: 'n1' })).toEqual({
+ id: 'r1',
+ ok: false,
+ body: { message: 'The desktop window is not available.' }
+ })
+ })
+})
+
+describe('chat.send', () => {
+ it('answers {result} with the sanitized text', async () => {
+ const { call, ops } = make()
+ const r = await call('chat.send', { nodeId: 'n1', text: 'a\x1b[2Jb\r\nc\td\x00e\x9bf' })
+ expect(r).toEqual({ id: 'r1', ok: true, body: { result: 'sent' } })
+ expect(ops.send).toHaveBeenCalledWith('n1', 'a[2Jb\nc\tdef')
+ })
+ it('refuses text over the cap (raw length) without sending', async () => {
+ const { call, ops } = make()
+ const r = await call('chat.send', { nodeId: 'n1', text: 'x'.repeat(CHAT_SEND_TEXT_MAX + 1) })
+ expect(r).toEqual({ id: 'r1', ok: false, body: { message: 'Text too long.' } })
+ expect(ops.send).not.toHaveBeenCalled()
+ })
+ it('accepts text exactly at the cap', async () => {
+ const { call } = make()
+ const r = await call('chat.send', { nodeId: 'n1', text: 'x'.repeat(CHAT_SEND_TEXT_MAX) })
+ expect(r?.ok).toBe(true)
+ })
+ it('refuses empty (or control-only / blank) text', async () => {
+ for (const text of [undefined, '', '\x1b\x1b', ' \n ']) {
+ const { call, ops } = make()
+ const r = await call('chat.send', { nodeId: 'n1', text })
+ expect(r).toEqual({ id: 'r1', ok: false, body: { message: 'chat.send requires non-empty text.' } })
+ expect(ops.send).not.toHaveBeenCalled()
+ }
+ })
+ it('passes a refusal and a partial delivery through verbatim', async () => {
+ for (const result of ['refused', 'pasted-not-submitted'] as const) {
+ const { call } = make({ send: vi.fn(async () => result) })
+ expect(await call('chat.send', { nodeId: 'n1', text: 'hi' })).toEqual({ id: 'r1', ok: true, body: { result } })
+ }
+ })
+ it('unknown node ⇒ "Unknown node."', async () => {
+ const { call } = make({ send: vi.fn(async () => 'unknown-node' as const) })
+ expect(await call('chat.send', { nodeId: 'n1', text: 'hi' })).toEqual({
+ id: 'r1',
+ ok: false,
+ body: { message: 'Unknown node.' }
+ })
+ })
+ it('a throwing send is a refusal, never "sent"', async () => {
+ const { call } = make({ send: vi.fn(async () => { throw new Error('x') }) })
+ expect(await call('chat.send', { nodeId: 'n1', text: 'hi' })).toEqual({ id: 'r1', ok: true, body: { result: 'refused' } })
+ })
+})
+
+describe('agent.answer', () => {
+ it('answers {ok} and passes the raw answer to the op (validated there against the pending file)', async () => {
+ const { call, ops } = make()
+ const answer = { kind: 'plan', mode: 'restore' }
+ expect(await call('agent.answer', { nodeId: 'n1', pendingId: 'p-1', answer })).toEqual({
+ id: 'r1',
+ ok: true,
+ body: { ok: true }
+ })
+ expect(ops.answer).toHaveBeenCalledWith('n1', 'p-1', answer)
+ })
+ it('refuses an invalid pending id without calling the op', async () => {
+ for (const pendingId of [undefined, '', '../x', 'a b', 'x'.repeat(257)]) {
+ const { call, ops } = make()
+ const r = await call('agent.answer', { nodeId: 'n1', pendingId, answer: { kind: 'deny' } })
+ expect(r).toEqual({ id: 'r1', ok: false, body: { message: 'Invalid pending id.' } })
+ expect(ops.answer).not.toHaveBeenCalled()
+ }
+ })
+ it('a refused or throwing answer is {ok:false}, never ok', async () => {
+ for (const answer of [vi.fn(async () => false), vi.fn(async () => { throw new Error('x') })]) {
+ const { call } = make({ answer })
+ expect(await call('agent.answer', { nodeId: 'n1', pendingId: 'p-1', answer: { kind: 'deny' } })).toEqual({
+ id: 'r1',
+ ok: true,
+ body: { ok: false }
+ })
+ }
+ })
+})
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index ab2adf9f1..e0408c16a 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -34,6 +34,15 @@ import { PtyManager, type DetachedSinks } from '../../core/pty-manager'
import * as fsOps from '../../core/fs-ops'
import { TITLE_MAX, type RemoteNodeInput } from '../../core/project-node-append'
import { parseCardLabelEdit, type CardLabelEdit } from '../../core/project-kanban-write'
+import { isValidPendingId } from '../../core/agents/pending-approvals'
+import { normalizeChatPage } from '../../shared/chat-page'
+import {
+ CHAT_SEND_TEXT_MAX,
+ sanitizeChatText,
+ type ChatPage,
+ type ChatSendResult,
+ type ChatStatus
+} from '../../shared/mobile-chat'
import { getStoredEntitlement, isPremium } from '../../core/license'
import { publicKeyToB64, type KeyPair } from './e2ee'
import { loadOrCreateHostKeyPair, HostKeyLockedError } from './host-identity'
@@ -179,6 +188,29 @@ export interface HostKanbanOps {
): Promise<{ edited: boolean; labels: KanbanLabel[]; cardLabelIds: string[] } | null>
}
+/**
+ * The phone's Chat screen (docs/mobile-chat-view.md §3.2): `chat.page` / `chat.status` /
+ * `chat.send` / `agent.answer`. The phone sends ONLY a node id (plus paging / text / answer);
+ * everything about the node — cwd, account, agent, session id, transcript path, SSH routing — is
+ * resolved host-side inside the ops from the desktop's own registry, because node ids are
+ * attacker-controllable and a phone-supplied path must never be trusted. Absent ⇒ every verb
+ * answers an honest "not served" (a pre-feature host, and every pre-feature test fake).
+ */
+export interface HostChatOps {
+ /** One page of the node's transcript. `null` ⇒ the host does not know this node. Rejects when
+ * the read failed (never an empty page standing in for a failure). */
+ page(nodeId: string, rawPage: unknown): Promise<ChatPage | null>
+ /** The node's agent state + held request. `null` ⇒ unknown node. Rejects when the desktop
+ * window did not answer — never a guessed state. */
+ status(nodeId: string): Promise<ChatStatus | null>
+ /** Type `text` (already stripped of control chars) into the node's pane through the desktop's
+ * own send gate. Only `'sent'` means Enter was confirmed. */
+ send(nodeId: string, text: string): Promise<ChatSendResult | 'unknown-node'>
+ /** Answer the node's held request (`answerHeldPermission`: validated against the pending
+ * request file, structured-ticket gated). `false` = nothing was written. */
+ answer(nodeId: string, pendingId: string, answer: unknown): Promise<boolean>
+}
+
interface Stream {
sessionId: string
/** The node id (tmux persistKey) this stream attached to. The ONLY tmux target a client can
@@ -263,7 +295,10 @@ export function createHostHandlers(
nodeActions?: HostNodeActions,
// Kanban board writes on the phone's behalf (`projects.ensureBoard` / `projects.setCardColumn`).
// Absent ⇒ the verbs answer an honest "not served".
- kanban?: HostKanbanOps
+ kanban?: HostKanbanOps,
+ // The phone's Chat screen (`chat.page` / `chat.status` / `chat.send` / `agent.answer`).
+ // Absent ⇒ the verbs answer an honest "not served".
+ chat?: HostChatOps
): HostHandlers {
// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no
// reverse (sessionId -> streamId) index is needed.
@@ -782,6 +817,85 @@ export function createHostHandlers(
socket.respond(req.id, true, {})
}
+ /**
+ * The phone Chat verbs. Same node-id envelope as `handleNodeAction` (REF_MAX_LEN, no control
+ * chars) — the id is the ONLY thing about the node the phone supplies. Each op resolves the node
+ * itself and answers "unknown" for a node the host has not got, which is refused here rather than
+ * answered with an empty success.
+ */
+ function handleChat(req: RpcRequest): void {
+ const fail = (message: string): void => socket.respond(req.id, false, { message })
+ if (!chat) {
+ fail(`${req.method} is not served on this host.`)
+ return
+ }
+ const p = asRecord(req.params)
+ const nodeId = str(p.nodeId)
+ // eslint-disable-next-line no-control-regex -- refusing control chars is the point
+ if (!nodeId || nodeId.length > REF_MAX_LEN || /[\x00-\x1f\x7f-\x9f]/.test(nodeId)) {
+ fail('Invalid node id.')
+ return
+ }
+ switch (req.method) {
+ case 'chat.page': {
+ // Only the two paging fields cross; validated HERE (normalizeChatPage throws on a bad
+ // `before`, which reaches a remote shell line on the SSH leg) so a refusal never costs a read.
+ const rawPage = { ...(p.before !== undefined ? { before: p.before } : {}), ...(p.maxBytes !== undefined ? { maxBytes: p.maxBytes } : {}) }
+ try {
+ normalizeChatPage(rawPage)
+ } catch {
+ fail('Invalid page.')
+ return
+ }
+ void chat
+ .page(nodeId, rawPage)
+ .then((page) => (page ? socket.respond(req.id, true, { page }) : fail('Unknown node.')))
+ .catch(() => fail('Could not read the transcript.'))
+ return
+ }
+ case 'chat.status':
+ void chat
+ .status(nodeId)
+ .then((status) => (status ? socket.respond(req.id, true, { status }) : fail('Unknown node.')))
+ .catch(() => fail('The desktop window is not available.'))
+ return
+ case 'chat.send': {
+ const raw = str(p.text) ?? ''
+ // The cap is on the RAW text (what crossed the wire), in UTF-16 units like every text cap.
+ if (raw.length > CHAT_SEND_TEXT_MAX) {
+ fail('Text too long.')
+ return
+ }
+ // ESC + C0/C1 stripped (\n and \t kept): a payload must never become a control sequence.
+ const text = sanitizeChatText(raw)
+ if (!text.trim()) {
+ fail('chat.send requires non-empty text.')
+ return
+ }
+ void chat
+ .send(nodeId, text)
+ .then((result) =>
+ result === 'unknown-node' ? fail('Unknown node.') : socket.respond(req.id, true, { result })
+ )
+ // A send that threw is a refusal, never "sent": the phone keeps the draft.
+ .catch(() => socket.respond(req.id, true, { result: 'refused' }))
+ return
+ }
+ case 'agent.answer': {
+ const pendingId = str(p.pendingId)
+ if (!pendingId || !isValidPendingId(pendingId)) {
+ fail('Invalid pending id.')
+ return
+ }
+ void chat
+ .answer(nodeId, pendingId, p.answer)
+ .then((ok) => socket.respond(req.id, true, { ok: ok === true }))
+ .catch(() => socket.respond(req.id, true, { ok: false }))
+ return
+ }
+ }
+ }
+
return {
onRpc(req) {
switch (req.method) {
@@ -827,6 +941,12 @@ export function createHostHandlers(
case 'projects.editCardLabels':
handleKanban(req)
break
+ case 'chat.page':
+ case 'chat.status':
+ case 'chat.send':
+ case 'agent.answer':
+ handleChat(req)
+ break
case 'node.wake':
case 'node.refresh':
case 'node.rename':
@@ -1076,6 +1196,8 @@ export interface HostSessionOptions {
/** Kanban board writes for the phone's Board sheet (`projects.ensureBoard` /
* `projects.setCardColumn`). Optional: absent ⇒ the verbs answer an honest "not served". */
kanban?: HostKanbanOps
+ /** The phone's Chat screen verbs (`chat.*` / `agent.answer`). Optional: absent ⇒ "not served". */
+ chat?: HostChatOps
/** 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. */
@@ -1200,7 +1322,8 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {
opts.destroyNode,
opts.remoteViewer,
opts.nodeActions,
- opts.kanban
+ opts.kanban,
+ opts.chat
)
canvasSync = createHostCanvasSync(socket, opts.applyMutation)
unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())
@@ -1231,6 +1354,8 @@ export interface HostBridgeDeps {
nodeActions?: HostNodeActions
/** Kanban board writes for the phone's Board sheet — see main/index.ts's WorkspaceStore wiring. */
kanban?: HostKanbanOps
+ /** The phone's Chat screen verbs — see main/remote/host-chat.ts and main/index.ts's wiring. */
+ chat?: HostChatOps
/** Workspace-level jail roots (local project cwds) merged with the canvas node cwds. */
workspaceRoots?: () => string[]
}
@@ -1305,6 +1430,7 @@ export function initRemoteHost(
remoteViewer: bridge.remoteViewer,
nodeActions: bridge.nodeActions,
kanban: bridge.kanban,
+ chat: bridge.chat,
extraRoots: bridge.workspaceRoots,
// Typing attribution: this session's input frames are this phone's keystrokes.
getClientId: () => phone.id(),
diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.ts
index 3036ecf4f..75135dc79 100644
--- a/src/main/remote/standing-host.ts
+++ b/src/main/remote/standing-host.ts
@@ -351,6 +351,7 @@ export function initStandingHost(
remoteViewer: bridge.remoteViewer,
nodeActions: bridge.nodeActions,
kanban: bridge.kanban,
+ chat: bridge.chat,
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 228751888..403b3345b 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -834,6 +834,12 @@ const api: NodeTerminalApi = {
return () => ipcRenderer.removeListener(IPC.browserControlResolve, handler)
},
sendBrowserControlResolveResult: (payload) => ipcRenderer.send(IPC.browserControlResolveResult, payload),
+ onHostChatQuery: (listener) => {
+ const handler = (_e: unknown, q: Parameters<typeof listener>[0]) => listener(q)
+ ipcRenderer.on(IPC.hostChatQuery, handler)
+ return () => ipcRenderer.removeListener(IPC.hostChatQuery, handler)
+ },
+ sendHostChatReply: (reply) => ipcRenderer.send(IPC.hostChatReply, reply),
agentMessage: {
deliver: (req) => ipcRenderer.invoke(IPC.agentMessageDeliver, req)
}
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index 2b719d138..45c24dcd1 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -159,6 +159,9 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):
// Browser control never rides the relay either (no CDP off the desktop) — inert no-ops.
onBrowserControlResolve: stub.onBrowserControlResolve,
sendBrowserControlResolveResult: stub.sendBrowserControlResolveResult,
+ // The phone Chat round-trip is the LOCAL desktop main's, never a relay peer's — inert here.
+ onHostChatQuery: stub.onHostChatQuery,
+ sendHostChatReply: stub.sendHostChatReply,
// Messaging rides the same decision: the browser client is never a sender (constraint 5 of
// the messaging plan — the phone drives canvas control over relay→IPC, not /control/*).
agentMessage: stub.agentMessage
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 17b0a755d..ea8f065c7 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -555,6 +555,10 @@ export function buildStubApi(): Omit<
// resolve round-trip is inert here — the verb is refused by name before it reaches a handler.
onBrowserControlResolve: noopUnsub,
sendBrowserControlResolveResult: noop,
+ // The phone Chat verbs are served by the phone relay host, which lives only in the desktop
+ // main process — the Server Edition serves no phone relay, so nothing asks this renderer.
+ onHostChatQuery: noopUnsub,
+ sendHostChatReply: noop,
// Messaging never runs in the browser: `onAgentControl` above is inert here, so no dispatch
// can ever reach this. It answers the honest terminal refusal all the same, so a stray call
// can never look like it delivered.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 53c2c20da..d9012869c 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -391,6 +391,7 @@ import {
} from '../lib/explorerPinHint'
import { useProjects } from '../state/projects'
import { useAgentStatus } from '../state/agentStatus'
+import { hostChatSend, hostChatStatus } from '../lib/hostChatQuery'
import { useLaunchDelivery } from '../state/launchDelivery'
import { useBrowserLease, drivingNodeIds } from '../state/browserLease'
import { useTerminalFocus } from '../state/terminalFocus'
@@ -9938,6 +9939,29 @@ export function Canvas() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ // The phone Chat verbs' renderer round-trip (main/remote/host-chat.ts). Main resolved the node
+ // host-side and asks the two things only this renderer owns: the node's agent status, and — for
+ // a send — the ⌘M composer's own gate, run against the store AT SEND TIME before `sendText`.
+ // Pure rules in lib/hostChatQuery.ts. Desktop only: the bridges' subscription is inert.
+ useEffect(() => {
+ return api.onHostChatQuery((q) => {
+ if (q.kind === 'status') {
+ api.sendHostChatReply({
+ requestId: q.requestId,
+ kind: 'status',
+ status: hostChatStatus(useAgentStatus.getState().byId[q.nodeId])
+ })
+ return
+ }
+ void hostChatSend(q, {
+ getStatus: (id) => useAgentStatus.getState().byId[id],
+ sendText: (id, text) => api.pty.sendText(id, text),
+ now: Date.now
+ }).then((result) => api.sendHostChatReply({ requestId: q.requestId, kind: 'send', result }))
+ })
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
// Apply canvas-control commands issued by a control-capable agent's `nodeterm` CLI. Reads the
// LATEST nodes via nodesRef (so the effect deps stay []), validates the source as the real
// authorization boundary, then applies the verb. Non-destructive verbs (list/open-*/show-*)
diff --git a/src/renderer/lib/hostChatQuery.test.ts b/src/renderer/lib/hostChatQuery.test.ts
new file mode 100644
index 000000000..a0926b770
--- /dev/null
+++ b/src/renderer/lib/hostChatQuery.test.ts
@@ -0,0 +1,87 @@
+// The renderer half of the phone Chat verbs: main asks, the renderer answers from the store it owns
+// and the ⌘M composer's own send gate. What these pin:
+// - status is read verbatim from the agent-status entry (unknown ⇒ state null, flags false);
+// - send runs `chatSendRefusal` AT SEND TIME and refuses a held request too, never types past
+// the deadline main set, and reports `'sent'` only for a sendText that answered `=== true`.
+import { describe, expect, it, vi } from 'vitest'
+import { hostChatSend, hostChatStatus } from './hostChatQuery'
+
+const HELD = { pendingId: 'p-1', toolName: 'ExitPlanMode' }
+
+describe('hostChatStatus', () => {
+ it('reads the entry verbatim', () => {
+ expect(
+ hostChatStatus({ state: 'waiting', held: HELD, hibernated: true, paused: false, dropped: true, sessionEnded: false })
+ ).toEqual({ state: 'waiting', held: HELD, hibernated: true, paused: false, dropped: true, sessionEnded: false })
+ })
+ it('no entry ⇒ unknown state, no hold, no flags', () => {
+ expect(hostChatStatus(undefined)).toEqual({
+ state: null,
+ held: null,
+ hibernated: false,
+ paused: false,
+ dropped: false,
+ sessionEnded: false
+ })
+ })
+})
+
+describe('hostChatSend', () => {
+ const base = { requestId: 'r', kind: 'send' as const, nodeId: 'n1', agentId: 'claude', text: 'hi', startBy: 2000 }
+ const run = (
+ status: Record<string, unknown> | undefined,
+ sendText: ReturnType<typeof vi.fn> = vi.fn(async () => true),
+ now = 1000
+ ) =>
+ hostChatSend(base, { getStatus: () => status as never, sendText: sendText as never, now: () => now }).then((r) => ({
+ r,
+ sendText
+ }))
+
+ it('sends in done / unknown and reports sent only for === true', async () => {
+ for (const st of [{ state: 'done' }, undefined, {}]) {
+ const { r, sendText } = await run(st)
+ expect(r).toBe('sent')
+ expect(sendText).toHaveBeenCalledWith('n1', 'hi')
+ }
+ })
+ it('refuses working / waiting / blocked, and a held request', async () => {
+ for (const st of [{ state: 'working' }, { state: 'waiting' }, { state: 'blocked' }, { state: 'done', held: HELD }]) {
+ const { r, sendText } = await run(st)
+ expect(r).toBe('refused')
+ expect(sendText).not.toHaveBeenCalled()
+ }
+ })
+ it('refuses when a shell owns the pane (hibernated, paused, dropped, exited)', async () => {
+ for (const st of [{ hibernated: true }, { paused: true }, { dropped: true }, { sessionEnded: true }]) {
+ const { r, sendText } = await run({ state: 'done', ...st })
+ expect(r).toBe('refused')
+ expect(sendText).not.toHaveBeenCalled()
+ }
+ })
+ it('refuses a node whose agent is unknown everywhere (no process can be proven in the pane)', async () => {
+ const sendText = vi.fn(async () => true as const)
+ const r = await hostChatSend({ ...base, agentId: undefined }, { getStatus: () => ({ state: 'done' }), sendText, now: () => 1000 })
+ expect(r).toBe('refused')
+ expect(sendText).not.toHaveBeenCalled()
+ })
+ it('falls back to the store\'s agent id when main has none', async () => {
+ const sendText = vi.fn(async () => true as const)
+ const r = await hostChatSend(
+ { ...base, agentId: undefined },
+ { getStatus: () => ({ state: 'done', agentId: 'claude' }), sendText, now: () => 1000 }
+ )
+ expect(r).toBe('sent')
+ })
+ it('a query received after startBy is refused unsent', async () => {
+ const { r, sendText } = await run({ state: 'done' }, vi.fn(async () => true as const), 2001)
+ expect(r).toBe('refused')
+ expect(sendText).not.toHaveBeenCalled()
+ })
+ it('passes a partial delivery through, and never reports sent for false / throw / truthy junk', async () => {
+ expect((await run({ state: 'done' }, vi.fn(async () => 'pasted-not-submitted' as const))).r).toBe('pasted-not-submitted')
+ expect((await run({ state: 'done' }, vi.fn(async () => false as const))).r).toBe('refused')
+ expect((await run({ state: 'done' }, vi.fn(async () => { throw new Error('x') }))).r).toBe('refused')
+ expect((await run({ state: 'done' }, vi.fn(async () => 'yes' as never))).r).toBe('refused')
+ })
+})
diff --git a/src/renderer/lib/hostChatQuery.ts b/src/renderer/lib/hostChatQuery.ts
new file mode 100644
index 000000000..2260f21bf
--- /dev/null
+++ b/src/renderer/lib/hostChatQuery.ts
@@ -0,0 +1,55 @@
+// The renderer half of the phone's Chat verbs (`chat.status` / `chat.send`, served by main's
+// host-chat.ts): main asks, and the renderer answers from the state it OWNS — the agent-status
+// store and the ⌘M composer's send gate. Pure over injected reads so the rules are tested without a
+// canvas; Canvas wires `useAgentStatus` + `api.pty.sendText` and replies over the IPC bridge.
+//
+// The send is gated exactly like the desktop composer's (`chatSendRefusal`, read at SEND time) plus
+// one refusal the composer gets for free from its surface: a held request. On the desktop the
+// composer is disabled while a plan / question / permission is held because the state is
+// `waiting`/`blocked`; the phone asks the same thing explicitly, so a held ticket that outlived its
+// state (a late hook) still refuses — text + Enter into a dialog ANSWERS it.
+import type { ChatSendResult, ChatStatus, HostChatQuery } from '@shared/mobile-chat'
+import type { TextDeliveryResult } from '@shared/text-delivery'
+import type { AgentNodeStatus } from '../state/agentStatus'
+import { chatSendRefusal } from './chatSendGate'
+
+type StatusSlice = Pick<AgentNodeStatus, 'state' | 'held' | 'hibernated' | 'paused' | 'dropped' | 'sessionEnded' | 'agentId'>
+
+export function hostChatStatus(st: Partial<StatusSlice> | undefined): Omit<ChatStatus, 'structuredAnswers'> {
+ return {
+ state: st?.state ?? null,
+ held: st?.held ?? null,
+ hibernated: st?.hibernated === true,
+ paused: st?.paused === true,
+ dropped: st?.dropped === true,
+ sessionEnded: st?.sessionEnded === true
+ }
+}
+
+export interface HostChatSendDeps {
+ getStatus(nodeId: string): Partial<StatusSlice> | undefined
+ sendText(nodeId: string, text: string): Promise<TextDeliveryResult>
+ now(): number
+}
+
+export async function hostChatSend(
+ q: Extract<HostChatQuery, { kind: 'send' }>,
+ deps: HostChatSendDeps
+): Promise<ChatSendResult> {
+ // Main has already told the phone "refused" past this instant; typing now would contradict it.
+ if (deps.now() > q.startBy) return 'refused'
+ const st = deps.getStatus(q.nodeId) ?? {}
+ // The host's own record of the agent wins; the store's hook-reported id is the fallback. With
+ // neither, `agentProcessInPane` cannot prove a CLI owns the pane and the gate refuses.
+ const agentId = q.agentId ?? st.agentId ?? ''
+ if (st.held) return 'refused'
+ if (chatSendRefusal(agentId, st) !== null) return 'refused'
+ try {
+ const r = await deps.sendText(q.nodeId, q.text)
+ if (r === true) return 'sent'
+ if (r === 'pasted-not-submitted') return 'pasted-not-submitted'
+ return 'refused'
+ } catch {
+ return 'refused'
+ }
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 2c21a5e07..636c5d2be 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -529,6 +529,11 @@ export const IPC = {
// does the CDP work itself; the renderer never runs a CDP command.
browserControlResolve: 'browser:control-resolve',
browserControlResolveResult: 'browser:control-resolve-result',
+ // The phone Chat verbs' renderer round-trip (main/remote/host-chat.ts): main asks the renderer —
+ // which owns the agent-status store and the ⌘M send gate — for a node's chat status, or to send
+ // a phone message through that gate; the renderer answers on the reply channel.
+ hostChatQuery: 'host:chat-query',
+ hostChatReply: 'host:chat-reply',
remoteHostStart: 'remote:host:start',
remoteHostStop: 'remote:host:stop',
// Connection approval gate: main → renderer when a client finishes the handshake (carries the
diff --git a/src/shared/mobile-chat.ts b/src/shared/mobile-chat.ts
new file mode 100644
index 000000000..a34a0abb5
--- /dev/null
+++ b/src/shared/mobile-chat.ts
@@ -0,0 +1,57 @@
+// The phone's Chat screen (docs/mobile-chat-view.md): the wire shapes the relay verbs `chat.page`
+// / `chat.status` / `chat.send` answer, and the one text rule `chat.send` applies. Shared because
+// three places must agree on them: the relay handler (main), the renderer that answers the status
+// and send queries, and — by hand, under golden fixtures — the iOS port.
+import type { AgentState } from './agents/normalize'
+import type { HeldPermission } from './agents/permission-answer'
+import type { ChatTranscriptResult } from './types'
+
+/** One page of a node's transcript as the phone receives it. `version` lets the phone refuse a
+ * newer shape honestly instead of misreading it. */
+export type ChatPage = ChatTranscriptResult & { version: 1 }
+
+/** What the phone needs to decide whether its composer and answer controls may act. */
+export interface ChatStatus {
+ /** The hook-reported state; `null` = no live hook state (unknown — the desktop's "Unknown"). */
+ state: AgentState | null
+ /** The request the node's hook is holding, if any (a plan, a question, a permission). */
+ held: HeldPermission | null
+ hibernated: boolean
+ paused: boolean
+ dropped: boolean
+ sessionEnded: boolean
+ /** The held request was posted by a hook script that understands structured answers
+ * (`isStructuredTicket`). False ⇒ the phone offers no answer controls, only "answer in the
+ * terminal". Always false with no `held`. */
+ structuredAnswers: boolean
+}
+
+export type ChatSendResult = 'sent' | 'refused' | 'pasted-not-submitted'
+
+/** Longest text `chat.send` accepts, in UTF-16 code units (JS `.length`, Swift `utf16.count`),
+ * checked on the RAW text before stripping. */
+export const CHAT_SEND_TEXT_MAX = 64000
+
+/**
+ * Text a phone asks to type into a pane: every C0/C1 control character is removed except `\n` and
+ * `\t`. ESC is the one that matters most — a payload must never be able to become a terminal
+ * control sequence (the paste-injection rule `node.rename` already applies) — and `\r` goes too,
+ * since in a pane it is Enter. The paste path frames the text itself and adds the one Enter.
+ */
+export function sanitizeChatText(text: string): string {
+ // eslint-disable-next-line no-control-regex -- stripping control chars is the point
+ return text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '')
+}
+
+/** Main → renderer: answer a status or send query for a node (the renderer owns the agent-status
+ * store and the send gate). `agentId` is the host's own record of the node's agent. `startBy`
+ * (epoch ms, same machine): a send received after it is refused unsent — main has already told
+ * the phone "refused". */
+export type HostChatQuery =
+ | { requestId: string; kind: 'status'; nodeId: string; agentId?: string }
+ | { requestId: string; kind: 'send'; nodeId: string; agentId?: string; text: string; startBy: number }
+
+/** Renderer → main. `status` omits `structuredAnswers`: main adds it (the ticket ledger is main's). */
+export type HostChatReply =
+ | { requestId: string; kind: 'status'; status: Omit<ChatStatus, 'structuredAnswers'> }
+ | { requestId: string; kind: 'send'; result: ChatSendResult }
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d01932b5f..5e23be23b 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -8,6 +8,7 @@ import type { KeybindingOverrides, TerminalShortcutPolicy } from './keybindings'
import type { NormalizedAgentEvent } from './agents/normalize'
import type { PaneOwner } from './agents/pane-owner-predicate'
import type { AnswerPermissionPayload, ChatQuestion } from './agents/permission-answer'
+import type { HostChatQuery, HostChatReply } from './mobile-chat'
import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'
import type { ControlConfirmWaivers } from './control-confirm'
import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'
@@ -3858,6 +3859,13 @@ export interface NodeTerminalApi {
sourceTitle?: string
browserTitle?: string
}): void
+ /** The phone Chat verbs' round-trip (main/remote/host-chat.ts): main asks this renderer for a
+ * node's chat status, or to send a phone message through the ⌘M composer's own gate. Desktop
+ * only — the phone relay host lives in the Electron main process; the browser and relay bridges
+ * subscribe to nothing. */
+ onHostChatQuery(listener: (q: HostChatQuery) => void): () => void
+ /** Answer a `onHostChatQuery` request. */
+ sendHostChatReply(reply: HostChatReply): void
/** Agent messaging (the `send`/`reply` control verbs): run one delivery in main, where the
* scope check, the per-project switch, flow control and the pane probes all live. The reply is
* already rendered as a control reply — Canvas forwards it verbatim. */