Skip to content

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

feat(chat): opencode in the ⌘M chat view (desktop + phone relay)

review8c851c2aac01
diff --git a/CLAUDE.md b/CLAUDE.md
index ccea29e57..f7547f9dd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1738,7 +1738,7 @@ else, and its context links must keep classifying across restarts).
`PERMISSION_MODE_CAPABLE`, `MODEL_SWITCH_CAPABLE`, with helpers (`hasHooks`,
`canBranch`, `canContextLink`, `canChat`, `canRename`, `canReadTitle`, `hasPermissionMode`, …).
Branch stays **Claude-only** purely by being in only `BRANCH_CAPABLE`. The ⌘M **ChatPanel**
- transcript view (`CHAT_CAPABLE` / `canChat`) is **claude + grok** since 2026-09: grok's
+ transcript view (`CHAT_CAPABLE` / `canChat`) is **claude + grok + opencode** since 2026-09: grok's
`chat_history.jsonl` gets its own reader, and `chat:read-transcript` routes by agent. That list had
to be SPLIT to do it — `CHAT_CAPABLE` carried two facts that coincided while claude was its only
member ("we can render this" and "claude's resolver can locate and parse this file"), and the
@@ -1873,6 +1873,27 @@ else, and its context links must keep classifying across restarts).
cost before the backgrounding. Full picture,
limits (permission prompt and ESC fire no hook) and the device checklist:
**`docs/antigravity-agent.md`**.
+- **opencode in the ⌘M chat view** (2026-09-28, opencode 1.18.25 measured) — opencode has NO
+ transcript file (SQLite since 1.18; that database also holds its account tokens and is never
+ opened), so `readChatTranscript` routes `capabilityAgentId(agentId) === 'opencode'` to
+ `core/opencode-chat.ts`, which runs `opencode export <sessionId>` (argv only, no flag an older
+ yargs-strict CLI might refuse) and parses the one JSON document into claude's `ChatMessage` shape:
+ user/assistant text, tool chips (arg by an opencode key order, result = 3 lines / 500 units,
+ `Error: …` on a failed call), `[name] message` for an errored turn, compaction/subtask chips,
+ `at` from `time.created`, `model`/`effort` from the newest assistant's `modelID`/`variant`.
+ Reasoning, `synthetic`/`ignored` text, file/agent parts and step bookkeeping are dropped;
+ unmappable shapes are skipped and counted. **One page, always** (`olderCursor: null`, newest
+ messages within 5 MB): there are no byte offsets to page by. Refusals: no/unsafe session id runs
+ nothing (a bare `opencode export` opens a picker over the NEWEST sessions — someone else's); an
+ export whose `info.id` is another session is `unreadable`; only `Session not found: <id>` with
+ exit 1 and empty stdout is a clean miss. **Remote (SSH) nodes are refused** (`unreadable`, no
+ export runs) — their sessions are in the host's database and there is no remote leg yet; the
+ panel's copy names both causes an opencode `unreadable` can have. One export costs 1.0–1.7 s and
+ ~320 MB, so `createOpencodeExportGate` runs at most one per session (starts ≥ 2 s apart, a caller
+ arriving mid-run gets a FRESH export, never a cached one) and two in total. Plan/question answer
+ cards stay claude-only (no `body`/`questions` on opencode's `question` tool). Desktop and Server
+ Edition both serve it (core handler); the phone gets it over the relay `chat.page` for free.
+ Fixtures + the exact rules for the iOS port: `src/shared/chat-fixtures/opencode/README.md`.
- **Gemini + codex parity** (2026-08-09) — brought both up to grok's level in the lists above. Unlike
grok, **both CLIs are installed** and gemini **ships its own hook reference**
(`/usr/lib/node_modules/@google/gemini-cli/bundle/docs/hooks/reference.md`), so almost every fact is
diff --git a/src/core/context-link.ts b/src/core/context-link.ts
index 3cf26539d..fc2738e1a 100644
--- a/src/core/context-link.ts
+++ b/src/core/context-link.ts
@@ -21,7 +21,8 @@ import { platform } from './platform'
import { IPC } from '../shared/ipc'
import type { ContextLinkInfo, ContextLinkMap } from '../shared/types'
import { type PtyManager } from './pty-manager'
-import { directExecutableInvocation, findInLoginPath } from './exec-path'
+import { findInLoginPath } from './exec-path'
+import { isSafeOpencodeSessionId, runOpencodeExportAt } from './opencode-export'
import { TMUX_SOCKET } from './tmux-naming'
import {
buildContextShimScript,
@@ -222,42 +223,16 @@ async function fetchTranscript(node: LinkDocEntry): Promise<string | null> {
}
}
-/** An export names ONE provider session. The id reaches us from a hook payload, so it is re-checked
- * here, where it becomes an argv entry: `directExecutableInvocation` stops it being read as shell
- * syntax, and nothing but this stops a leading `-` being read by opencode as an option. */
-const SAFE_OPENCODE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/
+// The id check and the export bounds live in `opencode-export.ts`, shared with the ⌘M chat view's
+// reader. Re-exported so this module's callers are unchanged.
+export { isSafeOpencodeSessionId } from './opencode-export'
-export function isSafeOpencodeSessionId(sessionId: string): boolean {
- return SAFE_OPENCODE_SESSION_ID.test(sessionId)
-}
-
-// A whole conversation comes back on stdout. execFile's default 1 MiB buffer turns a long session
-// into an error, which reads here as "no transcript"; and with no timeout a wedged CLI holds the
-// linked agent's read open for good.
-const OPENCODE_EXPORT_MAX_BYTES = 32 * 1024 * 1024
+// With no timeout a wedged CLI holds the linked agent's read open for good.
const OPENCODE_EXPORT_TIMEOUT_MS = 60_000
export async function opencodeExportAt(bin: string, sessionId: string): Promise<string | null> {
- const invocation = directExecutableInvocation(bin, ['export', sessionId])
- if (!invocation) return null
- try {
- const { execFile } = await import('node:child_process')
- return await new Promise<string | null>((resolve) => {
- execFile(
- invocation.executable,
- invocation.args,
- {
- ...invocation.options,
- encoding: 'utf-8',
- maxBuffer: OPENCODE_EXPORT_MAX_BYTES,
- timeout: OPENCODE_EXPORT_TIMEOUT_MS
- },
- (err, stdout) => resolve(err ? null : stdout)
- )
- })
- } catch {
- return null
- }
+ const out = await runOpencodeExportAt(bin, sessionId, OPENCODE_EXPORT_TIMEOUT_MS)
+ return out.ok ? out.stdout : null
}
async function fetchOpencodeExport(node: LinkDocEntry): Promise<string | null> {
diff --git a/src/core/opencode-chat.fixtures.test.ts b/src/core/opencode-chat.fixtures.test.ts
new file mode 100644
index 000000000..808fad036
--- /dev/null
+++ b/src/core/opencode-chat.fixtures.test.ts
@@ -0,0 +1,279 @@
+// Golden fixtures for the opencode leg of the chat view (src/shared/chat-fixtures/opencode/). The
+// TS implementation is the reference; `nodeterm-ios` keeps a byte-identical copy of the directory and
+// its Swift port must reproduce every `expected/*.json` from the same `inputs/*.json`.
+//
+// Regenerate (never in CI):
+// UPDATE_CHAT_FIXTURES=1 npx vitest run src/core/opencode-chat.fixtures.test.ts
+//
+// Every input is SYNTHETIC: an `opencode export` document built from the schema measured on
+// opencode 1.18.25 (see core/opencode-chat.ts). None is a slice of a real session.
+import fs from 'fs'
+import path from 'path'
+import { describe, expect, it } from 'vitest'
+import { parseOpencodeExport } from './opencode-chat'
+import { readChatTranscript } from './transcript-ipc'
+
+const UPDATE = process.env.UPDATE_CHAT_FIXTURES === '1'
+if (UPDATE && process.env.CI) throw new Error('UPDATE_CHAT_FIXTURES must not be set in CI')
+
+const DIR = path.join(__dirname, '../shared/chat-fixtures/opencode')
+const fixture = (rel: string): string => path.join(DIR, rel)
+
+/** The session every input is an export of — the Swift port passes the same id. */
+const SID = 'ses_0a1b2c3d4ffeSynthetic000001'
+const T0 = 1_780_000_000_000
+const TAIL_BYTES = 262144
+
+let seq = 0
+const pid = (): string => `prt_fixture${String(++seq).padStart(4, '0')}`
+const tick = (id: string): number => T0 + Number(id.replace(/\D/g, '')) * 1000
+
+const exportDoc = (messages: unknown[], id: string = SID): string =>
+ JSON.stringify(
+ {
+ info: {
+ id,
+ slug: 'quiet-harbor',
+ projectID: 'prj_fixture',
+ directory: '/srv/demo',
+ path: '',
+ title: 'Fixture session',
+ agent: 'build',
+ model: { id: 'demo-model', providerID: 'opencode' },
+ version: '1.18.25',
+ summary: { additions: 0, deletions: 0, files: 0 },
+ cost: 0,
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
+ time: { created: T0, updated: T0 }
+ },
+ messages
+ },
+ null,
+ 2
+ ) + '\n'
+
+const userMsg = (id: string, parts: unknown[], extra: Record<string, unknown> = {}) => ({
+ info: {
+ role: 'user',
+ time: { created: tick(id) },
+ agent: 'build',
+ model: { providerID: 'opencode', modelID: 'demo-model' },
+ summary: { diffs: [] },
+ id,
+ sessionID: SID,
+ ...extra
+ },
+ parts
+})
+const asstMsg = (id: string, parts: unknown[], extra: Record<string, unknown> = {}) => ({
+ info: {
+ parentID: 'msg_parent',
+ role: 'assistant',
+ mode: 'build',
+ agent: 'build',
+ path: { cwd: '/srv/demo', root: '/srv/demo' },
+ cost: 0,
+ tokens: { total: 20, input: 12, output: 8, reasoning: 0, cache: { write: 0, read: 0 } },
+ modelID: 'demo-model',
+ providerID: 'opencode',
+ time: { created: tick(id), completed: tick(id) + 500 },
+ finish: 'stop',
+ id,
+ sessionID: SID,
+ ...extra
+ },
+ parts
+})
+const part = (type: string, fields: Record<string, unknown> = {}) => ({ type, ...fields, id: pid(), sessionID: SID, messageID: 'msg_fixture' })
+const textPart = (text: string, fields: Record<string, unknown> = {}) => part('text', { text, ...fields })
+const stepStart = () => part('step-start', { snapshot: '4b825dc642cb6eb9a060e54bf8d69288fbee4904' })
+const stepFinish = (reason = 'stop') =>
+ part('step-finish', { reason, snapshot: '4b825dc642cb6eb9a060e54bf8d69288fbee4904', cost: 0, tokens: { total: 20, input: 12, output: 8, reasoning: 0, cache: { write: 0, read: 0 } } })
+const toolPart = (tool: string | undefined, state: Record<string, unknown>) =>
+ part('tool', { ...(tool === undefined ? {} : { tool }), callID: `call_fixture${seq}`, state })
+const done = (input: Record<string, unknown>, output: string, title = 'Done') => ({
+ status: 'completed',
+ input,
+ output,
+ title,
+ metadata: {},
+ time: { start: T0, end: T0 + 1 }
+})
+
+const lorem = (n: number): string =>
+ Array.from({ length: n }, (_, i) => ['lorem', 'ipsum', 'dolor', 'sit', 'amet'][i % 5]).join(' ')
+
+const INPUTS: Record<string, string> = {
+ // User/assistant text: markdown, two text blocks in one message, non-ASCII, `at` from
+ // `time.created`. Reasoning and step bookkeeping are dropped without being counted.
+ turns: exportDoc([
+ userMsg('msg_1', [textPart('Explain the **retry** policy.\n\n- one\n- two')]),
+ asstMsg('msg_2', [
+ stepStart(),
+ part('reasoning', { text: 'The user wants the retry policy.', time: { start: T0, end: T0 + 1 } }),
+ textPart('## Retry\n\nThree attempts, then a backoff:\n\n```ts\nconst n = 3\n```'),
+ textPart('Second block — ğüşçöı 😀'),
+ stepFinish()
+ ], { variant: 'high' }),
+ userMsg('msg_3', [textPart('Thanks!')]),
+ asstMsg('msg_4', [stepStart(), part('reasoning', { text: 'thinking only', time: { start: T0 } }), stepFinish()])
+ ]),
+ // Tool parts in every state, the arg key order, the question tool (no card fields), the title
+ // fallback, a missing tool name, and the arg / result caps.
+ tools: exportDoc([
+ userMsg('msg_1', [textPart('Look around the repo.')]),
+ asstMsg('msg_2', [
+ stepStart(),
+ toolPart('bash', done({ command: 'ls -la', description: 'List files' }, 'total 8\ndrwxr-xr-x a\ndrwxr-xr-x b\n-rw-r--r-- c', 'List files')),
+ toolPart('read', done({ filePath: '/srv/demo/src/app.ts' }, lorem(150), 'src/app.ts')),
+ toolPart('grep', done({ pattern: 'TODO', path: '/srv/demo/src' }, 'Found 2 matches', 'TODO')),
+ toolPart('edit', { status: 'error', input: { filePath: '/srv/demo/src/app.ts', oldString: 'a', newString: 'b' }, error: 'oldString not found in content\nMake the match unique.', time: { start: T0, end: T0 + 1 } }),
+ toolPart('webfetch', { status: 'running', input: { url: 'https://example.test/docs' }, title: 'Fetching', time: { start: T0 } }),
+ toolPart('bash', { status: 'pending', input: {}, raw: '{"comm' }),
+ toolPart('todowrite', done({ todos: [{ content: 'x', status: 'pending', priority: 'high' }] }, '[]', '1 todo')),
+ toolPart('question', done(
+ { questions: [{ question: 'Which colour should the badge be?', header: 'Colour', options: [{ label: 'Red', description: 'warm' }, { label: 'Blue', description: 'cool' }] }] },
+ 'User has answered your questions: "Which colour should the badge be?"="Blue".',
+ 'Asked 1 question'
+ )),
+ toolPart(undefined, { status: 'running', input: {}, time: { start: T0 } }),
+ toolPart('bash', done({ command: 'echo ' + 'z'.repeat(250) }, '')),
+ stepFinish('tool-calls')
+ ], { finish: 'tool-calls' }),
+ asstMsg('msg_3', [stepStart(), textPart('Done looking.'), stepFinish()])
+ ]),
+ // Text the speaker did not type: `synthetic` and `ignored` text, file attachments and @-agent
+ // mentions are dropped; a tool part inside a USER message becomes an assistant-side chip.
+ 'harness-text': exportDoc([
+ userMsg('msg_1', [
+ textPart('Review @src/app.ts please'),
+ part('file', { mime: 'text/plain', filename: 'app.ts', url: 'file:///srv/demo/src/app.ts', source: { type: 'file', path: 'src/app.ts', text: { value: '@src/app.ts', start: 7, end: 18 } } }),
+ textPart('Called the Read tool with the following input: {"filePath":"/srv/demo/src/app.ts"}', { synthetic: true }),
+ textPart('<file>\n00001| export {}\n</file>', { synthetic: true }),
+ part('agent', { name: 'plan', source: { value: '@plan', start: 0, end: 5 } }),
+ textPart('not for the model', { ignored: true })
+ ]),
+ userMsg('msg_2', [textPart('The following tool was executed by the user', { synthetic: true })]),
+ userMsg('msg_3', [
+ textPart('run the tests'),
+ toolPart('bash', done({ command: 'npm test' }, 'ok 12 tests', 'npm test'))
+ ]),
+ asstMsg('msg_4', [stepStart(), textPart('Looks fine.'), stepFinish()])
+ ]),
+ // An assistant message's `error`: after whatever text it wrote, `[name] message`; `[name]` alone
+ // when the error carries no message; a malformed error is skipped and counted. `retry` parts drop.
+ errors: exportDoc([
+ userMsg('msg_1', [textPart('Go.')]),
+ asstMsg('msg_2', [stepStart(), textPart('Starting on it'), part('retry', { attempt: 1, error: { name: 'APIError', data: { message: 'Overloaded', isRetryable: true } }, time: { created: T0 } })], {
+ error: { name: 'MessageAbortedError', data: { message: 'The operation was aborted.' } },
+ finish: undefined
+ }),
+ asstMsg('msg_3', [], { error: { name: 'APIError', data: { message: 'Rate limit exceeded', statusCode: 429, isRetryable: true } } }),
+ asstMsg('msg_4', [], { error: { name: 'MessageOutputLengthError', data: {} } }),
+ asstMsg('msg_5', [], { error: { name: 'ProviderAuthError', data: { providerID: 'opencode', message: ' Invalid API key ' } } }),
+ asstMsg('msg_6', [textPart('still here')], { error: 'not an object' })
+ ]),
+ // A compaction (auto and manual) is an assistant-side chip; the summary opencode writes after it
+ // (`summary: true`) is ordinary assistant text; a subtask part is a `task` chip.
+ 'compaction-subtask': exportDoc([
+ userMsg('msg_1', [part('compaction', { auto: true })]),
+ asstMsg('msg_2', [stepStart(), textPart('## Summary\n\nWe fixed the retry policy.'), stepFinish()], { summary: true, mode: 'compaction', agent: 'compaction' }),
+ userMsg('msg_3', [part('compaction', { auto: false, overflow: true })]),
+ userMsg('msg_4', [
+ textPart('/review'),
+ part('subtask', { prompt: 'Review the staged changes in full.', description: 'Review staged changes', agent: 'general', command: 'review' })
+ ])
+ ]),
+ // Shapes that cannot be mapped are skipped and COUNTED — never rendered, never a crash. A message
+ // filed under another session is one of them.
+ unmappable: exportDoc([
+ 'a string where a message should be',
+ null,
+ { parts: [textPart('no info')] },
+ { info: { role: 'system', id: 'msg_s', sessionID: SID }, parts: [textPart('unknown role')] },
+ userMsg('msg_1', 'parts is not an array' as unknown as unknown[]),
+ { info: { ...userMsg('msg_2', []).info, sessionID: 'ses_someoneElse00000000000' }, parts: [textPart('SOMEONE ELSE PRIVATE')] },
+ userMsg('msg_3', [textPart('kept'), 7, { no: 'type' }, part('future-kind', { secret: 'x' }), part('text', { text: 42 })]),
+ asstMsg('msg_4', [part('tool', { tool: 'bash', callID: 'c', state: 'not an object' })])
+ ]),
+ // The newest assistant message answers `model` and `effort` together; its missing `variant` is
+ // absent, never carried from the older message.
+ 'model-no-carry': exportDoc([
+ asstMsg('msg_1', [textPart('older')], { modelID: 'older-model', variant: 'max' }),
+ userMsg('msg_2', [textPart('next')], { model: { providerID: 'opencode', modelID: 'user-picked', variant: 'low' } }),
+ asstMsg('msg_3', [textPart('newest')], { modelID: 'newest-model' })
+ ]),
+ // The 100-unit cap counts UTF-16 code units: a 101-unit model is absent, a 100-unit variant kept.
+ 'model-utf16': exportDoc([asstMsg('msg_1', [textPart('x')], { modelID: '🧪'.repeat(50) + 'm', variant: '🧪'.repeat(50) })]),
+ // An export whose `info.id` is another session: nothing of it is shown, and the page is unreadable.
+ 'foreign-session': exportDoc([userMsg('msg_1', [textPart('SOMEONE ELSE PRIVATE')])], 'ses_someoneElse00000000000')
+}
+
+const serialize = (x: unknown): string => JSON.stringify(x, null, 2) + '\n'
+
+function golden(rel: string, content: string): void {
+ const p = fixture(rel)
+ if (UPDATE) {
+ fs.mkdirSync(path.dirname(p), { recursive: true })
+ fs.writeFileSync(p, content)
+ return
+ }
+ expect(fs.existsSync(p), `${rel} is missing — run UPDATE_CHAT_FIXTURES=1`).toBe(true)
+ expect(fs.readFileSync(p, 'utf8').replace(/\r\n/g, '\n')).toBe(content)
+}
+
+const listing = (dir: string): string[] => (fs.existsSync(fixture(dir)) ? fs.readdirSync(fixture(dir)).sort() : [])
+
+describe('opencode chat golden fixtures', () => {
+ it('inputs/ and expected/ hold exactly the generated set', () => {
+ const inputs = Object.keys(INPUTS).map((n) => `${n}.json`).sort()
+ const expected = Object.keys(INPUTS).map((n) => `${n}.json`).sort()
+ if (UPDATE) {
+ for (const f of listing('inputs')) if (!inputs.includes(f)) fs.rmSync(fixture(`inputs/${f}`))
+ for (const f of listing('expected')) if (!expected.includes(f)) fs.rmSync(fixture(`expected/${f}`))
+ return
+ }
+ expect(listing('inputs')).toEqual(inputs)
+ expect(listing('expected')).toEqual(expected)
+ })
+
+ for (const [name, raw] of Object.entries(INPUTS)) {
+ it(`${name}: parse + served page match expected/${name}.json`, async () => {
+ golden(`inputs/${name}.json`, raw)
+ const input = UPDATE ? raw : fs.readFileSync(fixture(`inputs/${name}.json`), 'utf8').replace(/\r\n/g, '\n')
+ const parse = parseOpencodeExport(input, SID)
+ // The served page is the real producer's answer (`readChatTranscript` → `readOpencodeChat`),
+ // so the fixture pins the wire, not a second implementation of it.
+ const page = await readChatTranscript(
+ { sessionId: SID, agentId: 'opencode' },
+ { maxBytes: TAIL_BYTES },
+ { opencodeExport: async () => ({ ok: true, stdout: input }) }
+ )
+ golden(`expected/${name}.json`, serialize({ sessionId: SID, parse, page }))
+ })
+ }
+
+ // What the boundary fixtures exist to exercise — pinned so a builder edit cannot quietly turn
+ // them into ordinary files.
+ it('foreign-session: the parse is refused and the page is unreadable with nothing in it', async () => {
+ const e = JSON.parse(fs.readFileSync(fixture('expected/foreign-session.json'), 'utf8'))
+ expect(e.parse).toBeNull()
+ expect(e.page).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
+ })
+
+ it('unmappable: every bad shape is counted and none of it is rendered', () => {
+ const e = JSON.parse(fs.readFileSync(fixture('expected/unmappable.json'), 'utf8'))
+ expect(e.parse.skipped).toBe(11) // 3 bad entries, a system role, non-array parts, a foreign session, 4 bad parts, a stateless tool
+ expect(JSON.stringify(e.page)).not.toContain('SOMEONE ELSE PRIVATE')
+ expect(e.page.messages).toEqual([{ role: 'user', parts: [{ kind: 'text', text: 'kept' }], at: T0 + 3000 }])
+ })
+
+ it('model-utf16: 101 UTF-16 units is over the cap, 100 is not', () => {
+ const input = JSON.parse(fs.readFileSync(fixture('inputs/model-utf16.json'), 'utf8'))
+ expect(input.messages[0].info.modelID.length).toBe(101)
+ expect(input.messages[0].info.variant.length).toBe(100)
+ const e = JSON.parse(fs.readFileSync(fixture('expected/model-utf16.json'), 'utf8'))
+ expect('model' in e.parse).toBe(false)
+ expect(e.parse.effort).toBe('🧪'.repeat(50))
+ })
+})
diff --git a/src/core/opencode-chat.test.ts b/src/core/opencode-chat.test.ts
new file mode 100644
index 000000000..6db647d83
--- /dev/null
+++ b/src/core/opencode-chat.test.ts
@@ -0,0 +1,620 @@
+// opencode's conversation as the ⌘M panel's structured messages, and the read that produces it.
+//
+// Every record shape below is SYNTHETIC, built from the schema measured on opencode 1.18.25 (the
+// `opencode export` document: `{info, messages:[{info, parts}]}`, see opencode-chat.ts). None of
+// it is a slice of a real session.
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ createOpencodeExportGate,
+ newestWithinBytes,
+ opencodeToolArg,
+ parseOpencodeExport
+} from './opencode-chat'
+import { readChatTranscript, type TranscriptIpcDeps } from './transcript-ipc'
+import type { OpencodeExportOutcome } from './opencode-export'
+import { setCustomAgentBaseResolver } from '../shared/agents/config'
+import type { ChatMessage } from '../shared/types'
+
+const SID = 'ses_0a1b2c3d4ffeSynthetic000001'
+const T0 = 1_780_000_000_000
+
+let n = 0
+const pid = () => `prt_${String(++n).padStart(4, '0')}`
+const doc = (messages: unknown[], id: string = SID): string =>
+ JSON.stringify(
+ {
+ info: { id, slug: 'demo', projectID: 'p1', directory: '/srv/demo', title: 't', version: '1.18.25', time: { created: T0, updated: T0 } },
+ messages
+ },
+ null,
+ 2
+ ) + '\n'
+const user = (id: string, parts: unknown[], extra: Record<string, unknown> = {}) => ({
+ info: {
+ role: 'user',
+ time: { created: T0 + Number(id.replace(/\D/g, '')) * 1000 },
+ agent: 'build',
+ model: { providerID: 'opencode', modelID: 'demo-model' },
+ summary: { diffs: [] },
+ id,
+ sessionID: SID,
+ ...extra
+ },
+ parts
+})
+const asst = (id: string, parts: unknown[], extra: Record<string, unknown> = {}) => ({
+ info: {
+ parentID: 'msg_u',
+ role: 'assistant',
+ mode: 'build',
+ agent: 'build',
+ path: { cwd: '/srv/demo', root: '/srv/demo' },
+ cost: 0,
+ tokens: { total: 10, input: 5, output: 5, reasoning: 0, cache: { write: 0, read: 0 } },
+ modelID: 'demo-model',
+ providerID: 'opencode',
+ time: { created: T0 + Number(id.replace(/\D/g, '')) * 1000, completed: T0 + 1 },
+ finish: 'stop',
+ id,
+ sessionID: SID,
+ ...extra
+ },
+ parts
+})
+const part = (type: string, fields: Record<string, unknown> = {}) => ({ type, ...fields, id: pid(), sessionID: SID, messageID: 'msg_x' })
+const text = (t: string, fields: Record<string, unknown> = {}) => part('text', { text: t, ...fields })
+const tool = (name: string | undefined, state: Record<string, unknown>) =>
+ part('tool', { ...(name === undefined ? {} : { tool: name }), callID: `call_${n}`, state })
+const bookkeeping = () => [
+ part('step-start', { snapshot: 'abc' }),
+ part('step-finish', { reason: 'stop', cost: 0, tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } } })
+]
+
+const parse = (raw: string) => {
+ const r = parseOpencodeExport(raw, SID)
+ if (!r) throw new Error('expected a parse')
+ return r
+}
+
+describe('parseOpencodeExport — turns', () => {
+ it('maps user and assistant text into bubbles, stamped with opencode\'s own created time', () => {
+ const r = parse(
+ doc([
+ user('msg_1', [text('merhaba — ğüşçöı')]),
+ asst('msg_2', [...bookkeeping().slice(0, 1), text('selam'), text('ikinci blok'), ...bookkeeping().slice(1)])
+ ])
+ )
+ expect(r.messages).toEqual([
+ { role: 'user', parts: [{ kind: 'text', text: 'merhaba — ğüşçöı' }], at: T0 + 1000 },
+ {
+ role: 'assistant',
+ parts: [
+ { kind: 'text', text: 'selam' },
+ { kind: 'text', text: 'ikinci blok' }
+ ],
+ at: T0 + 2000
+ }
+ ])
+ expect(r.skipped).toBe(0)
+ })
+
+ it('never states a time it was not given', () => {
+ const m = user('msg_1', [text('hi')])
+ delete (m.info as { time?: unknown }).time
+ expect(parse(doc([m])).messages[0]).not.toHaveProperty('at')
+ })
+
+ it('drops reasoning and bookkeeping parts on purpose — and does not count them as unmappable', () => {
+ const r = parse(
+ doc([
+ asst('msg_1', [
+ ...bookkeeping(),
+ part('reasoning', { text: 'private thinking', time: { start: 1, end: 2 } }),
+ part('snapshot', { snapshot: 'h' }),
+ part('patch', { hash: 'h', files: ['/srv/demo/a.ts'] }),
+ part('retry', { attempt: 1, error: { name: 'APIError', data: { message: 'x', isRetryable: true } }, time: { created: 1 } }),
+ part('agent', { name: 'plan' }),
+ part('file', { mime: 'image/png', url: 'data:image/png;base64,AAAA', filename: 'shot.png' })
+ ]),
+ asst('msg_2', [part('reasoning', { text: 'only thinking', time: { start: 1 } })])
+ ])
+ )
+ expect(r.messages).toEqual([])
+ expect(r.skipped).toBe(0)
+ expect(JSON.stringify(r)).not.toContain('private thinking')
+ })
+
+ it('never renders harness text as something the human said', () => {
+ // opencode injects `synthetic` text into USER messages (a file an @-mention read in full, the
+ // "tool was executed by the user" note) and marks some text `ignored`. Neither was typed.
+ const r = parse(
+ doc([
+ user('msg_1', [text('typed by the human'), text('Called the Read tool with …', { synthetic: true }), text('x', { ignored: true })]),
+ user('msg_2', [text('only injected', { synthetic: true })]),
+ asst('msg_3', [text('synthetic assistant note', { synthetic: true }), text('real answer')])
+ ])
+ )
+ expect(r.messages).toEqual([
+ { role: 'user', parts: [{ kind: 'text', text: 'typed by the human' }], at: T0 + 1000 },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'real answer' }], at: T0 + 3000 }
+ ])
+ })
+
+ it('keeps an empty text part out of the thread', () => {
+ expect(parse(doc([user('msg_1', [text('')]), asst('msg_2', [text('')])])).messages).toEqual([])
+ })
+})
+
+describe('parseOpencodeExport — tools', () => {
+ it('completed: the output summarized like claude\'s tool results (three lines, 500 units)', () => {
+ const out = ['line one', 'line two', 'line three', 'line four'].join('\n')
+ const long = 'y'.repeat(600)
+ const r = parse(
+ doc([
+ asst('msg_1', [
+ tool('bash', { status: 'completed', input: { command: 'ls -la', description: 'List' }, output: out, title: 'List', metadata: {}, time: { start: 1, end: 2 } }),
+ tool('read', { status: 'completed', input: { filePath: '/srv/demo/a.ts' }, output: long, title: 'a.ts', metadata: {}, time: { start: 1, end: 2 } })
+ ])
+ ])
+ )
+ expect(r.messages[0].parts).toEqual([
+ { kind: 'tool', name: 'bash', arg: 'ls -la', result: 'line one line two line three' },
+ { kind: 'tool', name: 'read', arg: '/srv/demo/a.ts', result: 'y'.repeat(500) }
+ ])
+ })
+
+ it('error: the tool\'s error text becomes its result, marked as an error', () => {
+ const r = parse(
+ doc([asst('msg_1', [tool('edit', { status: 'error', input: { filePath: '/srv/demo/b.ts' }, error: 'oldString not found\nsecond', time: { start: 1, end: 2 } })])])
+ )
+ expect(r.messages[0].parts).toEqual([{ kind: 'tool', name: 'edit', arg: '/srv/demo/b.ts', result: 'Error: oldString not found second' }])
+ })
+
+ it('pending and running calls have no result yet — the key is absent, never empty', () => {
+ const r = parse(
+ doc([
+ asst('msg_1', [
+ tool('bash', { status: 'pending', input: {}, raw: '{"comm' }),
+ tool('webfetch', { status: 'running', input: { url: 'https://example.test/a' }, title: 'Fetching', time: { start: 1 } })
+ ])
+ ])
+ )
+ expect(r.messages[0].parts).toEqual([
+ { kind: 'tool', name: 'bash', arg: '' },
+ { kind: 'tool', name: 'webfetch', arg: 'https://example.test/a' }
+ ])
+ for (const p of r.messages[0].parts) expect(p).not.toHaveProperty('result')
+ })
+
+ it('never carries claude-only card fields: no body, questions or id on any tool part', () => {
+ // opencode's `question` tool is an AskUserQuestion look-alike, but plan / question answer cards
+ // are claude-only: a `questions` field would be read as a card to answer.
+ const r = parse(
+ doc([
+ asst('msg_1', [
+ tool('question', {
+ status: 'completed',
+ input: { questions: [{ question: 'Which colour?', header: 'Colour', options: [{ label: 'Red', description: 'r' }] }] },
+ output: 'User answered: Red',
+ title: 'Asked 1 question',
+ metadata: { answers: [['Red']], truncated: false },
+ time: { start: 1, end: 2 }
+ })
+ ])
+ ])
+ )
+ const p = r.messages[0].parts[0]
+ expect(p).toEqual({ kind: 'tool', name: 'question', arg: 'Which colour?', result: 'User answered: Red' })
+ expect(p).not.toHaveProperty('body')
+ expect(p).not.toHaveProperty('questions')
+ expect(p).not.toHaveProperty('id')
+ })
+
+ it('a tool part with no tool name is still a tool, never raw JSON', () => {
+ const r = parse(doc([asst('msg_1', [tool(undefined, { status: 'running', input: {}, time: { start: 1 } })])]))
+ expect(r.messages[0].parts).toEqual([{ kind: 'tool', name: 'tool', arg: '' }])
+ })
+})
+
+describe('opencodeToolArg', () => {
+ it('picks the meaningful input of each builtin tool', () => {
+ expect(opencodeToolArg({ command: 'npm test', description: 'Run tests' })).toBe('npm test')
+ expect(opencodeToolArg({ filePath: '/a/b.ts', oldString: 'x', newString: 'y' })).toBe('/a/b.ts')
+ expect(opencodeToolArg({ file_path: '/a/c.ts' })).toBe('/a/c.ts')
+ expect(opencodeToolArg({ pattern: 'TODO', path: '/a' })).toBe('TODO') // grep/glob: the pattern
+ expect(opencodeToolArg({ path: '/a' })).toBe('/a') // list
+ expect(opencodeToolArg({ url: 'https://x.test' })).toBe('https://x.test')
+ expect(opencodeToolArg({ query: 'effect schema' })).toBe('effect schema')
+ expect(opencodeToolArg({ description: 'Explore', prompt: 'long…', subagent_type: 'general' })).toBe('Explore')
+ expect(opencodeToolArg({ prompt: 'p' })).toBe('p')
+ expect(opencodeToolArg({ name: 'my-skill' })).toBe('my-skill')
+ expect(opencodeToolArg({ questions: [{ question: 'Q1?' }, { question: 'Q2?' }] })).toBe('Q1?')
+ })
+
+ it('falls back to the title opencode wrote, then to nothing', () => {
+ expect(opencodeToolArg({ todos: [] }, 'Updated 3 todos')).toBe('Updated 3 todos')
+ expect(opencodeToolArg({ todos: [] })).toBe('')
+ expect(opencodeToolArg(undefined, undefined)).toBe('')
+ expect(opencodeToolArg({ command: 42 }, 'Title')).toBe('Title') // a non-string key never renders
+ })
+
+ it('caps at 200 UTF-16 units, like every other tool arg', () => {
+ expect(opencodeToolArg({ command: 'z'.repeat(250) })).toBe('z'.repeat(200))
+ expect(opencodeToolArg({}, 't'.repeat(250))).toBe('t'.repeat(200))
+ })
+})
+
+describe('parseOpencodeExport — errors, compaction, subtasks', () => {
+ it('an assistant turn that failed says so, after whatever it managed to write', () => {
+ const r = parse(
+ doc([
+ asst('msg_1', [text('partial')], { error: { name: 'MessageAbortedError', data: { message: 'The operation was aborted.' } } }),
+ asst('msg_2', [], { error: { name: 'APIError', data: { message: 'Rate limited', isRetryable: true, statusCode: 429 } } }),
+ asst('msg_3', [], { error: { name: 'MessageOutputLengthError', data: {} } }),
+ asst('msg_4', [], { error: 'not an object' })
+ ])
+ )
+ expect(r.messages.map((m) => m.parts)).toEqual([
+ [
+ { kind: 'text', text: 'partial' },
+ { kind: 'text', text: '[MessageAbortedError] The operation was aborted.' }
+ ],
+ [{ kind: 'text', text: '[APIError] Rate limited' }],
+ [{ kind: 'text', text: '[MessageOutputLengthError]' }]
+ ])
+ expect(r.skipped).toBe(1) // the malformed error object
+ })
+
+ it('a compaction is a chip, and the summary opencode wrote is the assistant\'s text', () => {
+ const r = parse(
+ doc([
+ user('msg_1', [part('compaction', { auto: true })]),
+ asst('msg_2', [text('Summary of the conversation so far.')], { summary: true }),
+ user('msg_3', [part('compaction', { auto: false, overflow: true })])
+ ])
+ )
+ expect(r.messages).toEqual([
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'compaction', arg: 'auto' }], at: T0 + 1000 },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'Summary of the conversation so far.' }], at: T0 + 2000 },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'compaction', arg: '' }], at: T0 + 3000 }
+ ])
+ })
+
+ it('a tool part inside a USER message is a chip on the assistant side, never in the user bubble', () => {
+ const r = parse(
+ doc([user('msg_1', [text('run it'), tool('bash', { status: 'completed', input: { command: 'ls' }, output: 'a', title: 'ls', metadata: {}, time: { start: 1, end: 2 } })])])
+ )
+ expect(r.messages).toEqual([
+ { role: 'user', parts: [{ kind: 'text', text: 'run it' }], at: T0 + 1000 },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'bash', arg: 'ls', result: 'a' }], at: T0 + 1000 }
+ ])
+ })
+
+ it('a subtask part becomes a task chip beside the user\'s own words', () => {
+ const r = parse(
+ doc([user('msg_1', [text('/review the diff'), part('subtask', { prompt: 'full prompt', description: 'Review changes', agent: 'general', command: 'review' })])])
+ )
+ expect(r.messages).toEqual([
+ { role: 'user', parts: [{ kind: 'text', text: '/review the diff' }], at: T0 + 1000 },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'task', arg: 'Review changes' }], at: T0 + 1000 }
+ ])
+ })
+})
+
+describe('parseOpencodeExport — shapes it cannot map', () => {
+ it('skips and COUNTS them, never crashes and never renders raw JSON', () => {
+ const r = parse(
+ doc([
+ 'a string where a message should be',
+ null,
+ { parts: [text('no info')] },
+ { info: { role: 'system', id: 'msg_s', sessionID: SID }, parts: [text('unknown role')] },
+ user('msg_1', 'parts is not an array' as unknown as unknown[]),
+ user('msg_2', [text('kept'), 7, { no: 'type' }, part('future-kind', { secret: 'RAWJSON' }), text(42 as unknown as string)])
+ ])
+ )
+ expect(r.messages).toEqual([{ role: 'user', parts: [{ kind: 'text', text: 'kept' }], at: T0 + 2000 }])
+ // string, null, no-info, unknown role, non-array parts, then 7 / {no:type} / future-kind / non-string text
+ expect(r.skipped).toBe(9)
+ expect(JSON.stringify(r.messages)).not.toContain('RAWJSON')
+ })
+
+ it('a message filed under ANOTHER session is skipped, never shown', () => {
+ const foreign = user('msg_1', [text('SOMEONE ELSE PRIVATE')])
+ ;(foreign.info as { sessionID: string }).sessionID = 'ses_someoneElse00000000000'
+ const r = parse(doc([foreign, user('msg_2', [text('mine')])]))
+ expect(JSON.stringify(r.messages)).not.toContain('SOMEONE ELSE PRIVATE')
+ expect(r.messages.map((m) => m.parts)).toEqual([[{ kind: 'text', text: 'mine' }]])
+ expect(r.skipped).toBe(1)
+ })
+
+ it('refuses the whole document when it is not this session\'s export', () => {
+ expect(parseOpencodeExport(doc([user('msg_1', [text('SOMEONE ELSE PRIVATE')])], 'ses_other000000000000000000'), SID)).toBeNull()
+ expect(parseOpencodeExport(JSON.stringify({ messages: [] }), SID)).toBeNull() // no info.id at all
+ expect(parseOpencodeExport('not json', SID)).toBeNull()
+ expect(parseOpencodeExport('[]', SID)).toBeNull()
+ expect(parseOpencodeExport(JSON.stringify({ info: { id: SID } }), SID)).toEqual({ messages: [], skipped: 0 })
+ })
+})
+
+describe('parseOpencodeExport — model and effort', () => {
+ it('the newest assistant message answers both fields, and nothing is carried from an older one', () => {
+ const r = parse(
+ doc([
+ asst('msg_1', [text('a')], { modelID: 'old-model', variant: 'high' }),
+ user('msg_2', [text('b')], { model: { providerID: 'x', modelID: 'user-picked', variant: 'max' } }),
+ asst('msg_3', [text('c')], { modelID: 'new-model' })
+ ])
+ )
+ expect(r.model).toBe('new-model')
+ expect('effort' in r).toBe(false)
+ })
+
+ it('the newest assistant message stating NO model leaves the key absent', () => {
+ const newest = asst('msg_2', [text('b')])
+ delete (newest.info as { modelID?: unknown }).modelID
+ const r = parse(doc([asst('msg_1', [text('a')], { modelID: 'old-model' }), newest]))
+ expect('model' in r).toBe(false)
+ })
+
+ it('states the variant as effort when the newest assistant message carries one', () => {
+ const r = parse(doc([asst('msg_1', [text('a')], { modelID: 'm', variant: 'high' })]))
+ expect(r).toMatchObject({ model: 'm', effort: 'high' })
+ })
+
+ it('a value over 100 UTF-16 units is not a model name', () => {
+ const r = parse(doc([asst('msg_1', [text('a')], { modelID: 'm'.repeat(101), variant: 'v'.repeat(100) })]))
+ expect('model' in r).toBe(false)
+ expect(r.effort).toBe('v'.repeat(100))
+ })
+
+ it('no assistant message = neither key', () => {
+ const r = parse(doc([user('msg_1', [text('a')])]))
+ expect(Object.keys(r)).toEqual(['messages', 'skipped'])
+ })
+})
+
+describe('newestWithinBytes', () => {
+ const m = (t: string): ChatMessage => ({ role: 'user', parts: [{ kind: 'text', text: t }] })
+ it('keeps the newest messages whose JSON fits the cap, in order', () => {
+ const msgs = [m('a'.repeat(100)), m('b'.repeat(100)), m('c'.repeat(100))]
+ const one = Buffer.byteLength(JSON.stringify(msgs[0]))
+ expect(newestWithinBytes(msgs, one * 2)).toEqual(msgs.slice(1))
+ expect(newestWithinBytes(msgs, one * 3)).toEqual(msgs)
+ expect(newestWithinBytes(msgs, one - 1)).toEqual([])
+ })
+ it('counts UTF-8 bytes, not UTF-16 units', () => {
+ const msgs = [m('ş'.repeat(10)), m('x')]
+ const last = Buffer.byteLength(JSON.stringify(msgs[1]))
+ const first = Buffer.byteLength(JSON.stringify(msgs[0]))
+ expect(first).toBeGreaterThan(JSON.stringify(msgs[0]).length)
+ expect(newestWithinBytes(msgs, last + first - 1)).toEqual([msgs[1]])
+ })
+})
+
+// ── The read (readChatTranscript's opencode branch) ────────────────────────────────────────────
+
+const exportOf = (outcome: OpencodeExportOutcome) => vi.fn(async (_sid: string) => outcome)
+const read = (q: Parameters<typeof readChatTranscript>[0], page: unknown, deps: TranscriptIpcDeps) =>
+ readChatTranscript(q, page, deps)
+const OK_DOC = doc([user('msg_1', [text('mine')]), asst('msg_2', [text('answer')], { modelID: 'm1', variant: 'low' })])
+
+afterEach(() => setCustomAgentBaseResolver(null))
+
+describe('readChatTranscript — opencode', () => {
+ it('serves a paged read as ONE page: nothing older, no carried results, model + effort', async () => {
+ const opencodeExport = exportOf({ ok: true, stdout: OK_DOC })
+ const res = await read({ sessionId: SID, agentId: 'opencode' }, { maxBytes: 262144 }, { opencodeExport })
+ expect(res).toStrictEqual({
+ messages: [
+ { role: 'user', parts: [{ kind: 'text', text: 'mine' }], at: T0 + 1000 },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'answer' }], at: T0 + 2000 }
+ ],
+ found: true,
+ olderCursor: null,
+ unmatchedResults: [],
+ model: 'm1',
+ effort: 'low'
+ })
+ expect(opencodeExport).toHaveBeenCalledWith(SID)
+ })
+
+ it('an unpaged read keeps the legacy shape exactly', async () => {
+ const res = await read({ sessionId: SID, agentId: 'opencode' }, undefined, { opencodeExport: exportOf({ ok: true, stdout: OK_DOC }) })
+ expect(Object.keys(res).sort()).toEqual(['found', 'messages'])
+ expect(res.found).toBe(true)
+ })
+
+ it('NEVER reaches claude\'s resolver, whose cwd fallback would hand over a stranger\'s session', async () => {
+ const pathFor = vi.fn(() => '/definitely/claude.jsonl')
+ const readRemotePage = vi.fn(async () => null)
+ const readRemote = vi.fn(async () => 'SOMEONE ELSE PRIVATE')
+ for (const page of [undefined, { maxBytes: 262144 }]) {
+ const res = await read(
+ { sessionId: SID, cwd: '/srv/demo', agentId: 'opencode' },
+ page,
+ { pathFor, readRemote, readRemotePage, opencodeExport: exportOf({ ok: false, absent: true }) }
+ )
+ expect(res.found).toBe(false)
+ expect(JSON.stringify(res)).not.toContain('SOMEONE ELSE PRIVATE')
+ }
+ expect(pathFor).not.toHaveBeenCalled()
+ expect(readRemote).not.toHaveBeenCalled()
+ expect(readRemotePage).not.toHaveBeenCalled()
+ })
+
+ it('a REMOTE node never reads this machine: refused before any export runs', async () => {
+ const opencodeExport = exportOf({ ok: true, stdout: OK_DOC })
+ expect(await read({ sessionId: SID, agentId: 'opencode', remoteOnly: true }, { maxBytes: 262144 }, { opencodeExport })).toStrictEqual({
+ messages: [],
+ found: false,
+ olderCursor: null,
+ unmatchedResults: [],
+ unreadable: true
+ })
+ expect(await read({ sessionId: SID, agentId: 'opencode', remoteOnly: true }, undefined, { opencodeExport })).toStrictEqual({
+ messages: [],
+ found: false
+ })
+ expect(opencodeExport).not.toHaveBeenCalled()
+ })
+
+ it('no session id, or one we would not put on argv, is not found — and nothing runs', async () => {
+ // `opencode export` with NO id opens an interactive picker over the NEWEST sessions — i.e.
+ // someone else's. It must never be invoked without one.
+ const opencodeExport = exportOf({ ok: true, stdout: OK_DOC })
+ for (const sessionId of [undefined, '', '--help', '-s', 'ses a', "ses';rm -rf ~;'"]) {
+ const res = await read({ sessionId, agentId: 'opencode' }, { maxBytes: 262144 }, { opencodeExport })
+ expect(res).toStrictEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })
+ }
+ expect(opencodeExport).not.toHaveBeenCalled()
+ })
+
+ it('a clean miss is not-found; a failed export is UNREADABLE', async () => {
+ const absent = await read({ sessionId: SID, agentId: 'opencode' }, { maxBytes: 262144 }, { opencodeExport: exportOf({ ok: false, absent: true }) })
+ expect(absent).toStrictEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })
+ const failed = await read({ sessionId: SID, agentId: 'opencode' }, { maxBytes: 262144 }, { opencodeExport: exportOf({ ok: false }) })
+ expect(failed).toStrictEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
+ const legacy = await read({ sessionId: SID, agentId: 'opencode' }, undefined, { opencodeExport: exportOf({ ok: false }) })
+ expect(legacy).toStrictEqual({ messages: [], found: false })
+ })
+
+ it('an export of ANOTHER session (or garbage) is unreadable, and none of it is shown', async () => {
+ for (const stdout of [doc([user('msg_1', [text('SOMEONE ELSE PRIVATE')])], 'ses_other000000000000000000'), 'garbage']) {
+ const res = await read({ sessionId: SID, agentId: 'opencode' }, { maxBytes: 262144 }, { opencodeExport: exportOf({ ok: true, stdout }) })
+ expect(res).toStrictEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
+ }
+ })
+
+ it('keeps a page within the legacy 5 MB cap: the newest messages, in order', async () => {
+ const big = (i: number) => asst(`msg_${i}`, [text(String(i).repeat(1024 * 1024))])
+ const stdout = doc([1, 2, 3, 4, 5, 6].map(big))
+ const res = await read({ sessionId: SID, agentId: 'opencode' }, { maxBytes: 262144 }, { opencodeExport: exportOf({ ok: true, stdout }) })
+ expect(res.messages.map((m) => (m.parts[0] as { text: string }).text[0])).toEqual(['3', '4', '5', '6'])
+ })
+
+ it('an OLDER-page request has nothing older to give, and costs no export', async () => {
+ const opencodeExport = exportOf({ ok: true, stdout: OK_DOC })
+ const res = await read({ sessionId: SID, agentId: 'opencode' }, { before: 1000, maxBytes: 524288 }, { opencodeExport })
+ expect(res).toStrictEqual({ messages: [], found: true, olderCursor: null, unmatchedResults: [] })
+ expect(opencodeExport).not.toHaveBeenCalled()
+ })
+
+ it('a custom agent built on opencode reads through opencode, not claude', async () => {
+ setCustomAgentBaseResolver((id) => (id === 'custom:oc' ? 'opencode' : undefined))
+ const pathFor = vi.fn(() => '/definitely/claude.jsonl')
+ const opencodeExport = exportOf({ ok: true, stdout: OK_DOC })
+ const res = await read({ sessionId: SID, agentId: 'custom:oc' }, { maxBytes: 262144 }, { pathFor, opencodeExport })
+ expect(res.found).toBe(true)
+ expect(pathFor).not.toHaveBeenCalled()
+ })
+})
+
+// ── The gate: one bounded export at a time ─────────────────────────────────────────────────────
+
+function deferred<T>() {
+ let resolve!: (v: T) => void
+ const promise = new Promise<T>((r) => (resolve = r))
+ return { promise, resolve }
+}
+
+describe('createOpencodeExportGate', () => {
+ const flush = () => new Promise((r) => setTimeout(r, 0))
+
+ it('callers arriving before an export STARTS share it', async () => {
+ const d = deferred<OpencodeExportOutcome>()
+ const run = vi.fn(() => d.promise)
+ const gate = createOpencodeExportGate(run, { minSpacingMs: 0, maxConcurrent: 2 })
+ const a = gate(SID)
+ const b = gate(SID)
+ await flush()
+ d.resolve({ ok: true, stdout: 'x' })
+ expect(await a).toEqual({ ok: true, stdout: 'x' })
+ expect(await b).toEqual({ ok: true, stdout: 'x' })
+ expect(run).toHaveBeenCalledTimes(1)
+ })
+
+ it('a caller arriving while an export RUNS gets a fresh one started after it — shared with its peers', async () => {
+ const first = deferred<OpencodeExportOutcome>()
+ const second = deferred<OpencodeExportOutcome>()
+ const run = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
+ const gate = createOpencodeExportGate(run, { minSpacingMs: 0, maxConcurrent: 2 })
+ const a = gate(SID)
+ await flush() // the first export has started
+ const b = gate(SID)
+ const c = gate(SID)
+ await flush()
+ expect(run).toHaveBeenCalledTimes(1) // the fresh export waits for the running one
+ first.resolve({ ok: true, stdout: 'old' })
+ expect(await a).toEqual({ ok: true, stdout: 'old' })
+ await flush()
+ expect(run).toHaveBeenCalledTimes(2)
+ second.resolve({ ok: true, stdout: 'new' })
+ expect(await b).toEqual({ ok: true, stdout: 'new' })
+ expect(await c).toEqual({ ok: true, stdout: 'new' })
+ })
+
+ it('spaces export starts for one session', async () => {
+ let t = 1000
+ const sleeps: number[] = []
+ const run = vi.fn(async () => ({ ok: true as const, stdout: String(t) }))
+ const gate = createOpencodeExportGate(run, {
+ minSpacingMs: 2000,
+ maxConcurrent: 2,
+ now: () => t,
+ sleep: async (ms) => {
+ sleeps.push(ms)
+ t += ms
+ }
+ })
+ await gate(SID)
+ t += 500
+ await gate(SID)
+ expect(sleeps).toEqual([1500])
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+
+ it('never reuses a failure: the next call runs again', async () => {
+ const run = vi.fn().mockResolvedValueOnce({ ok: false }).mockResolvedValueOnce({ ok: true, stdout: 'y' })
+ const gate = createOpencodeExportGate(run, { minSpacingMs: 0, maxConcurrent: 2 })
+ expect(await gate(SID)).toEqual({ ok: false })
+ expect(await gate(SID)).toEqual({ ok: true, stdout: 'y' })
+ })
+
+ it('sessions do not share an export', async () => {
+ const run = vi.fn(async (id: string) => ({ ok: true as const, stdout: id }))
+ const gate = createOpencodeExportGate(run, { minSpacingMs: 0, maxConcurrent: 2 })
+ expect(await Promise.all([gate('ses_a'), gate('ses_b')])).toEqual([
+ { ok: true, stdout: 'ses_a' },
+ { ok: true, stdout: 'ses_b' }
+ ])
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+
+ it('caps concurrent exports across sessions (each one is a ~320 MB process)', async () => {
+ const ds = [deferred<OpencodeExportOutcome>(), deferred<OpencodeExportOutcome>(), deferred<OpencodeExportOutcome>()]
+ let i = 0
+ const run = vi.fn(() => ds[i++].promise)
+ const gate = createOpencodeExportGate(run, { minSpacingMs: 0, maxConcurrent: 2 })
+ const a = gate('ses_a')
+ const b = gate('ses_b')
+ const c = gate('ses_c')
+ await flush()
+ expect(run).toHaveBeenCalledTimes(2)
+ ds[0].resolve({ ok: true, stdout: 'a' })
+ await a
+ await flush()
+ expect(run).toHaveBeenCalledTimes(3)
+ ds[1].resolve({ ok: true, stdout: 'b' })
+ ds[2].resolve({ ok: true, stdout: 'c' })
+ expect(await b).toEqual({ ok: true, stdout: 'b' })
+ expect(await c).toEqual({ ok: true, stdout: 'c' })
+ })
+
+ it('a runner that throws is a failed read, and does not wedge the session', async () => {
+ const run = vi.fn().mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce({ ok: true, stdout: 'z' })
+ const gate = createOpencodeExportGate(run, { minSpacingMs: 0, maxConcurrent: 1 })
+ expect(await gate(SID)).toEqual({ ok: false })
+ expect(await gate(SID)).toEqual({ ok: true, stdout: 'z' })
+ })
+})
diff --git a/src/core/opencode-chat.ts b/src/core/opencode-chat.ts
new file mode 100644
index 000000000..c91af8946
--- /dev/null
+++ b/src/core/opencode-chat.ts
@@ -0,0 +1,388 @@
+// opencode's conversation as the ⌘M panel's structured messages — and the bounded read behind it.
+//
+// Separate from `transcript-reader.ts`'s claude parser and from `grok-chat.ts`: opencode has no
+// transcript FILE. Since 1.18 it keeps sessions in SQLite (a database that also holds its account
+// tokens, so it is never opened here), and `opencode export <id>` is the contract — the same one
+// Context Link reads (`linesFromOpencodeExport`). One export is ONE JSON document, so there are no
+// byte offsets to page by: a read returns one page (`olderCursor: null`), exactly as grok does.
+//
+// MEASURED on opencode 1.18.25 (2026-09-28) — every shape below comes from its schema (the Effect
+// structs `UserMessage` / `AssistantMessage` / `Part` in the shipped binary) and was checked against
+// the 10 sessions, 25 messages and 65 parts on the measuring host:
+//
+// document {info: Session, messages: [{info: Message, parts: Part[]}]}; `info.id` is the session
+// user info {id, sessionID, role:"user", time:{created}, agent, model:{providerID, modelID,
+// variant?}, summary?, system?, tools?}
+// assistant info {id, sessionID, role:"assistant", parentID, modelID, providerID, mode, agent,
+// path, cost, tokens, time:{created, completed?}, finish?, variant?, summary?:true
+// (a compaction summary), error?: {name, data:{message?, …}}}
+// parts text {text, synthetic?, ignored?, time?} · reasoning {text, time} · tool {callID,
+// tool, state} · file {mime, url, filename?} · agent {name} · subtask {prompt,
+// description, agent, command?} · compaction {auto, overflow?} · retry {attempt, error}
+// · step-start · step-finish · snapshot · patch
+// tool state pending {input, raw} · running {input, title?, time} · completed {input, output,
+// title, metadata, time} · error {input, error, time}
+// errors ProviderAuthError · UnknownError · MessageOutputLengthError (data {}) ·
+// MessageAbortedError · StructuredOutputError · ContextOverflowError ·
+// ContentFilterError · APIError — all `{name, data}`
+//
+// Every mapping rule is written down in `src/shared/chat-fixtures/opencode/README.md` for the iOS
+// port, and pinned by the golden fixtures there.
+import type { ChatMessage, ChatPart, ChatTranscriptResult } from '../shared/types'
+import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'
+import { CHAT_PAGE_MAX_BYTES, type ChatTranscriptPage } from '../shared/chat-page'
+import { findInLoginPath } from './exec-path'
+import { isSafeOpencodeSessionId, runOpencodeExportAt, type OpencodeExportOutcome } from './opencode-export'
+
+/** Same bounds as claude's reader (`summarizeResult` / `metaString`). */
+const TOOL_RESULT_LINES = 3
+const TOOL_RESULT_MAX = 500
+const CHAT_META_MAX_CHARS = 100
+
+type ToolPart = Extract<ChatPart, { kind: 'tool' }>
+
+export interface OpencodeChatParse {
+ messages: ChatMessage[]
+ /** Records that could not be mapped (not an object, no `info`, an unknown role or part type, a
+ * message filed under another session, a malformed field). Skipped, never rendered raw. */
+ skipped: number
+ /** The newest assistant message's `modelID` — absent when it states none (never carried). */
+ model?: string
+ /** The newest assistant message's `variant` (opencode's reasoning-effort variant). */
+ effort?: string
+}
+
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
+
+function metaString(v: unknown): string | undefined {
+ return typeof v === 'string' && v.length > 0 && v.length <= CHAT_META_MAX_CHARS ? v : undefined
+}
+
+function summarize(text: string): string {
+ return text.split('\n').slice(0, TOOL_RESULT_LINES).join(' ').slice(0, TOOL_RESULT_MAX)
+}
+
+/**
+ * The one input worth showing on a collapsed tool chip, for opencode's builtin tools (bash
+ * `command`, read/write/edit `filePath`, grep/glob `pattern`, list `path`, webfetch `url`,
+ * websearch/codesearch `query`, task `description`/`prompt`, skill `name`, question
+ * `questions[0].question`). The key ORDER is the rule: `pattern` before `path`, because a grep's
+ * meaning is its pattern. Else the `title` opencode wrote for the call, else nothing. Capped like
+ * every tool arg (`CHAT_TOOL_ARG_MAX` UTF-16 units).
+ */
+export function opencodeToolArg(input: unknown, title?: unknown): string {
+ let v: unknown
+ if (isObj(input)) {
+ for (const k of ['command', 'filePath', 'file_path', 'pattern', 'path', 'url', 'query', 'description', 'prompt', 'name']) {
+ if (typeof input[k] === 'string') {
+ v = input[k]
+ break
+ }
+ }
+ if (v === undefined && Array.isArray(input.questions) && isObj(input.questions[0])) {
+ const q = input.questions[0].question
+ if (typeof q === 'string') v = q
+ }
+ }
+ if (v === undefined && typeof title === 'string') v = title
+ return typeof v === 'string' ? v.slice(0, CHAT_TOOL_ARG_MAX) : ''
+}
+
+/** A tool part's chip. `null` = not a mappable tool part. */
+function toolPart(p: Record<string, unknown>): ToolPart | null {
+ const state = p.state
+ if (!isObj(state)) return null
+ const part: ToolPart = {
+ kind: 'tool',
+ name: typeof p.tool === 'string' && p.tool ? p.tool : 'tool',
+ arg: opencodeToolArg(state.input, state.title)
+ }
+ // Claude-only card fields (`body`, `questions`) and the paged `id` are never set: opencode's
+ // `question` tool looks like AskUserQuestion, but answer cards are claude's, and this reader does
+ // not page.
+ if (state.status === 'completed' && typeof state.output === 'string') {
+ const s = summarize(state.output)
+ if (s) part.result = s
+ } else if (state.status === 'error' && typeof state.error === 'string') {
+ part.result = summarize(`Error: ${state.error}`)
+ }
+ return part
+}
+
+/** The sentence an errored assistant message ends with. `null` = malformed (counted as skipped). */
+function errorText(e: unknown): string | null {
+ if (!isObj(e)) return null
+ const name = typeof e.name === 'string' && e.name ? e.name : 'Error'
+ const message = isObj(e.data) && typeof e.data.message === 'string' ? e.data.message.trim() : ''
+ return message ? `[${name}] ${message}` : `[${name}]`
+}
+
+/** Parts dropped ON PURPOSE (not counted as skipped): model reasoning (the same product decision
+ * claude's and grok's readers make) and bookkeeping that is not conversation. `file` and `agent`
+ * are attachments and @-mentions; their text is already in the prompt, and claude's reader drops
+ * non-text user content the same way. */
+const DROPPED_PARTS = new Set(['reasoning', 'step-start', 'step-finish', 'snapshot', 'patch', 'retry', 'file', 'agent'])
+
+/**
+ * One `opencode export` document → ordered bubbles. `null` when the text is not an export of
+ * `sessionId` — not JSON, not an object, or `info.id` names another session. That check is what
+ * makes "never another session's transcript" a property of the parser rather than of the caller.
+ */
+export function parseOpencodeExport(raw: string, sessionId: string): OpencodeChatParse | null {
+ let doc: unknown
+ try {
+ doc = JSON.parse(raw)
+ } catch {
+ return null
+ }
+ if (!isObj(doc) || !isObj(doc.info) || doc.info.id !== sessionId) return null
+
+ const messages: ChatMessage[] = []
+ let skipped = 0
+ let lastAssistant: Record<string, unknown> | undefined
+ const entries = Array.isArray(doc.messages) ? doc.messages : []
+ for (const entry of entries) {
+ if (!isObj(entry) || !isObj(entry.info)) {
+ skipped++
+ continue
+ }
+ const info = entry.info
+ // A message filed under another session is never shown, even inside this session's export.
+ if (info.sessionID !== undefined && info.sessionID !== sessionId) {
+ skipped++
+ continue
+ }
+ const role = info.role
+ if ((role !== 'user' && role !== 'assistant') || !Array.isArray(entry.parts)) {
+ skipped++
+ continue
+ }
+ const created = isObj(info.time) ? info.time.created : undefined
+ const at = typeof created === 'number' && Number.isFinite(created) ? created : undefined
+ const stamp = (m: ChatMessage): ChatMessage => (at === undefined ? m : { ...m, at })
+
+ // `own` = the speaker's parts; `chips` = what a USER message carries that the human did not
+ // type (a compaction, a subtask): an assistant-side tool chip right after, never a user bubble.
+ const own: ChatPart[] = []
+ const chips: ChatPart[] = []
+ for (const p of entry.parts) {
+ if (!isObj(p) || typeof p.type !== 'string') {
+ skipped++
+ continue
+ }
+ switch (p.type) {
+ case 'text':
+ if (typeof p.text !== 'string') {
+ skipped++
+ break
+ }
+ // Harness text (`synthetic`: an @-mentioned file read in full, "the following tool was
+ // executed by the user") and `ignored` text were not written by the speaker.
+ if (p.synthetic === true || p.ignored === true || !p.text) break
+ own.push({ kind: 'text', text: p.text })
+ break
+ case 'tool': {
+ const t = toolPart(p)
+ if (t) (role === 'user' ? chips : own).push(t)
+ else skipped++
+ break
+ }
+ case 'compaction':
+ chips.push({ kind: 'tool', name: 'compaction', arg: p.auto === true ? 'auto' : '' })
+ break
+ case 'subtask':
+ chips.push({ kind: 'tool', name: 'task', arg: opencodeToolArg({ description: p.description, prompt: p.prompt }) })
+ break
+ default:
+ if (!DROPPED_PARTS.has(p.type)) skipped++
+ }
+ }
+
+ if (role === 'assistant') {
+ lastAssistant = info
+ if (info.error !== undefined) {
+ const t = errorText(info.error)
+ if (t === null) skipped++
+ else own.push({ kind: 'text', text: t })
+ }
+ const parts = [...own, ...chips]
+ if (parts.length) messages.push(stamp({ role: 'assistant', parts }))
+ } else {
+ if (own.length) messages.push(stamp({ role: 'user', parts: own }))
+ if (chips.length) messages.push(stamp({ role: 'assistant', parts: chips }))
+ }
+ }
+
+ const out: OpencodeChatParse = { messages, skipped }
+ // ONE message answers both fields; an absent field is absent, never carried from an older one.
+ const model = metaString(lastAssistant?.modelID)
+ const effort = metaString(lastAssistant?.variant)
+ if (model !== undefined) out.model = model
+ if (effort !== undefined) out.effort = effort
+ return out
+}
+
+/** The newest messages whose JSON fits in `maxBytes` (UTF-8), in order. One export is one page,
+ * and a page stays within the legacy read's cap (`CHAT_PAGE_MAX_BYTES`) — it crosses the relay
+ * to a phone. Like grok's capped tail, the cut is not announced (`olderCursor` stays null). */
+export function newestWithinBytes(messages: ChatMessage[], maxBytes: number): ChatMessage[] {
+ let total = 0
+ let i = messages.length
+ while (i > 0) {
+ const size = Buffer.byteLength(JSON.stringify(messages[i - 1]))
+ if (total + size > maxBytes) break
+ total += size
+ i--
+ }
+ return messages.slice(i)
+}
+
+// ── The export gate ─────────────────────────────────────────────────────────────────────────────
+
+export type OpencodeExportRun = (sessionId: string) => Promise<OpencodeExportOutcome>
+
+export interface OpencodeExportGateOptions {
+ /** Minimum time between two export STARTS for one session. */
+ minSpacingMs: number
+ /** Most exports running at once, across sessions. */
+ maxConcurrent: number
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+}
+
+/**
+ * One export costs 1.0–1.7 s and ~320 MB (measured), and the ⌘M panel re-reads on every hook event
+ * while the agent works — from the canvas node, the card modal and the phone at once. The gate:
+ *
+ * - joins a caller to an export that has not STARTED yet (its answer is still fresh for them);
+ * - gives a caller arriving while one RUNS a new export started after it — never a stale answer,
+ * which would leave the panel's final turn-end read one turn behind — shared by every such caller;
+ * - spaces starts for one session by `minSpacingMs`, and caps exports running at once;
+ * - caches nothing: a failure is answered once and the next call runs again.
+ */
+export function createOpencodeExportGate(run: OpencodeExportRun, opts: OpencodeExportGateOptions): OpencodeExportRun {
+ const now = opts.now ?? Date.now
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ interface Session {
+ waiting?: Promise<OpencodeExportOutcome>
+ running?: Promise<OpencodeExportOutcome>
+ lastStart: number
+ }
+ const sessions = new Map<string, Session>()
+ let active = 0
+ const queue: Array<() => void> = []
+ const acquire = (): Promise<void> => {
+ if (active < opts.maxConcurrent) {
+ active++
+ return Promise.resolve()
+ }
+ return new Promise((r) => queue.push(r))
+ }
+ const release = (): void => {
+ const next = queue.shift()
+ if (next) next()
+ else active--
+ }
+ const prune = (): void => {
+ const t = now()
+ for (const [id, s] of sessions) {
+ if (!s.waiting && !s.running && t - s.lastStart > opts.minSpacingMs) sessions.delete(id)
+ }
+ }
+
+ return (sessionId) => {
+ prune()
+ let s = sessions.get(sessionId)
+ if (!s) {
+ s = { lastStart: -Infinity }
+ sessions.set(sessionId, s)
+ }
+ const st = s
+ if (st.waiting) return st.waiting
+ // Assigned before its body's first `await` returns, so the body can recognise itself.
+ let job!: Promise<OpencodeExportOutcome>
+ job = (async () => {
+ if (st.running) await st.running
+ const wait = st.lastStart + opts.minSpacingMs - now()
+ if (wait > 0) await sleep(wait)
+ await acquire()
+ // Started: later callers get the NEXT export, not this one.
+ if (st.waiting === job) st.waiting = undefined
+ st.lastStart = now()
+ const running = (async (): Promise<OpencodeExportOutcome> => {
+ try {
+ return await run(sessionId)
+ } catch {
+ return { ok: false }
+ } finally {
+ release()
+ }
+ })()
+ st.running = running
+ const out = await running
+ if (st.running === running) st.running = undefined
+ return out
+ })()
+ st.waiting = job
+ return job
+ }
+}
+
+/** A chat export is interactive: 20 s is ~10× the measured cost, and a wedged CLI must not hold the
+ * panel's single-flight read for Context Link's full minute. */
+export const OPENCODE_CHAT_EXPORT_TIMEOUT_MS = 20_000
+
+let defaultExport: OpencodeExportRun | undefined
+/** The real, gated `opencode export` — resolved through the login PATH like Context Link's. */
+export function defaultOpencodeExport(): OpencodeExportRun {
+ defaultExport ??= createOpencodeExportGate(
+ async (sessionId) => {
+ const bin = await findInLoginPath('opencode')
+ return bin ? runOpencodeExportAt(bin, sessionId, OPENCODE_CHAT_EXPORT_TIMEOUT_MS) : { ok: false }
+ },
+ { minSpacingMs: 2000, maxConcurrent: 2 }
+ )
+ return defaultExport
+}
+
+// ── The read ────────────────────────────────────────────────────────────────────────────────────
+
+/**
+ * `chat:read-transcript` for an opencode node. Rules, each a refusal:
+ *
+ * - A REMOTE node (`remoteOnly`) is refused before anything runs: its sessions live in the HOST's
+ * database, and an export here would answer from the wrong machine (or find a same-id session
+ * that is not this one). There is no remote leg yet — see CLAUDE.md.
+ * - No session id, or one we would not put on argv, is not found and runs nothing: a bare
+ * `opencode export` opens a picker over the NEWEST sessions — someone else's.
+ * - `absent` (opencode looked) is a clean miss; any other export failure is `unreadable`.
+ * - An export whose `info.id` is not this session is `unreadable`, and none of it is shown.
+ * - An OLDER-page request has nothing to give (this reader never hands out a cursor).
+ */
+export async function readOpencodeChat(
+ q: { sessionId?: string; remoteOnly?: boolean },
+ page: ChatTranscriptPage | null,
+ run: OpencodeExportRun = defaultOpencodeExport()
+): Promise<ChatTranscriptResult> {
+ const notFound = (): ChatTranscriptResult =>
+ page ? { messages: [], found: false, olderCursor: null, unmatchedResults: [] } : { messages: [], found: false }
+ const unreadable = (): ChatTranscriptResult => (page ? { ...notFound(), unreadable: true } : notFound())
+ if (q.remoteOnly) return unreadable()
+ if (page && page.before !== null) return { messages: [], found: true, olderCursor: null, unmatchedResults: [] }
+ const sessionId = q.sessionId
+ if (!sessionId || !isSafeOpencodeSessionId(sessionId)) return notFound()
+ const out = await run(sessionId)
+ if (!out.ok) return out.absent ? notFound() : unreadable()
+ const parsed = parseOpencodeExport(out.stdout, sessionId)
+ if (!parsed) return unreadable()
+ const messages = newestWithinBytes(parsed.messages, CHAT_PAGE_MAX_BYTES)
+ if (!page) return { messages, found: true }
+ return {
+ messages,
+ found: true,
+ olderCursor: null,
+ unmatchedResults: [],
+ ...(parsed.model !== undefined ? { model: parsed.model } : {}),
+ ...(parsed.effort !== undefined ? { effort: parsed.effort } : {})
+ }
+}
diff --git a/src/core/opencode-export.test.ts b/src/core/opencode-export.test.ts
new file mode 100644
index 000000000..2c13f7b5f
--- /dev/null
+++ b/src/core/opencode-export.test.ts
@@ -0,0 +1,90 @@
+// The bounded `opencode export <id>` both readers share (Context Link's flat lines and the ⌘M chat
+// view). What this pins is the TRI-STATE the chat view needs and Context Link never did: a session
+// opencode positively reports as missing is a clean miss (`absent`), while every other failure —
+// no binary, a crash, a timeout, an oversized export — is a failed read. Measured on opencode
+// 1.18.25: an unknown id exits 1 with an empty stdout and `Session not found: <id>` on stderr.
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { runOpencodeExportAt } from './opencode-export'
+
+/** A stand-in `opencode` running `script` under this Node: a cmd shim on Windows (the shape npm
+ * installs there), an executable sh script elsewhere. Same helper as the Context Link test. */
+function writeFakeOpencode(dir: string, script: string): string {
+ const js = path.join(dir, 'opencode.js')
+ fs.writeFileSync(js, script)
+ if (process.platform === 'win32') {
+ const cmd = path.join(dir, 'opencode.cmd')
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${js}" %*\r\n`)
+ return cmd
+ }
+ const sh = path.join(dir, 'opencode')
+ fs.writeFileSync(sh, `#!/bin/sh\nexec '${process.execPath}' '${js}' "$@"\n`, { mode: 0o755 })
+ return sh
+}
+
+const SID = 'ses_0a1b2c3d4ffeSynthetic000001'
+
+describe('runOpencodeExportAt — the tri-state', () => {
+ let dir: string
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-opencode-export-tri-'))
+ })
+ afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('passes exactly `export <id>` on argv and returns stdout', async () => {
+ const bin = writeFakeOpencode(
+ dir,
+ "process.stderr.write('Exporting session: x\\n'); process.stdout.write(JSON.stringify(process.argv.slice(2)))\n"
+ )
+ const out = await runOpencodeExportAt(bin, SID, 10_000)
+ expect(out.ok).toBe(true)
+ expect(out.ok && JSON.parse(out.stdout)).toEqual(['export', SID])
+ })
+
+ it('reads the measured "Session not found" exit as a clean miss', async () => {
+ // Verbatim shape of 1.18.25's answer, ANSI colouring included.
+ const bin = writeFakeOpencode(
+ dir,
+ `process.stderr.write('Exporting session: ${SID}\\n\\x1b[91m\\x1b[1mError: \\x1b[0mSession not found: ${SID}\\n'); process.exit(1)\n`
+ )
+ expect(await runOpencodeExportAt(bin, SID, 10_000)).toEqual({ ok: false, absent: true })
+ })
+
+ it('a "not found" naming ANOTHER id is not evidence about this one', async () => {
+ const bin = writeFakeOpencode(dir, "process.stderr.write('Session not found: ses_other\\n'); process.exit(1)\n")
+ expect(await runOpencodeExportAt(bin, SID, 10_000)).toEqual({ ok: false })
+ })
+
+ it('the not-found line under any exit status but the measured 1 is not a clean miss', async () => {
+ const bin = writeFakeOpencode(dir, `process.stderr.write('Session not found: ${SID}\\n'); process.exit(2)\n`)
+ expect(await runOpencodeExportAt(bin, SID, 10_000)).toEqual({ ok: false })
+ })
+
+ it('any other failure is a failed read, never absence', async () => {
+ const bin = writeFakeOpencode(dir, "process.stderr.write('database is locked\\n'); process.exit(1)\n")
+ expect(await runOpencodeExportAt(bin, SID, 10_000)).toEqual({ ok: false })
+ })
+
+ it('a not-found message with output on stdout is not a clean miss', async () => {
+ const bin = writeFakeOpencode(
+ dir,
+ `process.stdout.write('{}'); process.stderr.write('Session not found: ${SID}\\n'); process.exit(1)\n`
+ )
+ expect(await runOpencodeExportAt(bin, SID, 10_000)).toEqual({ ok: false })
+ })
+
+ it('a wedged CLI is killed at the timeout and reads as a failure', async () => {
+ const bin = writeFakeOpencode(dir, 'setTimeout(() => {}, 60000)\n')
+ const t0 = Date.now()
+ expect(await runOpencodeExportAt(bin, SID, 300)).toEqual({ ok: false })
+ expect(Date.now() - t0).toBeLessThan(10_000)
+ })
+
+ it('a binary that does not exist is a failure', async () => {
+ expect(await runOpencodeExportAt(path.join(dir, 'nope'), SID, 10_000)).toEqual({ ok: false })
+ })
+})
diff --git a/src/core/opencode-export.ts b/src/core/opencode-export.ts
new file mode 100644
index 000000000..e29a42fbf
--- /dev/null
+++ b/src/core/opencode-export.ts
@@ -0,0 +1,78 @@
+// `opencode export <sessionID>` — the one way nodeterm reads an opencode conversation.
+//
+// opencode >= 1.18 keeps sessions in SQLite (`~/.local/share/opencode/opencode.db`, which also
+// holds its account tokens), so its disk is never parsed: the export is the contract. Two readers
+// share this module — Context Link (flat lines, `context-link.ts`) and the ⌘M chat view
+// (`opencode-chat.ts`) — so the id check and the bounds below exist once.
+//
+// MEASURED on opencode 1.18.25 (2026-09-28): stdout is the JSON document alone
+// (`JSON.stringify(doc, null, 2)` + EOL); stderr carries `Exporting session: <id>`; an unknown id
+// exits 1 with an EMPTY stdout and `Session not found: <id>` (ANSI-coloured) on stderr; an unknown
+// option exits 1 (yargs strict), so no flag is passed that an older CLI might not know. One export
+// costs 1.0–1.7 s wall and ~320 MB peak RSS on this host, which is why the chat view gates it
+// (`createOpencodeExportGate`).
+import { directExecutableInvocation } from './exec-path'
+
+/** An export names ONE provider session. The id reaches us from a hook payload, so it is re-checked
+ * here, where it becomes an argv entry: `directExecutableInvocation` stops it being read as shell
+ * syntax, and nothing but this stops a leading `-` being read by opencode as an option. */
+const SAFE_OPENCODE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/
+
+export function isSafeOpencodeSessionId(sessionId: string): boolean {
+ return SAFE_OPENCODE_SESSION_ID.test(sessionId)
+}
+
+// A whole conversation comes back on stdout. execFile's default 1 MiB buffer turns a long session
+// into an error, which reads as "no transcript".
+export const OPENCODE_EXPORT_MAX_BYTES = 32 * 1024 * 1024
+
+/**
+ * `ok` — the export's stdout. `absent` — opencode LOOKED and has no such session (a clean miss,
+ * positive evidence). Anything else — no binary, a crash, a timeout, an oversized export — is `{ok:false}`: we could not read, which is never evidence of absence.
+ */
+export type OpencodeExportOutcome = { ok: true; stdout: string } | { ok: false; absent?: true }
+
+// eslint-disable-next-line no-control-regex
+const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]/g
+
+/** Callers check `isSafeOpencodeSessionId` first — this runs whatever id it is handed, exactly as
+ * `opencodeExportAt` always has (the Windows shim test hands it an id with `&` and a space to
+ * prove the shim does not reinterpret it). */
+export async function runOpencodeExportAt(
+ bin: string,
+ sessionId: string,
+ timeoutMs: number
+): Promise<OpencodeExportOutcome> {
+ const invocation = directExecutableInvocation(bin, ['export', sessionId])
+ if (!invocation) return { ok: false }
+ try {
+ const { execFile } = await import('node:child_process')
+ return await new Promise<OpencodeExportOutcome>((resolve) => {
+ execFile(
+ invocation.executable,
+ invocation.args,
+ {
+ ...invocation.options,
+ encoding: 'utf-8',
+ maxBuffer: OPENCODE_EXPORT_MAX_BYTES,
+ timeout: timeoutMs
+ },
+ (err, stdout, stderr) => {
+ if (!err) return resolve({ ok: true, stdout })
+ // Only the measured answer about THIS id is absence: exit 1, nothing on stdout, and the
+ // not-found line naming exactly the id we asked for. A killed/timed-out process has a
+ // non-numeric code (or `killed`), so it can never match.
+ const code = (err as { code?: unknown }).code
+ const notFound =
+ code === 1 &&
+ !(err as { killed?: boolean }).killed &&
+ stdout === '' &&
+ String(stderr ?? '').replace(ANSI, '').includes(`Session not found: ${sessionId}`)
+ resolve(notFound ? { ok: false, absent: true } : { ok: false })
+ }
+ )
+ })
+ } catch {
+ return { ok: false }
+ }
+}
diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.ts
index a58b6a080..09dd06c70 100644
--- a/src/core/transcript-ipc.ts
+++ b/src/core/transcript-ipc.ts
@@ -15,6 +15,8 @@ import type { ChatTranscriptResult, TranscriptLine, TranscriptPresence } from '.
import { CHAT_PAGE_MAX_BYTES, normalizeChatPage, type ChatTranscriptPage } from '../shared/chat-page'
import { platform } from './platform'
import { chatMessagesFromGrok } from './grok-chat'
+import { readOpencodeChat, type OpencodeExportRun } from './opencode-chat'
+import { capabilityAgentId } from '../shared/agents/config'
import { locateGrok } from './handoff/locate'
import {
parseChatMessages,
@@ -78,6 +80,9 @@ export interface TranscriptIpcDeps {
* (the Server Edition — it runs ON the host) = no node is remote, which is correct there.
*/
isRemoteNode?(nodeId: string): boolean
+ /** `opencode export <id>` for an opencode node's chat read. A test seam: absent = the real,
+ * bounded and gated CLI call (`defaultOpencodeExport`) — both shells run it on their own host. */
+ opencodeExport?: OpencodeExportRun
}
export type RemoteTranscriptPage = { ok: true; data: Buffer; start: number } | { ok: false; absent?: true }
@@ -238,6 +243,14 @@ export async function readChatTranscript(
? { messages: [], found: false, ...paging }
: { messages: chatMessagesFromGrok(buf), found: true, ...paging }
}
+ // opencode has no transcript file — its sessions live in a database read through
+ // `opencode export <id>` — so it must never reach claude's resolver below (whose cwd fallback
+ // would answer with a stranger's session). Routed through the base harness, so a custom agent
+ // built on opencode reads as opencode. Local only: a remote node is refused inside, before
+ // anything runs. See core/opencode-chat.ts.
+ if (agentId && capabilityAgentId(agentId) === 'opencode') {
+ return readOpencodeChat({ sessionId, remoteOnly }, page, deps.opencodeExport)
+ }
if (page) return readChatPage({ sessionId, cwd, accountId, nodeId, ...(remoteOnly ? { remoteOnly } : {}) }, page, deps)
const remote = deps.readRemote ? await deps.readRemote({ sessionId, cwd, accountId, nodeId }) : null
// A resolved-but-unreadable remote file is NOT "no conversation yet" — the read failed
diff --git a/src/main/remote/host-chat.test.ts b/src/main/remote/host-chat.test.ts
index e1221089b..add304ee5 100644
--- a/src/main/remote/host-chat.test.ts
+++ b/src/main/remote/host-chat.test.ts
@@ -14,6 +14,7 @@ import { createHostChat, mirrorChatSendRefusal, type HostChatDeps } from './host
import { setCustomAgentBaseResolver } from '../../shared/agents/config'
import type { ChatTranscriptResult } from '../../shared/types'
import type { HeldPermissionIo } from '../../core/agents/permission-decision'
+import { readChatTranscript, type ChatReadQuery } from '../../core/transcript-ipc'
const RESULT: ChatTranscriptResult = { messages: [], found: true, olderCursor: null, unmatchedResults: [], model: 'm' }
const RSTATUS = { state: 'done' as const, held: null, hibernated: false, paused: false, dropped: false, sessionEnded: false }
@@ -80,6 +81,38 @@ describe('host-chat page', () => {
setCustomAgentBaseResolver(null)
}
})
+ it('serves an opencode node through the REAL reader: its own export locally, refused remote', async () => {
+ // The phone gets opencode for free once the desktop parses it: `page` gates on canChat, and the
+ // real `readChatTranscript` routes opencode to `opencode export <id>` (core/opencode-chat.ts).
+ const SID = 'ses_0a1b2c3d4ffeSynthetic000001'
+ const stdout = JSON.stringify({
+ info: { id: SID },
+ messages: [{ info: { id: 'msg_1', sessionID: SID, role: 'user', time: { created: 1 } }, parts: [{ type: 'text', text: 'hi from opencode' }] }]
+ })
+ const opencodeExport = vi.fn(async () => ({ ok: true as const, stdout }))
+ const real = (q: ChatReadQuery, rawPage: unknown) => readChatTranscript(q, rawPage, { opencodeExport })
+ const local = deps({
+ lookupNode: () => ({ cwd: '/srv/app', agentId: 'opencode', sessionId: SID }),
+ readTranscript: vi.fn(real),
+ renderer: { ...deps().renderer, session: vi.fn(async () => ({ sessionId: SID })) }
+ })
+ expect(await createHostChat(local).page('n1', {})).toMatchObject({
+ version: 1,
+ sessionId: SID,
+ found: true,
+ olderCursor: null,
+ messages: [{ role: 'user', parts: [{ kind: 'text', text: 'hi from opencode' }] }]
+ })
+ expect(opencodeExport).toHaveBeenCalledWith(SID)
+ opencodeExport.mockClear()
+ const remote = deps({
+ lookupNode: () => ({ cwd: '/srv/app', agentId: 'opencode', sessionId: SID, remote: true }),
+ readTranscript: vi.fn(real),
+ renderer: { ...deps().renderer, session: vi.fn(async () => ({ sessionId: SID })) }
+ })
+ await expect(createHostChat(remote).page('n1', {})).rejects.toThrow('Could not read the transcript.')
+ expect(opencodeExport).not.toHaveBeenCalled()
+ })
it('an absent page is the default paged tail, not the legacy read', async () => {
const d = deps()
await createHostChat(d).page('n1', undefined)
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 2bc3a415b..579b572b3 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -22,6 +22,7 @@ import { E_UNSUPPORTED } from '@shared/rpc'
import { Spinner } from '../components/Spinner'
import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'
import { sentCommand } from '@shared/chat-command'
+import { capabilityAgentId } from '@shared/agents/config'
import { ChatLoadingStatus } from './ChatPanelFallback'
import { answerCardState, answerRebindPending, rebindRetryDelay, type BoundAnswerCard } from '../lib/chatAnswer'
import { AnswerControlsUpdating, PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'
@@ -84,7 +85,7 @@ interface ChatPanelProps {
* initial `[]` because nothing caught the rejection, and a failed resolution was indistinguishable
* from a session nobody has spoken to. They need different words — and two of them are retryable.
*/
-type LoadState = 'loading' | 'ok' | 'missing' | 'unsupported' | 'remoteUnsupported' | 'error'
+type LoadState = 'loading' | 'ok' | 'missing' | 'unsupported' | 'remoteUnsupported' | 'exportError' | 'error'
/**
* An `unreadable` read of a GROK node can only be the remote case: core's grok leg is local-only
@@ -96,6 +97,16 @@ type LoadState = 'loading' | 'ok' | 'missing' | 'unsupported' | 'remoteUnsupport
*/
const remoteGrokUnreadable = (agentId: string | undefined): boolean => agentId === 'grok'
+/**
+ * An `unreadable` read of an OPENCODE node has two causes and nothing on the wire tells them apart:
+ * a local `opencode export` that failed (Retry heals it) and a remote node core refuses before
+ * running anything (it never heals). So its copy names both instead of guessing — and never blames
+ * an unreachable host for a local failure. Through the base harness, mirroring core's routing
+ * (`readChatTranscript` routes `capabilityAgentId(...) === 'opencode'` to `opencode-chat.ts`).
+ */
+const opencodeUnreadable = (agentId: string | undefined): boolean =>
+ !!agentId && capabilityAgentId(agentId) === 'opencode'
+
const isUnsupported = (e: unknown): boolean =>
!!e && typeof e === 'object' && (e as { code?: string }).code === E_UNSUPPORTED
@@ -116,6 +127,10 @@ const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {
detail: 'Open this session on the desktop app to read its conversation.'
},
remoteUnsupported: { title: "Reading a remote Grok session's transcript isn't supported yet." },
+ exportError: {
+ title: "Couldn't read this opencode session.",
+ detail: "opencode export failed on this machine — Retry once it works. A session on a remote host can't be read here yet."
+ },
error: {
title: "Couldn't read the transcript.",
detail: "The agent's host may not be reachable — Retry once it is."
@@ -338,7 +353,15 @@ export function ChatPanel({
setThread(emptyThread(identity))
// A read that FAILED (the host did not answer, a remote node with no reachable master)
// is not "no transcript": it gets the error copy, and ↻ is the way out.
- setLoadState(!res.unreadable ? 'missing' : remoteGrokUnreadable(agentId) ? 'remoteUnsupported' : 'error')
+ setLoadState(
+ !res.unreadable
+ ? 'missing'
+ : remoteGrokUnreadable(agentId)
+ ? 'remoteUnsupported'
+ : opencodeUnreadable(agentId)
+ ? 'exportError'
+ : 'error'
+ )
setHeldRead({ identity, pendingId: heldAtStart })
settleHeldReload(heldAtStart)
return
diff --git a/src/renderer/nodes/ChatPanel.ux.test.tsx b/src/renderer/nodes/ChatPanel.ux.test.tsx
index 34aad4a52..6a29ca9da 100644
--- a/src/renderer/nodes/ChatPanel.ux.test.tsx
+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx
@@ -250,6 +250,21 @@ describe('ChatPanel empty states', () => {
expect(host.querySelector('.term-chat__retry')).toBeNull()
})
+ it('an unreadable opencode read names BOTH causes it can have, and keeps Retry', async () => {
+ // opencode's reader sets `unreadable` for a local `opencode export` that failed (heals on retry)
+ // AND for a remote node it refuses (never heals). No wire field tells them apart, so the copy
+ // says both rather than guessing — and never blames an unreachable host for a local failure.
+ await render({ agentId: 'opencode' })
+ await act(async () => {
+ pending[0].resolve({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
+ })
+ expect(msgs().textContent).toContain("Couldn't read this opencode session.")
+ expect(msgs().textContent).toContain('opencode export')
+ expect(msgs().textContent).toContain('remote host')
+ expect(msgs().textContent).not.toContain("The agent's host may not be reachable")
+ expect(host.querySelector('.term-chat__retry')).not.toBeNull()
+ })
+
it('a clean miss still says no transcript was found', async () => {
await render()
await act(async () => {
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index aebbf4062..efa2df7b9 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -106,10 +106,17 @@ describe('opencode capabilities', () => {
expect(canControlCanvas('opencode')).toBe(true)
})
it('stays out of the claude-only capability lists', () => {
- for (const can of [canSubagent, canRecur, canBranch, hasUsage, canChat, canTransferFrom, canRename, canReadTitle, hasPermissionMode]) {
+ for (const can of [canSubagent, canRecur, canBranch, hasUsage, canTransferFrom, canRename, canReadTitle, hasPermissionMode]) {
expect(can('opencode')).toBe(false)
}
})
+ it('shows its conversation in the ⌘M chat panel — read through `opencode export`, never claude\'s resolver', () => {
+ // Same pair grok pins below: opencode's sessions live in a database read by `opencode export`
+ // (core/opencode-chat.ts), so claude's resolver — whose cwd fallback returns a stranger's newest
+ // transcript — must never be asked for one.
+ expect(canChat('opencode')).toBe(true)
+ expect(readsClaudeShapedTranscript('opencode')).toBe(false)
+ })
})
describe('createdAgentId', () => {
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index d58ae0867..b8cdad729 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -293,7 +293,10 @@ export const USAGE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const
// newest CLAUDE transcript for that cwd. A grok node in this list would therefore show a stranger's
// conversation in its find bar and rehydrate its meter from it. That exact bug already happened once
// with codex and gemini; transcriptGates.ts documents it.
-export const CHAT_CAPABLE = ['claude', 'grok'] as const
+//
+// opencode joined 2026-09-28: it has no transcript file at all (SQLite since 1.18), so its chat is
+// read through `opencode export <id>` (core/opencode-chat.ts) and it stays out of the list below.
+export const CHAT_CAPABLE = ['claude', 'grok', 'opencode'] as const
// Agents whose transcript CLAUDE's own resolver can locate and parse — the gate for everything that
// goes through `resolveTranscript` (the find bar's index, the meter's mount-time rehydration).
//
diff --git a/src/shared/chat-fixtures/README.md b/src/shared/chat-fixtures/README.md
index f324b2f15..69de81d91 100644
--- a/src/shared/chat-fixtures/README.md
+++ b/src/shared/chat-fixtures/README.md
@@ -157,3 +157,11 @@ Most inputs are a few KB. Three inputs have to be larger than a page to exercise
`tools-cross-page` (~290 KB), `utf8-edge` (~790 KB, which is one 512 KB page plus one 256 KB tail by
construction) and `huge-last-line` (~1.1 MB). Their filler is deterministic lorem ipsum, and the
base64 image is generated by a seeded generator.
+
+## opencode
+
+`opencode/` holds the fixtures for the opencode reader (`src/core/opencode-chat.ts`): synthetic
+`opencode export` documents and the parse + page the desktop serves for each. opencode has no
+transcript file (SQLite since 1.18), so a read is ONE page (`olderCursor: null`). Its rules and
+layout are in `opencode/README.md`; regenerate with
+`UPDATE_CHAT_FIXTURES=1 npx vitest run src/core/opencode-chat.fixtures.test.ts`.
diff --git a/src/shared/chat-fixtures/opencode/README.md b/src/shared/chat-fixtures/opencode/README.md
new file mode 100644
index 000000000..f9203aa97
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/README.md
@@ -0,0 +1,132 @@
+# opencode chat golden fixtures
+
+The reference outputs for the chat view's **opencode** reader (`src/core/opencode-chat.ts`). The TS
+implementation is the reference. `nodeterm-ios` keeps a byte-identical copy of this directory, and
+its Swift port must reproduce every `expected/*.json` from the same `inputs/*.json`.
+
+Every input is **synthetic**: an `opencode export` document built by
+`src/core/opencode-chat.fixtures.test.ts` from the schema measured on opencode 1.18.25. None is a
+slice of a real session. Do not add one.
+
+## Regenerate
+
+```sh
+UPDATE_CHAT_FIXTURES=1 npx vitest run src/core/opencode-chat.fixtures.test.ts
+```
+
+Refused when `CI` is set. Without the variable the test requires every file to equal what the code
+produces, and `inputs/` / `expected/` to hold exactly the generated set.
+
+## Where the input comes from
+
+opencode has no transcript file. Since 1.18 it keeps sessions in SQLite, and the reader runs
+`opencode export <sessionID>` (argv exactly `["export", id]`, no other flag: opencode's CLI is yargs
+strict and exits 1 on an option an older build does not know). Measured on 1.18.25:
+
+- stdout is the document alone, `JSON.stringify(doc, null, 2)` + EOL; stderr says `Exporting session: <id>`;
+- an unknown id exits **1** with an **empty** stdout and `Session not found: <id>` on stderr (ANSI
+ coloured) — the only answer read as a clean miss (`found: false`); every other failure is a
+ failed read (`unreadable: true`);
+- one export costs 1.0–1.7 s and ~320 MB peak RSS, so the desktop runs at most one per session at a
+ time (starts spaced 2 s apart) and two in total.
+
+The reader never runs an export without a session id (a bare `opencode export` opens a picker over
+the newest sessions), never for an id outside `^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$`, and never for a
+remote node (its sessions are in the host's database).
+
+## Layout
+
+| path | what it is |
+|---|---|
+| `inputs/<name>.json` | The export document, exactly as `opencode export` would print it. |
+| `expected/<name>.json` | `{ sessionId, parse, page }` — see below. |
+
+- `sessionId` — the id the reader was asked for (`ses_0a1b2c3d4ffeSynthetic000001` in every case).
+- `parse` — `parseOpencodeExport(input, sessionId)` verbatim: `{ messages, skipped, model?, effort? }`,
+ or `null` when the input is not an export of that session.
+- `page` — what the desktop serves for a paged request (`{maxBytes: 262144}`), i.e. what the phone
+ receives before `host-chat` adds `version` / `sessionId`.
+
+Same serialization rules as the parent README: `JSON.stringify(value, null, 2) + "\n"`, keys in the
+order the TS code builds them, optional keys **absent** when unset (never `null`).
+
+## The page (one page, always)
+
+An export is ONE JSON document, so there are no byte offsets to page by. A paged read returns:
+
+- success: `{ messages, found: true, olderCursor: null, unmatchedResults: [], model?, effort? }`;
+- a clean miss (no session id, an unsafe id, or opencode's `Session not found`):
+ `{ messages: [], found: false, olderCursor: null, unmatchedResults: [] }`;
+- a failed export, an export that is not this session's (`parse` is `null`), or a remote node:
+ the same plus `unreadable: true`;
+- a request WITH `before` (an older page): `{ messages: [], found: true, olderCursor: null,
+ unmatchedResults: [] }` without running anything — this reader never hands out a cursor.
+
+`messages` is the parse's messages cut to the NEWEST ones whose `JSON.stringify` UTF-8 sizes sum to
+at most 5242880 bytes (`CHAT_PAGE_MAX_BYTES`), walking from the end and stopping at the first that
+does not fit. No `key` is set (there are no offsets), no tool part carries an `id`, and
+`unmatchedResults` is always `[]`.
+
+An unpaged (legacy) read is `{ messages, found }` only, and a failure is `{ messages: [], found: false }`.
+
+## The parse (the Swift port must replicate this exactly)
+
+`parse` is `null` unless the input is valid JSON whose top level is an object with an object
+`info` whose `id` equals the requested session id. Otherwise `messages` is built from
+`doc.messages` (a missing or non-array `messages` is `[]`), one entry at a time, in order:
+
+1. **Skipped and counted** (`skipped += 1`, nothing rendered): an entry that is not an object or has
+ no object `info`; an `info.sessionID` that is present and not the requested id; a `role` other
+ than `user` / `assistant`; `parts` that is not an array.
+2. `at` = `info.time.created` when it is a finite number (epoch ms), else the key is absent. Every
+ message pushed for the entry carries the same `at`.
+3. Each part, in order. A part that is not an object or has no string `type` is skipped and counted.
+ - `text`: a non-string `text` is skipped and counted. `synthetic: true`, `ignored: true` or an
+ empty text is dropped silently. Otherwise `{kind:"text", text}` for the speaker (not trimmed).
+ - `tool`: a non-object `state` is skipped and counted. Otherwise a tool part (below) — for the
+ speaker in an assistant entry, as a **chip** in a user entry.
+ - `compaction`: a chip `{kind:"tool", name:"compaction", arg: auto === true ? "auto" : ""}`.
+ - `subtask`: a chip `{kind:"tool", name:"task", arg}` with `arg` from `{description, prompt}` by
+ the tool-arg rule.
+ - `reasoning`, `step-start`, `step-finish`, `snapshot`, `patch`, `retry`, `file`, `agent`: dropped
+ silently (NOT counted).
+ - any other type: skipped and counted.
+4. An **assistant** entry: when `info.error` is present, a non-object error is skipped and counted;
+ otherwise a text part is appended after the speaker's parts: `[<name>] <message>` where `name` is
+ `error.name` when a non-empty string else `Error`, and `message` is `error.data.message` trimmed
+ (JS `trim`) when a string; with an empty message it is `[<name>]`. Then one assistant message of
+ speaker parts followed by chips, when there is at least one part.
+5. A **user** entry: a user message of the speaker's text parts (when any), then an assistant
+ message of the chips (when any).
+6. `model` / `effort`: the LAST assistant entry that passed rule 1 (whether or not it produced a
+ message) answers both — `info.modelID` and `info.variant`, each kept only when a string of 1 to
+ 100 UTF-16 code units. A field that entry does not state is absent; nothing is carried from an
+ older entry.
+
+**Tool part.** `name` = `tool` when a non-empty string, else `"tool"`. `arg` = the first STRING among
+`state.input`'s `command`, `filePath`, `file_path`, `pattern`, `path`, `url`, `query`,
+`description`, `prompt`, `name` (in that order — `pattern` before `path`); else
+`state.input.questions[0].question` when a string; else `state.title` when a string; else `""`;
+then cut to its first 200 UTF-16 units. `result`, only when set:
+
+- `status: "completed"` with a string `output`: the summary of `output`, key absent when empty;
+- `status: "error"` with a string `error`: the summary of `"Error: " + error`;
+- anything else (`pending`, `running`): no `result` key.
+
+The summary is the first three `\n`-separated lines joined by one space, then the first 500 UTF-16
+units. A tool part never carries `body`, `questions` or `id`: opencode's `question` tool looks like
+Claude's AskUserQuestion, but answer cards are Claude-only.
+
+## What each fixture pins
+
+| fixture | pins |
+|---|---|
+| `turns` | Markdown and non-ASCII text, two text parts in one message, `at`; reasoning and step parts dropped uncounted; a reasoning-only assistant entry yields no message but still answers `model` (and its missing `variant` leaves `effort` absent). |
+| `tools` | Every tool state, the arg key order (`pattern` before `path`), the `questions[0].question` and `title` fallbacks, a missing tool name, the 200-unit arg cap, the 3-line / 500-unit summary, `Error: ` on an error, no `result` key while pending/running, no card fields on `question`. |
+| `harness-text` | `synthetic` / `ignored` text, `file` and `agent` parts dropped; a user entry with only synthetic text yields nothing; a tool part in a user entry becomes an assistant chip after the user bubble. |
+| `errors` | `[name] message` after the partial text, `[name]` for an empty `data`, a trimmed message, a malformed error counted while the entry's text is kept, `retry` dropped. |
+| `compaction-subtask` | Auto and manual compaction chips, the `summary: true` message as ordinary text, a subtask chip after the user's text. |
+| `unmappable` | Eleven counted shapes (bad entries, an unknown role, non-array parts, a message of another session, bad parts, a stateless tool); only `kept` renders. |
+| `model-no-carry` | The newest assistant entry answers both fields; a user entry's `model` is never read. |
+| `model-utf16` | 101 UTF-16 units (50 × U+1F9EA + 1) is over the cap; 100 is kept. |
+| `foreign-session` | An export of another session: `parse` is `null` and the page is unreadable and empty. |
diff --git a/src/shared/chat-fixtures/opencode/expected/compaction-subtask.json b/src/shared/chat-fixtures/opencode/expected/compaction-subtask.json
new file mode 100644
index 000000000..5eae1eed8
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/compaction-subtask.json
@@ -0,0 +1,123 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": "auto"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "## Summary\n\nWe fixed the retry policy."
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": ""
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "/review"
+ }
+ ],
+ "at": 1780000004000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "task",
+ "arg": "Review staged changes"
+ }
+ ],
+ "at": 1780000004000
+ }
+ ],
+ "skipped": 0,
+ "model": "demo-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": "auto"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "## Summary\n\nWe fixed the retry policy."
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": ""
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "/review"
+ }
+ ],
+ "at": 1780000004000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "task",
+ "arg": "Review staged changes"
+ }
+ ],
+ "at": 1780000004000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/errors.json b/src/shared/chat-fixtures/opencode/expected/errors.json
new file mode 100644
index 000000000..955a60cd4
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/errors.json
@@ -0,0 +1,145 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Go."
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Starting on it"
+ },
+ {
+ "kind": "text",
+ "text": "[MessageAbortedError] The operation was aborted."
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[APIError] Rate limit exceeded"
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[MessageOutputLengthError]"
+ }
+ ],
+ "at": 1780000004000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[ProviderAuthError] Invalid API key"
+ }
+ ],
+ "at": 1780000005000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "still here"
+ }
+ ],
+ "at": 1780000006000
+ }
+ ],
+ "skipped": 1,
+ "model": "demo-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Go."
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Starting on it"
+ },
+ {
+ "kind": "text",
+ "text": "[MessageAbortedError] The operation was aborted."
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[APIError] Rate limit exceeded"
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[MessageOutputLengthError]"
+ }
+ ],
+ "at": 1780000004000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[ProviderAuthError] Invalid API key"
+ }
+ ],
+ "at": 1780000005000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "still here"
+ }
+ ],
+ "at": 1780000006000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/foreign-session.json b/src/shared/chat-fixtures/opencode/expected/foreign-session.json
new file mode 100644
index 000000000..c64c4119b
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/foreign-session.json
@@ -0,0 +1,11 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": null,
+ "page": {
+ "messages": [],
+ "found": false,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "unreadable": true
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/harness-text.json b/src/shared/chat-fixtures/opencode/expected/harness-text.json
new file mode 100644
index 000000000..d1908bc76
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/harness-text.json
@@ -0,0 +1,101 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Review @src/app.ts please"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "run the tests"
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "npm test",
+ "result": "ok 12 tests"
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Looks fine."
+ }
+ ],
+ "at": 1780000004000
+ }
+ ],
+ "skipped": 0,
+ "model": "demo-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Review @src/app.ts please"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "run the tests"
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "npm test",
+ "result": "ok 12 tests"
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Looks fine."
+ }
+ ],
+ "at": 1780000004000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/model-no-carry.json b/src/shared/chat-fixtures/opencode/expected/model-no-carry.json
new file mode 100644
index 000000000..667b2e02b
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/model-no-carry.json
@@ -0,0 +1,77 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "older"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "next"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "newest"
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "skipped": 0,
+ "model": "newest-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "older"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "next"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "newest"
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "newest-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/model-utf16.json b/src/shared/chat-fixtures/opencode/expected/model-utf16.json
new file mode 100644
index 000000000..9ea1424d9
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/model-utf16.json
@@ -0,0 +1,37 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "x"
+ }
+ ],
+ "at": 1780000001000
+ }
+ ],
+ "skipped": 0,
+ "effort": "🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "x"
+ }
+ ],
+ "at": 1780000001000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "effort": "🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/tools.json b/src/shared/chat-fixtures/opencode/expected/tools.json
new file mode 100644
index 000000000..71765cb84
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/tools.json
@@ -0,0 +1,181 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Look around the repo."
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "ls -la",
+ "result": "total 8 drwxr-xr-x a drwxr-xr-x b"
+ },
+ {
+ "kind": "tool",
+ "name": "read",
+ "arg": "/srv/demo/src/app.ts",
+ "result": "lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum do"
+ },
+ {
+ "kind": "tool",
+ "name": "grep",
+ "arg": "TODO",
+ "result": "Found 2 matches"
+ },
+ {
+ "kind": "tool",
+ "name": "edit",
+ "arg": "/srv/demo/src/app.ts",
+ "result": "Error: oldString not found in content Make the match unique."
+ },
+ {
+ "kind": "tool",
+ "name": "webfetch",
+ "arg": "https://example.test/docs"
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": ""
+ },
+ {
+ "kind": "tool",
+ "name": "todowrite",
+ "arg": "1 todo",
+ "result": "[]"
+ },
+ {
+ "kind": "tool",
+ "name": "question",
+ "arg": "Which colour should the badge be?",
+ "result": "User has answered your questions: \"Which colour should the badge be?\"=\"Blue\"."
+ },
+ {
+ "kind": "tool",
+ "name": "tool",
+ "arg": ""
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "echo zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Done looking."
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "skipped": 0,
+ "model": "demo-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Look around the repo."
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "ls -la",
+ "result": "total 8 drwxr-xr-x a drwxr-xr-x b"
+ },
+ {
+ "kind": "tool",
+ "name": "read",
+ "arg": "/srv/demo/src/app.ts",
+ "result": "lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum do"
+ },
+ {
+ "kind": "tool",
+ "name": "grep",
+ "arg": "TODO",
+ "result": "Found 2 matches"
+ },
+ {
+ "kind": "tool",
+ "name": "edit",
+ "arg": "/srv/demo/src/app.ts",
+ "result": "Error: oldString not found in content Make the match unique."
+ },
+ {
+ "kind": "tool",
+ "name": "webfetch",
+ "arg": "https://example.test/docs"
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": ""
+ },
+ {
+ "kind": "tool",
+ "name": "todowrite",
+ "arg": "1 todo",
+ "result": "[]"
+ },
+ {
+ "kind": "tool",
+ "name": "question",
+ "arg": "Which colour should the badge be?",
+ "result": "User has answered your questions: \"Which colour should the badge be?\"=\"Blue\"."
+ },
+ {
+ "kind": "tool",
+ "name": "tool",
+ "arg": ""
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "echo zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Done looking."
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/turns.json b/src/shared/chat-fixtures/opencode/expected/turns.json
new file mode 100644
index 000000000..f04731ff7
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/turns.json
@@ -0,0 +1,85 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Explain the **retry** policy.\n\n- one\n- two"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "## Retry\n\nThree attempts, then a backoff:\n\n```ts\nconst n = 3\n```"
+ },
+ {
+ "kind": "text",
+ "text": "Second block — ğüşçöı 😀"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Thanks!"
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "skipped": 0,
+ "model": "demo-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Explain the **retry** policy.\n\n- one\n- two"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "## Retry\n\nThree attempts, then a backoff:\n\n```ts\nconst n = 3\n```"
+ },
+ {
+ "kind": "text",
+ "text": "Second block — ğüşçöı 😀"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Thanks!"
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/unmappable.json b/src/shared/chat-fixtures/opencode/expected/unmappable.json
new file mode 100644
index 000000000..569f6288c
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/unmappable.json
@@ -0,0 +1,37 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "kept"
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "skipped": 11,
+ "model": "demo-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "kept"
+ }
+ ],
+ "at": 1780000003000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/compaction-subtask.json b/src/shared/chat-fixtures/opencode/inputs/compaction-subtask.json
new file mode 100644
index 000000000..f8301c122
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/compaction-subtask.json
@@ -0,0 +1,197 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "compaction",
+ "auto": true,
+ "id": "prt_fixture0044",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "compaction",
+ "agent": "compaction",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000002000,
+ "completed": 1780000002500
+ },
+ "finish": "stop",
+ "id": "msg_2",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "summary": true
+ },
+ "parts": [
+ {
+ "type": "step-start",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "id": "prt_fixture0045",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "## Summary\n\nWe fixed the retry policy.",
+ "id": "prt_fixture0046",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "step-finish",
+ "reason": "stop",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "id": "prt_fixture0047",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000003000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_3",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "compaction",
+ "auto": false,
+ "overflow": true,
+ "id": "prt_fixture0048",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000004000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_4",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "/review",
+ "id": "prt_fixture0049",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "subtask",
+ "prompt": "Review the staged changes in full.",
+ "description": "Review staged changes",
+ "agent": "general",
+ "command": "review",
+ "id": "prt_fixture0050",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/errors.json b/src/shared/chat-fixtures/opencode/inputs/errors.json
new file mode 100644
index 000000000..1eb8e4497
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/errors.json
@@ -0,0 +1,294 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "Go.",
+ "id": "prt_fixture0039",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000002000,
+ "completed": 1780000002500
+ },
+ "id": "msg_2",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "error": {
+ "name": "MessageAbortedError",
+ "data": {
+ "message": "The operation was aborted."
+ }
+ }
+ },
+ "parts": [
+ {
+ "type": "step-start",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "id": "prt_fixture0040",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "Starting on it",
+ "id": "prt_fixture0041",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "retry",
+ "attempt": 1,
+ "error": {
+ "name": "APIError",
+ "data": {
+ "message": "Overloaded",
+ "isRetryable": true
+ }
+ },
+ "time": {
+ "created": 1780000000000
+ },
+ "id": "prt_fixture0042",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000003000,
+ "completed": 1780000003500
+ },
+ "finish": "stop",
+ "id": "msg_3",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "error": {
+ "name": "APIError",
+ "data": {
+ "message": "Rate limit exceeded",
+ "statusCode": 429,
+ "isRetryable": true
+ }
+ }
+ },
+ "parts": []
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000004000,
+ "completed": 1780000004500
+ },
+ "finish": "stop",
+ "id": "msg_4",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "error": {
+ "name": "MessageOutputLengthError",
+ "data": {}
+ }
+ },
+ "parts": []
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000005000,
+ "completed": 1780000005500
+ },
+ "finish": "stop",
+ "id": "msg_5",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "error": {
+ "name": "ProviderAuthError",
+ "data": {
+ "providerID": "opencode",
+ "message": " Invalid API key "
+ }
+ }
+ },
+ "parts": []
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000006000,
+ "completed": 1780000006500
+ },
+ "finish": "stop",
+ "id": "msg_6",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "error": "not an object"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "still here",
+ "id": "prt_fixture0043",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/foreign-session.json b/src/shared/chat-fixtures/opencode/inputs/foreign-session.json
new file mode 100644
index 000000000..f1d9eafa7
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/foreign-session.json
@@ -0,0 +1,64 @@
+{
+ "info": {
+ "id": "ses_someoneElse00000000000",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "SOMEONE ELSE PRIVATE",
+ "id": "prt_fixture0062",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/harness-text.json b/src/shared/chat-fixtures/opencode/inputs/harness-text.json
new file mode 100644
index 000000000..d34eeda6e
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/harness-text.json
@@ -0,0 +1,261 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "Review @src/app.ts please",
+ "id": "prt_fixture0027",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "file",
+ "mime": "text/plain",
+ "filename": "app.ts",
+ "url": "file:///srv/demo/src/app.ts",
+ "source": {
+ "type": "file",
+ "path": "src/app.ts",
+ "text": {
+ "value": "@src/app.ts",
+ "start": 7,
+ "end": 18
+ }
+ },
+ "id": "prt_fixture0028",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "Called the Read tool with the following input: {\"filePath\":\"/srv/demo/src/app.ts\"}",
+ "synthetic": true,
+ "id": "prt_fixture0029",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "<file>\n00001| export {}\n</file>",
+ "synthetic": true,
+ "id": "prt_fixture0030",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "agent",
+ "name": "plan",
+ "source": {
+ "value": "@plan",
+ "start": 0,
+ "end": 5
+ },
+ "id": "prt_fixture0031",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "not for the model",
+ "ignored": true,
+ "id": "prt_fixture0032",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000002000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_2",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "The following tool was executed by the user",
+ "synthetic": true,
+ "id": "prt_fixture0033",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000003000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_3",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "run the tests",
+ "id": "prt_fixture0034",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "bash",
+ "callID": "call_fixture34",
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "npm test"
+ },
+ "output": "ok 12 tests",
+ "title": "npm test",
+ "metadata": {},
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0035",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000004000,
+ "completed": 1780000004500
+ },
+ "finish": "stop",
+ "id": "msg_4",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "step-start",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "id": "prt_fixture0036",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "Looks fine.",
+ "id": "prt_fixture0037",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "step-finish",
+ "reason": "stop",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "id": "prt_fixture0038",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/model-no-carry.json b/src/shared/chat-fixtures/opencode/inputs/model-no-carry.json
new file mode 100644
index 000000000..8a2b1c59d
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/model-no-carry.json
@@ -0,0 +1,148 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "older-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000001000,
+ "completed": 1780000001500
+ },
+ "finish": "stop",
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "variant": "max"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "older",
+ "id": "prt_fixture0058",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000002000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "user-picked",
+ "variant": "low"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_2",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "next",
+ "id": "prt_fixture0059",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "newest-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000003000,
+ "completed": 1780000003500
+ },
+ "finish": "stop",
+ "id": "msg_3",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "newest",
+ "id": "prt_fixture0060",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/model-utf16.json b/src/shared/chat-fixtures/opencode/inputs/model-utf16.json
new file mode 100644
index 000000000..733ea4a6e
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/model-utf16.json
@@ -0,0 +1,79 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪m",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000001000,
+ "completed": 1780000001500
+ },
+ "finish": "stop",
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "variant": "🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "x",
+ "id": "prt_fixture0061",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/tools.json b/src/shared/chat-fixtures/opencode/inputs/tools.json
new file mode 100644
index 000000000..844b2fbd9
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/tools.json
@@ -0,0 +1,406 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "Look around the repo.",
+ "id": "prt_fixture0011",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000002000,
+ "completed": 1780000002500
+ },
+ "finish": "tool-calls",
+ "id": "msg_2",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "step-start",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "id": "prt_fixture0012",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "bash",
+ "callID": "call_fixture12",
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "ls -la",
+ "description": "List files"
+ },
+ "output": "total 8\ndrwxr-xr-x a\ndrwxr-xr-x b\n-rw-r--r-- c",
+ "title": "List files",
+ "metadata": {},
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0013",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "read",
+ "callID": "call_fixture13",
+ "state": {
+ "status": "completed",
+ "input": {
+ "filePath": "/srv/demo/src/app.ts"
+ },
+ "output": "lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet",
+ "title": "src/app.ts",
+ "metadata": {},
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0014",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "grep",
+ "callID": "call_fixture14",
+ "state": {
+ "status": "completed",
+ "input": {
+ "pattern": "TODO",
+ "path": "/srv/demo/src"
+ },
+ "output": "Found 2 matches",
+ "title": "TODO",
+ "metadata": {},
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0015",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "edit",
+ "callID": "call_fixture15",
+ "state": {
+ "status": "error",
+ "input": {
+ "filePath": "/srv/demo/src/app.ts",
+ "oldString": "a",
+ "newString": "b"
+ },
+ "error": "oldString not found in content\nMake the match unique.",
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0016",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "webfetch",
+ "callID": "call_fixture16",
+ "state": {
+ "status": "running",
+ "input": {
+ "url": "https://example.test/docs"
+ },
+ "title": "Fetching",
+ "time": {
+ "start": 1780000000000
+ }
+ },
+ "id": "prt_fixture0017",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "bash",
+ "callID": "call_fixture17",
+ "state": {
+ "status": "pending",
+ "input": {},
+ "raw": "{\"comm"
+ },
+ "id": "prt_fixture0018",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "todowrite",
+ "callID": "call_fixture18",
+ "state": {
+ "status": "completed",
+ "input": {
+ "todos": [
+ {
+ "content": "x",
+ "status": "pending",
+ "priority": "high"
+ }
+ ]
+ },
+ "output": "[]",
+ "title": "1 todo",
+ "metadata": {},
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0019",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "question",
+ "callID": "call_fixture19",
+ "state": {
+ "status": "completed",
+ "input": {
+ "questions": [
+ {
+ "question": "Which colour should the badge be?",
+ "header": "Colour",
+ "options": [
+ {
+ "label": "Red",
+ "description": "warm"
+ },
+ {
+ "label": "Blue",
+ "description": "cool"
+ }
+ ]
+ }
+ ]
+ },
+ "output": "User has answered your questions: \"Which colour should the badge be?\"=\"Blue\".",
+ "title": "Asked 1 question",
+ "metadata": {},
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0020",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "callID": "call_fixture20",
+ "state": {
+ "status": "running",
+ "input": {},
+ "time": {
+ "start": 1780000000000
+ }
+ },
+ "id": "prt_fixture0021",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "tool",
+ "tool": "bash",
+ "callID": "call_fixture21",
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "echo zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
+ },
+ "output": "",
+ "title": "Done",
+ "metadata": {},
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ }
+ },
+ "id": "prt_fixture0022",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "id": "prt_fixture0023",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000003000,
+ "completed": 1780000003500
+ },
+ "finish": "stop",
+ "id": "msg_3",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "step-start",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "id": "prt_fixture0024",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "Done looking.",
+ "id": "prt_fixture0025",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "step-finish",
+ "reason": "stop",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "id": "prt_fixture0026",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/turns.json b/src/shared/chat-fixtures/opencode/inputs/turns.json
new file mode 100644
index 000000000..bfab07758
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/turns.json
@@ -0,0 +1,247 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "Explain the **retry** policy.\n\n- one\n- two",
+ "id": "prt_fixture0001",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000002000,
+ "completed": 1780000002500
+ },
+ "finish": "stop",
+ "id": "msg_2",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "variant": "high"
+ },
+ "parts": [
+ {
+ "type": "step-start",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "id": "prt_fixture0002",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "reasoning",
+ "text": "The user wants the retry policy.",
+ "time": {
+ "start": 1780000000000,
+ "end": 1780000000001
+ },
+ "id": "prt_fixture0003",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "## Retry\n\nThree attempts, then a backoff:\n\n```ts\nconst n = 3\n```",
+ "id": "prt_fixture0004",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": "Second block — ğüşçöı 😀",
+ "id": "prt_fixture0005",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "step-finish",
+ "reason": "stop",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "id": "prt_fixture0006",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000003000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_3",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "Thanks!",
+ "id": "prt_fixture0007",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000004000,
+ "completed": 1780000004500
+ },
+ "finish": "stop",
+ "id": "msg_4",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "step-start",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "id": "prt_fixture0008",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "reasoning",
+ "text": "thinking only",
+ "time": {
+ "start": 1780000000000
+ },
+ "id": "prt_fixture0009",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "step-finish",
+ "reason": "stop",
+ "snapshot": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "id": "prt_fixture0010",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/unmappable.json b/src/shared/chat-fixtures/opencode/inputs/unmappable.json
new file mode 100644
index 000000000..bd8912fa0
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/unmappable.json
@@ -0,0 +1,200 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "slug": "quiet-harbor",
+ "projectID": "prj_fixture",
+ "directory": "/srv/demo",
+ "path": "",
+ "title": "Fixture session",
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode"
+ },
+ "version": "1.18.25",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000
+ }
+ },
+ "messages": [
+ "a string where a message should be",
+ null,
+ {
+ "parts": [
+ {
+ "type": "text",
+ "text": "no info",
+ "id": "prt_fixture0051",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "system",
+ "id": "msg_s",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "unknown role",
+ "id": "prt_fixture0052",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_1",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": "parts is not an array"
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000002000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_2",
+ "sessionID": "ses_someoneElse00000000000"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "SOMEONE ELSE PRIVATE",
+ "id": "prt_fixture0053",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "role": "user",
+ "time": {
+ "created": 1780000003000
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "opencode",
+ "modelID": "demo-model"
+ },
+ "summary": {
+ "diffs": []
+ },
+ "id": "msg_3",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "text",
+ "text": "kept",
+ "id": "prt_fixture0054",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ 7,
+ {
+ "no": "type"
+ },
+ {
+ "type": "future-kind",
+ "secret": "x",
+ "id": "prt_fixture0055",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ },
+ {
+ "type": "text",
+ "text": 42,
+ "id": "prt_fixture0056",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ },
+ {
+ "info": {
+ "parentID": "msg_parent",
+ "role": "assistant",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/srv/demo",
+ "root": "/srv/demo"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 20,
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "write": 0,
+ "read": 0
+ }
+ },
+ "modelID": "demo-model",
+ "providerID": "opencode",
+ "time": {
+ "created": 1780000004000,
+ "completed": 1780000004500
+ },
+ "finish": "stop",
+ "id": "msg_4",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001"
+ },
+ "parts": [
+ {
+ "type": "tool",
+ "tool": "bash",
+ "callID": "c",
+ "state": "not an object",
+ "id": "prt_fixture0057",
+ "sessionID": "ses_0a1b2c3d4ffeSynthetic000001",
+ "messageID": "msg_fixture"
+ }
+ ]
+ }
+ ]
+}