Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(mobile-chat): unconfirmed sends, renderer-first session id, bound answers

review486ac01df97f
diff --git a/CLAUDE.md b/CLAUDE.md
index 95542bdcc..9c37ea2ca 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5452,17 +5452,25 @@ to the class, and no bare `.react-flow__viewport` rule carries `will-change`).
`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` /
+ (`WorkspaceStore.getNodeResolved` + the mirror). The session id is asked of the RENDERER's
+ agent-status store first (what ⌘M reads; after a restart a hook-fed id lives only there), the
+ mirror / minted id only as a fallback; the cwd rides only for a REMOTE node with a known id, so a
+ local known-but-dead id — or no id at all — reads NOTHING rather than claude's cwd-newest fallback
+ (a stranger's session); (2) **the send gate is the host mirror's, then the renderer's** — refused
+ first when the mirror says working/waiting/blocked or holds a question/approval ticket (renderer
+ state is transient after a reload), then 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
+ ⌘M composer's `chatSendRefusal` at send time plus "no held request". A renderer that does not
+ answer FAILS CLOSED: status is an error; `'refused'` means nothing was typed (no window, a gate,
+ past `startBy`), while a DISPATCHED send with no answer in time (or a `sendText` that rejected
+ after starting) is `'unconfirmed'` — never `'refused'`, which would invite the phone to resend and
+ type the prompt twice; (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
+ gate, and the `pendingId` must be THIS node's (a mirror approval ticket for it, or the renderer's
+ `held.pendingId`), else `false` with no I/O and no answered event on the wrong node. 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).
diff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.md
index d0f96fbc9..d54b7837d 100644
--- a/docs/mobile-chat-view.md
+++ b/docs/mobile-chat-view.md
@@ -83,10 +83,10 @@ 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.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`. Session id: the RENDERER's agent-status id first (what ⌘M reads — after a desktop restart a hook-fed id lives only there), then the mirror's, then the node's minted id, the fallbacks only when the renderer does not answer within 3 s or knows none. The cwd rides ONLY for a remote (SSH) node with a known id (the host-side locate needs it): locally a known-but-dead id must not fall back to the cwd's newest transcript (another node's), and with no id at all ⇒ `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. |
+| `chat.send` | `{nodeId, text}` | `{result: 'sent' \| 'refused' \| 'pasted-not-submitted' \| 'unconfirmed'}` | text capped at 64000 UTF-16 units RAW, then ESC + C0/C1 stripped (`\n`, `\t` kept; `sanitizeChatText`); refused FIRST when the host's mirror says the agent is working / waiting / blocked or holds a question or approval ticket (renderer state is transient after a reload); then 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`. The `pendingId` must belong to THIS node — one of the mirror's approval tickets for it, or the renderer's `held.pendingId` (plans / questions) — else `{ok:false}` with no I/O and no answered event. Success emits the same optimistic "answered" event. |
Refusals are `respond(id, false, {message})`, with these exact strings:
@@ -102,10 +102,14 @@ Refusals are `respond(id, false, {message})`, with these exact strings:
| `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}`
+Fail-closed rules: `'refused'` means **nothing was typed** — no window, the mirror or renderer gate
+refused, or the renderer received the query after its `startBy` (3 s; a late renderer refuses rather
+than typing). `'unconfirmed'` means **the send was dispatched but no result came back**: a started
+send gets 15 s to report and is `'unconfirmed'` past it, and a `sendText` that REJECTED after starting
+is `'unconfirmed'` too — the text may have landed. **The phone must never auto-resend on
+`'unconfirmed'`** (that is a duplicate prompt): keep the draft visible as "may not have been sent",
+re-read the page, and let the user decide. A `chat.send` whose ops throw before dispatch 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:
@@ -164,6 +168,10 @@ N/A (it serves no phone relay; its bridge subscription is inert).
- Never type blindly into a pane: send and `/model` only when the state is `done` or unknown **and** no
held request exists **and** an agent process owns the pane; the gate is re-asked at send time. Relay:
the desktop decides. Text only via stdin; ESC stripped.
+- **iOS consumer of `chat.send`**: `'refused'` → keep the draft, say it was not sent, allow a resend;
+ `'unconfirmed'` → NEVER auto-resend (a duplicate prompt); keep the draft marked "may not have been
+ sent", reload the page, and leave the decision to the user. Unknown future values are treated as
+ `'unconfirmed'` (the safe side). Older desktops never return it.
- Answers validated against the host's pending request file; Swift and TS builders locked by golden
fixtures; `setMode auto` unrepresentable; expired ticket / old hook → "Couldn't send — answer in the
terminal", never a false "sent".
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 342d3f79d..5382366e8 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -34,6 +34,7 @@ import {
trimInboxFeed,
workingNodes,
_resetForTest,
+ pendingTicketsFor,
_snapshot,
_inboxSnapshot,
DONE_HOLDOFF_MS,
@@ -2592,3 +2593,20 @@ describe('MirrorEntry.account (observed Claude account)', () => {
expect(Object.keys(doc.nodes)).toEqual([])
})
})
+
+// The phone's `agent.answer` binds a pendingId to the node it names (main/remote/host-chat.ts): a
+// ticket the mirror recorded for THIS node passes, one recorded for another node — or one it has
+// since resolved — does not.
+describe('pendingTicketsFor', () => {
+ beforeEach(() => _resetForTest())
+ it('lists the node\'s unresolved approval tickets only', () => {
+ recordAgentEvent(ev({ state: 'working', newTurn: true }))
+ recordAgentEvent(ev({ state: 'blocked', lastMessage: 'Approve write', pendingId: 'n1-1-1' }))
+ recordAgentEvent(ev({ nodeId: 'n2', state: 'blocked', lastMessage: 'Approve', pendingId: 'n2-1-1' }))
+ expect(pendingTicketsFor('n1')).toEqual(['n1-1-1'])
+ expect(pendingTicketsFor('n2')).toEqual(['n2-1-1'])
+ expect(pendingTicketsFor('nope')).toEqual([])
+ recordAgentEvent(syntheticAnsweredEvent('n1', 'n1-1-1', 'allow')!)
+ expect(pendingTicketsFor('n1')).toEqual([])
+ })
+})
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index 8e02202d5..1263872bf 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -1233,6 +1233,22 @@ function pushInboxEvent(e: Omit<InboxEvent, 'id'>): void {
* event — never seen, or aged off the capped feed — is NOT relevant either (returns false), so a
* held push whose event the mirror no longer tracks is dropped rather than sent late. Pure read.
*/
+/**
+ * The hook-reply tickets the mirror still considers open for ONE node: its unresolved approval
+ * cards' `pendingId`s plus the approvals held concurrently with a picker. The phone's
+ * `agent.answer` uses it to bind a ticket to the node it names (a pendingId from another node, or
+ * one already answered, is refused). Question/plan holds are not here — their pendingId is
+ * stripped from the inbox card — so those bind through the renderer's `held` instead. Pure read.
+ */
+export function pendingTicketsFor(nodeId: string): string[] {
+ const out = new Set<string>()
+ for (const e of inboxEvents) {
+ if (e.nodeId === nodeId && !e.resolved && e.kind === 'approval' && e.pendingId) out.add(e.pendingId)
+ }
+ for (const id of state.get(nodeId)?.concurrentApprovalIds ?? []) out.add(id)
+ return [...out]
+}
+
export function isEventUnresolved(nodeId: string, eventId: string): boolean {
for (const e of inboxEvents) {
if (e.id === eventId && e.nodeId === nodeId) return !e.resolved
diff --git a/src/core/transcript-reader.test.ts b/src/core/transcript-reader.test.ts
index 8ecaeb401..b3ae007cc 100644
--- a/src/core/transcript-reader.test.ts
+++ b/src/core/transcript-reader.test.ts
@@ -547,3 +547,35 @@ describe('readSessionName — unchanged transcripts are not re-read', () => {
expect(await readSessionName(sid)).toBe('Second')
})
})
+
+describe('parseChatWindow — a null record or null content element is skipped, never fatal', () => {
+ // `JSON.parse('null')` succeeds, and so does `[null]` inside `content`: both used to throw on
+ // the property read that followed (outside the try), failing the WHOLE page — while the Swift
+ // port skips the line. A transcript is written by another program; one bad line must cost one line.
+ it('skips a top-level null / non-object record and keeps the rest', () => {
+ const lines = ['null', '42', '"str"', '[1,2]', JSON.stringify({ type: 'user', message: { content: 'kept' } })]
+ const r = parseChatWindow(Buffer.from(lines.join('\n') + '\n'), 0)
+ expect(r.messages.map(textOfMsg)).toEqual(['kept'])
+ })
+ it('skips null / non-object content elements and keeps the others', () => {
+ const a = JSON.stringify({
+ type: 'assistant',
+ message: { content: [null, 7, 'x', { type: 'text', text: 'hello' }, { type: 'tool_use', id: 't1', name: 'Bash', input: null }] }
+ })
+ const u = JSON.stringify({ type: 'user', message: { content: [null, { type: 'tool_result', tool_use_id: 't1', content: 'ok' }, { type: 'text', text: 'hi' }] } })
+ const r = parseChatWindow(Buffer.from(a + '\n' + u + '\n'), 0)
+ expect(r.messages.map((m) => m.role)).toEqual(['assistant', 'user'])
+ expect(r.messages[0].parts.map((p) => p.kind)).toEqual(['text', 'tool'])
+ expect(r.messages[1].parts).toEqual([{ kind: 'text', text: 'hi' }])
+ })
+ it('a null message is not fatal either (legacy read too)', () => {
+ expect(parseChatMessages(['{"type":"assistant","message":null}', 'null', '{"type":"user","message":{"content":"x"}}']).length).toBe(1)
+ })
+})
+
+describe('parseTranscriptLines — the find-bar index skips a null record / element too', () => {
+ it('indexes the good lines around a null', () => {
+ const text = ['null', JSON.stringify({ type: 'assistant', message: { content: [null, { type: 'text', text: 'found' }] } })].join('\n')
+ expect(parseTranscriptLines(text)).toEqual([{ role: 'assistant', text: 'found' }])
+ })
+})
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index 893a0e377..b17c33f25 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -59,10 +59,13 @@ function linesFrom(raw: string): TranscriptLine[] {
} catch {
return []
}
+ // Same rule as the chat parser: a `null` / scalar line is one skipped line, never a failed read.
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return []
const content = o.message?.content
const out: TranscriptLine[] = []
if (o.type === 'assistant' && Array.isArray(content)) {
for (const c of content as Array<{ type?: string; text?: string; name?: string; input?: unknown }>) {
+ if (!c || typeof c !== 'object') continue
if (c.type === 'text' && c.text) out.push({ role: 'assistant', text: c.text })
else if (c.type === 'tool_use') {
const arg = toolArg(c.input)
@@ -75,6 +78,7 @@ function linesFrom(raw: string): TranscriptLine[] {
}
} else if (o.type === 'user' && Array.isArray(content)) {
for (const c of content as Array<{ type?: string; text?: string; content?: unknown }>) {
+ if (!c || typeof c !== 'object') continue
if (c.type === 'text' && c.text) out.push({ role: 'user', text: c.text })
else if (c.type === 'tool_result') {
const s = summarizeResult(c.content)
@@ -192,6 +196,9 @@ function parseChatRecords(
} catch {
continue
}
+ // `null` / a number / a string parse fine and would throw on the reads below, failing the whole
+ // page over one line another program wrote. One bad line costs one line (the Swift port agrees).
+ if (!o || typeof o !== 'object' || Array.isArray(o)) continue
at = lineTime(o.timestamp)
const content = o.message?.content
if (paged && o.type === 'assistant' && o.message?.model !== SYNTHETIC_MODEL) {
@@ -207,6 +214,7 @@ function parseChatRecords(
id?: string
input?: unknown
}>) {
+ if (!c || typeof c !== 'object') continue
if (c.type === 'text' && c.text) parts.push({ kind: 'text', text: c.text })
else if (c.type === 'tool_use') {
const part: Extract<ChatPart, { kind: 'tool' }> = {
@@ -234,6 +242,7 @@ function parseChatRecords(
tool_use_id?: string
content?: unknown
}>) {
+ if (!c || typeof c !== 'object') continue
if (c.type === 'text' && c.text) parts.push({ kind: 'text', text: c.text })
else if (c.type === 'tool_result') {
const tool = c.tool_use_id ? toolById.get(c.tool_use_id) : undefined
diff --git a/src/main/index.ts b/src/main/index.ts
index 35d252d54..90c790fe2 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -186,7 +186,8 @@ import {
nodeState,
nodeSessionName,
workingNodes,
- mirrorEntry
+ mirrorEntry,
+ pendingTicketsFor
} from '../core/agent-status-mirror'
import { paneOwnerProject } from '../core/agents/pane-ownership'
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
@@ -229,7 +230,7 @@ import {
remoteTranscriptRoots
} from '../core/remote-transcript-locate'
import { readChatTranscript, registerTranscriptIpc, resolveTranscript, type TranscriptIpcDeps } from '../core/transcript-ipc'
-import { createHostChat } from './remote/host-chat'
+import { createHostChat, mirrorRefusesChatSend } from './remote/host-chat'
import type { ChatSendResult, ChatStatus, HostChatReply } from '../shared/mobile-chat'
import {
createReadRemotePage,
@@ -4056,9 +4057,13 @@ app.whenReady().then(async () => {
// 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
+ // Fallback only: host-chat asks the RENDERER's store first (what ⌘M reads).
+ sessionId: m?.sessionId ?? node.agentSessionId,
+ remote: workspaceStore.sshProjectIdForNode(nodeId) !== undefined
}
},
+ hostSendRefusal: (nodeId) => mirrorRefusesChatSend(mirrorEntry(nodeId)),
+ knownTickets: pendingTicketsFor,
readTranscript: (q, rawPage) => readChatTranscript(q, rawPage, transcriptIpcDeps),
answerIo: heldPermissionIoFor,
isStructuredTicket,
@@ -4078,7 +4083,7 @@ app.whenReady().then(async () => {
})
const ask = (q: { kind: 'status'; nodeId: string; agentId?: string } | {
kind: 'send'; nodeId: string; agentId?: string; text: string; startBy: number
- }): Promise<HostChatReply | null> => {
+ } | { kind: 'session'; nodeId: string }): 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
@@ -4096,6 +4101,10 @@ app.whenReady().then(async () => {
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
+ },
+ session: async (q: { nodeId: string }): Promise<{ sessionId?: string } | null> => {
+ const r = await ask({ kind: 'session', ...q })
+ return r && r.kind === 'session' ? { sessionId: r.sessionId } : null
}
}
})()
diff --git a/src/main/remote/host-chat.test.ts b/src/main/remote/host-chat.test.ts
index a1a91dd9c..64cb9e55b 100644
--- a/src/main/remote/host-chat.test.ts
+++ b/src/main/remote/host-chat.test.ts
@@ -10,7 +10,7 @@
// - `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 { createHostChat, mirrorRefusesChatSend, type HostChatDeps } from './host-chat'
import type { ChatTranscriptResult } from '../../shared/types'
import type { HeldPermissionIo } from '../../core/agents/permission-decision'
@@ -29,8 +29,11 @@ function deps(over: Partial<HostChatDeps> = {}): HostChatDeps {
isStructuredTicket: vi.fn(() => false),
renderer: {
status: vi.fn(async () => RSTATUS),
- send: vi.fn(async () => 'sent' as const)
+ send: vi.fn(async () => 'sent' as const),
+ session: vi.fn(async () => ({ sessionId: 'sid-1' }))
},
+ hostSendRefusal: vi.fn(() => false),
+ knownTickets: vi.fn(() => ['p-1']),
timeoutMs: 20,
sendTimeoutMs: 40,
now: () => 1000,
@@ -39,15 +42,22 @@ function deps(over: Partial<HostChatDeps> = {}): HostChatDeps {
}
describe('host-chat page', () => {
- it('resolves the node host-side, reads paged and stamps version 1', async () => {
+ it('resolves the node host-side, reads paged and stamps version 1 (local node: no cwd)', async () => {
const d = deps()
const page = await createHostChat(d).page('n1', { before: 10, maxBytes: 65536 })
expect(page).toEqual({ ...RESULT, version: 1 })
+ // A LOCAL node reads by session id only: with a cwd, a known-but-dead id would fall back to the
+ // newest transcript in that cwd — another node's session.
expect(d.readTranscript).toHaveBeenCalledWith(
- { sessionId: 'sid-1', cwd: '/srv/app', accountId: 'acc', nodeId: 'n1', agentId: 'claude' },
+ { sessionId: 'sid-1', cwd: undefined, accountId: 'acc', nodeId: 'n1', agentId: 'claude' },
{ before: 10, maxBytes: 65536 }
)
})
+ it('a REMOTE node keeps its cwd (the host-side locate is keyed on it)', async () => {
+ const d = deps({ lookupNode: () => ({ cwd: '/srv/app', agentId: 'claude', sessionId: 'sid-1', remote: true }) })
+ await createHostChat(d).page('n1', {})
+ expect(d.readTranscript).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/srv/app', sessionId: 'sid-1' }), {})
+ })
it('an absent page is the default paged tail, not the legacy read', async () => {
const d = deps()
await createHostChat(d).page('n1', undefined)
@@ -58,8 +68,30 @@ describe('host-chat page', () => {
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' }) })
+ it('the RENDERER\'s session id wins over the host records (what ⌘M shows)', async () => {
+ const d = deps({
+ lookupNode: () => ({ cwd: '/srv/app', agentId: 'claude', sessionId: 'stale-minted' }),
+ renderer: { status: vi.fn(), send: vi.fn(), session: vi.fn(async () => ({ sessionId: 'hook-fed' })) }
+ })
+ await createHostChat(d).page('n1', {})
+ expect(d.readTranscript).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'hook-fed' }), {})
+ expect(d.renderer.session).toHaveBeenCalledWith({ nodeId: 'n1' })
+ })
+ it('falls back to the host records when the renderer does not answer in time, or knows none', async () => {
+ for (const session of [() => new Promise<never>(() => {}), async () => null, async () => ({})]) {
+ const d = deps({
+ lookupNode: () => ({ agentId: 'claude', sessionId: 'mirror-id' }),
+ renderer: { status: vi.fn(), send: vi.fn(), session: session as never }
+ })
+ await createHostChat(d).page('n1', {})
+ expect(d.readTranscript).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'mirror-id' }), {})
+ }
+ })
+ it('no known session id anywhere ⇒ no cwd either, so no cwd fallback onto a stranger\'s transcript', async () => {
+ const d = deps({
+ lookupNode: () => ({ cwd: '/srv/app', agentId: 'claude', remote: true }),
+ renderer: { status: vi.fn(), send: vi.fn(), session: vi.fn(async () => ({})) }
+ })
await createHostChat(d).page('n1', {})
expect(d.readTranscript).toHaveBeenCalledWith(
{ sessionId: undefined, cwd: undefined, accountId: undefined, nodeId: 'n1', agentId: 'claude' },
@@ -72,7 +104,7 @@ 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() },
+ renderer: { status: vi.fn(async () => ({ ...RSTATUS, state: 'waiting' as const, held })), send: vi.fn(), session: vi.fn() },
isStructuredTicket: vi.fn((id: string) => id === 'p-1')
})
const s = await createHostChat(d).status('n1')
@@ -89,9 +121,9 @@ describe('host-chat status', () => {
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() } })
+ const hang = deps({ renderer: { status: () => new Promise(() => {}), send: vi.fn(), session: vi.fn() } })
await expect(createHostChat(hang).status('n1')).rejects.toThrow()
- const gone = deps({ renderer: { status: async () => null, send: vi.fn() } })
+ const gone = deps({ renderer: { status: async () => null, send: vi.fn(), session: vi.fn() } })
await expect(createHostChat(gone).status('n1')).rejects.toThrow()
})
})
@@ -108,12 +140,22 @@ describe('host-chat send', () => {
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 } })
+ it('never started (no window / a throw) ⇒ refused', async () => {
+ for (const send of [async () => null, async () => { throw new Error('x') }]) {
+ const d = deps({ renderer: { status: vi.fn(), send: send as never, session: vi.fn() } })
expect(await createHostChat(d).send('n1', 'hi')).toBe('refused')
}
})
+ it('dispatched but no answer in time ⇒ UNCONFIRMED, never refused (the phone must not resend)', async () => {
+ const d = deps({ renderer: { status: vi.fn(), send: () => new Promise<never>(() => {}), session: vi.fn() } })
+ expect(await createHostChat(d).send('n1', 'hi')).toBe('unconfirmed')
+ })
+ it('the host mirror says the agent is busy or asking ⇒ refused before the renderer is asked', async () => {
+ const d = deps({ hostSendRefusal: vi.fn(() => true) })
+ expect(await createHostChat(d).send('n1', 'hi')).toBe('refused')
+ expect(d.hostSendRefusal).toHaveBeenCalledWith('n1')
+ expect(d.renderer.send).not.toHaveBeenCalled()
+ })
})
describe('host-chat answer', () => {
@@ -131,6 +173,29 @@ describe('host-chat answer', () => {
expect(await createHostChat(d).answer('n1', 'p-1', { kind: 'deny' })).toBe(false)
expect(d.onAnswered).not.toHaveBeenCalled()
})
+ it('a pendingId that is not this node\'s ticket is refused: no I/O, no answered event', async () => {
+ const d = deps({
+ knownTickets: vi.fn(() => ['other-ticket']),
+ renderer: { status: vi.fn(async () => ({ ...RSTATUS, held: { pendingId: 'mine', toolName: 'ExitPlanMode' } })), send: vi.fn(), session: vi.fn() }
+ })
+ expect(await createHostChat(d).answer('n1', 'not-mine', { kind: 'deny' })).toBe(false)
+ expect(d.answerIo).not.toHaveBeenCalled()
+ expect(d.answerHeld).not.toHaveBeenCalled()
+ expect(d.onAnswered).not.toHaveBeenCalled()
+ })
+ it('binds through the renderer\'s held ticket OR the mirror\'s tickets for the node', async () => {
+ const viaHeld = deps({
+ knownTickets: vi.fn(() => []),
+ renderer: { status: vi.fn(async () => ({ ...RSTATUS, held: { pendingId: 'h-1', toolName: 'AskUserQuestion' } })), send: vi.fn(), session: vi.fn() }
+ })
+ expect(await createHostChat(viaHeld).answer('n1', 'h-1', { kind: 'deny' })).toBe(true)
+ const viaMirror = deps({
+ knownTickets: vi.fn(() => ['m-1']),
+ renderer: { status: () => new Promise<never>(() => {}), send: vi.fn(), session: vi.fn() }
+ })
+ expect(await createHostChat(viaMirror).answer('n1', 'm-1', { kind: 'deny' })).toBe(true)
+ expect(viaMirror.knownTickets).toHaveBeenCalledWith('n1')
+ })
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)
@@ -139,8 +204,23 @@ describe('host-chat answer', () => {
})
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 }) })
+ const d = deps({
+ answerHeld: undefined,
+ knownTickets: () => ['never-seen-ticket'],
+ answerIo: () => ({ readPending: async () => null, write })
+ })
expect(await createHostChat(d).answer('n1', 'never-seen-ticket', { kind: 'plan', mode: 'restore' })).toBe(false)
expect(write).not.toHaveBeenCalled()
})
})
+
+describe('mirrorRefusesChatSend (the host half of the send gate)', () => {
+ it('refuses a busy / asking agent and any held question or approval; passes done and unknown', () => {
+ for (const state of ['working', 'waiting', 'blocked']) expect(mirrorRefusesChatSend({ state })).toBe(true)
+ expect(mirrorRefusesChatSend({ state: 'done', pendingQuestion: { sessionId: 's', toolUseId: 't' } })).toBe(true)
+ expect(mirrorRefusesChatSend({ state: 'done', concurrentApprovalIds: ['p'] })).toBe(true)
+ expect(mirrorRefusesChatSend({ state: 'done' })).toBe(false)
+ expect(mirrorRefusesChatSend({ state: 'done', concurrentApprovalIds: [] })).toBe(false)
+ expect(mirrorRefusesChatSend(undefined)).toBe(false)
+ })
+})
diff --git a/src/main/remote/host-chat.ts b/src/main/remote/host-chat.ts
index 8efa11ce2..4dcce5d63 100644
--- a/src/main/remote/host-chat.ts
+++ b/src/main/remote/host-chat.ts
@@ -6,9 +6,11 @@
// - 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.
+// same one the ⌘M composer runs), asked at send time, after the host mirror's own refusal. A
+// renderer that does not answer fails CLOSED: status is an error; a send with no window is
+// 'refused', and one dispatched but unanswered is 'unconfirmed' (never 'refused', which invites
+// a resend and a duplicate prompt). 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.
@@ -27,6 +29,8 @@ export interface HostChatNode {
accountId?: string
agentId?: string
sessionId?: string
+ /** An SSH-project node: its transcript is located ON the host, keyed on cwd. */
+ remote?: boolean
}
export interface HostChatDeps {
@@ -47,7 +51,15 @@ export interface HostChatDeps {
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>
+ /** The store's session id for the node (what ⌘M reads). `null` = no window. */
+ session(q: { nodeId: string }): Promise<{ sessionId?: string } | null>
}
+ /** The HOST's own view of the node, asked before the renderer on a send: true when the mirror says
+ * the agent is working / waiting / blocked or holds a question. Renderer state is transient (a
+ * reload wipes it), the mirror is not — defense in depth, never the only gate. */
+ hostSendRefusal(nodeId: string): boolean
+ /** The approval tickets the host's mirror holds for this node (`pendingTicketsFor`). */
+ knownTickets(nodeId: string): string[]
/** 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
@@ -58,6 +70,17 @@ export interface HostChatDeps {
now?: () => number
}
+/** The host mirror's half of the send gate (`hostSendRefusal`): refuse while the agent is working,
+ * waiting or blocked, or holds a question / approval ticket. `done` and an unknown state pass on to
+ * the renderer's own gate, which still has the final say. */
+export function mirrorRefusesChatSend(
+ entry: { state?: string | null; pendingQuestion?: unknown; concurrentApprovalIds?: readonly string[] } | undefined
+): boolean {
+ if (!entry) return false
+ if (entry.state === 'working' || entry.state === 'waiting' || entry.state === 'blocked') return true
+ return !!entry.pendingQuestion || (entry.concurrentApprovalIds?.length ?? 0) > 0
+}
+
export const HOST_CHAT_RENDERER_TIMEOUT_MS = 3000
export const HOST_CHAT_SEND_TIMEOUT_MS = 15_000
@@ -76,16 +99,39 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {
const sendTimeoutMs = deps.sendTimeoutMs ?? HOST_CHAT_SEND_TIMEOUT_MS
const now = deps.now ?? Date.now
const answerHeld = deps.answerHeld ?? answerHeldPermission
+ async function ticketBelongsTo(nodeId: string, agentId: string | undefined, pendingId: string): Promise<boolean> {
+ if (deps.knownTickets(nodeId).includes(pendingId)) return true
+ try {
+ const st = await withTimeout(deps.renderer.status({ nodeId, agentId }), timeoutMs)
+ return st !== TIMED_OUT && st !== null && st.held?.pendingId === pendingId
+ } catch {
+ return false
+ }
+ }
+
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).
+ // The renderer's agent-status id first: it is what ⌘M reads, and after a desktop restart a
+ // hook-fed id lives there while the mirror is empty and the node carries a stale minted id.
+ // The host records are the fallback only when the renderer does not answer in time.
+ let sessionId = node.sessionId
+ try {
+ const fromRenderer = await withTimeout(deps.renderer.session({ nodeId }), timeoutMs)
+ if (fromRenderer !== TIMED_OUT && fromRenderer && typeof fromRenderer.sessionId === 'string' && fromRenderer.sessionId) {
+ sessionId = fromRenderer.sessionId
+ }
+ } catch {
+ // fall back to the host records
+ }
+ // A cwd rides only for a REMOTE node with a known session id — the host-side locate is keyed
+ // on it. Locally the id alone resolves the file, and a cwd would let a known-but-dead id fall
+ // back to the NEWEST transcript in that cwd: another node's session. With no id at all, not
+ // found is the honest answer.
const q: ChatReadQuery = {
- sessionId: node.sessionId,
- cwd: node.sessionId ? node.cwd : undefined,
+ sessionId,
+ cwd: sessionId && node.remote ? node.cwd : undefined,
accountId: node.accountId,
nodeId,
agentId: node.agentId
@@ -109,24 +155,31 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {
async send(nodeId, text) {
const node = deps.lookupNode(nodeId)
if (!node) return 'unknown-node'
+ if (deps.hostSendRefusal(nodeId)) return 'refused'
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.
+ // time gets the longer budget to finish; past it the answer is 'unconfirmed' — the text may
+ // still land, so the phone must not resend it (a duplicate prompt), only re-read.
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
+ if (result === TIMED_OUT) return 'unconfirmed'
+ return result === null ? 'refused' : result
} catch {
return 'refused'
}
},
async answer(nodeId, pendingId, answer) {
- if (!deps.lookupNode(nodeId)) return false
+ const node = deps.lookupNode(nodeId)
+ if (!node) return false
+ // The ticket must be THIS node's: the mirror's approval tickets, or the renderer's held request
+ // (plans / questions — the mirror strips a question's id). A mismatched pair touches no I/O and
+ // emits no answered event onto the wrong node.
+ if (!(await ticketBelongsTo(nodeId, node.agentId, pendingId))) 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
index d6484425a..477f16c55 100644
--- a/src/main/remote/host-service.chat.test.ts
+++ b/src/main/remote/host-service.chat.test.ts
@@ -172,7 +172,7 @@ describe('chat.send', () => {
}
})
it('passes a refusal and a partial delivery through verbatim', async () => {
- for (const result of ['refused', 'pasted-not-submitted'] as const) {
+ for (const result of ['refused', 'pasted-not-submitted', 'unconfirmed'] 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 } })
}
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index d9012869c..fd1ddc029 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -391,7 +391,7 @@ import {
} from '../lib/explorerPinHint'
import { useProjects } from '../state/projects'
import { useAgentStatus } from '../state/agentStatus'
-import { hostChatSend, hostChatStatus } from '../lib/hostChatQuery'
+import { hostChatSend, hostChatSession, hostChatStatus } from '../lib/hostChatQuery'
import { useLaunchDelivery } from '../state/launchDelivery'
import { useBrowserLease, drivingNodeIds } from '../state/browserLease'
import { useTerminalFocus } from '../state/terminalFocus'
@@ -9953,6 +9953,14 @@ export function Canvas() {
})
return
}
+ if (q.kind === 'session') {
+ api.sendHostChatReply({
+ requestId: q.requestId,
+ kind: 'session',
+ ...hostChatSession(useAgentStatus.getState().byId[q.nodeId])
+ })
+ return
+ }
void hostChatSend(q, {
getStatus: (id) => useAgentStatus.getState().byId[id],
sendText: (id, text) => api.pty.sendText(id, text),
diff --git a/src/renderer/lib/hostChatQuery.test.ts b/src/renderer/lib/hostChatQuery.test.ts
index a0926b770..797adba9a 100644
--- a/src/renderer/lib/hostChatQuery.test.ts
+++ b/src/renderer/lib/hostChatQuery.test.ts
@@ -4,7 +4,7 @@
// - 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'
+import { hostChatSend, hostChatSession, hostChatStatus } from './hostChatQuery'
const HELD = { pendingId: 'p-1', toolName: 'ExitPlanMode' }
@@ -26,6 +26,13 @@ describe('hostChatStatus', () => {
})
})
+describe('hostChatSession', () => {
+ it('answers the store\'s session id, or nothing', () => {
+ expect(hostChatSession({ sessionId: 'sid' })).toEqual({ sessionId: 'sid' })
+ expect(hostChatSession(undefined)).toEqual({})
+ })
+})
+
describe('hostChatSend', () => {
const base = { requestId: 'r', kind: 'send' as const, nodeId: 'n1', agentId: 'claude', text: 'hi', startBy: 2000 }
const run = (
@@ -81,7 +88,8 @@ describe('hostChatSend', () => {
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')
+ // A sendText that REJECTED may have pasted already: unconfirmed, so the phone does not resend.
+ expect((await run({ state: 'done' }, vi.fn(async () => { throw new Error('x') }))).r).toBe('unconfirmed')
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
index 2260f21bf..dec457bda 100644
--- a/src/renderer/lib/hostChatQuery.ts
+++ b/src/renderer/lib/hostChatQuery.ts
@@ -50,6 +50,14 @@ export async function hostChatSend(
if (r === 'pasted-not-submitted') return 'pasted-not-submitted'
return 'refused'
} catch {
- return 'refused'
+ // The call STARTED: a rejection may come after the paste landed (a dropped IPC reply), so this
+ // is not a refusal — 'refused' would invite the phone to resend and type the prompt twice.
+ return 'unconfirmed'
}
}
+
+/** The store's session id for a node — the id the ⌘M view reads. Main prefers it over its own
+ * records (after a desktop restart a hook-fed id lives only here). */
+export function hostChatSession(st: { sessionId?: string } | undefined): { sessionId?: string } {
+ return typeof st?.sessionId === 'string' && st.sessionId ? { sessionId: st.sessionId } : {}
+}
diff --git a/src/shared/mobile-chat.ts b/src/shared/mobile-chat.ts
index a34a0abb5..921d9c08e 100644
--- a/src/shared/mobile-chat.ts
+++ b/src/shared/mobile-chat.ts
@@ -26,7 +26,11 @@ export interface ChatStatus {
structuredAnswers: boolean
}
-export type ChatSendResult = 'sent' | 'refused' | 'pasted-not-submitted'
+/** `refused` = never started (nothing was typed: no window, the gate refused, or it arrived too
+ * late to start). `unconfirmed` = the send WAS dispatched to the desktop but no result came back in
+ * time — the text may or may not have landed, so the phone must NOT resend it (that would type the
+ * prompt twice); it should re-read the page instead. */
+export type ChatSendResult = 'sent' | 'refused' | 'pasted-not-submitted' | 'unconfirmed'
/** Longest text `chat.send` accepts, in UTF-16 code units (JS `.length`, Swift `utf16.count`),
* checked on the RAW text before stripping. */
@@ -50,8 +54,11 @@ export function sanitizeChatText(text: string): string {
export type HostChatQuery =
| { requestId: string; kind: 'status'; nodeId: string; agentId?: string }
| { requestId: string; kind: 'send'; nodeId: string; agentId?: string; text: string; startBy: number }
+ | { requestId: string; kind: 'session'; nodeId: string }
/** 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 }
+ /** The renderer's agent-status session id — the one the ⌘M view reads. Absent = it knows none. */
+ | { requestId: string; kind: 'session'; sessionId?: string }