diff --git a/phone-host/NOTICE b/phone-host/NOTICE index 90328905d0..5f50c215fb 100644 --- a/phone-host/NOTICE +++ b/phone-host/NOTICE @@ -1,7 +1,12 @@ @claude-flow/phone-host includes code ported from Orca (https://github.com/stablyai/orca, source commit 98e7dbecfedb732abc2358c8aff4a5d7e98f642a): the mobile E2EE v2 contract, framing and key schedule (src/e2ee-v2.mjs), the pairing offer -format (src/offer.mjs) and the mobile web bundle RPC contract (src/bundle.mjs). +format (src/offer.mjs) and the mobile web bundle RPC contract (src/bundle.mjs). The chat view +ports Orca's native-chat transcript decoders, turn lifecycle, tail and incremental readers, session +file layouts and RPC payload limits (src/chat-decode.mjs, src/chat-lifecycle.mjs, +src/chat-transcript.mjs, src/chat-sessions.mjs, src/chat-methods.mjs). It also follows Orca's +agent status entry (src/chat-status.mjs), mobile file search and file-kind rules +(src/files-methods.mjs) and terminal quick command normalization (src/quick-commands.mjs). test/fixtures/orca-e2ee-v2.mjs is a bundle of Orca's phone-side E2EE v2 client, used only in tests. MIT License diff --git a/phone-host/README.md b/phone-host/README.md index 4d0abb5685..4a74668641 100644 --- a/phone-host/README.md +++ b/phone-host/README.md @@ -86,8 +86,13 @@ A full-access phone can open terminal tabs and agent tabs in a shared workspace. - **Access is per phone and needs both sides.** The phone must be paired with `--full`, and the host must be running with `--full`. A host without `--full` never serves these methods. - **A workspace is a starting directory, not a sandbox.** Once a shell is open, the phone can run anything you can. -- **Agents come from a fixed table.** The phone sends an agent id, and the command line is looked up here, never taken from the phone. The new-tab menu lists only agents found on `PATH`. +- **Agents come from a fixed table.** The phone sends an agent id, and the command line is looked up here, never taken from the phone. The new-tab menu lists only agents found on `PATH`. One exception: a quick command can start Claude or Codex with a prompt. The prompt is never typed into the shell: it is passed in the terminal's environment and expanded as one argument after the fixed command, so the shell never runs it and the agent never reads it as an option. - **Every terminal is logged** when it starts and ends: at the prompt for `start`, or in `daemon.log`. Revoking a phone closes its terminals. +- **Chat view for Claude Code and Codex tabs.** The phone can show an agent tab as a chat as well as a terminal. The host starts Claude with a session id it chooses. For Codex, it finds the session log that Codex creates at the first prompt in that workspace. The phone then reads the conversation through `nativeChat.readSession`, `nativeChat.subscribe` and `nativeChat.unsubscribe`. It can only read sessions this host started, and only from Claude's `projects` folder and Codex's `sessions` folder. A file path sent by the phone is ignored. Long tool output is shortened, and inline images are left out. +- **Working state and Stop.** The host reads each Claude or Codex transcript as it grows. A tab shows as working from the prompt until the turn ends, and the chat view then offers Stop. Stop sends Escape twice, which interrupts both agents; the tab then shows as done and interrupted. When the agent is no longer running in the tab, the tab shows as done. A permission or question prompt still shows as working, because the transcript does not record it. +- **@-file picker and Files tab.** `files.searchPaths` and `files.list` list the workspace's files from `git ls-files`, so ignored folders such as `node_modules` stay out. `files.readDir` lists one folder, refuses `..`, absolute paths and `.git`, and never follows a link out of the workspace. They return names only, never file contents. +- **Quick commands.** `settings.getTerminalQuickCommands` and `settings.updateTerminalQuickCommands` keep the quick commands sheet in `quick-commands.json` (mode 0600) in the host's state folder, with Orca's limits: 40 commands, a 4,000-character command, a 6,000-character prompt. +- **Tab rename and display mode.** `terminal.rename` renames a tab for every phone. `terminal.setDisplayMode` with `desktop` keeps the terminal's size when the phone resizes; `auto` lets the phone size it again. - Terminals need `@lydell/node-pty`, an optional dependency (prebuilt, about 100 KB). Without it, `--full` stops with a clear error, and the read-only host still works. ## Host screens diff --git a/phone-host/package-lock.json b/phone-host/package-lock.json index cc7cdffbca..6f6d324926 100644 --- a/phone-host/package-lock.json +++ b/phone-host/package-lock.json @@ -1,12 +1,12 @@ { "name": "@claude-flow/phone-host", - "version": "0.1.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@claude-flow/phone-host", - "version": "0.1.0", + "version": "1.1.0", "license": "MIT", "dependencies": { "@lydell/node-pty": "1.2.0-beta.18", diff --git a/phone-host/package.json b/phone-host/package.json index 02862cb173..8cdb5f5b22 100644 --- a/phone-host/package.json +++ b/phone-host/package.json @@ -1,6 +1,6 @@ { "name": "@claude-flow/phone-host", - "version": "1.0.0", + "version": "1.1.0", "description": "Opt-in add-on: pair the RuFlo or Orca phone app with this computer over LAN or Tailscale (end-to-end encrypted), with an optional full-access mode for terminals and agent tabs", "type": "module", "license": "MIT", diff --git a/phone-host/src/agents.mjs b/phone-host/src/agents.mjs index b8082a63b2..bbb57ae349 100644 --- a/phone-host/src/agents.mjs +++ b/phone-host/src/agents.mjs @@ -1,6 +1,9 @@ // Agent command-line tools a full-access phone can open as a tab. Ids and default commands follow // Orca's TUI agent table (src/shared/tui-agent.ts, tui-agent-config.ts; MIT, see NOTICE). Commands -// are fixed here; nothing the phone sends is ever put into a command line. +// are fixed here. Apart from what the phone types into a shell (terminal.send, a quick command's +// `command`), the only phone text in an agent's command line is a quick command's starting prompt +// for Claude or Codex: one argument after the fixed command, passed through the environment and +// never an option (full-methods.mjs agentPromptArg). import { accessSync, constants } from 'node:fs'; import { delimiter, join } from 'node:path'; diff --git a/phone-host/src/chat-decode.mjs b/phone-host/src/chat-decode.mjs new file mode 100644 index 0000000000..2b5feb00c1 --- /dev/null +++ b/phone-host/src/chat-decode.mjs @@ -0,0 +1,306 @@ +// One transcript line -> one native-chat message, for Claude Code and Codex. Ported from Orca +// (src/main/native-chat/transcript-line-decoders-claude.ts, -codex.ts, transcript-record-blocks.ts, +// transcript-turn-markers.ts, src/shared/claude-pasted-content.ts; MIT, see NOTICE). The output is +// Orca's NativeChatMessage wire shape (src/shared/native-chat-types.ts), which the phone renders. +// Decoders are stateless and never throw: unknown or empty records return null. + +export const INTERRUPTED_STATUS_TEXT = 'Conversation interrupted'; +export const CODEX_EVENT_TURN_STARTED = 'task_started'; +export const CODEX_EVENT_TURN_COMPLETE = 'task_complete'; +export const CODEX_EVENT_TURN_ABORTED = 'turn_aborted'; +const MAX_EDIT_PATCH_HUNKS = 40; +const MAX_EDIT_PATCH_HUNK_LINES = 400; +const IMAGE_SOURCE_MARKER = /^\[Image:\s*source:\s*(.+?)\]\s*$/; + +export const asRecord = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : null); + +export function extractString(v) { + if (typeof v !== 'string') return null; + const t = v.trim(); + return t.length > 0 ? t : null; +} + +export function parseJsonObject(line) { + if (!line.trim()) return null; + try { return asRecord(JSON.parse(line)); } catch { return null; } +} + +export function timestampMs(v) { + if (typeof v === 'string') { const p = Date.parse(v); return Number.isFinite(p) ? p : NaN; } + if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) return NaN; + return v > 1_000_000_000_000 ? v : v * 1000; +} + +export function parseTimestamp(v) { + const p = timestampMs(v); + return Number.isFinite(p) ? p : null; +} + +/** The `interruptedMessageId` on Claude's injected interrupt notice (a user row), else undefined. */ +export function claudeInterruptedMessageId(record) { + if (record.type !== 'user') return undefined; + return extractString(record.interruptedMessageId) ?? undefined; +} + +// ── record blocks ─────────────────────────────────────────────────────────── + +/** Coerce an arbitrary tool-result payload into one output string. */ +export function toolResultOutput(value) { + if (typeof value === 'string') return value; + if (!Array.isArray(value)) { + const r = asRecord(value); + if (r) { const t = extractString(r.text) ?? extractString(r.content); if (t) return t; } + return value === undefined || value === null ? '' : JSON.stringify(value); + } + const parts = []; + for (const item of value) { + if (typeof item === 'string') { parts.push(item); continue; } + const r = asRecord(item); + const t = extractString(r?.text) ?? extractString(r?.content); + if (t) parts.push(t); + } + return parts.join('\n'); +} + +/** The blocks for one Claude content array (string or block[]). */ +export function claudeContentBlocks(content) { + if (typeof content === 'string') return content.trim() ? [{ type: 'text', text: content }] : []; + if (!Array.isArray(content)) return []; + const blocks = []; + for (const item of content) { + if (typeof item === 'string') { if (item.trim()) blocks.push({ type: 'text', text: item }); continue; } + const r = asRecord(item); + const block = r ? claudeContentBlock(r) : null; + if (block) blocks.push(block); + } + return blocks; +} + +function claudeContentBlock(r) { + switch (r.type) { + case 'text': { const text = extractString(r.text); return text ? { type: 'text', text } : null; } + case 'thinking': { + const text = extractString(r.thinking) ?? extractString(r.text); + return text ? { type: 'text', text } : null; + } + case 'tool_use': { + const name = extractString(r.name) ?? 'tool'; + const callId = extractString(r.id); + return { type: 'tool-call', name, input: r.input, ...(callId ? { callId } : {}) }; + } + case 'tool_result': { + const callId = extractString(r.tool_use_id); + return { type: 'tool-result', output: toolResultOutput(r.content), ...(callId ? { callId } : {}), ...(r.is_error === true ? { isError: true } : {}) }; + } + case 'image': { + const source = asRecord(r.source); + const url = extractString(source?.url) ?? extractString(r.url); + const path = extractString(r.path); + const alt = extractString(r.alt) ?? undefined; + if (!url && !path) return null; + return { type: 'image-ref', ...(path ? { path } : {}), ...(url ? { url } : {}), ...(alt ? { alt } : {}) }; + } + default: return null; + } +} + +// ── Claude ────────────────────────────────────────────────────────────────── + +function claudeEditPatch(record) { + const result = asRecord(record.toolUseResult); + const raw = result?.structuredPatch; + if (!Array.isArray(raw) || raw.length === 0) return null; + const hunks = []; + for (const entry of raw.slice(0, MAX_EDIT_PATCH_HUNKS)) { + const h = asRecord(entry); + if (typeof h?.oldStart !== 'number' || typeof h.newStart !== 'number' || !Array.isArray(h.lines)) continue; + hunks.push({ + oldStart: h.oldStart, oldLines: typeof h.oldLines === 'number' ? h.oldLines : 0, + newStart: h.newStart, newLines: typeof h.newLines === 'number' ? h.newLines : 0, + lines: h.lines.slice(0, MAX_EDIT_PATCH_HUNK_LINES).filter((l) => typeof l === 'string'), + }); + } + if (hunks.length === 0) return null; + const filePath = extractString(result?.filePath); + return { ...(filePath ? { filePath } : {}), hunks }; +} + +function withEditPatch(blocks, patch) { + let attached = false; + return blocks.map((b) => { + if (attached || b.type !== 'tool-result') return b; + attached = true; + return { ...b, editPatch: patch }; + }); +} + +/** Claude wraps a whole pasted text block; prose around it is still literal user text. */ +export function unwrapClaudePastedContent(text) { + const trimmed = text.trim(); + const open = /^\r\n]{1,64})")?>\r?\n/.exec(trimmed); + if (!open) return text; + const close = open[1] ? `` : ''; + if (!trimmed.endsWith(close)) return text; + const body = trimmed.slice(open[0].length, -close.length); + const ambiguous = open[1] + ? body.includes(close) || body.includes(``) + : body.includes(' { + if (b.type !== 'text') return b; + const text = unwrapClaudePastedContent(b.text); + return text === b.text ? b : { ...b, text }; +}; + +const isImageSourceRecord = (blocks) => blocks.length > 0 + && blocks.every((b) => b.type === 'text' && IMAGE_SOURCE_MARKER.test(b.text)); + +export function decodeClaudeTranscriptLine(line, fallbackId) { + const record = parseJsonObject(line); + if (!record) return null; + const role = record.type; + if (role !== 'user' && role !== 'assistant') return null; + const timestamp = parseTimestamp(record.timestamp); + const recordMessageId = extractString(record.uuid) ?? fallbackId; + const parentUuid = extractString(record.parentUuid); + const parent = parentUuid ? { parentId: parentUuid } : {}; + if (claudeInterruptedMessageId(record)) { + return { id: recordMessageId, role: 'system', blocks: [{ type: 'text', text: INTERRUPTED_STATUS_TEXT }], timestamp, source: 'transcript', ...parent }; + } + const message = asRecord(record.message); + const editPatch = claudeEditPatch(record); + const contentBlocks = claudeContentBlocks(message?.content); + const decoded = editPatch ? withEditPatch(contentBlocks, editPatch) : contentBlocks; + if (decoded.length === 0) return null; + const injected = role === 'user' && (record.isMeta === true || record.isSynthetic === true || record.isCompactSummary === true); + const blocks = injected + ? (isImageSourceRecord(decoded) ? decoded : decoded.filter((b) => b.type === 'tool-result')) + : decoded; + if (blocks.length === 0) return null; + const messageId = extractString(record.uuid) ?? extractString(message?.id); + const onlyToolResults = blocks.every((b) => b.type === 'tool-result'); + return { + id: messageId ?? fallbackId, + role: role === 'user' ? (onlyToolResults ? 'tool' : 'user') : role, + blocks: role === 'user' ? blocks.map(unwrapPasted) : blocks, + timestamp, source: 'transcript', ...parent, + }; +} + +// ── Codex ─────────────────────────────────────────────────────────────────── + +export function decodeCodexTranscriptLine(line, fallbackId) { + const record = parseJsonObject(line); + if (!record) return null; + const payload = asRecord(record.payload); + if (!payload) { + const id = extractString(record.id) ?? fallbackId; + return codexUnwrappedResponseItem(record, id, parseTimestamp(record.timestamp)); + } + const timestamp = parseTimestamp(record.timestamp); + const baseId = extractString(payload.id) ?? fallbackId; + if (record.type === 'response_item') return codexResponseItem(payload, baseId, timestamp); + if (record.type === 'event_msg') return codexEventMessage(payload, baseId, timestamp); + return null; +} + +const isSkillContext = (b) => b.type === 'text' && b.text.trimStart().slice(0, 7).toLowerCase() === ''; +const roleOf = (r) => (r === 'assistant' ? 'assistant' : r === 'user' ? 'user' : null); + +function codexUnwrappedResponseItem(record, id, timestamp) { + if (record.type !== 'message') return codexResponseItem(record, id, timestamp); + const role = roleOf(record.role); + const decoded = codexTurnItemBlocks(record.content); + const blocks = role === 'user' ? decoded.filter((b) => !isSkillContext(b)) : decoded; + return role && blocks.length > 0 ? { id, role, blocks, timestamp, source: 'transcript' } : null; +} + +function codexResponseItem(payload, id, timestamp) { + if (payload.type === 'message') { + const role = roleOf(payload.role); + if (!role) return null; + // Orca decodes these with the Claude block mapper, which knows no input_text/output_text: + // current rollouts' response_item messages decode to nothing and the item_completed rows + // below carry the conversation instead (so a turn is not shown twice). + const decoded = claudeContentBlocks(payload.content); + const blocks = role === 'user' ? decoded.filter((b) => !isSkillContext(b)) : decoded; + return blocks.length === 0 ? null : { id, role, blocks, timestamp, source: 'transcript' }; + } + if (payload.type === 'reasoning') { + const text = extractString(payload.text) ?? codexSummaryText(payload.summary); + return text ? { id, role: 'reasoning', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' } : null; + } + if (payload.type === 'function_call' || payload.type === 'local_shell_call' || payload.type === 'custom_tool_call') { + const name = extractString(payload.name) ?? 'tool'; + const callId = extractString(payload.call_id); + const input = payload.arguments !== undefined ? payload.arguments : payload.input ?? payload.action ?? null; + return { id, role: 'assistant', blocks: [{ type: 'tool-call', name, input, ...(callId ? { callId } : {}) }], timestamp, source: 'transcript' }; + } + if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output') { + return { id, role: 'tool', blocks: [codexToolResult(payload.output, extractString(payload.call_id))], timestamp, source: 'transcript' }; + } + return null; +} + +function codexEventMessage(payload, id, timestamp) { + if (payload.type === CODEX_EVENT_TURN_ABORTED) { + return { id, role: 'system', blocks: [{ type: 'text', text: INTERRUPTED_STATUS_TEXT }], timestamp, source: 'transcript' }; + } + if (payload.type === 'item_completed') return codexCompletedTurnItem(payload, id, timestamp); + if (payload.type === 'user_message' || payload.type === 'agent_message') { + const text = extractString(payload.message); + const role = payload.type === 'user_message' ? 'user' : 'assistant'; + return text ? { id, role, blocks: [{ type: 'text', text }], timestamp, source: 'transcript' } : null; + } + return null; +} + +function codexCompletedTurnItem(payload, fallbackId, timestamp) { + const item = asRecord(payload.item); + if (!item) return null; + const id = extractString(item.id) ?? fallbackId; + const blocks = codexTurnItemBlocks(item.content); + if (blocks.length === 0) return null; + if (item.type === 'UserMessage' || item.type === 'user_message') return { id, role: 'user', blocks, timestamp, source: 'transcript' }; + if (item.type === 'AgentMessage' || item.type === 'agent_message') return { id, role: 'assistant', blocks, timestamp, source: 'transcript' }; + return null; +} + +function codexTurnItemBlocks(content) { + if (!Array.isArray(content)) return []; + const blocks = []; + for (const value of content) { + const item = asRecord(value); + if (!item) continue; + if (['text', 'Text', 'input_text', 'output_text'].includes(item.type)) { + const text = extractString(item.text); + if (text) blocks.push({ type: 'text', text }); + } else if (['image', 'Image', 'input_image'].includes(item.type)) { + const url = extractString(item.image_url) ?? extractString(item.url); + if (url) blocks.push({ type: 'image-ref', url }); + } else if (item.type === 'local_image' || item.type === 'LocalImage') { + const path = extractString(item.path); + if (path) blocks.push({ type: 'image-ref', path }); + } + } + return blocks; +} + +function codexToolResult(output, callId) { + const r = asRecord(output); + const isError = r?.success === false || r?.is_error === true; + return { + type: 'tool-result', output: toolResultOutput(r?.content ?? r?.output ?? output), + ...(callId ? { callId } : {}), ...(isError ? { isError: true } : {}), + }; +} + +function codexSummaryText(summary) { + if (!Array.isArray(summary)) return null; + const parts = []; + for (const item of summary) { const t = extractString(asRecord(item)?.text) ?? extractString(item); if (t) parts.push(t); } + return parts.length ? parts.join('\n') : null; +} diff --git a/phone-host/src/chat-lifecycle.mjs b/phone-host/src/chat-lifecycle.mjs new file mode 100644 index 0000000000..61ae66c55a --- /dev/null +++ b/phone-host/src/chat-lifecycle.mjs @@ -0,0 +1,85 @@ +// Turn lifecycle (working / completed / interrupted) recovered from a transcript line, so the phone +// can settle its chat spinner. Ported from Orca (src/main/native-chat/transcript-turn-lifecycle.ts, +// src/shared/harness-injected-user-turns.ts, native-chat-noise.ts; MIT, see NOTICE). +import { + asRecord, claudeInterruptedMessageId, CODEX_EVENT_TURN_ABORTED, CODEX_EVENT_TURN_COMPLETE, + CODEX_EVENT_TURN_STARTED, decodeClaudeTranscriptLine, extractString, parseJsonObject, parseTimestamp, +} from './chat-decode.mjs'; + +const LEADING_TAG_NAME = /^<([a-z][a-z0-9-]*)(?:[\s>]|$)/; +const KNOWN_HARNESS_TAG_NAMES = new Set([ + 'agent-message', 'bash-input', 'bash-stderr', 'bash-stdout', 'command-args', 'command-message', + 'command-name', 'cross-session-message', 'fork-boilerplate', 'local-command-caveat', + 'local-command-stderr', 'local-command-stdout', 'mcp-polling-update', 'mcp-resource-update', + 'system-reminder', 'task-notification', 'teammate-message', 'user-memory-input', 'user-prompt-submit-hook', +]); +const HARNESS_INJECTED_TURN_PREFIXES = [ + '= text.length) return false; + const head = text.slice(start, Math.min(text.length, start + 256)).toLowerCase(); + const tag = LEADING_TAG_NAME.exec(head)?.[1]; + if (tag && KNOWN_HARNESS_TAG_NAMES.has(tag)) return true; + return HARNESS_INJECTED_TURN_PREFIXES.some((p) => head.startsWith(p)); +} + +function isNoiseMessage(m) { + if (m.role !== 'user' && m.role !== 'system') return false; + if (m.blocks.some((b) => b.type === 'tool-call' || b.type === 'tool-result')) return false; + return isKnownHarnessInjectedUserTurnText(m.blocks.filter((b) => b.type === 'text').map((b) => b.text).join('').trim()); +} + +export function decodeCodexTurnLifecycle(line, fallbackId) { + const record = parseJsonObject(line); + const payload = asRecord(record?.payload); + if (record?.type !== 'event_msg' || !payload) return null; + const t = payload.type; + if (t !== CODEX_EVENT_TURN_STARTED && t !== CODEX_EVENT_TURN_COMPLETE && t !== CODEX_EVENT_TURN_ABORTED) return null; + const state = t === CODEX_EVENT_TURN_STARTED ? 'working' : t === CODEX_EVENT_TURN_ABORTED ? 'interrupted' : 'completed'; + return { state, turnId: extractString(payload.turn_id) ?? fallbackId, timestamp: parseTimestamp(record.timestamp) }; +} + +const CLAUDE_TERMINAL_STOP_REASONS = new Set(['end_turn', 'max_tokens', 'stop_sequence', 'refusal']); + +function assistantHasRenderableContent(message) { + const content = message?.content; + if (typeof content === 'string') return content.trim().length > 0; + if (!Array.isArray(content)) return false; + return content.some((b) => { + const r = asRecord(b); + if (!r) return false; + if (r.type === 'text' && typeof r.text === 'string' && r.text.trim().length > 0) return true; + return r.type === 'thinking' || r.type === 'redacted_thinking'; + }); +} + +const assistantHasToolUse = (message) => Array.isArray(message?.content) && message.content.some((b) => asRecord(b)?.type === 'tool_use'); + +export function decodeClaudeTurnLifecycle(line, fallbackId) { + const record = parseJsonObject(line); + if (!record) return null; + const message = asRecord(record.message); + const timestamp = parseTimestamp(record.timestamp); + const interrupted = claudeInterruptedMessageId(record); + if (interrupted) return { state: 'interrupted', turnId: interrupted, timestamp }; + if (record.type === 'assistant') { + const stop = message?.stop_reason; + const terminal = (typeof stop === 'string' && CLAUDE_TERMINAL_STOP_REASONS.has(stop)) + || (stop == null && assistantHasRenderableContent(message) && !assistantHasToolUse(message)); + if (!terminal) return null; + return { state: 'completed', turnId: extractString(record.uuid) ?? extractString(message?.id) ?? fallbackId, timestamp }; + } + if (record.type !== 'user') return null; + const decoded = decodeClaudeTranscriptLine(line, fallbackId); + if (decoded?.role !== 'user' || decoded.blocks.some((b) => b.type === 'tool-result')) return null; + if (isNoiseMessage(decoded)) return null; + return { state: 'working', turnId: decoded.id, timestamp }; +} diff --git a/phone-host/src/chat-methods.mjs b/phone-host/src/chat-methods.mjs new file mode 100644 index 0000000000..8b52dc37ee --- /dev/null +++ b/phone-host/src/chat-methods.mjs @@ -0,0 +1,190 @@ +// The phone's chat view for Claude Code and Codex tabs: nativeChat.readSession (a page of +// history), nativeChat.subscribe (a tail window, then live appends) and nativeChat.unsubscribe. +// Request and frame shapes follow Orca (src/main/runtime/rpc/methods/native-chat.ts, +// native-chat-rpc-block-sanitize.ts, native-chat-rpc-image-block.ts, +// src/shared/rpc-contract/native-chat-params.ts; MIT, see NOTICE), with the mobile payload limits. +// Only sessions this host started are readable (chat-sessions.mjs); a phone-supplied +// `transcriptPath` is accepted for compatibility and never used. +import { readTail, watchTranscript } from './chat-transcript.mjs'; +import { CHAT_AGENTS } from './chat-sessions.mjs'; +import { RpcError, STREAMING } from './rpc.mjs'; + +const DEFAULT_WINDOW = 40; +export const MAX_WINDOW = 2000; +const UNFLUSHED_SETTLE_MS = 1_500; +const UNAVAILABLE = 'Transcript unavailable'; +const TEXT_CAP = 64_000; const BLOCK_CAP = 4000; const INPUT_ITEMS_CAP = 20; const INPUT_NODE_CAP = 100; +const IMAGE_META_CAP = 512; +const MARK = '\n… (truncated)'; + +const clip = (t, cap) => (t.length > cap ? t.slice(0, cap) + MARK : t); +const boundedMeta = (v) => (typeof v === 'string' && v.length <= IMAGE_META_CAP ? v : undefined); + +function sanitizeToolInput(value, budget, depth) { + budget.nodes -= 1; + if (budget.nodes < 0 || budget.remaining <= 0) return '… (truncated)'; + if (typeof value === 'string') { + const n = Math.min(value.length, budget.remaining); + budget.remaining -= n; + return n < value.length ? `${value.slice(0, n)}… (truncated)` : value; + } + if (!value || typeof value !== 'object' || depth >= 5) return value && typeof value === 'object' ? '… (truncated)' : value; + if (Array.isArray(value)) { + const out = value.slice(0, INPUT_ITEMS_CAP).map((v) => sanitizeToolInput(v, budget, depth + 1)); + if (value.length > INPUT_ITEMS_CAP) out.push('… (truncated)'); + return out; + } + const out = {}; let count = 0; + for (const key of Object.keys(value)) { + if (count >= INPUT_ITEMS_CAP || budget.remaining <= 0) { out['…'] = 'truncated'; break; } + let k = key.slice(0, Math.min(key.length, budget.remaining, 128)); + if (Object.hasOwn(out, k)) k = `${k}~${count}`; + budget.remaining -= k.length; + out[k] = sanitizeToolInput(value[key], budget, depth + 1); + count += 1; + } + return out; +} + +/** Orca's mobile payload diet: no inline image bytes, long bodies clipped. */ +export function sanitizeBlock(b) { + if (b.type === 'image-ref') { + const path = boundedMeta(b.path); const url0 = boundedMeta(b.url); const alt = boundedMeta(b.alt); + const url = url0 && !/^data:/i.test(url0.trimStart()) ? url0 : undefined; + return { type: 'image-ref', ...(path ? { path } : {}), ...(url ? { url } : {}), ...(alt ? { alt } : {}) }; + } + if (b.type === 'text') return b.text.length > TEXT_CAP ? { ...b, text: clip(b.text, TEXT_CAP) } : b; + if (b.type === 'tool-result') return b.output.length > BLOCK_CAP ? { ...b, output: clip(b.output, BLOCK_CAP) } : b; + if (b.type === 'tool-call') return { ...b, input: sanitizeToolInput(b.input, { remaining: BLOCK_CAP, nodes: INPUT_NODE_CAP }, 0) }; + return b; +} +const sanitize = (messages) => messages.map((m) => ({ ...m, blocks: m.blocks.map(sanitizeBlock) })); + +function page(r, limit) { + const w = Math.min(Math.max(limit, 1), MAX_WINDOW); + const messages = r.messages.length > w ? r.messages.slice(-w) : r.messages; + return { messages: sanitize(messages), hasMore: r.hasMore, beforeOffset: r.beforeOffset }; +} + +/** Validates params the way Orca's NativeChatSession schema does. */ +function chatParams(p) { + const agent = typeof p?.agent === 'string' ? p.agent : ''; + const sessionId = typeof p?.sessionId === 'string' ? p.sessionId : ''; + if (!agent) throw new RpcError('invalid_argument', 'Missing agent'); + if (!sessionId) throw new RpcError('invalid_argument', 'Missing session id'); + let limit = DEFAULT_WINDOW; + if (p.limit !== undefined) { + if (!Number.isInteger(p.limit) || p.limit <= 0) throw new RpcError('invalid_argument', 'Invalid limit'); + limit = Math.min(p.limit, MAX_WINDOW); + } + if (p.beforeOffset !== undefined && (!Number.isInteger(p.beforeOffset) || p.beforeOffset < 0)) { + throw new RpcError('invalid_argument', 'Invalid beforeOffset'); + } + const subscriptionId = typeof p.subscriptionId === 'string' && p.subscriptionId ? p.subscriptionId.slice(0, 256) : null; + return { + agent, sessionId, limit, beforeOffset: p.beforeOffset, subscriptionId, + pendingCapable: p.capabilities?.transcriptPending === 1, + }; +} + +/** + * @param {{ sessions: ReturnType, + * pollMs?: number, resolvePollMs?: number }} deps + */ +export function createChatMethods({ sessions, pollMs = 750, resolvePollMs = 500 }) { + const lookup = (q) => (CHAT_AGENTS.has(q.agent) ? sessions.find(q.agent, q.sessionId) : null); + + function streamsOf(conn) { + let m = conn.state.get('chat-streams'); + if (!m) { + m = new Map(); conn.state.set('chat-streams', m); + conn.onClose(() => { for (const stop of m.values()) stop(false); m.clear(); }); + } + return m; + } + + return { + 'nativeChat.readSession': async (p) => { + const q = chatParams(p); + const s = lookup(q); + const file = s ? await sessions.resolveFile(s) : null; + if (!file) return { error: UNAVAILABLE, notFound: true }; + try { + const r = await readTail(file, s.agent, { limit: q.limit, endOffset: q.beforeOffset, includeTrailingLine: true }); + return { ...page(r, q.limit), ...(q.beforeOffset === undefined && r.lifecycle ? { lifecycle: r.lifecycle } : {}) }; + } catch (e) { + return e?.code === 'ENOENT' ? { error: UNAVAILABLE, notFound: true } : { error: UNAVAILABLE }; + } + }, + + 'nativeChat.subscribe': async (p, conn) => { + const q = chatParams(p); + const streams = streamsOf(conn); + const token = q.subscriptionId ?? `${q.agent}:${q.sessionId}`; + streams.get(token)?.(true); + let closed = false; let stopWatch = () => {}; let resolveTimer = null; let settleTimer = null; + let snapshotSent = false; let errorSent = false; + const push = (frame) => { if (!closed) conn.push(frame); }; + const stop = (sendEnd = true) => { + if (closed) return; + closed = true; + stopWatch(); + if (resolveTimer) clearTimeout(resolveTimer); + if (settleTimer) clearTimeout(settleTimer); + if (streams.get(token) === stop) streams.delete(token); + if (streams.get(conn.requestId) === stop) streams.delete(conn.requestId); + if (sendEnd) conn.push({ type: 'end' }, false); + }; + streams.set(token, stop); + streams.set(conn.requestId, stop); + + const s = lookup(q); + if (!s) { push({ type: 'snapshot', messages: [], hasMore: false, error: UNAVAILABLE }); return STREAMING; } + + const install = (file) => { + stopWatch = watchTranscript({ + filePath: file, agent: s.agent, limit: q.limit, pollMs, + onSnapshot: (r) => { + snapshotSent = true; + push({ type: 'snapshot', ...page(r, q.limit), ...(r.lifecycle ? { lifecycle: r.lifecycle } : {}) }); + }, + onReplace: (r) => push({ type: 'replacement', ...page(r, q.limit), ...(r.lifecycle ? { lifecycle: r.lifecycle } : {}) }), + onAppend: (messages, lifecycle) => push({ type: 'appended', messages: sanitize(messages), ...(lifecycle ? { lifecycle } : {}) }), + onError: () => { + if (errorSent || snapshotSent) return; + errorSent = true; + push({ type: 'snapshot', messages: [], hasMore: false, beforeOffset: 0, error: UNAVAILABLE }); + }, + }); + }; + // A new session's transcript appears at its first prompt: keep looking until it does. + let delay = resolvePollMs; + const attempt = async () => { + resolveTimer = null; + if (closed) return; + const file = await sessions.resolveFile(s).catch(() => null); + if (closed) return; + if (file) { if (settleTimer) { clearTimeout(settleTimer); settleTimer = null; } install(file); return; } + resolveTimer = setTimeout(attempt, delay); resolveTimer.unref?.(); + delay = Math.min(delay * 2, 5_000); + }; + if (q.pendingCapable) { + settleTimer = setTimeout(() => { + settleTimer = null; + if (!snapshotSent) push({ type: 'snapshot', messages: [], hasMore: false, pending: true }); + }, UNFLUSHED_SETTLE_MS); + settleTimer.unref?.(); + } + await attempt(); + return STREAMING; + }, + + 'nativeChat.unsubscribe': (p, conn) => { + const streams = streamsOf(conn); + const id = typeof p?.subscriptionId === 'string' && p.subscriptionId ? p.subscriptionId.slice(0, 256) : null; + if (id) streams.get(id)?.(true); + else for (const stop of [...new Set(streams.values())]) stop(true); + return { unsubscribed: true }; + }, + }; +} diff --git a/phone-host/src/chat-sessions.mjs b/phone-host/src/chat-sessions.mjs new file mode 100644 index 0000000000..8426591602 --- /dev/null +++ b/phone-host/src/chat-sessions.mjs @@ -0,0 +1,184 @@ +// The agent sessions this host started, and where their transcripts are. The chat view only ever +// reads a transcript through this registry: a phone names (agent, session id), never a path, and +// the file must resolve (after symlinks) inside the agent's own transcript root — Claude Code's +// `projects` dir, Codex's `sessions` dir. Layouts follow Orca's session-file resolver +// (src/main/native-chat/session-file-resolver.ts, session-file-id-layouts.ts, +// ai-vault/session-scanner-roots.ts; MIT, see NOTICE). +import { randomUUID } from 'node:crypto'; +import { open, readdir, realpath, stat } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, isAbsolute, join, sep } from 'node:path'; + +export const CHAT_AGENTS = new Set(['claude', 'codex']); +const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-]{7,127}$/; +const CODEX_ROLLOUT = /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([A-Za-z0-9-]{8,128})\.jsonl$/; +const MAX_SESSIONS = 256; +const LAUNCH_SKEW_MS = 5_000; +const MAX_META_LINE_BYTES = 4 * 1024 * 1024; + +const absOr = (v, fallback) => (typeof v === 'string' && isAbsolute(v.trim()) ? v.trim() : fallback); + +/** Claude's `projects` and Codex's `sessions` roots for this user (CLAUDE_CONFIG_DIR / CODEX_HOME honoured). */ +export function defaultChatRoots(env = process.env) { + const claudeHome = join(homedir(), '.claude'); + const claude = [join(absOr(env.CLAUDE_CONFIG_DIR, claudeHome), 'projects'), join(claudeHome, 'projects')]; + return { + claude: [...new Set(claude)], + codex: [join(absOr(env.CODEX_HOME, join(homedir(), '.codex')), 'sessions')], + }; +} + +/** Claude Code's project directory name for a cwd (every non-alphanumeric becomes '-'). */ +export const claudeProjectSlug = (cwd) => cwd.replace(/[^A-Za-z0-9]/g, '-'); + +export const isSessionId = (v) => typeof v === 'string' && SESSION_ID.test(v); + +/** `file` after symlinks, if it is a regular file strictly inside one of `roots`; else null. */ +export async function confinedFile(file, roots) { + let real; + try { real = await realpath(file); if (!(await stat(real)).isFile()) return null; } catch { return null; } + for (const root of roots) { + let r; + try { r = await realpath(root); } catch { continue; } + if (real.startsWith(r + sep)) return real; + } + return null; +} + +async function listDir(dir) { + try { return await readdir(dir, { withFileTypes: true }); } catch { return []; } +} + +/** First line of a file (bounded), parsed as JSON, or null. Codex's session_meta line is tens of KB. */ +async function readFirstJsonLine(file) { + let fh; + try { + fh = await open(file, 'r'); + const chunks = []; let total = 0; + for (;;) { + const buf = Buffer.allocUnsafe(64 * 1024); + const { bytesRead } = await fh.read(buf, 0, buf.length, total); + if (bytesRead === 0) return null; + const nl = buf.subarray(0, bytesRead).indexOf(0x0a); + chunks.push(buf.subarray(0, nl === -1 ? bytesRead : nl)); + total += bytesRead; + if (nl !== -1) break; + if (total > MAX_META_LINE_BYTES) return null; + } + return JSON.parse(Buffer.concat(chunks).toString('utf8')); + } catch { return null; } finally { await fh?.close(); } +} + +const pad = (n) => String(n).padStart(2, '0'); +/** `YYYY/MM/DD` day directories (local and UTC) from `since` through now. */ +function codexDayDirs(since, now) { + const out = new Set(); + for (let t = since - 86_400_000; t <= now + 86_400_000; t += 3_600_000) { + const d = new Date(t); + out.add(join(String(d.getFullYear()), pad(d.getMonth() + 1), pad(d.getDate()))); + out.add(join(String(d.getUTCFullYear()), pad(d.getUTCMonth() + 1), pad(d.getUTCDate()))); + } + return [...out]; +} + +/** + * @param {{ roots?: { claude: string[], codex: string[] }, pollMs?: number, maxPollMs?: number }} [o] + */ +export function createChatSessions({ roots = defaultChatRoots(), pollMs = 1_000, maxPollMs = 5_000 } = {}) { + /** `${agent}:${sessionId}` -> session */ + const sessions = new Map(); + const remember = (s) => { + sessions.set(`${s.agent}:${s.sessionId}`, s); + while (sessions.size > MAX_SESSIONS) sessions.delete(sessions.keys().next().value); + }; + const claimedCodex = () => new Set([...sessions.values()].filter((s) => s.agent === 'codex').map((s) => s.sessionId)); + + /** A new Claude session id, and the path Claude will write its transcript to. */ + function startClaude({ cwd }) { + const sessionId = randomUUID(); + const s = { agent: 'claude', sessionId, cwd, transcriptPath: join(roots.claude[0], claudeProjectSlug(cwd), `${sessionId}.jsonl`) }; + remember(s); + return s; + } + + async function findCodexRollout(cwd, launchedAt) { + let realCwd; + try { realCwd = await realpath(cwd); } catch { realCwd = cwd; } + const claimed = claimedCodex(); + let best = null; + for (const root of roots.codex) { + for (const day of codexDayDirs(launchedAt, Date.now())) { + const dir = join(root, day); + for (const ent of await listDir(dir)) { + const id = ent.isFile() ? CODEX_ROLLOUT.exec(ent.name)?.[1] : null; + if (!id || claimed.has(id)) continue; + const file = join(dir, ent.name); + try { if ((await stat(file)).mtimeMs < launchedAt - LAUNCH_SKEW_MS) continue; } catch { continue; } + const meta = await readFirstJsonLine(file); + const p = meta?.type === 'session_meta' ? meta.payload : null; + if (!p || (p.id !== id && p.session_id !== id) || typeof p.cwd !== 'string') continue; + const started = Date.parse(p.timestamp); + if (!Number.isFinite(started) || started < launchedAt - LAUNCH_SKEW_MS) continue; + let metaCwd; + try { metaCwd = await realpath(p.cwd); } catch { metaCwd = p.cwd; } + if (metaCwd !== realCwd) continue; + if (!best || started < best.started) best = { id, file, started }; + } + } + } + return best; + } + + /** + * Codex names its session itself and writes the rollout file lazily (at the first prompt), so + * the host watches for the earliest unclaimed rollout that started after the launch, in this + * workspace. `alive()` false stops the search (the tab closed). + */ + function watchCodex({ cwd, launchedAt = Date.now(), alive, onFound }) { + let delay = pollMs; let timer = null; let stopped = false; + const tick = async () => { + timer = null; + if (stopped || !alive()) return; + const hit = await findCodexRollout(cwd, launchedAt).catch(() => null); + if (stopped || !alive()) return; + if (hit && !claimedCodex().has(hit.id)) { + const s = { agent: 'codex', sessionId: hit.id, cwd, transcriptPath: hit.file }; + remember(s); + onFound(s); + return; + } + delay = Math.min(delay * 1.5, maxPollMs); + timer = setTimeout(tick, delay); timer.unref?.(); + }; + timer = setTimeout(tick, 0); timer.unref?.(); + return () => { stopped = true; if (timer) clearTimeout(timer); }; + } + + /** The registered session for exactly (agent, sessionId), or null. */ + function find(agent, sessionId) { + if (!CHAT_AGENTS.has(agent) || !isSessionId(sessionId)) return null; + return sessions.get(`${agent}:${sessionId}`) ?? null; + } + + /** The session's transcript file, confined to the agent's root, or null while it does not exist. */ + async function resolveFile(s) { + const rootsFor = roots[s.agent]; + if (s.agent === 'codex') { + return basename(s.transcriptPath).endsWith(`-${s.sessionId}.jsonl`) ? confinedFile(s.transcriptPath, rootsFor) : null; + } + const name = `${s.sessionId}.jsonl`; + const direct = await confinedFile(s.transcriptPath, rootsFor); + if (direct && basename(direct) === name) return direct; + // Claude shortens and hashes very long project names: look one level down for the id. + for (const root of rootsFor) { + for (const ent of await listDir(root)) { + if (!ent.isDirectory()) continue; + const hit = await confinedFile(join(root, ent.name, name), rootsFor); + if (hit && basename(hit) === name) return hit; + } + } + return null; + } + + return { startClaude, watchCodex, find, resolveFile, roots }; +} diff --git a/phone-host/src/chat-status.mjs b/phone-host/src/chat-status.mjs new file mode 100644 index 0000000000..5b5abf53f0 --- /dev/null +++ b/phone-host/src/chat-status.mjs @@ -0,0 +1,203 @@ +// Live turn state for a Claude/Codex tab, so the phone's chat view shows "working" and its Stop +// button. The host owns these sessions from their first line, so it folds the whole transcript from +// byte 0 (a tail window can miss the turn's opening line) with the ported turn lifecycle +// (chat-lifecycle.mjs). Also picks up the model the agent reports (Claude `message.model`, Codex +// `turn_context.payload.model`) and the user's latest prompt. State shapes follow Orca's +// AgentStatusEntry (src/shared/agent-status-types.ts; MIT, see NOTICE). +import { watch } from 'node:fs'; +import { open, stat } from 'node:fs/promises'; +import { asRecord, parseJsonObject, parseTimestamp } from './chat-decode.mjs'; +import { isKnownHarnessInjectedUserTurnText } from './chat-lifecycle.mjs'; +import { DECODERS, MAX_RECORD_BYTES } from './chat-transcript.mjs'; + +const READ_CHUNK = 256 * 1024; +const PROMPT_CAP = 500; +const MODEL_CAP = 128; + +/** The model id a transcript line reports, if any. */ +export function lineModel(agent, record) { + const m = agent === 'codex' + ? (record.type === 'turn_context' ? asRecord(record.payload)?.model : null) + : (record.type === 'assistant' ? asRecord(record.message)?.model : null); + return typeof m === 'string' && m && m.length <= MODEL_CAP && m !== '' ? m : null; +} + +/** The text of a real user prompt (not a tool result or harness notice), clipped, else null. */ +export function linePrompt(agent, line, id) { + const m = DECODERS[agent].decode(line, id); + if (m?.role !== 'user' || m.blocks.some((b) => b.type === 'tool-result')) return null; + const text = m.blocks.filter((b) => b.type === 'text').map((b) => b.text).join('').trim(); + if (!text || isKnownHarnessInjectedUserTurnText(text)) return null; + return text.length > PROMPT_CAP ? text.slice(0, PROMPT_CAP) : text; +} + +/** A Claude record that can only appear inside a turn: a tool call or its result. */ +function continuesTurn(record) { + if (record.type === 'assistant' && asRecord(record.message)?.stop_reason === 'tool_use') return true; + const content = asRecord(record.message)?.content; + if (!Array.isArray(content)) return false; + const kind = record.type === 'assistant' ? 'tool_use' : record.type === 'user' ? 'tool_result' : null; + return Boolean(kind) && content.some((b) => asRecord(b)?.type === kind); +} + +/** + * Folds transcript lines into { state: 'working'|'done', interrupted, model, prompt }. + * Only a lifecycle line moves the state; everything else is carried along. + */ +export function createStatusFold(agent) { + const { lifecycle } = DECODERS[agent]; + const status = { state: 'done', interrupted: false, model: null, prompt: '', turnStartedAt: null }; + let n = 0; let soft = false; + return { + status, + /** @returns {boolean} whether anything visible changed */ + line(line) { + n += 1; + const record = parseJsonObject(line); + if (!record) return false; + const before = JSON.stringify(status); + const id = `line-${n}`; + const lc = lifecycle(line, id); + if (lc?.state === 'working') { + if (status.state !== 'working') status.turnStartedAt = lc.timestamp ?? Date.now(); + Object.assign(status, { state: 'working', interrupted: false }); + soft = false; + } else if (lc) { + Object.assign(status, { state: 'done', interrupted: lc.state === 'interrupted', turnStartedAt: null }); + // Claude without a stop_reason: text or thinking that looked final may still be followed by a tool call. + soft = agent === 'claude' && lc.state === 'completed' && asRecord(record.message)?.stop_reason == null; + } else if (agent === 'claude' && continuesTurn(record) && (soft || (record.type === 'assistant' && !status.interrupted))) { + // A tool call always belongs to an open turn: this also opens turns whose prompt the lifecycle + // skips as harness text, such as a slash command (`/init`). + Object.assign(status, { state: 'working', interrupted: false, turnStartedAt: parseTimestamp(record.timestamp) ?? Date.now() }); + soft = false; + } + const model = lineModel(agent, record); + if (model) status.model = model; + const prompt = linePrompt(agent, line, id); + if (prompt) status.prompt = prompt; + return JSON.stringify(status) !== before; + }, + }; +} + +/** + * Watches one session's transcript and calls onChange(status) whenever the folded status changes. + * `resolveFile()` returns the confined transcript path or null while it does not exist yet. + * @param {{ agent: 'claude'|'codex', resolveFile: () => Promise, onChange: Function, pollMs?: number }} o + * @returns {() => void} stop + */ +export function watchChatStatus({ agent, resolveFile, onChange, pollMs = 750 }) { + const fold = createStatusFold(agent); + let closed = false; let file = null; let offset = 0; let ino = null; let reading = false; let again = false; + let pending = []; let pendingBytes = 0; let dropping = false; let fsw = null; + + const reset = () => { + Object.assign(fold.status, { state: 'done', interrupted: false, model: null, prompt: '', turnStartedAt: null }); + offset = 0; pending = []; pendingBytes = 0; dropping = false; + }; + const takeLine = () => { + const line = dropping ? '' : Buffer.concat(pending).toString('utf8').replace(/\r$/, ''); + pending = []; pendingBytes = 0; dropping = false; + return line && fold.line(line); + }; + + async function readMore() { + const st = await stat(file); + if (ino !== null && (st.ino !== ino || st.size < offset)) { reset(); onChange({ ...fold.status }); } + ino = st.ino; + if (st.size <= offset) return; + const fh = await open(file, 'r'); + let changed = false; + try { + while (offset < st.size && !closed) { + const len = Math.min(READ_CHUNK, st.size - offset); + const buf = Buffer.allocUnsafe(len); + const { bytesRead } = await fh.read(buf, 0, len, offset); + if (bytesRead <= 0) break; + let start = 0; + for (let nl = buf.indexOf(0x0a, 0); nl !== -1 && nl < bytesRead; nl = buf.indexOf(0x0a, start)) { + keep(buf.subarray(start, nl)); + if (takeLine()) changed = true; + start = nl + 1; + } + if (start < bytesRead) keep(buf.subarray(start, bytesRead)); + offset += bytesRead; + } + } finally { await fh.close(); } + if (changed && !closed) onChange({ ...fold.status }); + } + function keep(part) { + if (dropping) return; + pendingBytes += part.length; + if (pendingBytes > MAX_RECORD_BYTES) { pending = []; dropping = true; return; } + pending.push(Buffer.from(part)); + } + + async function tick() { + if (closed) return; + if (reading) { again = true; return; } + reading = true; + try { + do { + again = false; + if (!file) { + file = await resolveFile().catch(() => null); + if (file && !closed) { try { fsw = watch(file, () => void tick()); fsw.on('error', () => {}); fsw.unref?.(); } catch { fsw = null; } } + } + if (file) await readMore(); + } while (again && !closed); + } catch { /* the file may be mid-rewrite; the next poll retries */ } finally { reading = false; } + } + const timer = setInterval(() => void tick(), pollMs); + timer.unref?.(); + void tick(); + return () => { + if (closed) return; + closed = true; + clearInterval(timer); + try { fsw?.close(); } catch { /* already closed */ } + }; +} + +const HISTORY_MAX = 20; + +/** A tab's status before its transcript says anything: an idle session boundary. */ +export const initialTabStatus = (now = Date.now()) => ({ + state: 'done', boundary: true, interrupted: false, model: null, prompt: '', turnStartedAt: null, + since: now, updatedAt: now, history: [], +}); + +/** + * The tab status after a fold update. `running` false (the agent is no longer the terminal's + * foreground process) forces done: a stale "working" would offer Stop, and Stop sends Escape into + * whatever runs there now. Returns the same object when nothing visible changed. + */ +export function nextTabStatus(prev, folded, running, now = Date.now()) { + const state = folded.state === 'working' && running ? 'working' : 'done'; + const interrupted = state === 'done' && folded.interrupted; + const boundary = prev.boundary && state === 'done' && prev.state === 'done'; + const next = { + ...prev, state, interrupted, boundary, model: folded.model ?? prev.model, prompt: folded.prompt || prev.prompt, + turnStartedAt: state === 'working' ? folded.turnStartedAt ?? prev.turnStartedAt ?? now : null, + }; + const same = ['state', 'interrupted', 'boundary', 'model', 'prompt', 'turnStartedAt'].every((k) => next[k] === prev[k]); + if (same) return prev; + if (state !== prev.state) { + next.history = [...prev.history, { state: prev.state, prompt: prev.prompt, startedAt: prev.since, ...(prev.interrupted ? { interrupted: true } : {}) }].slice(-HISTORY_MAX); + next.since = now; + } + next.updatedAt = now; + return next; +} + +/** The status fields of Orca's AgentStatusEntry for a tab status. */ +export function statusFields(s) { + return { + state: s.state, prompt: s.prompt, updatedAt: s.updatedAt, stateStartedAt: s.since, stateHistory: s.history, + ...(s.boundary ? { sessionBoundary: true } : {}), + ...(s.interrupted ? { interrupted: true } : {}), + ...(s.turnStartedAt ? { turnStartedAt: s.turnStartedAt } : {}), + ...(s.model ? { model: s.model } : {}), + }; +} diff --git a/phone-host/src/chat-transcript.mjs b/phone-host/src/chat-transcript.mjs new file mode 100644 index 0000000000..ce3c599aa3 --- /dev/null +++ b/phone-host/src/chat-transcript.mjs @@ -0,0 +1,222 @@ +// Reading an agent's JSONL transcript for the phone's chat view: a bounded tail window (newest N +// messages, with a byte cursor to page older ones), incremental reads of what was appended since, +// and a small watcher. Ported from Orca (src/main/native-chat/transcript-tail-reader.ts, +// transcript-incremental-reader.ts, transcript-tail-boundary.ts, transcript-fallback-id.ts, +// transcript-watch-engine.ts; MIT, see NOTICE), without Orca's WSL and SSH paths. +import { watch } from 'node:fs'; +import { open, stat } from 'node:fs/promises'; +import { decodeClaudeTranscriptLine, decodeCodexTranscriptLine } from './chat-decode.mjs'; +import { decodeClaudeTurnLifecycle, decodeCodexTurnLifecycle } from './chat-lifecycle.mjs'; + +export const MAX_RECORD_BYTES = 2 * 1024 * 1024; +const TAIL_CHUNK_BYTES = 64 * 1024; +const APPEND_BATCH = 40; + +export const DECODERS = { + claude: { decode: decodeClaudeTranscriptLine, lifecycle: decodeClaudeTurnLifecycle }, + codex: { decode: decodeCodexTranscriptLine, lifecycle: decodeCodexTurnLifecycle }, +}; + +/** Stable JSONL position id shared by tail reads and incremental reads. */ +export const fallbackId = (filePath, offset) => `${filePath}:${offset.toString().padStart(16, '0')}`; + +async function readAt(fh, length, position) { + const buf = Buffer.allocUnsafe(length); + const { bytesRead } = await fh.read(buf, 0, length, position); + return bytesRead === length ? buf : null; +} + +/** End offset (exclusive) of the last newline-terminated line at or before `end`. */ +async function lastCompleteLineEnd(fh, end) { + const last = await readAt(fh, 1, end - 1); + if (!last) return 0; + if (last[0] === 0x0a) return end; + let cursor = end; + while (cursor > 0) { + const start = Math.max(0, cursor - TAIL_CHUNK_BYTES); + const buf = await readAt(fh, cursor - start, start); + if (!buf) return 0; + const nl = buf.lastIndexOf(0x0a); + if (nl !== -1) return start + nl + 1; + cursor = start; + } + return 0; +} + +/** + * The newest `limit` messages ending at `endOffset` (default: end of file). With + * `includeTrailingLine` a final line without a newline is read too (page reads); the watcher + * leaves it for the incremental reader so a half-written record is never decoded. + */ +export async function readTail(filePath, agent, { limit, endOffset, includeTrailingLine = false }) { + const { decode, lifecycle: decodeLifecycle } = DECODERS[agent]; + const size = (await stat(filePath)).size; + const end = Math.min(size, endOffset ?? Number.MAX_SAFE_INTEGER); + const empty = { messages: [], consumedTo: 0, hasMore: false, beforeOffset: 0 }; + if (end === 0) return empty; + const fh = await open(filePath, 'r'); + let lifecycle; + try { + const consumedTo = includeTrailingLine ? end : await lastCompleteLineEnd(fh, end); + if (consumedTo === 0) return empty; + const final = await readAt(fh, 1, consumedTo - 1); + if (!final) return empty; + let cursor = consumedTo - (final[0] === 0x0a ? 1 : 0); + const newestFirst = []; + let parts = []; let partBytes = 0; let oversized = false; + const retain = (part) => { + if (oversized) return; + partBytes += part.length; + if (partBytes > MAX_RECORD_BYTES) { parts = []; oversized = true; return; } + parts.push(part); + }; + const decodeLine = (lineOffset) => { + if (oversized) return; + let line = (parts.length === 1 ? parts[0] : Buffer.concat(parts.toReversed())).toString('utf8'); + if (line.endsWith('\r')) line = line.slice(0, -1); + if (!line) return; + try { JSON.parse(line); } catch { return; } // a malformed record is skipped + const id = fallbackId(filePath, lineOffset); + lifecycle ??= decodeLifecycle(line, id) ?? undefined; + const message = decode(line, id); + if (message) newestFirst.push({ message, offset: lineOffset }); + }; + const reset = () => { parts = []; partBytes = 0; oversized = false; }; + while (cursor > 0 && newestFirst.length <= limit) { + const start = Math.max(0, cursor - TAIL_CHUNK_BYTES); + const buf = await readAt(fh, cursor - start, start); + if (!buf) break; // the file shrank mid-walk + let segmentEnd = buf.length; + for (let i = buf.length - 1; i >= 0 && newestFirst.length <= limit; i--) { + if (buf[i] !== 0x0a) continue; + retain(buf.subarray(i + 1, segmentEnd)); + decodeLine(start + i + 1); + reset(); + segmentEnd = i; + } + if (segmentEnd > 0) retain(buf.subarray(0, segmentEnd)); + cursor = start; + } + if (cursor === 0 && parts.length > 0 && newestFirst.length <= limit) decodeLine(0); + const chronological = newestFirst.toReversed(); + const selected = limit > 0 ? chronological.slice(Math.max(0, chronological.length - limit)) : []; + return { + messages: selected.map((e) => e.message), + ...(lifecycle ? { lifecycle } : {}), + consumedTo, + hasMore: limit > 0 && chronological.length > limit, + beforeOffset: selected[0]?.offset ?? end, + }; + } finally { + await fh.close(); + } +} + +export const newIncrementalState = () => ({ offset: 0, pending: [], pendingStart: 0, pendingBytes: 0, dropping: false }); + +/** Messages appended since `state.offset`; a trailing partial line stays pending in `state`. */ +export async function readAppended(filePath, agent, state, onBatch) { + const { decode, lifecycle: decodeLifecycle } = DECODERS[agent]; + const end = (await stat(filePath)).size; + const messages = []; + let lifecycle; + if (end <= state.offset) return { messages, lifecycle }; + const fh = await open(filePath, 'r'); + try { + let pos = state.offset; + while (pos < end) { + const chunk = await readAt(fh, Math.min(TAIL_CHUNK_BYTES, end - pos), pos); + if (!chunk) break; + let segStart = 0; + let nl = chunk.indexOf(0x0a); + while (nl >= 0) { + retain(chunk.subarray(segStart, nl)); + if (!state.dropping) decodeLine(); + state.pending = []; state.pendingBytes = 0; state.dropping = false; state.pendingStart = pos + nl + 1; + segStart = nl + 1; + nl = chunk.indexOf(0x0a, segStart); + } + if (segStart < chunk.length) retain(chunk.subarray(segStart)); + pos += chunk.length; + state.offset = pos; + } + } finally { + await fh.close(); + } + return { messages, lifecycle }; + + function retain(part) { + if (state.dropping) return; + state.pendingBytes += part.length; + if (state.pendingBytes > MAX_RECORD_BYTES) { state.pending = []; state.dropping = true; return; } + state.pending.push(Buffer.from(part)); + } + function decodeLine() { + let line = Buffer.concat(state.pending).toString('utf8'); + if (line.endsWith('\r')) line = line.slice(0, -1); + if (!line) return; + const id = fallbackId(filePath, state.pendingStart); + lifecycle = decodeLifecycle(line, id) ?? lifecycle; + const message = decode(line, id); + if (!message) return; + messages.push(message); + if (onBatch && messages.length >= APPEND_BATCH) onBatch(messages.splice(0)); + } +} + +/** + * Tails one transcript file: the first drain emits a snapshot of the newest `limit` messages, + * later drains emit appended messages, and a truncated or replaced file emits a replacement + * window. Wakes on fs.watch and on a poll (fs.watch alone misses some rewrites). Timers are + * unref'd so a forgotten watcher never keeps the process alive. + * @param {{ filePath: string, agent: 'claude'|'codex', limit: number, pollMs?: number, + * onSnapshot: Function, onAppend: Function, onReplace: Function, onError?: Function }} o + */ +export function watchTranscript(o) { + let closed = false; let reading = false; let again = false; let first = true; + let version = null; let fsw = null; + const state = newIncrementalState(); + const snapshot = async () => { + const r = await readTail(o.filePath, o.agent, { limit: o.limit }); + Object.assign(state, newIncrementalState(), { offset: r.consumedTo, pendingStart: r.consumedTo }); + return r; + }; + async function drainOnce() { + const st = await stat(o.filePath); + const replaced = version !== null && (st.ino !== version.ino || st.size < state.offset); + version = { ino: st.ino, size: st.size }; + if (first) { + first = false; + const r = await snapshot(); + if (!closed) o.onSnapshot(r); + return; + } + if (replaced) { + const r = await snapshot(); + if (!closed) o.onReplace(r); + return; + } + const { messages, lifecycle } = await readAppended(o.filePath, o.agent, state, (batch) => { if (!closed) o.onAppend(batch); }); + if (!closed && (messages.length > 0 || lifecycle)) o.onAppend(messages, lifecycle); + } + async function drain() { + if (closed) return; + if (reading) { again = true; return; } + reading = true; + try { + do { again = false; await drainOnce(); } while (again && !closed); + } catch (e) { + if (first && !closed) o.onError?.(e); + } finally { reading = false; } + } + const timer = setInterval(() => void drain(), o.pollMs ?? 750); + timer.unref?.(); + try { fsw = watch(o.filePath, () => void drain()); fsw.on('error', () => {}); fsw.unref?.(); } catch { fsw = null; } + void drain(); + return () => { + if (closed) return; + closed = true; + clearInterval(timer); + try { fsw?.close(); } catch { /* already closed */ } + }; +} diff --git a/phone-host/src/files-methods.mjs b/phone-host/src/files-methods.mjs new file mode 100644 index 0000000000..99e826bc50 --- /dev/null +++ b/phone-host/src/files-methods.mjs @@ -0,0 +1,135 @@ +// Read-only file listings for a full-access phone: the chat composer's @-file picker +// (files.searchPaths, falling back to files.list) and the Files tab (files.readDir). Shapes and +// ranking follow Orca (src/main/runtime/rpc/methods/files.ts, files/search/file-search.ts, +// files/search/mobile-path-search.ts, files/mobile-file-kind.ts; MIT, see NOTICE). +// +// Only names are returned, never contents. Everything is confined to the shared workspace's root: +// the inventory comes from `git ls-files` (tracked plus untracked-not-ignored, so node_modules and +// other ignored trees stay out), and a directory listing must resolve, after symlinks, inside the +// workspace's real path. +import { execFile } from 'node:child_process'; +import { readdir, realpath, stat } from 'node:fs/promises'; +import { join, sep } from 'node:path'; +import { RpcError } from './rpc.mjs'; + +export const MOBILE_FILE_LIST_LIMIT = 5000; +const INVENTORY_LIMIT = 20_000; +const INVENTORY_BYTES = 8 * 1024 * 1024; +const INVENTORY_TTL_MS = 30_000; +const INVENTORY_ENTRIES = 8; +const MAX_QUERY = 256; +const MAX_DIR_ENTRIES = 5000; +const MAX_REL_PATH = 4096; +const SKIP_DIR_NAMES = new Set(['.git']); +const BINARY_EXT = new Set(['.avif', '.bmp', '.gif', '.heic', '.ico', '.jpeg', '.jpg', '.mov', '.mp3', '.mp4', '.pdf', '.png', '.webp', '.zip']); + +/** A relative path with no root, drive, empty, `.` or `..` segment (Orca's isSafeMobileRelativePath). */ +export function isSafeRelativePath(p) { + if (typeof p !== 'string' || !p || p.length > MAX_REL_PATH || p.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(p) || p.includes('\0')) return false; + return p.replace(/\\/g, '/').split('/').every((part) => part !== '' && part !== '.' && part !== '..'); +} + +const basenameOf = (p) => p.slice(p.lastIndexOf('/') + 1); +function fileKind(p) { + const b = basenameOf(p); const dot = b.lastIndexOf('.'); + return dot > 0 && BINARY_EXT.has(b.slice(dot).toLowerCase()) ? 'binary' : 'text'; +} +const fileRow = (relativePath) => ({ relativePath, basename: basenameOf(relativePath), kind: fileKind(relativePath) }); + +/** Full-path or basename prefix matches first, then substring matches (Orca's composer ranking). */ +export function rankPaths(paths, query, limit) { + const q = query.trim().toLowerCase(); + if (!q) return { paths: paths.slice(0, limit), totalCount: paths.length }; + const prefix = []; const substring = []; let totalCount = 0; + for (const p of paths) { + const lower = p.toLowerCase(); + if (lower.startsWith(q) || basenameOf(lower).startsWith(q)) { totalCount += 1; if (prefix.length < limit) prefix.push(p); } else if (lower.includes(q)) { totalCount += 1; if (substring.length < limit) substring.push(p); } + } + return { paths: [...prefix, ...substring].slice(0, limit), totalCount }; +} + +/** Workspace files git would show: tracked plus untracked-not-ignored, sorted, capped. */ +export function gitListFiles(root) { + return new Promise((resolve) => { + // fsmonitor off: a repo's configured hook must not run because a phone typed '@'. + execFile('git', ['-c', 'core.fsmonitor=false', '-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], + { timeout: 15_000, maxBuffer: INVENTORY_BYTES, encoding: 'utf8' }, (err, out) => { + if (err && !out) { resolve({ paths: [], totalCount: 0, truncated: false }); return; } + const all = [...new Set(String(out).split('\0'))].filter(isSafeRelativePath).sort((a, b) => a.localeCompare(b)); + resolve({ paths: all.slice(0, INVENTORY_LIMIT), totalCount: all.length, truncated: all.length > INVENTORY_LIMIT || Boolean(err) }); + }); + }); +} + +const withinRoot = (real, root) => real === root || real.startsWith(root + sep); + +/** + * @param {{ projects: { find: Function }, listFiles?: (root: string) => Promise<{ paths: string[], totalCount: number, truncated: boolean }>, now?: () => number }} deps + */ +export function createFilesMethods({ projects, listFiles = gitListFiles, now = Date.now }) { + /** worktree path -> { expiresAt, promise } */ + const cache = new Map(); + + async function worktreeOf(params) { + const row = await projects.find(params?.worktree ?? params?.worktreeId); + if (!row) throw new RpcError('worktree_not_found', 'That workspace is not shared with this phone'); + return row; + } + function inventory(root) { + const hit = cache.get(root); + if (hit && hit.expiresAt > now()) return hit.promise; + const promise = listFiles(root); + cache.set(root, { expiresAt: now() + INVENTORY_TTL_MS, promise }); + while (cache.size > INVENTORY_ENTRIES) cache.delete(cache.keys().next().value); + return promise; + } + const reply = (row, files, totalCount, truncated) => ({ worktree: row.worktreeId, rootPath: row.path, files: files.map(fileRow), totalCount, truncated }); + + return { + 'files.list': async (p) => { + const row = await worktreeOf(p); + const inv = await inventory(row.path); + return reply(row, inv.paths.slice(0, MOBILE_FILE_LIST_LIMIT), inv.totalCount, inv.truncated || inv.paths.length > MOBILE_FILE_LIST_LIMIT); + }, + + 'files.searchPaths': async (p) => { + const row = await worktreeOf(p); + const query = p?.query ?? ''; + if (typeof query !== 'string' || query.length > MAX_QUERY) throw new RpcError('invalid_argument', 'Invalid query'); + const limit = p?.limit ?? 16; + if (!Number.isInteger(limit) || limit < 1 || limit > 32) throw new RpcError('invalid_argument', 'Invalid limit'); + // Orca's quick-open mode (the desktop's fuzzy search) is not served: an empty, versionless answer. + if (p?.mode === 'quick-open') return { ...reply(row, [], 0, false), quickOpenSearchVersion: 0 }; + const inv = await inventory(row.path); + const ranked = rankPaths(inv.paths, query, limit); + return reply(row, ranked.paths, ranked.totalCount, inv.truncated || ranked.totalCount > limit); + }, + + 'files.readDir': async (p) => { + const row = await worktreeOf(p); + const rel = p?.relativePath ?? ''; + if (typeof rel !== 'string' || (rel !== '' && !isSafeRelativePath(rel))) throw new RpcError('invalid_argument', 'Invalid path'); + let root; let dir; + try { root = await realpath(row.path); dir = await realpath(rel ? join(root, rel) : root); } catch { throw new RpcError('not_found', 'No such directory'); } + if (!withinRoot(dir, root)) throw new RpcError('forbidden', 'Outside the workspace'); + if (rel.split(/[\\/]/).some((part) => SKIP_DIR_NAMES.has(part))) throw new RpcError('forbidden', 'Not listed'); + let ents; + try { ents = await readdir(dir, { withFileTypes: true }); } catch { throw new RpcError('not_found', 'No such directory'); } + const out = []; + for (const e of ents) { + if (out.length >= MAX_DIR_ENTRIES) break; + if (SKIP_DIR_NAMES.has(e.name)) continue; + if (!e.isSymbolicLink()) { out.push({ name: e.name, isDirectory: e.isDirectory(), isSymlink: false }); continue; } + // A link counts as a directory only when it lands inside the workspace; one that points out is a plain row. + let isDirectory = false; + try { + const target = await realpath(join(dir, e.name)); + isDirectory = withinRoot(target, root) && (await stat(target)).isDirectory(); + } catch { /* dangling */ } + out.push({ name: e.name, isDirectory, isSymlink: true }); + } + return out.sort((a, b) => (a.isDirectory === b.isDirectory ? a.name.localeCompare(b.name) : a.isDirectory ? -1 : 1)); + }, + }; +} + diff --git a/phone-host/src/full-methods.mjs b/phone-host/src/full-methods.mjs index 2b481e0855..d5f84ccd71 100644 --- a/phone-host/src/full-methods.mjs +++ b/phone-host/src/full-methods.mjs @@ -7,19 +7,52 @@ // user can. import { randomUUID } from 'node:crypto'; import { AGENT_TITLES, agentCommand, detectAgents, shellQuote } from './agents.mjs'; +import { createChatMethods } from './chat-methods.mjs'; +import { createChatSessions } from './chat-sessions.mjs'; +import { initialTabStatus, nextTabStatus, statusFields, watchChatStatus } from './chat-status.mjs'; +import { createFilesMethods } from './files-methods.mjs'; +import { createQuickCommands } from './quick-commands.mjs'; import { RpcError, STREAMING } from './rpc.mjs'; import { defaultShell } from './terminals.mjs'; const MAX_SEND_CHARS = 32 * 1024; + +/** Orca's submit delay: a 500 ms settle plus paste ingest time (4096 bytes/ms, 64 on Windows ConPTY). */ +export function submitDelayMs(text, platform = process.platform) { + const bytes = Buffer.byteLength(text, 'utf8') + 12; // + bracketed-paste markers, as Orca counts them + return 500 + Math.ceil(bytes / (platform === 'win32' ? 64 : 4096)); +} const MUTATION_MEMORY = 256; +const MAX_TITLE = 200; +const FOREGROUND_CHECK_MS = 2000; +// A quick command's starting prompt for Claude or Codex, one argument after the fixed command +// (Orca's 'argv' prompt injection, src/shared/tui-agent-startup.ts). The prompt is never typed: it +// rides in the terminal's environment and the typed line ends in "$RUFLO_PHONE_AGENT_PROMPT", so the +// shell never parses it, and a long prompt cannot overrun the tty's ~4 KB line limit (which would +// leave the shell waiting for a closing quote). Control characters other than newline are dropped. +export const AGENT_PROMPT_ENV = 'RUFLO_PHONE_AGENT_PROMPT'; +const PROMPT_ARGV_AGENTS = new Set(['claude', 'codex']); +const MAX_AGENT_PROMPT = 6000; +export function agentPromptArg(agent, value) { + if (value === undefined || value === null || value === '') return null; + if (typeof value !== 'string' || value.length > MAX_AGENT_PROMPT) throw new RpcError('invalid_argument', 'Invalid agent prompt'); + if (!PROMPT_ARGV_AGENTS.has(agent)) throw new RpcError('invalid_argument', 'This agent cannot start with a prompt'); + // eslint-disable-next-line no-control-regex + const p = value.replace(/\t/g, ' ').replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/g, '').trim(); + if (!p) return null; + return p.startsWith('-') ? ` ${p}` : p; // never an option +} /** Not an RPC method (symbol keys never match a method name): used by the host to close a revoked phone's terminals. */ export const CLOSE_REVOKED = Symbol('closeRevoked'); /** * @param {{ terminals: ReturnType, - * projects: { find: (selector: string) => Promise }, log?: Function, detect?: () => string[] }} deps + * projects: { find: (selector: string) => Promise }, log?: Function, detect?: () => string[], + * chatSessions?: ReturnType, chatPollMs?: number, stateDir?: string|null }} deps + * chatSessions: where Claude/Codex transcripts are looked for (tests pass their own roots). + * stateDir: where quick commands are saved; without one they live in memory. */ -export function createFullMethods({ terminals, projects, log = () => {}, detect = detectAgents }) { +export function createFullMethods({ terminals, projects, log = () => {}, detect = detectAgents, chatSessions = createChatSessions(), chatPollMs, stateDir = null }) { const publicationEpoch = `ruflo-phone:${randomUUID()}`; let snapshotVersion = 0; /** worktreeId -> { tabs: Tab[], activeTabId: string|null } (tab = { tabId, leafId, handle, title, launchAgent }) */ @@ -28,6 +61,8 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect const tabSubscribers = new Map(); /** clientMutationId -> createTerminal result, so a retried create never spawns twice. */ const mutations = new Map(); + /** handle -> tail of that terminal's send queue */ + const sendQueues = new Map(); const sessionOf = (worktreeId) => { let s = sessions.get(worktreeId); @@ -36,6 +71,19 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect }; const surfaceId = (t) => `${t.tabId}::${t.leafId}`; + /** + * Orca's AgentStatusEntry (src/shared/agent-status-types.ts) for a Claude/Codex tab. The phone's + * chat view needs `agentType` and `providerSession`; `state` comes from the transcript's turn + * lifecycle (chat-status.mjs): `working` shows the chat's Stop button, `done` settles it. + */ + function agentStatus(t, worktreeId) { + return { + ...statusFields(t.chat.status), + agentType: t.chat.agent, paneKey: `${t.tabId}:${t.leafId}`, terminalHandle: t.handle, tabId: t.tabId, worktreeId, + ...(t.chat.sessionId ? { providerSession: { key: 'session_id', id: t.chat.sessionId, transcriptPath: t.chat.transcriptPath } } : {}), + }; + } + function snapshot(worktreeId) { const s = sessionOf(worktreeId); const active = s.tabs.find((t) => t.tabId === s.activeTabId) ?? s.tabs[s.tabs.length - 1] ?? null; @@ -50,6 +98,7 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect type: 'terminal', id: surfaceId(t), parentTabId: t.tabId, leafId: t.leafId, title: t.title, status: 'ready', terminal: t.handle, isActive: t === active, ...(t.launchAgent ? { launchAgent: t.launchAgent } : {}), + ...(t.chat ? { agentStatus: agentStatus(t, worktreeId) } : {}), })), }; } @@ -76,6 +125,7 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect const s = sessions.get(worktreeId); if (!s) return; const before = s.tabs.length; + for (const t of s.tabs) if (t.handle === handle) t.chat?.stopStatus?.(); s.tabs = s.tabs.filter((t) => t.handle !== handle); if (s.tabs.length !== before) { if (!s.tabs.some((t) => t.tabId === s.activeTabId)) s.activeTabId = s.tabs[s.tabs.length - 1]?.tabId ?? null; @@ -83,23 +133,82 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect } } + /** Whether the tab's agent (not the shell it was typed into) is the terminal's foreground process. */ + function agentRunning(tab) { + const t = terminals.get(tab.handle); + if (!t || t.exited) return false; + const fg = terminals.foreground(t); + return !fg || fg !== tab.shellName; + } + + function applyStatus(tab, worktreeId) { + const next = nextTabStatus(tab.chat.status, tab.chat.folded, agentRunning(tab)); + if (next === tab.chat.status) return; + tab.chat.status = next; + if (sessionOf(worktreeId).tabs.includes(tab)) publish(worktreeId); + } + + /** Follows the session's transcript, so the tab row reports working / done (chat-status.mjs). */ + function followStatus(tab, worktreeId, session) { + tab.chat.stopStatus?.(); + tab.chat.folded = { state: 'done', interrupted: false, model: null, prompt: '', turnStartedAt: null }; + tab.chat.stopStatus = watchChatStatus({ + agent: session.agent, resolveFile: () => chatSessions.resolveFile(session), pollMs: chatPollMs ?? 750, + onChange: (folded) => { tab.chat.folded = folded; applyStatus(tab, worktreeId); }, + }); + } + + // A turn the transcript left open (the agent crashed or was quit mid-turn) must not keep Stop up. + const foregroundTimer = setInterval(() => { + for (const [worktreeId, s] of sessions) for (const tab of s.tabs) if (tab.chat?.status.state === 'working') applyStatus(tab, worktreeId); + }, FOREGROUND_CHECK_MS); + foregroundTimer.unref?.(); + function startTerminal(row, params, owner = null) { const agent = params?.agent ?? params?.launchAgent ?? null; - const argv = agent ? agentCommand(agent) : null; + let argv = agent ? agentCommand(agent) : null; if (agent && !argv) throw new RpcError('agent_unknown', `Unknown agent: ${String(agent).slice(0, 40)}`); + // Claude takes a session id the host chooses, so the chat view knows its transcript at once. + const claude = agent === 'claude' ? chatSessions.startClaude({ cwd: row.path }) : null; + if (claude) argv = [...argv, '--session-id', claude.sessionId]; + const prompt = agentPromptArg(agent, params?.agentPrompt); const shell = defaultShell(); const posix = process.platform !== 'win32'; + if (prompt && !posix) throw new RpcError('invalid_argument', 'Starting an agent with a prompt needs a POSIX shell'); const t = terminals.create({ cwd: row.path, worktreeId: row.worktreeId, file: shell, args: posix ? ['-l'] : [], title: agent ? AGENT_TITLES[agent] ?? agent : shell.split(/[\\/]/).pop(), launchAgent: agent, cols: params?.viewport?.cols, rows: params?.viewport?.rows, owner, + ...(prompt ? { env: { [AGENT_PROMPT_ENV]: prompt } } : {}), }); // The agent runs inside a login shell, typed as its first command, so quitting it leaves a shell // rather than a dead tab. `command` (quick commands) is typed the same way: it is what the user // would type, from a device they paired with full access. - const first = argv ? argv.map(shellQuote).join(' ') : typeof params?.command === 'string' ? params.command : null; + const first = argv ? argv.map(shellQuote).join(' ') + (prompt ? ` "$${AGENT_PROMPT_ENV}"` : '') + : typeof params?.command === 'string' ? params.command : null; if (first) terminals.write(t, `${first}\r`); - const tab = { tabId: `tab-${randomUUID()}`, leafId: randomUUID(), handle: t.handle, title: t.title, launchAgent: agent }; + const tab = { + tabId: `tab-${randomUUID()}`, leafId: randomUUID(), handle: t.handle, title: t.title, launchAgent: agent, + shellName: shell.split(/[\\/]/).pop(), + }; + const launchedAt = Date.now(); + if (claude) { + tab.chat = { agent: 'claude', sessionId: claude.sessionId, transcriptPath: claude.transcriptPath, status: initialTabStatus(launchedAt) }; + followStatus(tab, row.worktreeId, claude); + } + if (agent === 'codex') { + // Codex names its own session when it writes the first prompt; the tab gains it then. + tab.chat = { agent: 'codex', sessionId: null, transcriptPath: null, status: initialTabStatus(launchedAt) }; + chatSessions.watchCodex({ + cwd: row.path, launchedAt, alive: () => terminals.get(t.handle) === t, + onFound: (found) => { + Object.assign(tab.chat, { sessionId: found.sessionId, transcriptPath: found.transcriptPath }); + log('chat-session-found', { agent: 'codex' }); + followStatus(tab, row.worktreeId, found); + if (sessionOf(row.worktreeId).tabs.includes(tab)) publish(row.worktreeId); + }, + }); + } const s = sessionOf(row.worktreeId); s.tabs.push(tab); if (params?.select !== false) s.activeTabId = tab.tabId; @@ -130,6 +239,9 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect } return { + ...createChatMethods({ sessions: chatSessions, ...(chatPollMs ? { pollMs: chatPollMs, resolvePollMs: chatPollMs } : {}) }), + ...createFilesMethods({ projects }), + ...createQuickCommands({ stateDir }), [CLOSE_REVOKED]: closeTerminalsOf, 'settings.get': () => { const found = detect(); @@ -194,7 +306,7 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect 'terminal.close': (p) => { const t = terminals.get(p?.terminal); - if (t) { const w = t.worktreeId; terminals.close(t); removeTab(w, t.handle); } + if (t) { const w = t.worktreeId; terminals.close(t); removeTab(w, t.handle); sendQueues.delete(t.handle); } return { closed: Boolean(t) }; }, @@ -217,7 +329,7 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect streams.get(subId)?.(); // Resize first, so the scrollback reports the size the phone asked for (it re-subscribes until // the sizes match). - if (p?.viewport) terminals.resize(t, p.viewport.cols, p.viewport.rows); + if (p?.viewport && t.displayMode !== 'desktop') terminals.resize(t, p.viewport.cols, p.viewport.rows); conn.push({ type: 'subscribed', streamId: null }); conn.push({ type: 'scrollback', serialized: terminals.scrollback(t), cols: t.cols, rows: t.rows, truncated: false, seq: t.seq }); if (t.exited) { conn.push({ type: 'end' }, false); return STREAMING; } @@ -239,7 +351,7 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect 'terminal.updateViewport': (p) => { const t = terminalOf(p); - terminals.resize(t, p?.viewport?.cols, p?.viewport?.rows); + if (t.displayMode !== 'desktop') terminals.resize(t, p?.viewport?.cols, p?.viewport?.rows); return { updated: true, applied: false, seq: t.seq }; }, @@ -247,11 +359,48 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect const t = terminalOf(p); const text = typeof p?.text === 'string' ? p.text : ''; if (text.length > MAX_SEND_CHARS) throw new RpcError('invalid_argument', 'Input too long'); - const data = text + (p?.enter ? '\r' : '') + (p?.interrupt ? '\x03' : ''); - const bytesWritten = data ? terminals.write(t, data) : 0; - return { send: { handle: t.handle, accepted: !t.exited, bytesWritten } }; + const suffix = (p?.enter ? '\r' : '') + (p?.interrupt ? '\x03' : ''); + // Sends to one terminal run in order, so a later keystroke cannot overtake a delayed Enter. + const run = async () => { + let bytesWritten = text ? terminals.write(t, text) : 0; + if (suffix) { + // Text and Enter in one write reach a TUI agent as a paste, and Codex then keeps the + // Enter in its input box instead of submitting. Orca waits for the paste to settle + // first (agent-prompt-injection.ts): 500 ms plus the time to ingest the bytes. + if (text) await new Promise((r) => setTimeout(r, submitDelayMs(text))); + bytesWritten += terminals.write(t, suffix); + } + return { send: { handle: t.handle, accepted: !t.exited, bytesWritten } }; + }; + const result = (sendQueues.get(t.handle) ?? Promise.resolve()).then(run, run); + sendQueues.set(t.handle, result.catch(() => {})); + return result; }, 'terminal.focus': () => ({ focused: true }), + + // A tab rename. An empty or null title restores the tab's own name. + 'terminal.rename': (p) => { + const t = terminalOf(p); + if (p?.title !== null && typeof p?.title !== 'string') throw new RpcError('invalid_argument', 'Missing title'); + // eslint-disable-next-line no-control-regex + const title = (p.title ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim().slice(0, MAX_TITLE) || null; + const tab = sessionOf(t.worktreeId).tabs.find((x) => x.handle === t.handle); + if (tab) { + tab.title = title ?? t.title; + publish(t.worktreeId); + } + return { rename: { handle: t.handle, tabId: tab ? surfaceId(tab) : null, title } }; + }, + + // 'auto': the phone drives the terminal's size; 'desktop': it keeps its size and the phone scales + // to fit. There is no desktop window here, so 'desktop' simply stops phone resizes. + 'terminal.setDisplayMode': (p) => { + const t = terminalOf(p); + if (p?.mode !== 'auto' && p?.mode !== 'desktop') throw new RpcError('invalid_argument', 'Invalid display mode'); + t.displayMode = p.mode; + if (p.mode === 'auto' && p.viewport) terminals.resize(t, p.viewport.cols, p.viewport.rows); + return { mode: p.mode, seq: t.seq }; + }, }; } diff --git a/phone-host/src/host-runtime.mjs b/phone-host/src/host-runtime.mjs index 312988124f..cbc4e71a6f 100644 --- a/phone-host/src/host-runtime.mjs +++ b/phone-host/src/host-runtime.mjs @@ -34,7 +34,7 @@ export async function runHost({ store, bind, port, bundleDir, projects = [], wor for (const d of skipped) warn(`Not a git repository, skipped: ${d}`); const catalog = createProjectCatalog({ repos, only }); const terminals = full ? createTerminalManager({ pty: await loadPty(), log }) : null; - const fullMethods = terminals ? createFullMethods({ terminals, projects: catalog }) : null; + const fullMethods = terminals ? createFullMethods({ terminals, projects: catalog, stateDir: store.dir }) : null; const host = await startPhoneHost({ store, bind: address, port, bundle, projects: catalog, fullMethods, log }); // Method names (never params) a phone asked for and was refused: what the app needs next. diff --git a/phone-host/src/quick-commands.mjs b/phone-host/src/quick-commands.mjs new file mode 100644 index 0000000000..1234d7957e --- /dev/null +++ b/phone-host/src/quick-commands.mjs @@ -0,0 +1,126 @@ +// Saved quick commands for a full-access phone's terminal screen: settings.getTerminalQuickCommands +// and settings.updateTerminalQuickCommands. Normalization, limits and the one-mutation update follow +// Orca (src/shared/terminal-quick-commands.ts, terminal-quick-command-prompt-limit.ts, +// rpc-contract/terminal-quick-command-params.ts, rpc/methods/client-ui.ts; MIT, see NOTICE). +// +// The phone rejects the whole list unless every row is already in normalized form (exact keys, +// `action` and `scope` always present), so the host only ever stores and returns normalized rows. +// The list lives in `quick-commands.json` (0600) in the host's state directory; without one (tests) +// it stays in memory. +import { randomUUID } from 'node:crypto'; +import { readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { RpcError } from './rpc.mjs'; + +export const MAX_QUICK_COMMANDS = 40; +const MAX_ID = 80; const MAX_LABEL = 80; const MAX_REPO_ID = 200; const MAX_COMMAND = 4000; +// Orca's pre-long-prompt cap: every phone build accepts a list within it. +export const MAX_AGENT_PROMPT = 6000; +const MAX_FILE_BYTES = 1024 * 1024; +/** Agents whose quick command can start with a prompt here (full-methods.mjs agentPromptArg). */ +export const PROMPT_AGENTS = new Set(['claude', 'codex']); +const FILE = 'quick-commands.json'; + +function scopeOf(input) { + if (!input || typeof input !== 'object' || Array.isArray(input) || input.type !== 'repo') return { type: 'global' }; + const repoId = typeof input.repoId === 'string' ? input.repoId.trim() : ''; + return repoId ? { type: 'repo', repoId: repoId.slice(0, MAX_REPO_ID) } : { type: 'global' }; +} + +/** Orca's normalizeTerminalQuickCommands, with prompt agents limited to the ones this host can start. */ +export function normalizeQuickCommands(input) { + if (!Array.isArray(input)) return []; + const out = []; const seen = new Set(); + for (const item of input) { + if (!item || typeof item !== 'object' || Array.isArray(item)) continue; + const rawId = typeof item.id === 'string' ? item.id.trim() : ''; + const hasLabel = typeof item.label === 'string'; + const prompt = item.action === 'agent-prompt'; + if (!hasLabel && typeof item.command !== 'string' && typeof item.prompt !== 'string') continue; + if (prompt && !PROMPT_AGENTS.has(item.agent)) continue; + const idBase = rawId || `quick-command-${out.length + 1}`; + let id = idBase.slice(0, MAX_ID); let suffix = 2; + while (seen.has(id)) { id = `${idBase.slice(0, MAX_ID - 4)}-${suffix}`; suffix += 1; } + seen.add(id); + const base = { id, label: hasLabel ? item.label.trim().slice(0, MAX_LABEL) : '', scope: scopeOf(item.scope) }; + if (prompt) { + const text = typeof item.prompt === 'string' ? item.prompt.trimEnd() : ''; + if (text.length > MAX_AGENT_PROMPT) continue; + out.push({ id: base.id, label: base.label, action: 'agent-prompt', agent: item.agent, prompt: text, scope: base.scope }); + } else { + const command = typeof item.command === 'string' ? item.command.trimEnd().slice(0, MAX_COMMAND) : ''; + out.push({ id: base.id, label: base.label, action: 'terminal-command', command, appendEnter: item.appendEnter !== false, scope: base.scope }); + } + if (out.length >= MAX_QUICK_COMMANDS) break; + } + return out; +} + +const UPSERT_KEYS = { + 'terminal-command': new Set(['id', 'label', 'action', 'command', 'appendEnter', 'scope']), + 'agent-prompt': new Set(['id', 'label', 'action', 'agent', 'prompt', 'scope']), +}; + +/** Validates one upsert item the way Orca's strict update schema does. */ +function upsertItem(c) { + if (!c || typeof c !== 'object' || Array.isArray(c)) return null; + const action = c.action === 'agent-prompt' ? 'agent-prompt' : 'terminal-command'; + if (c.action !== undefined && c.action !== action) return null; + if (Object.keys(c).some((k) => !UPSERT_KEYS[action].has(k))) return null; + if (typeof c.id !== 'string' || c.id.length > MAX_ID || typeof c.label !== 'string' || c.label.length > MAX_LABEL) return null; + if (action === 'terminal-command' && (typeof c.command !== 'string' || c.command.length > MAX_COMMAND || typeof c.appendEnter !== 'boolean')) return null; + if (action === 'agent-prompt' && (typeof c.prompt !== 'string' || c.prompt.length > MAX_AGENT_PROMPT || !PROMPT_AGENTS.has(c.agent))) return null; + if (c.scope !== undefined) { + const s = c.scope; + const ok = s && typeof s === 'object' && ((s.type === 'global' && Object.keys(s).length === 1) + || (s.type === 'repo' && typeof s.repoId === 'string' && s.repoId.length <= MAX_REPO_ID && Object.keys(s).length === 2)); + if (!ok) return null; + } + return normalizeQuickCommands([c])[0] ?? null; +} + +/** @param {{ stateDir?: string|null }} [o] */ +export function createQuickCommands({ stateDir = null } = {}) { + let list = null; + const path = stateDir ? join(stateDir, FILE) : null; + const load = () => { + if (list) return list; + list = []; + if (path) { + try { + const text = readFileSync(path, 'utf8'); + if (text.length <= MAX_FILE_BYTES) list = normalizeQuickCommands(JSON.parse(text)); + } catch { /* none saved yet, or unreadable: start empty */ } + } + return list; + }; + const save = (next) => { + if (path) { + const tmp = `${path}.${randomUUID()}.tmp`; + writeFileSync(tmp, JSON.stringify(next), { mode: 0o600 }); + renameSync(tmp, path); + } + list = next; + }; + + return { + 'settings.getTerminalQuickCommands': () => ({ terminalQuickCommands: load() }), + 'settings.updateTerminalQuickCommands': (p) => { + const m = p?.mutation; + if (!m || typeof m !== 'object' || Object.keys(p).length !== 1) throw new RpcError('invalid_argument', 'Invalid quick command update'); + const current = load(); + if (m.type === 'delete' && Object.keys(m).length === 2 && typeof m.id === 'string' && m.id && m.id.length <= MAX_ID) { + save(current.filter((c) => c.id !== m.id)); + } else if (m.type === 'upsert' && Object.keys(m).length === 2) { + const c = upsertItem(m.command); + if (!c) throw new RpcError('invalid_argument', 'Quick command cannot be normalized'); + const i = current.findIndex((x) => x.id === c.id); + if (i === -1 && current.length >= MAX_QUICK_COMMANDS) throw new RpcError('invalid_argument', `At most ${MAX_QUICK_COMMANDS} quick commands`); + save(i === -1 ? [...current, c] : current.map((x, j) => (j === i ? c : x))); + } else { + throw new RpcError('invalid_argument', 'Invalid quick command update'); + } + return { terminalQuickCommands: load() }; + }, + }; +} diff --git a/phone-host/src/terminals.mjs b/phone-host/src/terminals.mjs index 5e2b42f797..ca16467309 100644 --- a/phone-host/src/terminals.mjs +++ b/phone-host/src/terminals.mjs @@ -92,6 +92,11 @@ export function createTerminalManager({ pty, log = () => {} }) { get, list: (worktreeId) => [...terminals.values()].filter((t) => !worktreeId || t.worktreeId === worktreeId), scrollback: (t) => t.chunks.join(''), + /** Name of the terminal's foreground process (node-pty reads it from the OS), or null if unknown. */ + foreground(t) { + if (t.exited) return null; + try { const p = t.proc.process; return typeof p === 'string' && p ? p.split(/[\\/]/).pop().replace(/^-/, '') : null; } catch { return null; } + }, /** Subscribes to output; returns the unsubscribe function. */ listen(t, fn) { t.listeners.add(fn); return () => t.listeners.delete(fn); }, write(t, text) { diff --git a/phone-host/test/chat-controls.test.mjs b/phone-host/test/chat-controls.test.mjs new file mode 100644 index 0000000000..9378151c52 --- /dev/null +++ b/phone-host/test/chat-controls.test.mjs @@ -0,0 +1,224 @@ +// Chat-view controls end to end over the real E2EE phone client: the working/done state behind +// the Stop button (and Stop itself, two Escapes through terminal.send), the @-file picker, quick +// commands (including one that starts Claude with a prompt), tab rename and display mode. +// `claude` is a fake agent on PATH that records its argv and writes a transcript like the real one. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { createChatSessions } from '../src/chat-sessions.mjs'; +import { createFullMethods } from '../src/full-methods.mjs'; +import { decodePairingOffer } from '../src/offer.mjs'; +import { mintPairing } from '../src/pairing.mjs'; +import { createProjectCatalog, resolveProjects } from '../src/projects.mjs'; +import { startPhoneHost } from '../src/server.mjs'; +import { openStore } from '../src/store.mjs'; +import { createTerminalManager, loadPty } from '../src/terminals.mjs'; +import { connectPhone } from './helpers/phone-client.mjs'; + +const tmp = () => realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-phone-controls-'))); + +// Opens a turn at once (a prompt line), then waits; an Escape on its terminal ends the turn with +// Claude's interrupt notice. A prompt passed on argv becomes the turn's prompt. +const FAKE_CLAUDE = `#!/usr/bin/env node +const fs = require('fs'); const path = require('path'); +const args = process.argv.slice(2); +const id = args[args.indexOf('--session-id') + 1]; +fs.writeFileSync(path.join(process.env.FAKE_ARGV_DIR, id + '.json'), JSON.stringify(args)); +const dir = path.join(process.env.FAKE_CLAUDE_ROOT, process.cwd().replace(/[^A-Za-z0-9]/g, '-')); +fs.mkdirSync(dir, { recursive: true }); +const file = path.join(dir, id + '.jsonl'); +const rest = args.filter((a, i) => a !== '--session-id' && args[i - 1] !== '--session-id'); +const at = () => new Date().toISOString(); +const line = (r) => fs.appendFileSync(file, JSON.stringify({ ...r, timestamp: at(), sessionId: id }) + '\\n'); +line({ type: 'user', uuid: 'u-1', message: { role: 'user', content: rest[0] ?? 'keep going' } }); +line({ type: 'assistant', uuid: 'a-1', message: { id: 'm1', role: 'assistant', model: 'claude-fake-1', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }], stop_reason: 'tool_use' } }); +if (process.stdin.isTTY) process.stdin.setRawMode(true); +let stopped = false; +process.stdin.on('data', (d) => { + if (stopped || !d.includes(0x1b)) return; + stopped = true; + line({ type: 'user', uuid: 'u-2', interruptedMessageId: 'm1', message: { role: 'user', content: [{ type: 'text', text: '[Request interrupted by user]' }] } }); +}); +setTimeout(() => {}, 60000); +`; + +describe('chat controls over the phone connection', () => { + let store; let stateDir; let host; let terminals; let worktreeId; let repoDir; let phone; let readOnly; let argvDir; let tabs; + const saved = { PATH: process.env.PATH, SHELL: process.env.SHELL, HOME: process.env.HOME }; + const wt = () => ({ worktree: `id:${worktreeId}` }); + + before(async () => { + const bin = tmp(); + writeFileSync(join(bin, 'claude'), FAKE_CLAUDE); chmodSync(join(bin, 'claude'), 0o755); + const claudeRoot = tmp(); argvDir = tmp(); + Object.assign(process.env, { PATH: `${bin}:${saved.PATH}`, SHELL: '/bin/sh', HOME: tmp(), FAKE_CLAUDE_ROOT: claudeRoot, FAKE_ARGV_DIR: argvDir }); + + repoDir = tmp(); + const g = (...a) => execFileSync('git', ['-C', repoDir, ...a], { stdio: 'pipe' }); + g('init', '-q', '-b', 'main'); + mkdirSync(join(repoDir, 'src/deep'), { recursive: true }); + mkdirSync(join(repoDir, 'node_modules/pkg'), { recursive: true }); + writeFileSync(join(repoDir, '.gitignore'), 'node_modules/\n'); + writeFileSync(join(repoDir, 'README.md'), '# r\n'); + writeFileSync(join(repoDir, 'src/main.mjs'), ''); + writeFileSync(join(repoDir, 'src/deep/readme-notes.txt'), ''); + writeFileSync(join(repoDir, 'src/logo.png'), ''); + writeFileSync(join(repoDir, 'node_modules/pkg/index.js'), ''); + symlinkSync(tmpdir(), join(repoDir, 'outside')); + symlinkSync(join(repoDir, 'src'), join(repoDir, 'src-link')); + g('add', '-A'); g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'init'); + writeFileSync(join(repoDir, 'untracked.md'), ''); + const projects = createProjectCatalog(await resolveProjects({ projects: [repoDir] })); + worktreeId = (await projects.worktreePs({})).worktrees[0].worktreeId; + + store = openStore({ dir: tmp() }); stateDir = tmp(); + terminals = createTerminalManager({ pty: await loadPty() }); + const chatSessions = createChatSessions({ roots: { claude: [claudeRoot], codex: [tmp()] }, pollMs: 100, maxPollMs: 200 }); + const fullMethods = createFullMethods({ terminals, projects, chatSessions, chatPollMs: 100, stateDir }); + host = await startPhoneHost({ store, bind: '127.0.0.1', port: 0, projects, fullMethods }); + phone = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'Full', access: 'full' }).url)); + readOnly = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'RO' }).url)); + tabs = phone.stream('session.tabs.subscribe', wt()); + await tabs.until((f) => f.result?.type === 'snapshot'); + }); + + after(async () => { + await phone?.close(); await readOnly?.close(); terminals?.closeAll(); await host?.close(); + Object.assign(process.env, saved); + for (const k of ['FAKE_CLAUDE_ROOT', 'FAKE_ARGV_DIR']) delete process.env[k]; + }); + + const tabRow = async (id, pred) => (await tabs.until((f) => f.result?.type === 'updated' + && f.result.tabs.some((t) => t.id === id && pred(t)), 15000)).result.tabs.find((t) => t.id === id); + + it('reports a Claude turn as working, and Stop (two Escapes) ends it as interrupted', async () => { + const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude' }); + const id = created.result.tab.id; + const working = (await tabRow(id, (t) => t.agentStatus?.state === 'working')).agentStatus; + assert.equal(working.prompt, 'keep going'); + assert.equal(working.model, 'claude-fake-1'); + assert.equal(working.sessionBoundary, undefined); + assert.ok(working.turnStartedAt > 0); + for (const n of [1, 2]) await phone.call('terminal.send', { terminal: created.result.tab.terminal, text: '\x1b', step: n }); + const done = (await tabRow(id, (t) => t.agentStatus?.state === 'done' && t.agentStatus.stateHistory.length > 0)).agentStatus; + assert.equal(done.interrupted, true); + assert.deepEqual(done.stateHistory.map((h) => h.state), ['done', 'working']); + await phone.call('session.tabs.close', { ...wt(), tabId: id }); + }); + + it('serves the @-file picker from the workspace only', async () => { + const list = (await phone.call('files.list', wt())).result; + const paths = list.files.map((f) => f.relativePath); + assert.equal(list.rootPath, repoDir); + for (const p of ['README.md', 'src/main.mjs', 'untracked.md']) assert.ok(paths.includes(p), p); + assert.ok(!paths.some((p) => p.startsWith('node_modules/') || p.startsWith('.git/'))); + assert.deepEqual(list.files.find((f) => f.relativePath === 'src/logo.png'), { relativePath: 'src/logo.png', basename: 'logo.png', kind: 'binary' }); + + const hits = (await phone.call('files.searchPaths', { ...wt(), query: 'readme', limit: 16 })).result; + assert.deepEqual(hits.files.map((f) => f.relativePath), ['README.md', 'src/deep/readme-notes.txt']); + assert.equal(hits.totalCount, 2); + const one = (await phone.call('files.searchPaths', { ...wt(), query: 'src', limit: 1 })).result; + assert.equal(one.files.length, 1); assert.equal(one.truncated, true); + for (const bad of [{ limit: 0 }, { limit: 33 }, { limit: 1.5 }, { query: 'x'.repeat(257) }, { query: 7 }]) { + assert.equal((await phone.call('files.searchPaths', { ...wt(), ...bad })).error.code, 'invalid_argument', JSON.stringify(bad).slice(0, 40)); + } + assert.equal((await phone.call('files.list', { worktree: 'id:repo_x::/etc' })).error.code, 'worktree_not_found'); + }); + + it('lists directories without leaving the workspace', async () => { + const root = (await phone.call('files.readDir', { ...wt(), relativePath: '' })).result; + const names = root.map((e) => e.name); + assert.ok(!names.includes('.git')); + assert.deepEqual(root.find((e) => e.name === 'src'), { name: 'src', isDirectory: true, isSymlink: false }); + assert.deepEqual(root.find((e) => e.name === 'outside'), { name: 'outside', isDirectory: false, isSymlink: true }, 'a link out is not browsable'); + assert.deepEqual(root.find((e) => e.name === 'src-link'), { name: 'src-link', isDirectory: true, isSymlink: true }); + assert.ok((await phone.call('files.readDir', { ...wt(), relativePath: 'src/deep' })).result.some((e) => e.name === 'readme-notes.txt')); + assert.equal((await phone.call('files.readDir', { ...wt(), relativePath: 'outside' })).error.code, 'forbidden'); + for (const rel of ['..', '../', 'src/../..', '/etc', 'src/./deep', 'a//b']) { + assert.equal((await phone.call('files.readDir', { ...wt(), relativePath: rel })).error.code, 'invalid_argument', rel); + } + assert.equal((await phone.call('files.readDir', { ...wt(), relativePath: '.git' })).error.code, 'forbidden'); + assert.equal((await phone.call('files.readDir', { ...wt(), relativePath: 'nope' })).error.code, 'not_found'); + }); + + it('keeps quick commands in a private file, validated', async () => { + assert.deepEqual((await phone.call('settings.getTerminalQuickCommands')).result, { terminalQuickCommands: [] }); + const cmd = { id: 'qc-1', label: 'Status', action: 'terminal-command', command: 'git status', appendEnter: true, scope: { type: 'global' } }; + const up = await phone.call('settings.updateTerminalQuickCommands', { mutation: { type: 'upsert', command: cmd } }); + assert.deepEqual(up.result.terminalQuickCommands, [cmd]); + const ask = { id: 'qc-2', label: 'Ask', action: 'agent-prompt', agent: 'claude', prompt: 'explain', scope: { type: 'repo', repoId: 'r1' } }; + await phone.call('settings.updateTerminalQuickCommands', { mutation: { type: 'upsert', command: ask } }); + const file = join(stateDir, 'quick-commands.json'); + assert.equal(statSync(file).mode & 0o777, 0o600); + assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), [cmd, ask]); + const bad = [ + { type: 'upsert', command: { ...cmd, extra: 1 } }, + { type: 'upsert', command: { ...cmd, command: 'x'.repeat(4001) } }, + { type: 'upsert', command: { ...ask, agent: 'gemini' } }, + { type: 'upsert', command: { ...cmd, scope: { type: 'repo' } } }, + { type: 'rename', id: 'qc-1' }, + ]; + for (const mutation of bad) assert.equal((await phone.call('settings.updateTerminalQuickCommands', { mutation })).error.code, 'invalid_argument'); + const del = await phone.call('settings.updateTerminalQuickCommands', { mutation: { type: 'delete', id: 'qc-1' } }); + assert.deepEqual(del.result.terminalQuickCommands, [ask]); + }); + + it('starts Claude with a quick command prompt as one argument, never as shell code', async () => { + const prompt = "it's $(touch pwned) `id`; echo \"x\"\n-- second line"; + const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude', agentPrompt: prompt, activate: false, select: true }); + assert.equal(created.ok, true); + const row = await tabRow(created.result.tab.id, (t) => t.agentStatus?.providerSession); + const argvFile = join(argvDir, `${row.agentStatus.providerSession.id}.json`); + const deadline = Date.now() + 20000; + while (!existsSync(argvFile) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50)); + const argv = JSON.parse(readFileSync(argvFile, 'utf8')); + assert.deepEqual(argv.slice(-1), [prompt]); + assert.equal(existsSync(join(repoDir, 'pwned')), false); + const leading = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude', agentPrompt: '--dangerously-skip-permissions' }); + const lrow = await tabRow(leading.result.tab.id, (t) => t.agentStatus?.providerSession); + const lfile = join(argvDir, `${lrow.agentStatus.providerSession.id}.json`); + while (!existsSync(lfile) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50)); + assert.ok(!JSON.parse(readFileSync(lfile, 'utf8')).includes('--dangerously-skip-permissions'), 'never an option'); + // Longer than a tty line (~4 KB) once encoded: typed, it would be cut off mid-quote. + const long = `${'é'.repeat(5990)} end`; + const big = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude', agentPrompt: long }); + const brow = await tabRow(big.result.tab.id, (t) => t.agentStatus?.providerSession); + const bfile = join(argvDir, `${brow.agentStatus.providerSession.id}.json`); + while (!existsSync(bfile) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50)); + assert.equal(JSON.parse(readFileSync(bfile, 'utf8')).at(-1), long); + assert.equal((await phone.call('session.tabs.createTerminal', { ...wt(), agentPrompt: 'hi' })).error.code, 'invalid_argument'); + assert.equal((await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude', agentPrompt: 'x'.repeat(6001) })).error.code, 'invalid_argument'); + for (const t of [created, leading, big]) await phone.call('session.tabs.close', { ...wt(), tabId: t.result.tab.id }); + }); + + it('renames a tab and switches its display mode', async () => { + const created = await phone.call('session.tabs.createTerminal', wt()); + const { id, terminal } = created.result.tab; + const r = await phone.call('terminal.rename', { terminal, title: ' Build\u0007 logs ' }); + assert.deepEqual(r.result.rename, { handle: terminal, tabId: id, title: 'Build logs' }); + assert.equal((await tabRow(id, (t) => t.title === 'Build logs')).title, 'Build logs'); + await phone.call('terminal.rename', { terminal, title: null }); + assert.notEqual((await tabRow(id, (t) => t.title !== 'Build logs')).title, 'Build logs'); + assert.equal((await phone.call('terminal.rename', { terminal, title: 5 })).error.code, 'invalid_argument'); + + const d = await phone.call('terminal.setDisplayMode', { terminal, mode: 'desktop' }); + assert.equal(d.result.mode, 'desktop'); + const t = terminals.get(terminal); + const before = [t.cols, t.rows]; + await phone.call('terminal.updateViewport', { terminal, viewport: { cols: 40, rows: 10 } }); + assert.deepEqual([t.cols, t.rows], before, 'desktop mode keeps the size'); + await phone.call('terminal.setDisplayMode', { terminal, mode: 'auto', viewport: { cols: 50, rows: 12 } }); + assert.deepEqual([t.cols, t.rows], [50, 12]); + assert.equal((await phone.call('terminal.setDisplayMode', { terminal, mode: 'tablet' })).error.code, 'invalid_argument'); + await phone.call('session.tabs.close', { ...wt(), tabId: id }); + }); + + it('gives a read-only phone none of these methods', async () => { + const methods = ['files.list', 'files.searchPaths', 'files.readDir', 'settings.getTerminalQuickCommands', + 'settings.updateTerminalQuickCommands', 'terminal.rename', 'terminal.setDisplayMode']; + for (const m of methods) assert.equal((await readOnly.call(m, wt())).error.code, 'method_not_found', m); + }); +}); diff --git a/phone-host/test/chat-host.test.mjs b/phone-host/test/chat-host.test.mjs new file mode 100644 index 0000000000..95c9c0e1c6 --- /dev/null +++ b/phone-host/test/chat-host.test.mjs @@ -0,0 +1,167 @@ +// The chat view end to end, over the real E2EE phone client: agent tabs started by the host gain +// `agentStatus.providerSession`, and nativeChat.* serves their transcripts. `claude` and `codex` +// are fake agents on PATH that write fixture transcripts where the real ones would. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { chmodSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { createChatSessions } from '../src/chat-sessions.mjs'; +import { createFullMethods } from '../src/full-methods.mjs'; +import { decodePairingOffer } from '../src/offer.mjs'; +import { mintPairing } from '../src/pairing.mjs'; +import { createProjectCatalog, resolveProjects } from '../src/projects.mjs'; +import { startPhoneHost } from '../src/server.mjs'; +import { openStore } from '../src/store.mjs'; +import { createTerminalManager, loadPty } from '../src/terminals.mjs'; +import { connectPhone } from './helpers/phone-client.mjs'; + +const tmp = () => realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-phone-chat-host-'))); +const fixtureDir = fileURLToPath(new URL('./fixtures/', import.meta.url)); + +// Writes the first 7 Claude records at once and the rest a moment later, as a live session would. +const FAKE_CLAUDE = `#!/usr/bin/env node +const fs = require('fs'); const path = require('path'); +const id = process.argv[process.argv.indexOf('--session-id') + 1]; +const dir = path.join(process.env.FAKE_CLAUDE_ROOT, process.cwd().replace(/[^A-Za-z0-9]/g, '-')); +fs.mkdirSync(dir, { recursive: true }); +const file = path.join(dir, id + '.jsonl'); +const lines = fs.readFileSync(path.join(process.env.FAKE_FIXTURES, 'claude-transcript.jsonl'), 'utf8').replaceAll('SESSION', id).split('\\n'); +console.log('FAKE-CLAUDE ' + id); +fs.writeFileSync(file, lines.slice(0, 7).join('\\n') + '\\n'); +setTimeout(() => fs.appendFileSync(file, lines.slice(7).join('\\n')), 700); +setTimeout(() => {}, 60000); +`; + +// Codex names its own session and creates the rollout only after a while (its first prompt). +const FAKE_CODEX = `#!/usr/bin/env node +const fs = require('fs'); const path = require('path'); const { randomUUID } = require('crypto'); +const id = randomUUID(); const now = new Date(); const p = (n) => String(n).padStart(2, '0'); +const dir = path.join(process.env.FAKE_CODEX_ROOT, String(now.getFullYear()), p(now.getMonth() + 1), p(now.getDate())); +const stamp = now.getFullYear() + '-' + p(now.getMonth() + 1) + '-' + p(now.getDate()) + 'T' + p(now.getHours()) + '-' + p(now.getMinutes()) + '-' + p(now.getSeconds()); +console.log('FAKE-CODEX'); +setTimeout(() => { + fs.mkdirSync(dir, { recursive: true }); + const text = fs.readFileSync(path.join(process.env.FAKE_FIXTURES, 'codex-rollout.jsonl'), 'utf8') + .replaceAll('SESSION', id).replace('"STARTED"', JSON.stringify(now.toISOString())).replace('"CWD"', JSON.stringify(process.cwd())); + fs.writeFileSync(path.join(dir, 'rollout-' + stamp + '-' + id + '.jsonl'), text); +}, 400); +setTimeout(() => {}, 60000); +`; + +describe('chat view over the phone connection', () => { + let store; let host; let terminals; let worktreeId; let phone; let readOnly; let claudeRoot; let codexRoot; let tabs; + const saved = { PATH: process.env.PATH, SHELL: process.env.SHELL, HOME: process.env.HOME }; + const wt = () => ({ worktree: `id:${worktreeId}` }); + + before(async () => { + const bin = tmp(); + writeFileSync(join(bin, 'claude'), FAKE_CLAUDE); chmodSync(join(bin, 'claude'), 0o755); + writeFileSync(join(bin, 'codex'), FAKE_CODEX); chmodSync(join(bin, 'codex'), 0o755); + claudeRoot = tmp(); codexRoot = tmp(); + // A fresh HOME: the login shell must not read the user's ~/.profile, which could put the real + // `claude` ahead of the fake one on PATH. + Object.assign(process.env, { PATH: `${bin}:${saved.PATH}`, SHELL: '/bin/sh', HOME: tmp(), FAKE_CLAUDE_ROOT: claudeRoot, FAKE_CODEX_ROOT: codexRoot, FAKE_FIXTURES: fixtureDir }); + + const repoDir = tmp(); + const g = (...a) => execFileSync('git', ['-C', repoDir, ...a], { stdio: 'pipe' }); + g('init', '-q', '-b', 'main'); g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '--allow-empty', '-m', 'init'); + const projects = createProjectCatalog(await resolveProjects({ projects: [repoDir] })); + worktreeId = (await projects.worktreePs({})).worktrees[0].worktreeId; + + store = openStore({ dir: tmp() }); + terminals = createTerminalManager({ pty: await loadPty() }); + const chatSessions = createChatSessions({ roots: { claude: [claudeRoot], codex: [codexRoot] }, pollMs: 100, maxPollMs: 200 }); + const fullMethods = createFullMethods({ terminals, projects, chatSessions, chatPollMs: 100 }); + host = await startPhoneHost({ store, bind: '127.0.0.1', port: 0, projects, fullMethods }); + phone = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'Full', access: 'full' }).url)); + readOnly = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'RO' }).url)); + tabs = phone.stream('session.tabs.subscribe', wt()); + await tabs.until((f) => f.result?.type === 'snapshot'); + }); + + after(async () => { + await phone?.close(); await readOnly?.close(); terminals?.closeAll(); await host?.close(); + Object.assign(process.env, saved); + for (const k of ['FAKE_CLAUDE_ROOT', 'FAKE_CODEX_ROOT', 'FAKE_FIXTURES']) delete process.env[k]; + }); + + const tabRow = async (id, pred) => (await tabs.until((f) => f.result?.type === 'updated' + && f.result.tabs.some((t) => t.id === id && pred(t)), 15000)).result.tabs.find((t) => t.id === id); + + it('a Claude tab carries its session from the start, and its transcript streams to the chat view', async () => { + const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude' }); + const row = await tabRow(created.result.tab.id, (t) => t.agentStatus); + const { agentStatus } = row; + assert.equal(row.launchAgent, 'claude'); + assert.equal(agentStatus.agentType, 'claude'); + assert.equal(agentStatus.providerSession.key, 'session_id'); + assert.match(agentStatus.providerSession.id, /^[0-9a-f-]{36}$/); + assert.ok(agentStatus.providerSession.transcriptPath.startsWith(`${claudeRoot}/`)); + assert.equal(agentStatus.paneKey, `${row.parentTabId}:${row.leafId}`); + assert.equal(agentStatus.terminalHandle, row.terminal); + const sessionId = agentStatus.providerSession.id; + + // The phone may send any transcriptPath; the host reads only its own record of the session. + const chat = phone.stream('nativeChat.subscribe', { + agent: 'claude', sessionId, limit: 40, subscriptionId: `claude:${sessionId}:x1`, + capabilities: { transcriptPending: 1 }, transcriptPath: '/etc/passwd', + }); + const snap = await chat.until((f) => f.result?.type === 'snapshot' && f.result.messages?.length > 0, 15000); + assert.equal(snap.streaming, true); + assert.deepEqual(snap.result.messages.map((m) => m.id), ['u-1', 'a-1', 'a-2', 'u-2', 'a-3']); + assert.equal(snap.result.hasMore, false); + assert.equal(typeof snap.result.beforeOffset, 'number'); + assert.equal(snap.result.lifecycle.state, 'completed'); + const appended = await chat.until((f) => f.result?.type === 'appended' && f.result.messages.some((m) => m.id === 'u-5'), 15000); + assert.equal(appended.result.messages.at(-1).role, 'system'); + + const page = await phone.call('nativeChat.readSession', { agent: 'claude', sessionId, limit: 2 }); + assert.deepEqual(page.result.messages.map((m) => m.id), ['u-4', 'u-5']); + assert.equal(page.result.hasMore, true); + const older = await phone.call('nativeChat.readSession', { agent: 'claude', sessionId, limit: 2, beforeOffset: page.result.beforeOffset }); + assert.deepEqual(older.result.messages.map((m) => m.id), ['u-2', 'a-3']); + + const un = await phone.call('nativeChat.unsubscribe', { subscriptionId: `claude:${sessionId}:x1` }); + assert.equal(un.result.unsubscribed, true); + const end = await chat.until((f) => f.result?.type === 'end'); + assert.equal(end.streaming, undefined); + }); + + it('a Codex tab gains its session once Codex writes its rollout, and the chat view reads it', async () => { + const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'codex' }); + const id = created.result.tab.id; + const before = await tabRow(id, (t) => t.agentStatus); + assert.equal(before.agentStatus.agentType, 'codex'); + assert.equal(before.agentStatus.providerSession, undefined, 'no session before Codex names one'); + const row = await tabRow(id, (t) => t.agentStatus?.providerSession); + const { id: sessionId, transcriptPath } = row.agentStatus.providerSession; + assert.ok(transcriptPath.startsWith(`${codexRoot}/`) && transcriptPath.endsWith(`-${sessionId}.jsonl`)); + + const chat = phone.stream('nativeChat.subscribe', { agent: 'codex', sessionId, limit: 40 }); + const snap = await chat.until((f) => f.result?.type === 'snapshot', 15000); + assert.deepEqual(snap.result.messages.map((m) => m.role), ['user', 'assistant', 'tool', 'assistant']); + assert.equal(snap.result.lifecycle.state, 'completed'); + await phone.call('nativeChat.unsubscribe', {}); + await chat.until((f) => f.result?.type === 'end'); + }); + + it('refuses sessions it did not start, other agents, and read-only phones', async () => { + const unknown = await phone.call('nativeChat.readSession', { agent: 'claude', sessionId: '6f1e1c32-0000-4000-8000-000000000000', transcriptPath: '/etc/passwd' }); + assert.deepEqual(unknown.result, { error: 'Transcript unavailable', notFound: true }); + const traversal = await phone.call('nativeChat.readSession', { agent: 'claude', sessionId: '../../../../etc/passwd' }); + assert.equal(traversal.result.notFound, true); + const grok = await phone.call('nativeChat.readSession', { agent: 'grok', sessionId: 'abcdefgh-1' }); + assert.equal(grok.result.notFound, true); + const bad = await phone.call('nativeChat.readSession', { agent: 'claude' }); + assert.equal(bad.error.code, 'invalid_argument'); + const sub = phone.stream('nativeChat.subscribe', { agent: 'codex', sessionId: 'not-a-session-of-ours' }); + const f = await sub.until((x) => x.result?.type === 'snapshot'); + assert.equal(f.result.error, 'Transcript unavailable'); + await phone.call('nativeChat.unsubscribe', {}); + const ro = await readOnly.call('nativeChat.readSession', { agent: 'claude', sessionId: 'abcdefgh-1' }); + assert.equal(ro.error.code, 'method_not_found'); + }); +}); diff --git a/phone-host/test/chat-status.test.mjs b/phone-host/test/chat-status.test.mjs new file mode 100644 index 0000000000..c9fdf28f12 --- /dev/null +++ b/phone-host/test/chat-status.test.mjs @@ -0,0 +1,129 @@ +// Turn state for Claude/Codex tabs (chat-status.mjs): the fold over transcript lines, the tab +// status that drives the phone's Stop button, and the file watcher that feeds it. +import assert from 'node:assert/strict'; +import { appendFileSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { createStatusFold, initialTabStatus, lineModel, nextTabStatus, statusFields, watchChatStatus } from '../src/chat-status.mjs'; + +const fixture = (name) => readFileSync(fileURLToPath(new URL(`./fixtures/${name}`, import.meta.url)), 'utf8').split('\n').filter(Boolean); +const fold = (agent, lines) => { const f = createStatusFold(agent); for (const l of lines) f.line(l); return f.status; }; +const until = async (pred, ms = 3000) => { + const end = Date.now() + ms; + while (Date.now() < end) { if (pred()) return; await new Promise((r) => setTimeout(r, 20)); } + throw new Error('timed out'); +}; + +describe('status fold', () => { + const claude = fixture('claude-transcript.jsonl'); + + it('Claude: a prompt opens a turn, end_turn closes it, the interrupt notice marks it interrupted', () => { + assert.equal(fold('claude', claude.slice(0, 2)).state, 'working'); + assert.equal(fold('claude', claude.slice(0, 2)).prompt, 'List the files here'); + // a-1 is thinking with no stop_reason (looks final), then a-2 is a tool call: still the same turn. + assert.equal(fold('claude', claude.slice(0, 3)).state, 'done'); + assert.equal(fold('claude', claude.slice(0, 4)).state, 'working'); + assert.equal(fold('claude', claude.slice(0, 6)).state, 'working', 'tool result and harness reminder keep it working'); + const done = fold('claude', claude.slice(0, 7)); + assert.equal(done.state, 'done'); assert.equal(done.interrupted, false); + const stopped = fold('claude', claude); + assert.equal(stopped.state, 'done'); assert.equal(stopped.interrupted, true); + }); + + it('a turn closed by end_turn does not reopen on a later stray record', () => { + const late = JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'x', content: 'late' }] } }); + assert.equal(fold('claude', [...claude.slice(0, 7), late]).state, 'done'); + }); + + it('Claude: a slash command turn reads working from its first tool call', () => { + const at = '2026-11-30T10:00:00.000Z'; + const slash = JSON.stringify({ type: 'user', timestamp: at, message: { role: 'user', content: 'init\n/init' } }); + const tool = JSON.stringify({ type: 'assistant', timestamp: at, message: { role: 'assistant', content: [{ type: 'tool_use', id: 't', name: 'Read', input: {} }], stop_reason: 'tool_use' } }); + const end = JSON.stringify({ type: 'assistant', timestamp: at, message: { role: 'assistant', content: [{ type: 'text', text: 'done' }], stop_reason: 'end_turn' } }); + assert.equal(fold('claude', [...claude.slice(0, 7), slash]).state, 'done'); + assert.equal(fold('claude', [...claude.slice(0, 7), slash, tool]).state, 'working'); + assert.equal(fold('claude', [...claude.slice(0, 7), slash, tool, end]).state, 'done'); + assert.equal(fold('claude', [...claude, tool]).state, 'done', 'not after an interrupt'); + }); + + it('Codex: task_started / task_complete / turn_aborted', () => { + const codex = fixture('codex-rollout.jsonl'); + const startedAt = codex.findIndex((l) => l.includes('"task_started"')); + const s = fold('codex', codex.slice(0, startedAt + 1)); + assert.equal(s.state, 'working'); + assert.ok(s.turnStartedAt > 0); + assert.equal(fold('codex', codex).state, 'done'); + const aborted = JSON.stringify({ type: 'event_msg', payload: { type: 'turn_aborted', turn_id: 'turn-1' } }); + const a = fold('codex', [...codex.slice(0, startedAt + 1), aborted]); + assert.deepEqual([a.state, a.interrupted], ['done', true]); + }); + + it('picks up the model each agent reports', () => { + assert.equal(lineModel('claude', { type: 'assistant', message: { model: 'claude-x-1' } }), 'claude-x-1'); + assert.equal(lineModel('claude', { type: 'assistant', message: { model: '' } }), null); + assert.equal(lineModel('codex', { type: 'turn_context', payload: { model: 'gpt-x' } }), 'gpt-x'); + assert.equal(lineModel('codex', { type: 'turn_context', payload: { model: 'm'.repeat(500) } }), null); + assert.equal(fold('codex', [JSON.stringify({ type: 'turn_context', payload: { model: 'gpt-x' } })]).model, 'gpt-x'); + }); + + it('ignores malformed lines', () => { + const f = createStatusFold('claude'); + assert.equal(f.line('not json'), false); + assert.equal(f.line('{"type":'), false); + assert.equal(f.status.state, 'done'); + }); +}); + +describe('tab status', () => { + const working = { state: 'working', interrupted: false, model: 'm1', prompt: 'p', turnStartedAt: 1000 }; + + it('starts as an idle session boundary', () => { + const s = statusFields(initialTabStatus(5)); + assert.deepEqual([s.state, s.sessionBoundary, s.stateStartedAt, s.prompt], ['done', true, 5, '']); + assert.deepEqual(s.stateHistory, []); + }); + + it('records each state change once, with history, and drops the boundary after a turn', () => { + const a = nextTabStatus(initialTabStatus(5), working, true, 10); + assert.deepEqual([a.state, a.boundary, a.since, a.turnStartedAt, a.model], ['working', false, 10, 1000, 'm1']); + assert.equal(nextTabStatus(a, working, true, 11), a, 'unchanged → same object (no publish)'); + const b = nextTabStatus(a, { ...working, state: 'done', interrupted: true, turnStartedAt: null }, true, 20); + const f = statusFields(b); + assert.deepEqual([f.state, f.interrupted, f.sessionBoundary, f.stateStartedAt], ['done', true, undefined, 20]); + assert.deepEqual(f.stateHistory.map((h) => h.state), ['done', 'working']); + assert.equal(f.model, 'm1'); + }); + + it('a working transcript with the agent gone reads done (Stop must not reach a bare shell)', () => { + const s = nextTabStatus(initialTabStatus(5), working, false, 10); + assert.equal(s.state, 'done'); + assert.equal(s.interrupted, false); + }); +}); + +describe('watchChatStatus', () => { + it('waits for the transcript, folds it from the start, follows appends and a rewrite', async () => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-phone-status-'))); + const file = join(dir, 's.jsonl'); + let exists = false; const seen = []; + const stop = watchChatStatus({ agent: 'claude', pollMs: 30, resolveFile: async () => (exists ? file : null), onChange: (s) => seen.push(s) }); + try { + const lines = fixture('claude-transcript.jsonl'); + writeFileSync(file, `${lines.slice(0, 2).join('\n')}\n`); exists = true; + await until(() => seen.at(-1)?.state === 'working'); + appendFileSync(file, `${lines.slice(2, 7).join('\n')}\n`); + await until(() => seen.at(-1)?.state === 'done' && seen.at(-1).interrupted === false && seen.length >= 2); + // A half-written line is not read until it is complete. + const last = lines.at(-1); + appendFileSync(file, last.slice(0, 20)); + await new Promise((r) => setTimeout(r, 120)); + assert.equal(seen.at(-1).interrupted, false); + appendFileSync(file, `${last.slice(20)}\n`); + await until(() => seen.at(-1)?.interrupted === true); + writeFileSync(file, `${lines.slice(0, 2).join('\n')}\n`); // replaced: shorter than what was read + await until(() => seen.at(-1)?.state === 'working' && seen.at(-1).interrupted === false); + } finally { stop(); } + }); +}); diff --git a/phone-host/test/chat-transcript.test.mjs b/phone-host/test/chat-transcript.test.mjs new file mode 100644 index 0000000000..1ae0675cca --- /dev/null +++ b/phone-host/test/chat-transcript.test.mjs @@ -0,0 +1,129 @@ +import assert from 'node:assert/strict'; +import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { sanitizeBlock } from '../src/chat-methods.mjs'; +import { claudeProjectSlug, confinedFile, createChatSessions } from '../src/chat-sessions.mjs'; +import { newIncrementalState, readAppended, readTail, watchTranscript } from '../src/chat-transcript.mjs'; + +const fixture = (name) => readFileSync(fileURLToPath(new URL(`./fixtures/${name}`, import.meta.url)), 'utf8'); +const tmp = () => realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-phone-chat-'))); +const write = (text) => { const f = join(tmp(), 'transcript.jsonl'); writeFileSync(f, text); return f; }; +const texts = (m) => m.blocks.map((b) => b.text ?? b.output ?? b.name).join('|'); + +describe('chat view: transcript decoding (Orca wire shape)', () => { + it('decodes a Claude transcript into messages, newest lifecycle first', async () => { + const r = await readTail(write(fixture('claude-transcript.jsonl')), 'claude', { limit: 40 }); + assert.deepEqual(r.messages.map((m) => [m.id, m.role]), [ + ['u-1', 'user'], ['a-1', 'assistant'], ['a-2', 'assistant'], ['u-2', 'tool'], + ['a-3', 'assistant'], ['u-4', 'user'], ['u-5', 'system'], + ], 'the injected isMeta reminder is dropped'); + assert.deepEqual(r.messages[0], { + id: 'u-1', role: 'user', blocks: [{ type: 'text', text: 'List the files here' }], + timestamp: Date.parse('2026-11-30T10:00:00.000Z'), source: 'transcript', + }); + assert.deepEqual(r.messages[2].blocks, [{ type: 'tool-call', name: 'Bash', input: { command: 'ls' }, callId: 'toolu_1' }]); + assert.deepEqual(r.messages[3].blocks, [{ type: 'tool-result', output: 'README.md\nsrc', callId: 'toolu_1' }]); + assert.equal(r.messages[3].parentId, 'a-2'); + assert.equal(texts(r.messages[5]), 'some pasted text', 'a whole pasted block is unwrapped'); + assert.equal(texts(r.messages[6]), 'Conversation interrupted'); + assert.deepEqual(r.lifecycle, { state: 'interrupted', turnId: 'msg_3', timestamp: Date.parse('2026-11-30T10:00:06.000Z') }); + assert.equal(r.hasMore, false); + }); + + it('decodes a Codex rollout once per message (item_completed rows, not response_item duplicates)', async () => { + const r = await readTail(write(fixture('codex-rollout.jsonl')), 'codex', { limit: 40 }); + assert.deepEqual(r.messages.map((m) => [m.role, texts(m)]), [ + ['user', 'What is 2+2?'], ['assistant', 'shell'], ['tool', '4\n'], ['assistant', '2+2 is 4.'], + ]); + assert.equal(r.messages[0].id, 'user-item-1'); + assert.equal(r.messages[1].blocks[0].callId, 'call_1'); + assert.equal(r.messages[1].blocks[0].input, '{"command":["echo","4"]}'); + assert.deepEqual(r.lifecycle, { state: 'completed', turnId: 'turn-1', timestamp: Date.parse('2026-11-30T10:00:03.300Z') }); + }); + + it('pages older history with the byte cursor', async () => { + const f = write(fixture('claude-transcript.jsonl')); + const tail = await readTail(f, 'claude', { limit: 2 }); + assert.deepEqual(tail.messages.map((m) => m.id), ['u-4', 'u-5']); + assert.equal(tail.hasMore, true); + const older = await readTail(f, 'claude', { limit: 3, endOffset: tail.beforeOffset, includeTrailingLine: true }); + assert.deepEqual(older.messages.map((m) => m.id), ['a-2', 'u-2', 'a-3']); + assert.equal(older.hasMore, true); + }); + + it('reads appends incrementally and holds a half-written line until it is complete', async () => { + const lines = fixture('claude-transcript.jsonl').split('\n'); + const f = write(lines.slice(0, 3).join('\n') + '\n'); + const first = await readTail(f, 'claude', { limit: 40 }); + const state = Object.assign(newIncrementalState(), { offset: first.consumedTo, pendingStart: first.consumedTo }); + appendFileSync(f, lines[3].slice(0, 40)); + assert.deepEqual((await readAppended(f, 'claude', state)).messages, []); + appendFileSync(f, `${lines[3].slice(40)}\n`); + const r = await readAppended(f, 'claude', state); + assert.deepEqual(r.messages.map((m) => m.id), ['a-2']); + assert.deepEqual(first.messages.map((m) => m.id), ['u-1', 'a-1']); + }); + + it('watches a file: snapshot, then appends, then a replacement when it is rewritten', async () => { + const lines = fixture('claude-transcript.jsonl').split('\n'); + const f = write(lines.slice(0, 2).join('\n') + '\n'); + const frames = []; + const seen = (n) => new Promise((ok) => { const t = setInterval(() => { if (frames.length >= n) { clearInterval(t); ok(); } }, 10); }); + const stop = watchTranscript({ + filePath: f, agent: 'claude', limit: 40, pollMs: 30, + onSnapshot: (r) => frames.push(['snapshot', r.messages.map((m) => m.id)]), + onAppend: (m) => frames.push(['appended', m.map((x) => x.id)]), + onReplace: (r) => frames.push(['replacement', r.messages.map((m) => m.id)]), + }); + try { + await seen(1); + appendFileSync(f, `${lines[2]}\n`); + await seen(2); + writeFileSync(f, `${lines[1]}\n`); + await seen(3); + } finally { stop(); } + assert.deepEqual(frames, [['snapshot', ['u-1']], ['appended', ['a-1']], ['replacement', ['u-1']]]); + }); + + it('clips long bodies and drops inline image bytes like Orca does for phones', () => { + assert.match(sanitizeBlock({ type: 'tool-result', output: 'x'.repeat(5000) }).output, /\n… \(truncated\)$/); + assert.equal(sanitizeBlock({ type: 'tool-result', output: 'x'.repeat(5000) }).output.length, 4000 + '\n… (truncated)'.length); + assert.deepEqual(sanitizeBlock({ type: 'image-ref', url: 'data:image/png;base64,AAAA', path: '/tmp/a.png' }), { type: 'image-ref', path: '/tmp/a.png' }); + const call = sanitizeBlock({ type: 'tool-call', name: 'Write', input: { content: 'y'.repeat(9000) } }); + assert.ok(call.input.content.length < 4100); + }); +}); + +describe('chat view: transcript confinement', () => { + it('reads only files inside the agent root, after symlinks', async () => { + const root = tmp(); const outside = tmp(); + writeFileSync(join(outside, 'secret.jsonl'), '{}\n'); + mkdirSync(join(root, 'p')); + writeFileSync(join(root, 'p', 'ok.jsonl'), '{}\n'); + symlinkSync(join(outside, 'secret.jsonl'), join(root, 'p', 'link.jsonl')); + assert.equal(await confinedFile(join(root, 'p', 'ok.jsonl'), [root]), join(root, 'p', 'ok.jsonl')); + assert.equal(await confinedFile(join(root, 'p', 'link.jsonl'), [root]), null, 'a symlink out of the root is refused'); + assert.equal(await confinedFile(join(root, 'p', '..', '..', outside.split('/').pop(), 'secret.jsonl'), [root]), null); + assert.equal(await confinedFile(join(outside, 'secret.jsonl'), [root]), null); + }); + + it('finds only sessions this host started, by exact agent and id', async () => { + const claudeRoot = tmp(); const cwd = tmp(); + const sessions = createChatSessions({ roots: { claude: [claudeRoot], codex: [tmp()] } }); + const s = sessions.startClaude({ cwd }); + assert.equal(s.transcriptPath, join(claudeRoot, claudeProjectSlug(cwd), `${s.sessionId}.jsonl`)); + assert.equal(sessions.find('claude', s.sessionId), s); + assert.equal(sessions.find('codex', s.sessionId), null); + assert.equal(sessions.find('claude', '00000000-0000-4000-8000-000000000000'), null); + assert.equal(sessions.find('claude', '../../../etc/passwd'), null); + assert.equal(sessions.find('grok', s.sessionId), null); + assert.equal(await sessions.resolveFile(s), null, 'nothing to read before the agent writes'); + mkdirSync(join(claudeRoot, claudeProjectSlug(cwd))); + const outside = join(tmp(), 'x.jsonl'); writeFileSync(outside, '{}\n'); + symlinkSync(outside, s.transcriptPath); + assert.equal(await sessions.resolveFile(s), null, 'the session file may not point out of the root'); + }); +}); diff --git a/phone-host/test/fixtures/claude-transcript.jsonl b/phone-host/test/fixtures/claude-transcript.jsonl new file mode 100644 index 0000000000..09a80460a5 --- /dev/null +++ b/phone-host/test/fixtures/claude-transcript.jsonl @@ -0,0 +1,9 @@ +{"type":"permission-mode","permissionMode":"default","sessionId":"SESSION"} +{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"List the files here"},"uuid":"u-1","timestamp":"2026-11-30T10:00:00.000Z","sessionId":"SESSION"} +{"parentUuid":"u-1","type":"assistant","message":{"id":"msg_1","role":"assistant","content":[{"type":"thinking","thinking":"I should run ls."}],"stop_reason":null},"uuid":"a-1","timestamp":"2026-11-30T10:00:01.000Z"} +{"parentUuid":"a-1","type":"assistant","message":{"id":"msg_1","role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"}}],"stop_reason":"tool_use"},"uuid":"a-2","timestamp":"2026-11-30T10:00:02.000Z"} +{"parentUuid":"a-2","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_1","type":"tool_result","content":"README.md\nsrc","is_error":false}]},"uuid":"u-2","timestamp":"2026-11-30T10:00:03.000Z"} +{"parentUuid":"u-2","type":"user","isMeta":true,"message":{"role":"user","content":"internal"},"uuid":"u-3","timestamp":"2026-11-30T10:00:03.500Z"} +{"parentUuid":"u-3","type":"assistant","message":{"id":"msg_2","role":"assistant","content":[{"type":"text","text":"There are two entries: README.md and src."}],"stop_reason":"end_turn"},"uuid":"a-3","timestamp":"2026-11-30T10:00:04.000Z"} +{"parentUuid":"a-3","type":"user","message":{"role":"user","content":"\nsome pasted text\n"},"uuid":"u-4","timestamp":"2026-11-30T10:00:05.000Z"} +{"parentUuid":"u-4","type":"user","message":{"role":"user","content":[{"type":"text","text":"[Request interrupted by user]"}]},"interruptedMessageId":"msg_3","uuid":"u-5","timestamp":"2026-11-30T10:00:06.000Z"} diff --git a/phone-host/test/fixtures/codex-rollout.jsonl b/phone-host/test/fixtures/codex-rollout.jsonl new file mode 100644 index 0000000000..0782432ff2 --- /dev/null +++ b/phone-host/test/fixtures/codex-rollout.jsonl @@ -0,0 +1,12 @@ +{"timestamp":"2026-11-30T10:00:00.500Z","type":"session_meta","payload":{"session_id":"SESSION","id":"SESSION","timestamp":"STARTED","cwd":"CWD","originator":"codex-tui","cli_version":"0.172.0","base_instructions":{"text":"You are Codex."}}} +{"timestamp":"2026-11-30T10:00:01.000Z","type":"response_item","payload":{"type":"message","role":"developer","content":[{"type":"input_text","text":""}]}} +{"timestamp":"2026-11-30T10:00:01.100Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"What is 2+2?"}]}} +{"timestamp":"2026-11-30T10:00:01.200Z","type":"event_msg","payload":{"type":"task_started","turn_id":"turn-1"}} +{"timestamp":"2026-11-30T10:00:01.300Z","type":"event_msg","payload":{"type":"item_completed","thread_id":"SESSION","turn_id":"turn-1","item":{"type":"UserMessage","id":"user-item-1","content":[{"type":"text","text":"What is 2+2?"}]}}} +{"timestamp":"2026-11-30T10:00:02.000Z","type":"response_item","payload":{"type":"reasoning","id":"rs_1","summary":[],"content":null}} +{"timestamp":"2026-11-30T10:00:02.100Z","type":"response_item","payload":{"type":"function_call","id":"fc_1","name":"shell","arguments":"{\"command\":[\"echo\",\"4\"]}","call_id":"call_1"}} +{"timestamp":"2026-11-30T10:00:02.200Z","type":"response_item","payload":{"type":"function_call_output","call_id":"call_1","output":{"content":"4\n","success":true}}} +{"timestamp":"2026-11-30T10:00:03.000Z","type":"response_item","payload":{"type":"message","role":"assistant","id":"msg_a1","content":[{"type":"output_text","text":"2+2 is 4."}]}} +{"timestamp":"2026-11-30T10:00:03.100Z","type":"event_msg","payload":{"type":"item_completed","thread_id":"SESSION","turn_id":"turn-1","item":{"type":"AgentMessage","id":"msg_a1","content":[{"type":"Text","text":"2+2 is 4."}]}}} +{"timestamp":"2026-11-30T10:00:03.200Z","type":"event_msg","payload":{"type":"token_count","info":null}} +{"timestamp":"2026-11-30T10:00:03.300Z","type":"event_msg","payload":{"type":"task_complete","turn_id":"turn-1"}} diff --git a/phone-host/test/send-submit.test.mjs b/phone-host/test/send-submit.test.mjs new file mode 100644 index 0000000000..8703a682eb --- /dev/null +++ b/phone-host/test/send-submit.test.mjs @@ -0,0 +1,52 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { createFullMethods, submitDelayMs } from '../src/full-methods.mjs'; + +// A fake terminal manager that records each write and when it happened. +function fakeTerminals() { + const writes = []; + const t = { handle: 'term-1', exited: null }; + return { + writes, + get: (h) => (h === t.handle ? t : null), + write: (_t, s) => { writes.push({ s, at: Date.now() }); return Buffer.byteLength(s); }, + list: () => [], close() {}, closeAll() {}, listen: () => () => {}, scrollback: () => '', resize() {}, + }; +} + +describe('terminal.send submits like Orca', () => { + it('writes Enter separately, after the paste settles, so a TUI agent submits instead of pasting it', async () => { + const terms = fakeTerminals(); + const m = createFullMethods({ terminals: terms, projects: { list: () => [] }, detect: () => [] }); + const r = await m['terminal.send']({ terminal: 'term-1', text: 'Reply with pong', enter: true }); + assert.deepEqual(terms.writes.map((w) => w.s), ['Reply with pong', '\r']); + assert.ok(terms.writes[1].at - terms.writes[0].at >= 450, 'Enter waits for the paste to settle'); + assert.equal(r.send.bytesWritten, 16); + assert.equal(r.send.accepted, true); + }); + + it('keeps sends in order, so a keystroke cannot overtake a delayed Enter', async () => { + const terms = fakeTerminals(); + const m = createFullMethods({ terminals: terms, projects: { list: () => [] }, detect: () => [] }); + const a = m['terminal.send']({ terminal: 'term-1', text: 'first', enter: true }); + const b = m['terminal.send']({ terminal: 'term-1', text: 'x' }); + await Promise.all([a, b]); + assert.deepEqual(terms.writes.map((w) => w.s), ['first', '\r', 'x']); + }); + + it('sends a bare Enter or keystroke at once', async () => { + const terms = fakeTerminals(); + const m = createFullMethods({ terminals: terms, projects: { list: () => [] }, detect: () => [] }); + const t0 = Date.now(); + await m['terminal.send']({ terminal: 'term-1', text: '', enter: true }); + await m['terminal.send']({ terminal: 'term-1', text: 'q' }); + assert.deepEqual(terms.writes.map((w) => w.s), ['\r', 'q']); + assert.ok(Date.now() - t0 < 200); + }); + + it('scales the wait with the paste size, as Orca does', () => { + assert.equal(submitDelayMs('hi', 'linux'), 501); + assert.equal(submitDelayMs('x'.repeat(40960), 'linux'), 511); + assert.equal(submitDelayMs('x'.repeat(6400), 'win32'), 601); + }); +}); diff --git a/scripts/ci-test-excluded.txt b/scripts/ci-test-excluded.txt index c594f50a69..aed23316c1 100644 --- a/scripts/ci-test-excluded.txt +++ b/scripts/ci-test-excluded.txt @@ -128,3 +128,8 @@ plugins/ruflo-console/tests/desktop-rich.test.ts phone-host/test/daemon.test.mjs phone-host/test/full.test.mjs phone-host/test/host.test.mjs +phone-host/test/chat-controls.test.mjs +phone-host/test/chat-host.test.mjs +phone-host/test/chat-status.test.mjs +phone-host/test/chat-transcript.test.mjs +phone-host/test/send-submit.test.mjs