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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(mobile-chat): host view in status, send reasons, single flight, page gate
review811dd1f127c0
diff --git a/src/main/index.ts b/src/main/index.tsindex 90c790fe2..d1c36260f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -230,10 +230,11 @@ import {remoteTranscriptRoots} from '../core/remote-transcript-locate'import { readChatTranscript, registerTranscriptIpc, resolveTranscript, type TranscriptIpcDeps } from '../core/transcript-ipc'-import { createHostChat, mirrorRefusesChatSend } from './remote/host-chat'-import type { ChatSendResult, ChatStatus, HostChatReply } from '../shared/mobile-chat'+import { createHostChat, mirrorChatSendRefusal } from './remote/host-chat'+import type { ChatSendOutcome, HostChatReply, RendererChatStatus } from '../shared/mobile-chat'import {createReadRemotePage,+ remoteTargetForNode,forgetLocatedRef,rememberHookRef,type RemoteTranscriptRefCache@@ -2672,6 +2673,15 @@ app.whenReady().then(async () => {// 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.// Named so the phone Chat verbs (hostBridge.chat) read through the SAME deps as the ⌘M panel.+ // The master a remote transcript read goes over: the live pty's, else the node's SSH PROJECT's —+ // an unmounted node (idle tab, after a restart) has no pty, and resolving it only through the pty+ // read it as "not remote" and sent the read to THIS machine's disk.+ const sshTargetForNode = (nodeId: string) =>+ remoteTargetForNode(nodeId, {+ live: (id) => ptyManager.sshRemoteForNode(id),+ projectIdFor: (id) => workspaceStore.sshProjectIdForNode(id),+ refForProject: (projectId) => sshProjectManager?.refForProject(projectId)+ })const transcriptIpcDeps: TranscriptIpcDeps = {pathFor: (sessionId) => contextTail.pathFor(sessionId),readRemote: async ({ sessionId, cwd, accountId, nodeId }) => {@@ -2685,7 +2695,7 @@ app.whenReady().then(async () => {readRemotePage: createReadRemotePage({cache: remoteTranscriptRefs,refFor: ({ sessionId, cwd, accountId, nodeId }) =>- remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId),+ remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId, nodeId ? sshTargetForNode(nodeId) : undefined),readPage: (ref, before, maxBytes) => remoteFile.readTranscriptPage(ref, before, maxBytes)}),remoteExists: async ({ sessionId, accountId, nodeId }) =>@@ -4062,7 +4072,7 @@ app.whenReady().then(async () => {remote: workspaceStore.sshProjectIdForNode(nodeId) !== undefined}},- hostSendRefusal: (nodeId) => mirrorRefusesChatSend(mirrorEntry(nodeId)),+ hostSendRefusal: (nodeId) => mirrorChatSendRefusal(mirrorEntry(nodeId)),knownTickets: pendingTicketsFor,readTranscript: (q, rawPage) => readChatTranscript(q, rawPage, transcriptIpcDeps),answerIo: heldPermissionIoFor,@@ -4075,7 +4085,10 @@ app.whenReady().then(async () => {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+ // Resolved at receive time (getMainWindow), like the query below: a macOS window closed+ // and re-created must keep answering. (Sibling nodeActions still use the captured `win`.)+ const w = getMainWindow()+ if (!w || w.isDestroyed() || e.sender !== w.webContents) returnconst resolve = reply && typeof reply.requestId === 'string' ? pending.get(reply.requestId) : undefinedif (!resolve) returnpending.delete(reply.requestId)@@ -4084,23 +4097,24 @@ app.whenReady().then(async () => {const ask = (q: { kind: 'status'; nodeId: string; agentId?: string } | {kind: 'send'; nodeId: string; agentId?: string; text: string; startBy: number} | { kind: 'session'; nodeId: string }): Promise<HostChatReply | null> => {- if (win.isDestroyed()) return Promise.resolve(null)+ const w = getMainWindow()+ if (!w || w.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 })+ w.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> => {+ status: async (q: { nodeId: string; agentId?: string }): Promise<RendererChatStatus | 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> => {+ send: async (q: { nodeId: string; agentId?: string; text: string; startBy: number }): Promise<ChatSendOutcome | null> => {const r = await ask({ kind: 'send', ...q })- return r && r.kind === 'send' ? r.result : null+ return r && r.kind === 'send' ? { result: r.result, ...(r.reason ? { reason: r.reason } : {}) } : null},session: async (q: { nodeId: string }): Promise<{ sessionId?: string } | null> => {const r = await ask({ kind: 'session', ...q })diff --git a/src/main/remote/host-chat-wiring.test.ts b/src/main/remote/host-chat-wiring.test.tsindex dc53c52dc..0a78f3a17 100644--- a/src/main/remote/host-chat-wiring.test.ts+++ b/src/main/remote/host-chat-wiring.test.ts@@ -22,6 +22,17 @@ describe('phone chat verbs are wired end to end', () => {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 remote transcript leg resolves an UNMOUNTED SSH node by its project', () => {+ const src = read('main/index.ts')+ expect(src).toMatch(/remoteTranscriptRefFor\(sessionId, cwd, accountId, nodeId, nodeId \? sshTargetForNode\(nodeId\) : undefined\)/)+ expect(src).toMatch(/refForProject: \(projectId\) => sshProjectManager\?\.refForProject\(projectId\)/)+ })+ it('the hostChat round-trip resolves the window at send time (a re-created macOS window keeps working)', () => {+ const src = read('main/index.ts')+ const block = src.slice(src.indexOf('chat: createHostChat({'), src.indexOf('workspaceRoots: () =>'))+ expect(block).toMatch(/getMainWindow\(\)/)+ expect(block).not.toMatch(/\bwin\.(webContents|isDestroyed)/)+ })it('the renderer answers the round-trip', () => {const canvas = read('renderer/canvas/Canvas.tsx')expect(canvas).toMatch(/api\.onHostChatQuery\(/)diff --git a/src/main/remote/host-chat.test.ts b/src/main/remote/host-chat.test.tsindex 64cb9e55b..4843a19c5 100644--- a/src/main/remote/host-chat.test.ts+++ b/src/main/remote/host-chat.test.ts@@ -10,7 +10,8 @@// - `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, mirrorRefusesChatSend, type HostChatDeps } from './host-chat'+import { createHostChat, mirrorChatSendRefusal, type HostChatDeps } from './host-chat'+import { setCustomAgentBaseResolver } from '../../shared/agents/config'import type { ChatTranscriptResult } from '../../shared/types'import type { HeldPermissionIo } from '../../core/agents/permission-decision'@@ -29,10 +30,10 @@ 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 () => ({ result: 'sent' as const })),session: vi.fn(async () => ({ sessionId: 'sid-1' }))},- hostSendRefusal: vi.fn(() => false),+ hostSendRefusal: vi.fn(() => null),knownTickets: vi.fn(() => ['p-1']),timeoutMs: 20,sendTimeoutMs: 40,@@ -53,10 +54,31 @@ describe('host-chat page', () => {{ before: 10, maxBytes: 65536 })})- it('a REMOTE node keeps its cwd (the host-side locate is keyed on it)', async () => {+ it('a REMOTE node keeps its cwd (the host-side locate is keyed on it) and is read REMOTE-ONLY', 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' }), {})+ expect(d.readTranscript).toHaveBeenCalledWith(+ expect.objectContaining({ cwd: '/srv/app', sessionId: 'sid-1', remoteOnly: true }),+ {}+ )+ })+ it('an UNREADABLE read (a remote read that failed) rejects — the relay says "Could not read the transcript."', async () => {+ const d = deps({ readTranscript: vi.fn(async () => ({ ...RESULT, found: false, unreadable: true as const })) })+ await expect(createHostChat(d).page('n1', {})).rejects.toThrow()+ })+ it('serves only chat-capable agents (resolved through the base harness), and reads nothing otherwise', async () => {+ for (const agentId of ['codex', 'gemini', undefined]) {+ const d = deps({ lookupNode: () => ({ agentId, sessionId: 'sid-1' }) })+ expect(await createHostChat(d).page('n1', {})).toBe('unsupported')+ expect(d.readTranscript).not.toHaveBeenCalled()+ }+ setCustomAgentBaseResolver((id) => (id === 'custom:x' ? 'claude' : undefined))+ try {+ const d = deps({ lookupNode: () => ({ agentId: 'custom:x', sessionId: 'sid-1' }) })+ expect(await createHostChat(d).page('n1', {})).toMatchObject({ version: 1 })+ } finally {+ setCustomAgentBaseResolver(null)+ }})it('an absent page is the default paged tail, not the legacy read', async () => {const d = deps()@@ -94,7 +116,7 @@ describe('host-chat page', () => {})await createHostChat(d).page('n1', {})expect(d.readTranscript).toHaveBeenCalledWith(- { sessionId: undefined, cwd: undefined, accountId: undefined, nodeId: 'n1', agentId: 'claude' },+ { sessionId: undefined, cwd: undefined, accountId: undefined, nodeId: 'n1', agentId: 'claude', remoteOnly: true },{})})@@ -108,9 +130,16 @@ describe('host-chat status', () => {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(s).toEqual({ ...RSTATUS, state: 'waiting', held, structuredAnswers: true, version: 1, hostRefuses: false })expect(d.renderer.status).toHaveBeenCalledWith({ nodeId: 'n1', agentId: 'claude' })})+ it('carries the HOST view: after a restart the renderer knows nothing while the mirror holds a dialog', async () => {+ const d = deps({+ renderer: { status: vi.fn(async () => ({ ...RSTATUS, state: null })), send: vi.fn(), session: vi.fn() },+ hostSendRefusal: vi.fn(() => 'dialog' as const)+ })+ expect(await createHostChat(d).status('n1')).toMatchObject({ state: null, hostRefuses: true, refusal: 'dialog', version: 1 })+ })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)@@ -131,7 +160,7 @@ describe('host-chat status', () => {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')+ expect(await createHostChat(d).send('n1', 'hello')).toEqual({ result: '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 })})@@ -140,19 +169,51 @@ describe('host-chat send', () => {expect(await createHostChat(d).send('nope', 'hi')).toBe('unknown-node')expect(d.renderer.send).not.toHaveBeenCalled()})- it('never started (no window / a throw) ⇒ refused', async () => {+ it('never started (no window / a throw) ⇒ refused, reason unavailable', 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')+ expect(await createHostChat(d).send('n1', 'hi')).toEqual({ result: 'refused', reason: 'unavailable' })}})+ it('passes the renderer\'s refusal reason through', async () => {+ const d = deps({ renderer: { status: vi.fn(), send: vi.fn(async () => ({ result: 'refused' as const, reason: 'working' as const })), session: vi.fn() } })+ expect(await createHostChat(d).send('n1', 'hi')).toEqual({ result: 'refused', reason: 'working' })+ })+ it('a second send to the same node while one is in flight is refused as busy; other nodes are not held', async () => {+ let finish!: (v: { result: 'sent' }) => void+ const send = vi.fn(() => new Promise<{ result: 'sent' }>((r) => (finish = r)))+ const d = deps({+ lookupNode: vi.fn((id: string) => ({ agentId: 'claude', sessionId: id })),+ renderer: { status: vi.fn(), send: send as never, session: vi.fn() },+ sendTimeoutMs: 1000+ })+ const hc = createHostChat(d)+ const first = hc.send('n1', 'a')+ expect(await hc.send('n1', 'b')).toEqual({ result: 'refused', reason: 'busy' })+ expect(send).toHaveBeenCalledTimes(1)+ finish({ result: 'sent' })+ expect(await first).toEqual({ result: 'sent' })+ send.mockImplementation(async () => ({ result: 'sent' as const }))+ expect(await hc.send('n1', 'c')).toEqual({ result: 'sent' })+ })+ it('an UNCONFIRMED send keeps the node busy until the dispatched send settles', async () => {+ let finish!: (v: { result: 'sent' }) => void+ const send = vi.fn(() => new Promise<{ result: 'sent' }>((r) => (finish = r)))+ const hc = createHostChat(deps({ renderer: { status: vi.fn(), send: send as never, session: vi.fn() } }))+ expect(await hc.send('n1', 'a')).toEqual({ result: 'unconfirmed' })+ expect(await hc.send('n1', 'b')).toEqual({ result: 'refused', reason: 'busy' })+ finish({ result: 'sent' })+ await new Promise((r) => setTimeout(r, 0))+ send.mockImplementation(async () => ({ result: 'sent' as const }))+ expect(await hc.send('n1', 'c')).toEqual({ result: 'sent' })+ })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')+ expect(await createHostChat(d).send('n1', 'hi')).toEqual({ result: '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')+ const d = deps({ hostSendRefusal: vi.fn(() => 'working' as const) })+ expect(await createHostChat(d).send('n1', 'hi')).toEqual({ result: 'refused', reason: 'working' })expect(d.hostSendRefusal).toHaveBeenCalledWith('n1')expect(d.renderer.send).not.toHaveBeenCalled()})@@ -214,13 +275,14 @@ describe('host-chat answer', () => {})})-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)+describe('mirrorChatSendRefusal (the host half of the send gate)', () => {+ it('names why: working, or a dialog (waiting / blocked / held question or approval); passes done and unknown', () => {+ expect(mirrorChatSendRefusal({ state: 'working' })).toBe('working')+ for (const state of ['waiting', 'blocked']) expect(mirrorChatSendRefusal({ state })).toBe('dialog')+ expect(mirrorChatSendRefusal({ state: 'done', pendingQuestion: { sessionId: 's', toolUseId: 't' } })).toBe('dialog')+ expect(mirrorChatSendRefusal({ state: 'done', concurrentApprovalIds: ['p'] })).toBe('dialog')+ expect(mirrorChatSendRefusal({ state: 'done' })).toBeNull()+ expect(mirrorChatSendRefusal({ state: 'done', concurrentApprovalIds: [] })).toBeNull()+ expect(mirrorChatSendRefusal(undefined)).toBeNull()})})diff --git a/src/main/remote/host-chat.ts b/src/main/remote/host-chat.tsindex 4dcce5d63..ead64b644 100644--- a/src/main/remote/host-chat.ts+++ b/src/main/remote/host-chat.ts@@ -15,7 +15,8 @@// 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 { ChatHostRefusal, ChatSendOutcome, RendererChatStatus } from '../../shared/mobile-chat'+import { canChat, capabilityAgentId } from '../../shared/agents/config'import type { ChatReadQuery } from '../../core/transcript-ipc'import {answerHeldPermission,@@ -49,15 +50,15 @@ export interface HostChatDeps {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>+ status(q: { nodeId: string; agentId?: string }): Promise<RendererChatStatus | null>+ send(q: { nodeId: string; agentId?: string; text: string; startBy: number }): Promise<ChatSendOutcome | 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 HOST's own view of the node (`mirrorChatSendRefusal`), asked before the renderer on a send+ * and reported on every status: why the mirror refuses, or null. Renderer state is transient (a+ * reload or a desktop restart wipes it), the mirror is not — defense in depth, never the only gate. */+ hostSendRefusal(nodeId: string): ChatHostRefusal | null/** 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@@ -73,14 +74,19 @@ export interface HostChatDeps {/** 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(+export function mirrorChatSendRefusal(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+): ChatHostRefusal | null {+ if (!entry) return null+ if (entry.state === 'working') return 'working'+ if (entry.state === 'waiting' || entry.state === 'blocked') return 'dialog'+ return entry.pendingQuestion || (entry.concurrentApprovalIds?.length ?? 0) > 0 ? 'dialog' : null}+/** How long a node stays busy after an UNCONFIRMED send whose dispatch never settles (main drops an+ * unanswered query after 30 s, so its promise may never settle at all). */+export const HOST_CHAT_BUSY_CAP_MS = 30_000+export const HOST_CHAT_RENDERER_TIMEOUT_MS = 3000export const HOST_CHAT_SEND_TIMEOUT_MS = 15_000@@ -99,6 +105,10 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {const sendTimeoutMs = deps.sendTimeoutMs ?? HOST_CHAT_SEND_TIMEOUT_MSconst now = deps.now ?? Date.nowconst answerHeld = deps.answerHeld ?? answerHeldPermission+ // Per-node single flight: a second send while the first is still being typed would splice two+ // prompts into one pane. Held until the DISPATCHED send settles (not merely until the phone got an+ // answer) — an 'unconfirmed' send may still be pasting — capped so a lost reply cannot wedge it.+ const sending = new Set<string>()async function ticketBelongsTo(nodeId: string, agentId: string | undefined, pendingId: string): Promise<boolean> {if (deps.knownTickets(nodeId).includes(pendingId)) return truetry {@@ -113,6 +123,10 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {async page(nodeId, rawPage) {const node = deps.lookupNode(nodeId)if (!node) return null+ // Only agents whose transcript the ⌘M view can render (through a custom agent's base harness).+ // Anything else would read claude's resolver for a codex / gemini / plain node: a stranger's+ // conversation, or a confident "not found".+ if (!node.agentId || !canChat(capabilityAgentId(node.agentId))) return 'unsupported'// 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.@@ -134,10 +148,15 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {cwd: sessionId && node.remote ? node.cwd : undefined,accountId: node.accountId,nodeId,- agentId: node.agentId+ agentId: node.agentId,+ // A node the host KNOWS is remote never falls back to THIS machine's disk, even when no pty+ // is attached (idle tab, after a restart).+ ...(node.remote ? { remoteOnly: true } : {})}// Always PAGED: an absent page is the default tail, never the legacy 5 MB read.const result = await deps.readTranscript(q, rawPage ?? {})+ // A read that FAILED (a remote host that did not answer) is an error, never "no transcript".+ if (result.unreadable) throw new Error('Could not read the transcript.')return { ...result, version: 1 }},@@ -149,27 +168,52 @@ export function createHostChat(deps: HostChatDeps): HostChatOps {throw new Error('The desktop window is not available.')}const structuredAnswers = answered.held ? deps.isStructuredTicket(answered.held.pendingId) : false- return { ...answered, structuredAnswers }+ // The host's view rides every status: after a desktop restart the window knows nothing (state+ // null) while the mirror may still hold a live dialog, and `chat.send` refuses on it — the+ // phone must see the same lock the send will apply.+ const refusal = deps.hostSendRefusal(nodeId)+ return {+ version: 1 as const,+ ...answered,+ structuredAnswers,+ hostRefuses: refusal !== null,+ ...(refusal ? { refusal } : {})+ }},async send(nodeId, text) {const node = deps.lookupNode(nodeId)if (!node) return 'unknown-node'- if (deps.hostSendRefusal(nodeId)) return 'refused'+ const refusal = deps.hostSendRefusal(nodeId)+ if (refusal) return { result: 'refused', reason: refusal }+ if (sending.has(nodeId)) return { result: 'refused', reason: 'busy' }+ sending.add(nodeId)+ let released = false+ let cap: ReturnType<typeof setTimeout> | undefined+ const release = () => {+ if (released) return+ released = true+ if (cap) clearTimeout(cap)+ sending.delete(nodeId)+ }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 '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- )- if (result === TIMED_OUT) return 'unconfirmed'- return result === null ? 'refused' : result+ const dispatched = deps.renderer.send({ nodeId, agentId: node.agentId, text, startBy })+ dispatched.then(release, release)+ const result = await withTimeout(dispatched, sendTimeoutMs)+ if (result === TIMED_OUT) {+ cap = setTimeout(release, HOST_CHAT_BUSY_CAP_MS)+ cap.unref?.()+ return { result: 'unconfirmed' }+ }+ return result === null ? { result: 'refused', reason: 'unavailable' } : result} catch {- return 'refused'+ release()+ return { result: 'refused', reason: 'unavailable' }}},diff --git a/src/main/remote/host-service.chat.test.ts b/src/main/remote/host-service.chat.test.tsindex 477f16c55..b36333802 100644--- a/src/main/remote/host-service.chat.test.ts+++ b/src/main/remote/host-service.chat.test.ts@@ -27,7 +27,9 @@ const STATUS: ChatStatus = {paused: false,dropped: false,sessionEnded: false,- structuredAnswers: false+ structuredAnswers: false,+ version: 1,+ hostRefuses: false}function make(chat?: Partial<HostChatOps>, served = true) {@@ -45,7 +47,7 @@ function make(chat?: Partial<HostChatOps>, served = true) {const ops: HostChatOps = {page: vi.fn(async () => PAGE),status: vi.fn(async () => STATUS),- send: vi.fn(async () => 'sent' as const),+ send: vi.fn(async () => ({ result: 'sent' as const })),answer: vi.fn(async () => true),...chat}@@ -116,6 +118,14 @@ describe('chat.page', () => {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 non-chat agent is refused by name, never an empty page', async () => {+ const { call } = make({ page: vi.fn(async () => 'unsupported' as const) })+ expect(await call('chat.page', { nodeId: 'n1' })).toEqual({+ id: 'r1',+ ok: false,+ body: { message: 'Chat is not available for this agent.' }+ })+ })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({@@ -173,9 +183,15 @@ describe('chat.send', () => {})it('passes a refusal and a partial delivery through verbatim', async () => {for (const result of ['refused', 'pasted-not-submitted', 'unconfirmed'] as const) {- const { call } = make({ send: vi.fn(async () => result) })+ const { call } = make({ send: vi.fn(async () => ({ result })) })expect(await call('chat.send', { nodeId: 'n1', text: 'hi' })).toEqual({ id: 'r1', ok: true, body: { result } })}+ const { call } = make({ send: vi.fn(async () => ({ result: 'refused' as const, reason: 'busy' as const })) })+ expect(await call('chat.send', { nodeId: 'n1', text: 'hi' })).toEqual({+ id: 'r1',+ ok: true,+ body: { result: 'refused', reason: 'busy' }+ })})it('unknown node ⇒ "Unknown node."', async () => {const { call } = make({ send: vi.fn(async () => 'unknown-node' as const) })@@ -187,7 +203,11 @@ describe('chat.send', () => {})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' } })+ expect(await call('chat.send', { nodeId: 'n1', text: 'hi' })).toEqual({+ id: 'r1',+ ok: true,+ body: { result: 'refused', reason: 'unavailable' }+ })})})diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex e0408c16a..2b1f76443 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -40,7 +40,7 @@ import {CHAT_SEND_TEXT_MAX,sanitizeChatText,type ChatPage,- type ChatSendResult,+ type ChatSendOutcome,type ChatStatus} from '../../shared/mobile-chat'import { getStoredEntitlement, isPremium } from '../../core/license'@@ -197,15 +197,16 @@ export interface HostKanbanOps {* 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>+ /** One page of the node's transcript. `null` ⇒ the host does not know this node; `'unsupported'`+ * ⇒ its agent has no chat view. Rejects when the read failed (never an empty page standing in+ * for a failure). */+ page(nodeId: string, rawPage: unknown): Promise<ChatPage | null | 'unsupported'>/** 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'>+ send(nodeId: string, text: string): Promise<ChatSendOutcome | '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>@@ -849,7 +850,13 @@ export function createHostHandlers(}void chat.page(nodeId, rawPage)- .then((page) => (page ? socket.respond(req.id, true, { page }) : fail('Unknown node.')))+ .then((page) =>+ page === 'unsupported'+ ? fail('Chat is not available for this agent.')+ : page+ ? socket.respond(req.id, true, { page })+ : fail('Unknown node.')+ ).catch(() => fail('Could not read the transcript.'))return}@@ -874,11 +881,13 @@ export function createHostHandlers(}void chat.send(nodeId, text)- .then((result) =>- result === 'unknown-node' ? fail('Unknown node.') : socket.respond(req.id, true, { result })+ .then((out) =>+ out === 'unknown-node'+ ? fail('Unknown node.')+ : socket.respond(req.id, true, { result: out.result, ...(out.reason ? { reason: out.reason } : {}) }))// A send that threw is a refusal, never "sent": the phone keeps the draft.- .catch(() => socket.respond(req.id, true, { result: 'refused' }))+ .catch(() => socket.respond(req.id, true, { result: 'refused', reason: 'unavailable' }))return}case 'agent.answer': {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex fd1ddc029..cafec2cd3 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -9965,7 +9965,7 @@ export function Canvas() {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 }))+ }).then((out) => api.sendHostChatReply({ requestId: q.requestId, kind: 'send', ...out }))})// eslint-disable-next-line react-hooks/exhaustive-deps}, [])diff --git a/src/renderer/lib/hostChatQuery.test.ts b/src/renderer/lib/hostChatQuery.test.tsindex 797adba9a..da5e77095 100644--- a/src/renderer/lib/hostChatQuery.test.ts+++ b/src/renderer/lib/hostChatQuery.test.ts@@ -48,28 +48,30 @@ describe('hostChatSend', () => {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(r).toEqual({ result: '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 want = ['working', 'dialog', 'dialog', 'dialog']+ for (const [i, st] of [{ state: 'working' }, { state: 'waiting' }, { state: 'blocked' }, { state: 'done', held: HELD }].entries()) {const { r, sendText } = await run(st)- expect(r).toBe('refused')+ expect(r).toEqual({ result: 'refused', reason: want[i] })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 want = ['asleep', 'paused', 'dropped', 'exited']+ for (const [i, st] of [{ hibernated: true }, { paused: true }, { dropped: true }, { sessionEnded: true }].entries()) {const { r, sendText } = await run({ state: 'done', ...st })- expect(r).toBe('refused')+ expect(r).toEqual({ result: 'refused', reason: want[i] })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(r).toEqual({ result: 'refused', reason: 'exited' })expect(sendText).not.toHaveBeenCalled()})it('falls back to the store\'s agent id when main has none', async () => {@@ -78,18 +80,18 @@ describe('hostChatSend', () => {{ ...base, agentId: undefined },{ getStatus: () => ({ state: 'done', agentId: 'claude' }), sendText, now: () => 1000 })- expect(r).toBe('sent')+ expect(r).toEqual({ result: '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(r).toEqual({ result: 'refused', reason: 'late' })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 () => 'pasted-not-submitted' as const))).r).toEqual({ result: 'pasted-not-submitted' })+ expect((await run({ state: 'done' }, vi.fn(async () => false as const))).r).toEqual({ result: 'refused', reason: 'failed' })// 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')+ expect((await run({ state: 'done' }, vi.fn(async () => { throw new Error('x') }))).r).toEqual({ result: 'unconfirmed' })+ expect((await run({ state: 'done' }, vi.fn(async () => 'yes' as never))).r).toEqual({ result: 'refused', reason: 'failed' })})})diff --git a/src/renderer/lib/hostChatQuery.ts b/src/renderer/lib/hostChatQuery.tsindex dec457bda..2158cdb81 100644--- a/src/renderer/lib/hostChatQuery.ts+++ b/src/renderer/lib/hostChatQuery.ts@@ -8,14 +8,14 @@// 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 { ChatSendOutcome, HostChatQuery, RendererChatStatus } 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'> {+export function hostChatStatus(st: Partial<StatusSlice> | undefined): RendererChatStatus {return {state: st?.state ?? null,held: st?.held ?? null,@@ -35,24 +35,25 @@ export interface HostChatSendDeps {export async function hostChatSend(q: Extract<HostChatQuery, { kind: 'send' }>,deps: HostChatSendDeps-): Promise<ChatSendResult> {+): Promise<ChatSendOutcome> {// Main has already told the phone "refused" past this instant; typing now would contradict it.- if (deps.now() > q.startBy) return 'refused'+ if (deps.now() > q.startBy) return { result: 'refused', reason: 'late' }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'+ const refusal = chatSendRefusal(agentId, st)+ if (refusal !== null) return { result: 'refused', reason: refusal }+ if (st.held) return { result: 'refused', reason: 'dialog' }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'+ if (r === true) return { result: 'sent' }+ if (r === 'pasted-not-submitted') return { result: 'pasted-not-submitted' }+ return { result: 'refused', reason: 'failed' }} catch {// 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'+ return { result: 'unconfirmed' }}}diff --git a/src/shared/mobile-chat.ts b/src/shared/mobile-chat.tsindex 921d9c08e..de10eafa9 100644--- a/src/shared/mobile-chat.ts+++ b/src/shared/mobile-chat.ts@@ -10,9 +10,20 @@ import type { ChatTranscriptResult } from './types'* 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. */+/** Why the HOST's own record refuses a send: the agent is mid-turn, or a dialog (a permission,+ * plan or question) holds the pane — whose Enter would ANSWER it. */+export type ChatHostRefusal = 'working' | 'dialog'++/** What the phone needs to decide whether its composer and answer controls may act.+ *+ * The phone's composer is unlocked ONLY when `version` is one it knows, `hostRefuses` is false,+ * `held` is null and `state` is `done` or `null`. Any `state` value it does not recognize (a newer+ * desktop) ⇒ locked. The desktop re-checks every send regardless. */export interface ChatStatus {- /** The hook-reported state; `null` = no live hook state (unknown — the desktop's "Unknown"). */+ /** Shape version; a phone that does not know it treats the composer as locked. */+ version: 1+ /** The hook-reported state from the desktop WINDOW; `null` = the window has no live hook state+ * (unknown — e.g. just after a desktop restart). */state: AgentState | null/** The request the node's hook is holding, if any (a plan, a question, a permission). */held: HeldPermission | null@@ -24,14 +35,45 @@ export interface ChatStatus {* (`isStructuredTicket`). False ⇒ the phone offers no answer controls, only "answer in the* terminal". Always false with no `held`. */structuredAnswers: boolean+ /** The host's own agent-status mirror refuses sends right now, whatever `state` says. It survives+ * a desktop restart that leaves `state` null, so a live dialog still locks the composer. */+ hostRefuses: boolean+ /** Why, when `hostRefuses`. */+ refusal?: ChatHostRefusal}+/** What the renderer contributes to `ChatStatus`; main adds the rest (ticket ledger, host mirror). */+export type RendererChatStatus = Omit<ChatStatus, 'structuredAnswers' | 'version' | 'hostRefuses' | 'refusal'>+/** `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'+/** Why a send was `refused` (only ever set with `refused`). The composer gate's own kinds+ * (`working`, `dialog`, `asleep`, `paused`, `dropped`, `exited`), plus: `busy` = another send to+ * this node is still in flight; `late` = the desktop received it after its start deadline;+ * `unavailable` = no desktop window to ask; `failed` = the paste itself was refused. Unknown+ * values from a newer desktop: show a generic "not sent". */+export type ChatSendReason =+ | 'working'+ | 'dialog'+ | 'asleep'+ | 'paused'+ | 'dropped'+ | 'exited'+ | 'busy'+ | 'late'+ | 'unavailable'+ | 'failed'++/** `chat.send`'s reply body. */+export interface ChatSendOutcome {+ result: ChatSendResult+ reason?: ChatSendReason+}+/** 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@@ -56,9 +98,10 @@ export type HostChatQuery =| { 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). */+/** Renderer → main. `status` is the renderer's half (`RendererChatStatus`): main adds the ticket+ * ledger's `structuredAnswers` and the host mirror's view. */export type HostChatReply =- | { requestId: string; kind: 'status'; status: Omit<ChatStatus, 'structuredAnswers'> }- | { requestId: string; kind: 'send'; result: ChatSendResult }+ | { requestId: string; kind: 'status'; status: RendererChatStatus }+ | { requestId: string; kind: 'send'; result: ChatSendResult; reason?: ChatSendReason }/** The renderer's agent-status session id — the one the ⌘M view reads. Absent = it knows none. */| { requestId: string; kind: 'session'; sessionId?: string }