Skip to content

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

fix(opencode): read OpenCode 2.x sessions (export spelling + message shape)

reviewb211b482e6bd
diff --git a/CLAUDE.md b/CLAUDE.md
index 85b3aafad..303889504 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3145,8 +3145,25 @@ its agent status" under Hosted team relay.
- **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:
+ `core/opencode-chat.ts`, which runs the session export (`core/opencode-export.ts`, shared with
+ Context Link) and parses the one JSON document into claude's `ChatMessage` shape. **The export
+ has two spellings and NO single one works on both lines** (issue #1438, measured on
+ @opencode/cli 2.2.7 and opencode-ai 1.18.33): 1.x is `opencode export <id>` (argv only — a
+ yargs-strict CLI exits on an unknown flag); 2.x refuses that with usage text + `Unexpected
+ positional argument` and wants `opencode session export --standalone <id>`, which 1.x does not
+ know. 1.x's is tried first, 2.x's ONLY on that measured refusal (a timeout or a locked database
+ must not buy a second ~1.5 s spawn), and the spelling that answered is remembered per binary.
+ **`--standalone` is not optional**: without it 2.x talks to its shared background service and
+ STARTS it when it is not running — a daemon that outlives the read (the same trap as #1136) —
+ and fails outright when the service port is taken. The SSH leg of Context Link has no second
+ round trip, so it is one generated `sh -c` line (`remoteOpencodeExportCommand`) that holds the
+ first spelling's stdout back until it succeeds; it is run under a real `/bin/sh` in
+ `opencode-export.test.ts`. **The document's messages also changed shape in 2.x** — flat records
+ discriminated by `type` (`user {text}`, `assistant {content[]}`, `shell`, `compaction`, harness
+ and bookkeeping types) instead of `{info:{role}, parts[]}` — and BOTH readers
+ (`parseOpencodeExport`, `linesFromOpencodeExport`) carry a branch per shape; only the
+ user / assistant-text / completed-tool path was seen in a real 2.x export, the rest is composed
+ from the schema in the shipped binary. The mapping below is 1.x's; 2.x's is in the fixtures README:
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`.
diff --git a/src/core/context-link-render.opencode.test.ts b/src/core/context-link-render.opencode.test.ts
new file mode 100644
index 000000000..89cec7f46
--- /dev/null
+++ b/src/core/context-link-render.opencode.test.ts
@@ -0,0 +1,89 @@
+// Context Link's flat-line reading of an opencode export, in both measured shapes. Issue #1438:
+// opencode 2.x messages carry no `info` / `parts`, so the 1.x-only reader dropped every USER
+// message (its prompt is a top-level `text`) and a summary showed one side of the conversation.
+import { describe, expect, it } from 'vitest'
+import { linesFromOpencodeExport, renderContextLink, type ContextLinkFetch } from './context-link-render'
+
+/** The shape of a real `opencode session export` (@opencode/cli 2.2.7), values replaced. */
+const V2_EXPORT = JSON.stringify({
+ info: { id: 'ses_fixture', title: 'Fixture', model: { id: 'demo', providerID: 'opencode', variant: 'default' } },
+ messages: [
+ { id: 'msg_0', time: { created: 1 }, type: 'system', text: 'SYSTEM TEXT NEVER SHOWN' },
+ { id: 'msg_1', time: { created: 2 }, text: 'Read note.txt please', files: [], type: 'user' },
+ { id: 'msg_s', time: { created: 2 }, type: 'synthetic', text: 'SYNTHETIC TEXT NEVER SHOWN' },
+ {
+ id: 'msg_2',
+ time: { created: 3 },
+ type: 'assistant',
+ agent: 'build',
+ content: [
+ { type: 'reasoning', text: 'REASONING NEVER SHOWN' },
+ {
+ type: 'tool',
+ id: 'call_1',
+ name: 'read',
+ executed: false,
+ state: { status: 'completed', input: { path: 'note.txt' }, content: [{ type: 'text', text: '1: hello' }] }
+ }
+ ],
+ finish: 'tool-calls'
+ },
+ { id: 'msg_3', time: { created: 4 }, type: 'assistant', content: [{ type: 'text', text: 'It says hello.' }] },
+ { id: 'msg_4', time: { created: 5 }, type: 'idle', outcome: 'succeeded' }
+ ]
+})
+
+const V1_EXPORT = JSON.stringify({
+ info: { id: 'ses_fixture' },
+ messages: [
+ { info: { role: 'user' }, parts: [{ type: 'text', text: 'Run the tests' }] },
+ {
+ info: { role: 'assistant' },
+ parts: [
+ { type: 'tool', tool: 'bash', state: { status: 'completed', input: { command: 'npm test' }, output: 'ok' } },
+ { type: 'text', text: 'All green.' }
+ ]
+ }
+ ]
+})
+
+describe('linesFromOpencodeExport', () => {
+ it('2.x: both speakers, the tool call, and none of the harness entries', () => {
+ expect(linesFromOpencodeExport(V2_EXPORT)).toEqual([
+ 'user: Read note.txt please',
+ ' $ read note.txt',
+ 'assistant: It says hello.'
+ ])
+ })
+
+ it('1.x: unchanged', () => {
+ expect(linesFromOpencodeExport(V1_EXPORT)).toEqual(['user: Run the tests', ' $ bash npm test', 'assistant: All green.'])
+ })
+
+ it('not JSON is null (an unreadable export), an empty document is no lines', () => {
+ expect(linesFromOpencodeExport('USAGE\n opencode <subcommand>')).toBeNull()
+ expect(linesFromOpencodeExport('{"info":{},"messages":[]}')).toEqual([])
+ })
+})
+
+describe('renderContextLink — an opencode node', () => {
+ const doc = { self: 'node-A', links: [{ id: 'node-O', title: 'API project', tmux: '', transcriptPath: '', cwd: '', agent: 'opencode', sessionId: 'ses_fixture' }] }
+ const fetch = (out: string | null): ContextLinkFetch => ({
+ transcript: async () => null,
+ terminal: async () => '',
+ opencodeExport: async () => out
+ })
+
+ it('summarises a 2.x session with the user turns in it', async () => {
+ const out = await renderContextLink(doc as never, 'summary', { n: '15' }, fetch(V2_EXPORT))
+ expect(out).toContain('user: Read note.txt please')
+ expect(out).toContain('assistant: It says hello.')
+ })
+
+ it('a failed export does not claim opencode is missing', async () => {
+ const out = await renderContextLink(doc as never, 'summary', {}, fetch(null))
+ expect(out).toContain('Could not export "API project" session')
+ expect(out).toContain('export failed')
+ expect(out).not.toContain('is opencode installed')
+ })
+})
diff --git a/src/core/context-link-render.ts b/src/core/context-link-render.ts
index 2047c242b..02bc38e35 100644
--- a/src/core/context-link-render.ts
+++ b/src/core/context-link-render.ts
@@ -150,9 +150,15 @@ export function linesFromGemini(buf: string): string[] {
}
/**
- * An `opencode export <sessionID>` JSON document -> display strings. opencode >= 1.18 keeps
- * sessions in SQLite, so its disk is never parsed; the export is the contract. Shapes are read
- * defensively: a messages array whose items carry role + parts[] (text / tool) or a plain string.
+ * An opencode export JSON document -> display strings. opencode >= 1.18 keeps sessions in SQLite,
+ * so its disk is never parsed; the export is the contract. Two measured message shapes:
+ *
+ * 1.x `{info: {role}, parts: [{type:'text', text} | {type:'tool', tool, state:{input}}]}`
+ * 2.x `{type:'user', text}` · `{type:'assistant', content: [{type:'text', text} |
+ * {type:'tool', name, state:{input}}]}` · bookkeeping types with no conversation in them
+ * (`idle`, `synthetic`, `system`, `skill`, `*-switched`, …) — measured on 2.2.7, issue #1438
+ *
+ * Anything else is read defensively: a role + parts[] or a plain string content.
*/
export function linesFromOpencodeExport(raw: string): string[] | null {
const o = parseJson(raw) as
@@ -166,15 +172,26 @@ export function linesFromOpencodeExport(raw: string): string[] | null {
const m = raw as {
role?: string
info?: { role?: string }
+ type?: unknown
+ text?: unknown
parts?: unknown[]
content?: unknown
}
if (!m) continue
- const role = (m.role ?? m.info?.role) === 'user' ? 'user' : 'assistant'
+ const stated = m.role ?? m.info?.role
+ // A 2.x entry states its kind in `type`. One that is neither speaker is harness bookkeeping
+ // (a `synthetic` or `system` entry carries `text` the human never typed) — never a line.
+ if (stated === undefined && typeof m.type === 'string' && m.type !== 'user' && m.type !== 'assistant') continue
+ const role = (stated ?? m.type) === 'user' ? 'user' : 'assistant'
if (typeof m.content === 'string' && m.content) {
res.push(`${role}: ${m.content}`)
continue
}
+ // 2.x user message: the prompt is a top-level `text`, with no parts at all.
+ if (stated === undefined && m.type === 'user' && typeof m.text === 'string' && m.text) {
+ res.push(`user: ${m.text}`)
+ continue
+ }
const parts = m.parts ?? (Array.isArray(m.content) ? (m.content as unknown[]) : null)
if (!Array.isArray(parts)) continue
for (const p of parts) {
@@ -192,7 +209,10 @@ export function linesFromOpencodeExport(raw: string): string[] | null {
} else if (c.type === 'tool' || c.type === 'tool_use' || c.tool) {
const name = c.tool || c.name || 'tool'
const input = c.state?.input ?? c.input
- const a = input && (input.command ?? input.filePath ?? input.file_path ?? input.pattern ?? input.description)
+ // `path` last: 2.x's read/list tools state the file as `path` (1.x: `filePath`).
+ const a =
+ input &&
+ (input.command ?? input.filePath ?? input.file_path ?? input.pattern ?? input.description ?? input.path)
res.push(` $ ${name}${typeof a === 'string' ? ` ${a.slice(0, TOOL_ARG_MAX)}` : ''}`)
}
}
@@ -536,7 +556,7 @@ export interface ContextLinkFetch {
transcript: (node: LinkDocEntry) => Promise<string | null>
/** The linked node's recent terminal output ('' when the session is not running). */
terminal: (node: LinkDocEntry) => Promise<string>
- /** `opencode export <sessionId>` output, or null when it could not be produced. */
+ /** The opencode export document for the node's session, or null when it could not be produced. */
opencodeExport: (node: LinkDocEntry) => Promise<string | null>
}
@@ -572,7 +592,12 @@ async function transcriptLinesFor(node: LinkDocEntry, fetch: ContextLinkFetch):
if (node.agent === 'opencode') {
if (!node.sessionId) return `"${node.title}" has no session id yet.`
const raw = await fetch.opencodeExport(node)
- if (raw == null) return `Could not export "${node.title}" session (is opencode installed?).`
+ // Null covers every failed read — no binary on the login PATH, a CLI that refused or crashed, a
+ // timeout, a session opencode does not have. Naming one of them as THE cause sent a user with a
+ // working opencode 2.x looking for a missing install (issue #1438).
+ if (raw == null) {
+ return `Could not export "${node.title}" session: opencode was not found, or its export failed or timed out.`
+ }
const lines = linesFromOpencodeExport(raw)
if (lines == null) return `Unreadable opencode export for "${node.title}".`
if (!lines.length) return `"${node.title}" export contained no readable messages.`
diff --git a/src/core/context-link.handler.test.ts b/src/core/context-link.handler.test.ts
index c8094f038..dcd8be9e5 100644
--- a/src/core/context-link.handler.test.ts
+++ b/src/core/context-link.handler.test.ts
@@ -198,7 +198,11 @@ describe('handleContextLinkRequest — remote (SSH) reads', () => {
'node-A': [{ id: 'node-R', title: 'Remote', agentId: 'opencode', sessionId: 'ses_6f2a9c1d' }]
})
await handleContextLinkRequest({ verb: 'transcript', nodeId: 'node-A', args: {} })
- expect(sent).toEqual([`opencode export 'ses_6f2a9c1d'`])
+ // One command line that works on opencode 1.x and 2.x (issue #1438); the id reaches it ONLY as
+ // the single-quoted positional after the script, never interpolated into the script itself.
+ expect(sent).toHaveLength(1)
+ expect(sent[0].endsWith(` sh 'ses_6f2a9c1d'`)).toBe(true)
+ expect(sent[0].split('ses_6f2a9c1d')).toHaveLength(2)
})
// The id is refused before the remote branch too: quoting keeps shell syntax out, but only the
diff --git a/src/core/context-link.ts b/src/core/context-link.ts
index 2045ab2d5..fee46e9e2 100644
--- a/src/core/context-link.ts
+++ b/src/core/context-link.ts
@@ -22,7 +22,7 @@ import { IPC } from '../shared/ipc'
import type { ContextLinkInfo, ContextLinkMap } from '../shared/types'
import { type PtyManager } from './pty-manager'
import { findInLoginPath } from './exec-path'
-import { isSafeOpencodeSessionId, runOpencodeExportAt } from './opencode-export'
+import { isSafeOpencodeSessionId, remoteOpencodeExportCommand, runOpencodeExportAt } from './opencode-export'
import { TMUX_SOCKET } from './tmux-naming'
import {
buildContextShimScript,
@@ -225,7 +225,7 @@ async function fetchOpencodeExport(node: LinkDocEntry): Promise<string | null> {
if (!node.sessionId || !isSafeOpencodeSessionId(node.sessionId)) return null
if (deps.isRemoteNode?.(node.id)) {
return deps.runRemoteCommand
- ? await deps.runRemoteCommand(node.id, `opencode export ${shellQuote(node.sessionId)}`)
+ ? await deps.runRemoteCommand(node.id, remoteOpencodeExportCommand(shellQuote(node.sessionId)))
: null
}
const bin = await findInLoginPath('opencode')
diff --git a/src/core/opencode-chat.fixtures.test.ts b/src/core/opencode-chat.fixtures.test.ts
index 808fad036..7509bf339 100644
--- a/src/core/opencode-chat.fixtures.test.ts
+++ b/src/core/opencode-chat.fixtures.test.ts
@@ -5,8 +5,9 @@
// 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.
+// Every input is SYNTHETIC: an export document built from the schema measured on opencode 1.18.25
+// and, for the `v2-*` set, @opencode/cli 2.2.7 (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'
@@ -100,6 +101,59 @@ const done = (input: Record<string, unknown>, output: string, title = 'Done') =>
time: { start: T0, end: T0 + 1 }
})
+// ── opencode 2.x builders — the schema measured on @opencode/cli 2.2.7 (see core/opencode-chat.ts) ──
+const exportDocV2 = (messages: unknown[], id: string = SID): string =>
+ JSON.stringify(
+ {
+ info: {
+ id,
+ projectID: 'prj_fixture',
+ model: { id: 'demo-model', providerID: 'opencode', variant: 'default' },
+ cost: 0,
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
+ outcome: 'succeeded',
+ time: { created: T0, updated: T0, busy: T0, idle: T0 },
+ title: 'Fixture session',
+ location: { directory: '/srv/demo' }
+ },
+ messages
+ },
+ null,
+ 2
+ ) + '\n'
+const v2Entry = (id: string, type: string, fields: Record<string, unknown> = {}) => ({
+ id,
+ time: { created: tick(id) },
+ ...fields,
+ type
+})
+const v2User = (id: string, text: string) => v2Entry(id, 'user', { text, files: [] })
+const v2Asst = (id: string, content: unknown[], extra: Record<string, unknown> = {}) =>
+ v2Entry(id, 'assistant', {
+ agent: 'build',
+ model: { id: 'demo-model', providerID: 'opencode', variant: 'default' },
+ content,
+ finish: 'stop',
+ rawFinish: 'stop',
+ cost: 0,
+ tokens: { input: 12, output: 8, reasoning: 0, cache: { read: 0, write: 0 } },
+ ...extra
+ })
+const v2Tool = (name: string | undefined, state: Record<string, unknown>) => ({
+ type: 'tool',
+ id: `call_fixture${++seq}`,
+ ...(name === undefined ? {} : { name }),
+ executed: false,
+ state,
+ time: { created: T0, ran: T0 + 1, completed: T0 + 2 }
+})
+const v2Done = (input: Record<string, unknown>, texts: string[]) => ({
+ status: 'completed',
+ input,
+ content: texts.map((text) => ({ type: 'text', text })),
+ metadata: { truncated: false }
+})
+
const lorem = (n: number): string =>
Array.from({ length: n }, (_, i) => ['lorem', 'ipsum', 'dolor', 'sit', 'amet'][i % 5]).join(' ')
@@ -206,7 +260,68 @@ const INPUTS: Record<string, string> = {
// 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')
+ 'foreign-session': exportDoc([userMsg('msg_1', [textPart('SOMEONE ELSE PRIVATE')])], 'ses_someoneElse00000000000'),
+
+ // ── opencode 2.x (`opencode session export`): flat entries discriminated by `type` ────────────
+ // The measured turn: a prompt, a tool-only assistant entry, the answer, the `idle` marker. The
+ // newest assistant entry answers `model`; its `variant: "default"` is not an effort.
+ 'v2-turns': exportDocV2([
+ v2User('msg_1', 'Read `note.txt` — özet lütfen 🧪'),
+ v2Asst('msg_2', [v2Tool('read', v2Done({ path: 'note.txt' }, ['Read file note.txt, lines 1-1\n1: hello fixture']))], {
+ finish: 'tool-calls'
+ }),
+ v2Asst('msg_3', [{ type: 'reasoning', text: 'thinking it over' }, { type: 'text', text: 'It holds **one** line.' }, { type: 'text', text: 'Second block.' }]),
+ v2Entry('msg_4', 'idle', { outcome: 'succeeded' }),
+ v2User('msg_5', 'and with a variant?'),
+ v2Asst('msg_6', [{ type: 'text', text: 'Yes.' }], { model: { id: 'demo-model-2', providerID: 'opencode', variant: 'high' } })
+ ]),
+ // Every 2.x tool state: the raw-string `streaming` input, running, completed (text blocks joined,
+ // a `file` block ignored, the 3-line / 500-unit summary), error, a missing name, a stateless tool.
+ 'v2-tools': exportDocV2([
+ v2Asst('msg_1', [
+ v2Tool('bash', { status: 'streaming', input: '{"command":"ls' }),
+ v2Tool('bash', { status: 'running', input: { command: 'sleep 5' }, metadata: {} }),
+ v2Tool('grep', v2Done({ pattern: 'TODO', path: 'src' }, ['a\nb', 'c\nd'])),
+ v2Tool('read', {
+ status: 'completed',
+ input: { path: 'shot.png' },
+ content: [{ type: 'file', uri: 'media:00', mime: 'image/png' }]
+ }),
+ v2Tool('bash', v2Done({ command: 'x'.repeat(250) }, [lorem(200)])),
+ v2Tool('bash', { status: 'error', input: { command: 'false' }, error: { type: 'tool.failed', message: 'exit 1\nmore' } }),
+ v2Tool(undefined, v2Done({}, ['unnamed'])),
+ { type: 'tool', id: 'call_fixture_stateless', name: 'bash' }
+ ])
+ ]),
+ // Everything that is not a user/assistant turn: the user's own shell command and a compaction are
+ // chips; harness text and bookkeeping are dropped uncounted; an assistant error ends its text; an
+ // unknown type, a text-less user, a content-less assistant and a bad content block are counted.
+ 'v2-entries': exportDocV2([
+ v2Entry('msg_1', 'system', { text: 'SYSTEM TEXT NEVER SHOWN' }),
+ v2Entry('msg_2', 'synthetic', { text: 'SYNTHETIC TEXT NEVER SHOWN', description: 'file read' }),
+ v2Entry('msg_3', 'skill', { skill: 'skl_fixture', name: 'demo', text: 'SKILL TEXT NEVER SHOWN' }),
+ v2Entry('msg_4', 'agent-switched', { agent: 'plan', previous: 'build' }),
+ v2Entry('msg_5', 'model-switched', { model: { id: 'other', providerID: 'opencode', variant: 'default' } }),
+ v2Entry('msg_6', 'location-switched', { location: { directory: '/srv/other' } }),
+ v2User('msg_7', ''),
+ v2Entry('msg_8', 'shell', {
+ shellID: 'sh_fixture',
+ command: 'git status',
+ status: 'exited',
+ exit: 0,
+ output: { output: 'On branch main\nnothing to commit', cursor: 0, size: 33, truncated: false }
+ }),
+ v2Entry('msg_9', 'shell', { shellID: 'sh_fixture2', command: 'sleep 9', status: 'running' }),
+ v2Entry('msg_10', 'compaction', { status: 'completed', reason: 'auto', summary: 'Summary of the work so far.' }),
+ v2Entry('msg_11', 'compaction', { status: 'running', reason: 'manual', summary: 'PARTIAL SUMMARY NEVER SHOWN' }),
+ v2Asst('msg_12', [{ type: 'text', text: 'partial' }], { error: { type: 'provider.error', message: ' rate limited ', status: 429 } }),
+ v2Asst('msg_13', [], { error: { type: 'aborted', message: '' } }),
+ v2Asst('msg_14', [{ type: 'text', text: 'kept' }, { type: 'image', url: 'x' }, 'nope', { type: 'text', text: 7 }], { error: 'boom' }),
+ v2Entry('msg_15', 'hologram', { text: 'UNKNOWN TYPE NEVER SHOWN' }),
+ { id: 'msg_16', time: { created: tick('msg_16') }, type: 'user' },
+ { id: 'msg_17', time: { created: tick('msg_17') }, type: 'assistant', model: { id: 'last-model', providerID: 'opencode', variant: 'default' } },
+ v2Entry('msg_18', 'shell', { shellID: 'sh_fixture3', status: 'exited' })
+ ])
}
const serialize = (x: unknown): string => JSON.stringify(x, null, 2) + '\n'
@@ -268,6 +383,24 @@ describe('opencode chat golden fixtures', () => {
expect(e.page.messages).toEqual([{ role: 'user', parts: [{ kind: 'text', text: 'kept' }], at: T0 + 3000 }])
})
+ it('v2-entries: harness text is never rendered and exactly the unmappable shapes are counted', () => {
+ const e = JSON.parse(fs.readFileSync(fixture('expected/v2-entries.json'), 'utf8'))
+ expect(JSON.stringify(e.page)).not.toContain('NEVER SHOWN')
+ // a non-object error, 3 bad content blocks, an unknown type, a text-less user, a content-less
+ // assistant, a command-less shell
+ expect(e.parse.skipped).toBe(8)
+ // The content-less assistant entry is the newest one, and still answers `model`.
+ expect(e.parse.model).toBe('last-model')
+ expect('effort' in e.parse).toBe(false)
+ })
+
+ it('v2-turns: both speakers render, and "default" is not an effort', () => {
+ const e = JSON.parse(fs.readFileSync(fixture('expected/v2-turns.json'), 'utf8'))
+ expect(e.parse.skipped).toBe(0)
+ expect(e.page.messages.map((m: { role: string }) => m.role)).toEqual(['user', 'assistant', 'assistant', 'user', 'assistant'])
+ expect(e.parse.effort).toBe('high')
+ })
+
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)
diff --git a/src/core/opencode-chat.ts b/src/core/opencode-chat.ts
index 8ca1cd08f..a3ed5020a 100644
--- a/src/core/opencode-chat.ts
+++ b/src/core/opencode-chat.ts
@@ -125,6 +125,133 @@ function errorText(e: unknown): string | null {
* non-text user content the same way. */
const DROPPED_PARTS = new Set(['reasoning', 'step-start', 'step-finish', 'snapshot', 'patch', 'retry', 'file', 'agent'])
+// ── opencode 2.x messages ───────────────────────────────────────────────────────────────────────
+//
+// MEASURED on @opencode/cli 2.2.7 (2026-11-13, issue #1438): one real export (a prompt, a `read`
+// tool call, the answer) plus the Effect structs `Session.Message.*` in the shipped binary. The
+// document is still `{info: Session, messages}` with `info.id` the session — but a message has NO
+// `info` / `parts`. It is a flat record discriminated by `type`, all carrying `{id, time:{created}}`:
+//
+// user {text, files?, agents?, skills?}
+// assistant {agent, model:{id, providerID, variant}, content: Content[], finish?, error?, retry?}
+// content text {text} · reasoning {text} · tool {id, name, executed?, state}
+// tool state streaming {input: STRING} · running {input, metadata} · completed {input, content:
+// (text {text} | file {uri, mime, name?})[]} · error {input, error, content?}
+// shell {command, status, exit?, output?: {output, truncated, …}} — the user's own `!cmd`
+// compaction {status: running|completed|failed, reason: auto|manual, summary}
+// synthetic · system · skill harness text the human did not type
+// agent-switched · model-switched · location-switched · idle bookkeeping
+// error {type, message, status?, …} (`Session.StructuredError`) wherever one appears
+//
+// Only the user / assistant-text / completed-tool path was seen in a real export; every other
+// mapping is composed from the schema. A wrong guess costs a missing chip, never wrong text.
+
+/** Entries dropped ON PURPOSE (not counted): text the human did not write, and bookkeeping. */
+const V2_DROPPED_ENTRIES = new Set([
+ 'synthetic',
+ 'system',
+ 'skill',
+ 'agent-switched',
+ 'model-switched',
+ 'location-switched',
+ 'idle'
+])
+
+/** A 2.x structured error as the `[name] message` sentence 1.x errors end with. */
+function v2ErrorText(e: unknown): string | null {
+ if (!isRecord(e)) return null
+ const name = typeof e.type === 'string' && e.type ? e.type : 'Error'
+ const message = typeof e.message === 'string' ? e.message.trim() : ''
+ return message ? `[${name}] ${message}` : `[${name}]`
+}
+
+/** A 2.x tool content block's chip. `null` = not a mappable tool block. */
+function v2ToolPart(p: Record<string, unknown>): ToolPart | null {
+ const state = p.state
+ if (!isRecord(state)) return null
+ const part: ToolPart = {
+ kind: 'tool',
+ name: typeof p.name === 'string' && p.name ? p.name : 'tool',
+ // `streaming` carries the raw argument STRING, which `opencodeToolArg` reads as nothing.
+ arg: opencodeToolArg(state.input)
+ }
+ if (state.status === 'completed' && Array.isArray(state.content)) {
+ const text = state.content
+ .filter((c): c is Record<string, unknown> => isRecord(c) && c.type === 'text' && typeof c.text === 'string')
+ .map((c) => c.text as string)
+ .join('\n')
+ const s = summarize(text)
+ if (s) part.result = s
+ } else if (state.status === 'error' && isRecord(state.error) && typeof state.error.message === 'string') {
+ part.result = summarize(`Error: ${state.error.message}`)
+ }
+ return part
+}
+
+/** One 2.x entry (`type` is a string). `meta` is set for every assistant entry, message or not. */
+function v2Entry(entry: Record<string, unknown>): {
+ messages: ChatMessage[]
+ skipped: number
+ meta?: { model: unknown; effort: unknown }
+} {
+ const created = isRecord(entry.time) ? entry.time.created : undefined
+ const at = typeof created === 'number' && Number.isFinite(created) ? created : undefined
+ const stamp = (m: ChatMessage): ChatMessage => (at === undefined ? m : { ...m, at })
+ const one = (m: ChatMessage | null, skipped = 0) => ({ messages: m ? [stamp(m)] : [], skipped })
+
+ switch (entry.type) {
+ case 'user':
+ if (typeof entry.text !== 'string') return one(null, 1)
+ return one(entry.text ? { role: 'user', parts: [{ kind: 'text', text: entry.text }] } : null)
+ case 'assistant': {
+ // `variant: "default"` is what 2.x writes when no variant was chosen — not an effort.
+ const model = isRecord(entry.model) ? entry.model : {}
+ const meta = { model: model.id, effort: model.variant === 'default' ? undefined : model.variant }
+ if (!Array.isArray(entry.content)) return { messages: [], skipped: 1, meta }
+ let skipped = 0
+ const parts: ChatPart[] = []
+ for (const p of entry.content) {
+ if (!isRecord(p) || typeof p.type !== 'string') {
+ skipped++
+ } else if (p.type === 'text') {
+ if (typeof p.text !== 'string') skipped++
+ else if (p.text) parts.push({ kind: 'text', text: p.text })
+ } else if (p.type === 'tool') {
+ const t = v2ToolPart(p)
+ if (t) parts.push(t)
+ else skipped++
+ } else if (p.type !== 'reasoning') {
+ skipped++
+ }
+ }
+ if (entry.error !== undefined) {
+ const t = v2ErrorText(entry.error)
+ if (t === null) skipped++
+ else parts.push({ kind: 'text', text: t })
+ }
+ return { ...one(parts.length ? { role: 'assistant', parts } : null, skipped), meta }
+ }
+ case 'shell': {
+ if (typeof entry.command !== 'string') return one(null, 1)
+ const chip: ToolPart = { kind: 'tool', name: 'shell', arg: entry.command.slice(0, CHAT_TOOL_ARG_MAX) }
+ const output = isRecord(entry.output) ? entry.output.output : undefined
+ const s = typeof output === 'string' ? summarize(output) : ''
+ if (s) chip.result = s
+ return one({ role: 'assistant', parts: [chip] })
+ }
+ case 'compaction': {
+ const parts: ChatPart[] = [{ kind: 'tool', name: 'compaction', arg: entry.reason === 'auto' ? 'auto' : '' }]
+ // The summary is the conversation from here on, exactly as 1.x's `summary: true` message is.
+ if (entry.status === 'completed' && typeof entry.summary === 'string' && entry.summary) {
+ parts.push({ kind: 'text', text: entry.summary })
+ }
+ return one({ role: 'assistant', parts })
+ }
+ default:
+ return one(null, V2_DROPPED_ENTRIES.has(entry.type as string) ? 0 : 1)
+ }
+}
+
/**
* 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
@@ -141,13 +268,25 @@ export function parseOpencodeExport(raw: string, sessionId: string): OpencodeCha
const messages: ChatMessage[] = []
let skipped = 0
- let lastAssistant: Record<string, unknown> | undefined
+ let lastMeta: { model: unknown; effort: unknown } | undefined
const entries = Array.isArray(doc.messages) ? doc.messages : []
for (const entry of entries) {
- if (!isRecord(entry) || !isRecord(entry.info)) {
+ if (!isRecord(entry)) {
skipped++
continue
}
+ if (!isRecord(entry.info)) {
+ // No per-message `info`: an opencode 2.x entry, which states its kind in `type` instead.
+ if (typeof entry.type !== 'string') {
+ skipped++
+ continue
+ }
+ const v2 = v2Entry(entry)
+ skipped += v2.skipped
+ messages.push(...v2.messages)
+ if (v2.meta) lastMeta = v2.meta
+ 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) {
@@ -201,7 +340,7 @@ export function parseOpencodeExport(raw: string, sessionId: string): OpencodeCha
}
if (role === 'assistant') {
- lastAssistant = info
+ lastMeta = { model: info.modelID, effort: info.variant }
if (info.error !== undefined) {
const t = errorText(info.error)
if (t === null) skipped++
@@ -217,8 +356,8 @@ export function parseOpencodeExport(raw: string, sessionId: string): OpencodeCha
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)
+ const model = metaString(lastMeta?.model)
+ const effort = metaString(lastMeta?.effort)
if (model !== undefined) out.model = model
if (effort !== undefined) out.effort = effort
return out
diff --git a/src/core/opencode-export.test.ts b/src/core/opencode-export.test.ts
index a6bede7d8..fa05892ca 100644
--- a/src/core/opencode-export.test.ts
+++ b/src/core/opencode-export.test.ts
@@ -7,7 +7,8 @@ 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'
+import { execFileSync } from 'child_process'
+import { remoteOpencodeExportCommand, resetOpencodeExportDialects, 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. */
@@ -30,6 +31,7 @@ describe('runOpencodeExportAt — the tri-state', () => {
let dir: string
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-opencode-export-tri-'))
+ resetOpencodeExportDialects()
})
afterEach(() => {
fs.rmSync(dir, { recursive: true, force: true })
@@ -96,3 +98,125 @@ describe('runOpencodeExportAt — the tri-state', () => {
expect(await runOpencodeExportAt(path.join(dir, 'nope'), SID, 10_000)).toEqual({ ok: false })
})
})
+
+// Issue #1438. opencode 2.x renamed the command: `export <id>` is refused with usage text and
+// `Unexpected positional argument`, and the working spelling is `session export --standalone <id>`
+// — which 1.x in turn does not know. Every answer below is the one measured on @opencode/cli 2.2.7
+// / opencode-ai 1.18.33; the fakes log each argv they were started with.
+describe('runOpencodeExportAt — the 1.x and 2.x spellings', () => {
+ let dir: string
+ let log: string
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-opencode-export-v2-'))
+ log = path.join(dir, 'calls.log')
+ resetOpencodeExportDialects()
+ })
+ afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+ })
+ const calls = (): string[][] =>
+ fs.existsSync(log) ? fs.readFileSync(log, 'utf8').trim().split('\n').map((l) => JSON.parse(l)) : []
+ const LOG = `const a = process.argv.slice(2); require('fs').appendFileSync(${JSON.stringify('LOGPATH')}, JSON.stringify(a) + '\\n');`
+ const fake = (body: string): string => writeFakeOpencode(dir, LOG.replace('LOGPATH', log.replace(/\\/g, '\\\\')) + body)
+
+ /** 2.2.7: refuses `export <id>` (usage on STDOUT, exit 1), answers `session export`. */
+ const V2 = `
+ if (a[0] === 'export') { process.stdout.write('USAGE\\n opencode <subcommand>\\n\\nERROR\\n Unexpected positional argument: "' + a[1] + '"\\n'); process.exit(1) }
+ if (a[0] === 'session' && a[1] === 'export') {
+ const id = a[a.length - 1]
+ if (id === 'ses_missing') { process.stderr.write('Session not found: ' + id + '\\n'); process.exit(1) }
+ process.stdout.write(JSON.stringify({ info: { id }, messages: [] })); process.exit(0)
+ }
+ process.exit(3)
+ `
+ /** 1.18.33: answers `export <id>`, prints help for `session export` (exit 1). */
+ const V1 = `
+ if (a[0] === 'export') { process.stdout.write(JSON.stringify({ info: { id: a[1] }, messages: [] })); process.exit(0) }
+ process.stdout.write('opencode session\\n\\nmanage sessions\\n'); process.exit(1)
+ `
+
+ it('2.x: falls through to `session export --standalone <id>` and returns ONLY its stdout', async () => {
+ const out = await runOpencodeExportAt(fake(V2), SID, 10_000)
+ expect(out.ok && JSON.parse(out.stdout)).toEqual({ info: { id: SID }, messages: [] })
+ expect(calls()).toEqual([
+ ['export', SID],
+ ['session', 'export', '--standalone', SID]
+ ])
+ })
+
+ it('2.x: the spelling is remembered, so the next read spawns once', async () => {
+ const bin = fake(V2)
+ await runOpencodeExportAt(bin, SID, 10_000)
+ fs.rmSync(log)
+ expect((await runOpencodeExportAt(bin, SID, 10_000)).ok).toBe(true)
+ expect(calls()).toEqual([['session', 'export', '--standalone', SID]])
+ })
+
+ it('2.x: its "Session not found" is the same clean miss', async () => {
+ expect(await runOpencodeExportAt(fake(V2), 'ses_missing', 10_000)).toEqual({ ok: false, absent: true })
+ })
+
+ it('1.x: answers on the first spelling and never tries the second', async () => {
+ const bin = fake(V1)
+ expect((await runOpencodeExportAt(bin, SID, 10_000)).ok).toBe(true)
+ expect((await runOpencodeExportAt(bin, SID, 10_000)).ok).toBe(true)
+ expect(calls()).toEqual([
+ ['export', SID],
+ ['export', SID]
+ ])
+ })
+
+ it('a 1.x failure that is not the spelling refusal is NOT answered by a second spawn', async () => {
+ const bin = fake("process.stderr.write('database is locked\\n'); process.exit(1)\n")
+ expect(await runOpencodeExportAt(bin, SID, 10_000)).toEqual({ ok: false })
+ expect(calls()).toEqual([['export', SID]])
+ })
+
+ it('a remembered 2.x spelling that stops answering is forgotten (binary downgraded in place)', async () => {
+ const bin = fake(V2)
+ await runOpencodeExportAt(bin, SID, 10_000)
+ fake(V1) // same path, now a 1.x CLI
+ fs.rmSync(log)
+ expect(await runOpencodeExportAt(bin, SID, 10_000)).toEqual({ ok: false })
+ expect((await runOpencodeExportAt(bin, SID, 10_000)).ok).toBe(true)
+ expect(calls()).toEqual([
+ ['session', 'export', '--standalone', SID],
+ ['export', SID]
+ ])
+ })
+
+ // The SSH leg is one generated command line; it is run for real, under a real /bin/sh.
+ describe.skipIf(process.platform === 'win32')('remoteOpencodeExportCommand under /bin/sh', () => {
+ const run = (body: string, id: string): { code: number; stdout: string } => {
+ fake(body)
+ try {
+ const stdout = execFileSync('/bin/sh', ['-c', remoteOpencodeExportCommand(`'${id}'`)], {
+ env: { ...process.env, PATH: `${dir}${path.delimiter}${process.env.PATH}` },
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore']
+ })
+ return { code: 0, stdout }
+ } catch (e) {
+ return { code: (e as { status: number }).status, stdout: String((e as { stdout?: unknown }).stdout ?? '') }
+ }
+ }
+
+ it('2.x host: the document alone — none of the refused spelling\'s usage text', () => {
+ const r = run(V2, SID)
+ expect(r.code).toBe(0)
+ expect(JSON.parse(r.stdout)).toEqual({ info: { id: SID }, messages: [] })
+ })
+
+ it('1.x host: the document from the first spelling, one spawn', () => {
+ const r = run(V1, SID)
+ expect(r.code).toBe(0)
+ expect(JSON.parse(r.stdout)).toEqual({ info: { id: SID }, messages: [] })
+ expect(calls()).toEqual([['export', SID]])
+ })
+
+ it('a missing session exits non-zero on both lines (read as "could not export")', () => {
+ expect(run(V2, 'ses_missing').code).not.toBe(0)
+ expect(run("process.stderr.write('Session not found\\n'); process.exit(1)\n", SID).code).not.toBe(0)
+ })
+ })
+})
diff --git a/src/core/opencode-export.ts b/src/core/opencode-export.ts
index 86a768f92..f5267c3a5 100644
--- a/src/core/opencode-export.ts
+++ b/src/core/opencode-export.ts
@@ -1,4 +1,5 @@
-// `opencode export <sessionID>` — the one way nodeterm reads an opencode conversation.
+// The opencode session export — the one way nodeterm reads an opencode conversation. Two spellings:
+// `opencode export <id>` (1.x) and `opencode session export --standalone <id>` (2.x).
//
// 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
@@ -11,6 +12,20 @@
// 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`).
+//
+// MEASURED on @opencode/cli 2.2.7 (2026-11-13, issue #1438) — NO spelling works on both lines:
+// - 2.x: `export <id>` exits 1 with usage text on stdout ending in
+// `Unexpected positional argument: "<id>"`. The command is `session export [flags] [<session>]`.
+// - 1.x (1.18.33): `session` has only `list` / `delete`; `session export <id>` prints help, exit 1.
+// - 2.x WITHOUT `--standalone` talks to the shared background service and STARTS it when it is
+// not running (a daemon that outlives the read and keeps the environment of whoever started it
+// — see hooks/opencode.ts), and fails outright when the service port is taken. `--standalone`
+// runs a private server for the one command and reads the same `opencode.db`: 1.5 s wall,
+// ~160 MB peak RSS, and it answers while the service is running too.
+// - 2.x unknown id: exit 1, EMPTY stdout, `Session not found: <id>` on stderr (no ANSI) — the same
+// answer the 1.x detector below already reads as a clean miss.
+// So 1.x's spelling is tried first and 2.x's only on 2.x's own measured refusal of it; which one
+// worked is remembered per binary, so a 2.x host pays the wasted first spawn once.
import os from 'os'
import { directExecutableInvocation } from './exec-path'
@@ -36,19 +51,41 @@ export type OpencodeExportOutcome = { ok: true; stdout: string } | { ok: false;
// 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(
+type OpencodeExportDialect = 'v1' | 'v2'
+
+const EXPORT_ARGV: Record<OpencodeExportDialect, (sessionId: string) => string[]> = {
+ v1: (sessionId) => ['export', sessionId],
+ // `--standalone` BEFORE the id, and no other flag (see the header for why it is not optional).
+ v2: (sessionId) => ['session', 'export', '--standalone', sessionId]
+}
+
+/** 2.x's refusal of the 1.x spelling. The only failure that proves the OTHER spelling is the right
+ * one — a timeout, a crash or a locked database on 1.x must not be answered by a second spawn. */
+const V1_SPELLING_REFUSED = 'Unexpected positional argument'
+
+/** Which spelling last produced an answer, per binary path. An in-place upgrade or downgrade is
+ * healed by the rules in `runOpencodeExportAt`, never by trusting this forever. */
+const dialectByBin = new Map<string, OpencodeExportDialect>()
+
+/** Test seam: forget every remembered spelling. */
+export function resetOpencodeExportDialects(): void {
+ dialectByBin.clear()
+}
+
+type Attempt = { outcome: OpencodeExportOutcome; v1SpellingRefused: boolean }
+
+async function attemptExport(
bin: string,
+ dialect: OpencodeExportDialect,
sessionId: string,
timeoutMs: number
-): Promise<OpencodeExportOutcome> {
- const invocation = directExecutableInvocation(bin, ['export', sessionId])
- if (!invocation) return { ok: false }
+): Promise<Attempt> {
+ const fail: Attempt = { outcome: { ok: false }, v1SpellingRefused: false }
+ const invocation = directExecutableInvocation(bin, EXPORT_ARGV[dialect](sessionId))
+ if (!invocation) return fail
try {
const { execFile } = await import('node:child_process')
- return await new Promise<OpencodeExportOutcome>((resolve) => {
+ return await new Promise<Attempt>((resolve) => {
execFile(
invocation.executable,
invocation.args,
@@ -63,21 +100,68 @@ export async function runOpencodeExportAt(
timeout: timeoutMs
},
(err, stdout, stderr) => {
- if (!err) return resolve({ ok: true, stdout })
+ if (!err) return resolve({ outcome: { ok: true, stdout }, v1SpellingRefused: false })
// 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 })
+ const exited1 = code === 1 && !(err as { killed?: boolean }).killed
+ const errText = String(stderr ?? '').replace(ANSI, '')
+ const notFound = exited1 && stdout === '' && errText.includes(`Session not found: ${sessionId}`)
+ resolve({
+ outcome: notFound ? { ok: false, absent: true } : { ok: false },
+ // 2.2.7 prints its usage (and this line) on stdout; either stream is accepted.
+ v1SpellingRefused:
+ exited1 && (String(stdout ?? '').includes(V1_SPELLING_REFUSED) || errText.includes(V1_SPELLING_REFUSED))
+ })
}
)
})
} catch {
- return { ok: false }
+ return fail
+ }
+}
+
+/** 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).
+ *
+ * Spelling: the remembered one, else 1.x's. 1.x's falls through to 2.x's ONLY on 2.x's own
+ * refusal of it. A remembered 2.x spelling that fails without an answer is forgotten (the binary
+ * may have been downgraded in place), so the next read starts from 1.x's again; that read itself
+ * stays a failed read. */
+export async function runOpencodeExportAt(
+ bin: string,
+ sessionId: string,
+ timeoutMs: number
+): Promise<OpencodeExportOutcome> {
+ const answered = (o: OpencodeExportOutcome): boolean => o.ok || o.absent === true
+ if (dialectByBin.get(bin) === 'v2') {
+ const { outcome } = await attemptExport(bin, 'v2', sessionId, timeoutMs)
+ if (!answered(outcome)) dialectByBin.delete(bin)
+ return outcome
}
+ const first = await attemptExport(bin, 'v1', sessionId, timeoutMs)
+ if (!first.v1SpellingRefused) {
+ if (answered(first.outcome)) dialectByBin.set(bin, 'v1')
+ return first.outcome
+ }
+ const second = await attemptExport(bin, 'v2', sessionId, timeoutMs)
+ if (answered(second.outcome)) dialectByBin.set(bin, 'v2')
+ return second.outcome
+}
+
+/**
+ * The same read as ONE remote command line (Context Link over an SSH project's ControlMaster),
+ * where there is no second round trip to spend on a retry. `quotedSessionId` is already
+ * single-quoted by the caller. Wrapped in `sh -c` because the host's login shell may not be POSIX
+ * (fish has no `if …; then`). The 1.x spelling's stdout is held back until it SUCCEEDS: 2.x answers
+ * it with usage text on stdout, which would otherwise land in front of the real document.
+ * Run for real under /bin/sh in `opencode-export.test.ts`.
+ */
+export function remoteOpencodeExportCommand(quotedSessionId: string): string {
+ const script =
+ 'if o=$(opencode export "$1" 2>/dev/null); then printf "%s\\n" "$o"; ' +
+ 'else opencode session export --standalone "$1"; fi'
+ return `sh -c '${script}' sh ${quotedSessionId}`
}
diff --git a/src/shared/chat-fixtures/opencode/README.md b/src/shared/chat-fixtures/opencode/README.md
index 128a70b4f..73815d218 100644
--- a/src/shared/chat-fixtures/opencode/README.md
+++ b/src/shared/chat-fixtures/opencode/README.md
@@ -4,9 +4,9 @@ The reference outputs for the chat view's **opencode** reader (`src/core/opencod
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.
+Every input is **synthetic**: an export document built by
+`src/core/opencode-chat.fixtures.test.ts` from the schema measured on opencode 1.18.25 and, for the
+`v2-*` fixtures, on @opencode/cli 2.2.7. None is a slice of a real session. Do not add one.
## Regenerate
@@ -34,6 +34,14 @@ strict and exits 1 on an option an older build does not know). Measured on 1.18.
claude's reader does), and a newest message above 5 MB is served truncated with a note, never as
an empty page. The phone should expect that note in the text, not a separate field.
+**opencode 2.x** (measured on @opencode/cli 2.2.7, issue #1438) renamed the command and reshaped
+the document. `export <id>` exits 1 with usage text and `Unexpected positional argument` on stdout;
+the reader then runs `["session", "export", "--standalone", id]` and remembers that spelling for the
+binary. 1.x does not know `session export`, so no single spelling serves both. `--standalone` keeps
+the read from starting (or depending on) opencode's shared background service. An unknown id is
+the same clean miss: exit 1, empty stdout, `Session not found: <id>` on stderr. Cost: ~1.5 s,
+~160 MB. The database path and the change gate are unchanged.
+
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).
@@ -79,8 +87,9 @@ An unpaged (legacy) read is `{ messages, found }` only, and a failure is `{ mess
`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
+1. **Skipped and counted** (`skipped += 1`, nothing rendered): an entry that is not an object, or
+ has neither an object `info` nor a string `type` (one WITH a string `type` is a 2.x entry — see
+ "opencode 2.x entries" below, which replaces rules 1–5 for it); 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`.
@@ -107,6 +116,42 @@ An unpaged (legacy) read is `{ messages, found }` only, and a failure is `{ mess
100 UTF-16 code units. A field that entry does not state is absent; nothing is carried from an
older entry.
+### opencode 2.x entries
+
+An entry that is an object with **no object `info`** and a **string `type`** is a 2.x entry (an
+entry with neither is skipped and counted, rule 1). `at` = `time.created` as in rule 2. By `type`:
+
+- `user`: a non-string `text` is skipped and counted; an empty one yields nothing; otherwise a user
+ message with one text part. `files` / `agents` / `skills` are not read.
+- `assistant`: it answers `model` / `effort` (rule 6) whether or not it yields a message — `model`
+ is `model.id`, `effort` is `model.variant` **unless it is the string `"default"`** (what 2.x
+ writes when no variant was chosen), each under the same 1–100 unit rule. A non-array `content`
+ is skipped and counted. Each content block, in order: not an object or no string `type` →
+ counted; `text` → a text part (non-string counted, empty dropped); `tool` → a 2.x tool part
+ (below; a non-object `state` is counted); `reasoning` → dropped silently; anything else →
+ counted. Then, when `error` is present: a non-object is counted; otherwise a text part
+ `[<type>] <message>` (`type` when a non-empty string else `Error`; `message` trimmed; `[<type>]`
+ when empty). One assistant message when there is at least one part.
+- `shell` (the user's own `!command`): a non-string `command` is counted; otherwise an assistant
+ message of one chip `{kind:"tool", name:"shell", arg}` with `arg` = `command` cut to 200 units and
+ `result` = the summary of `output.output` when that is a non-empty string.
+- `compaction`: an assistant message of a chip `{kind:"tool", name:"compaction", arg: reason ===
+ "auto" ? "auto" : ""}`, followed by a text part of `summary` only when `status` is `"completed"`
+ and `summary` is a non-empty string.
+- `synthetic`, `system`, `skill`, `agent-switched`, `model-switched`, `location-switched`, `idle`:
+ dropped silently (NOT counted).
+- any other type: skipped and counted.
+
+**2.x tool part.** `name` = the block's `name` when a non-empty string, else `"tool"`. `arg` = the
+tool-arg rule over `state.input` with no title fallback (a `streaming` state's `input` is a raw
+string and yields `""`). `result`, only when set: `status: "completed"` with an array `content` →
+the summary of its `{type:"text", text}` blocks' texts joined by `\n` (other blocks ignored), key
+absent when empty; `status: "error"` with an object `error` whose `message` is a string → the
+summary of `"Error: " + message`; anything else → no `result` key.
+
+Only the user / assistant-text / completed-tool path was observed in a real 2.2.7 export. Every
+other 2.x rule is composed from the `Session.Message.*` schema in the shipped binary.
+
**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
@@ -134,3 +179,6 @@ Claude's AskUserQuestion, but answer cards are Claude-only.
| `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. |
+| `v2-turns` | The 2.x turn: top-level user `text`, a tool-only assistant entry, two text blocks, reasoning and `idle` dropped uncounted, `variant: "default"` is no effort while `"high"` is. |
+| `v2-tools` | Every 2.x tool state: a raw-string `streaming` input, running, completed text blocks joined then summarized, a `file`-only result (no `result` key), the 200-unit arg cap, `Error: ` from `error.message`, a missing name, a stateless tool counted. |
+| `v2-entries` | Harness and bookkeeping entries dropped uncounted, shell and compaction chips (a running compaction's partial summary is not shown), `[type] message` after partial text, eight counted shapes, and a content-less newest assistant entry still answering `model`. |
diff --git a/src/shared/chat-fixtures/opencode/expected/v2-entries.json b/src/shared/chat-fixtures/opencode/expected/v2-entries.json
new file mode 100644
index 000000000..62ddb9b83
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/v2-entries.json
@@ -0,0 +1,183 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "shell",
+ "arg": "git status",
+ "result": "On branch main nothing to commit"
+ }
+ ],
+ "at": 1780000008000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "shell",
+ "arg": "sleep 9"
+ }
+ ],
+ "at": 1780000009000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": "auto"
+ },
+ {
+ "kind": "text",
+ "text": "Summary of the work so far."
+ }
+ ],
+ "at": 1780000010000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": ""
+ }
+ ],
+ "at": 1780000011000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "partial"
+ },
+ {
+ "kind": "text",
+ "text": "[provider.error] rate limited"
+ }
+ ],
+ "at": 1780000012000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[aborted]"
+ }
+ ],
+ "at": 1780000013000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "kept"
+ }
+ ],
+ "at": 1780000014000
+ }
+ ],
+ "skipped": 8,
+ "model": "last-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "shell",
+ "arg": "git status",
+ "result": "On branch main nothing to commit"
+ }
+ ],
+ "at": 1780000008000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "shell",
+ "arg": "sleep 9"
+ }
+ ],
+ "at": 1780000009000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": "auto"
+ },
+ {
+ "kind": "text",
+ "text": "Summary of the work so far."
+ }
+ ],
+ "at": 1780000010000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "compaction",
+ "arg": ""
+ }
+ ],
+ "at": 1780000011000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "partial"
+ },
+ {
+ "kind": "text",
+ "text": "[provider.error] rate limited"
+ }
+ ],
+ "at": 1780000012000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[aborted]"
+ }
+ ],
+ "at": 1780000013000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "kept"
+ }
+ ],
+ "at": 1780000014000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "last-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/v2-tools.json b/src/shared/chat-fixtures/opencode/expected/v2-tools.json
new file mode 100644
index 000000000..8762e90c8
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/v2-tools.json
@@ -0,0 +1,107 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": ""
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "sleep 5"
+ },
+ {
+ "kind": "tool",
+ "name": "grep",
+ "arg": "TODO",
+ "result": "a b c"
+ },
+ {
+ "kind": "tool",
+ "name": "read",
+ "arg": "shot.png"
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ "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": "bash",
+ "arg": "false",
+ "result": "Error: exit 1 more"
+ },
+ {
+ "kind": "tool",
+ "name": "tool",
+ "arg": "",
+ "result": "unnamed"
+ }
+ ],
+ "at": 1780000001000
+ }
+ ],
+ "skipped": 1,
+ "model": "demo-model"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": ""
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "sleep 5"
+ },
+ {
+ "kind": "tool",
+ "name": "grep",
+ "arg": "TODO",
+ "result": "a b c"
+ },
+ {
+ "kind": "tool",
+ "name": "read",
+ "arg": "shot.png"
+ },
+ {
+ "kind": "tool",
+ "name": "bash",
+ "arg": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ "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": "bash",
+ "arg": "false",
+ "result": "Error: exit 1 more"
+ },
+ {
+ "kind": "tool",
+ "name": "tool",
+ "arg": "",
+ "result": "unnamed"
+ }
+ ],
+ "at": 1780000001000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/expected/v2-turns.json b/src/shared/chat-fixtures/opencode/expected/v2-turns.json
new file mode 100644
index 000000000..49d28811f
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/expected/v2-turns.json
@@ -0,0 +1,131 @@
+{
+ "sessionId": "ses_0a1b2c3d4ffeSynthetic000001",
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Read `note.txt` — özet lütfen 🧪"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "read",
+ "arg": "note.txt",
+ "result": "Read file note.txt, lines 1-1 1: hello fixture"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "It holds **one** line."
+ },
+ {
+ "kind": "text",
+ "text": "Second block."
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "and with a variant?"
+ }
+ ],
+ "at": 1780000005000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Yes."
+ }
+ ],
+ "at": 1780000006000
+ }
+ ],
+ "skipped": 0,
+ "model": "demo-model-2",
+ "effort": "high"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Read `note.txt` — özet lütfen 🧪"
+ }
+ ],
+ "at": 1780000001000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "read",
+ "arg": "note.txt",
+ "result": "Read file note.txt, lines 1-1 1: hello fixture"
+ }
+ ],
+ "at": 1780000002000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "It holds **one** line."
+ },
+ {
+ "kind": "text",
+ "text": "Second block."
+ }
+ ],
+ "at": 1780000003000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "and with a variant?"
+ }
+ ],
+ "at": 1780000005000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Yes."
+ }
+ ],
+ "at": 1780000006000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "demo-model-2",
+ "effort": "high"
+ }
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/v2-entries.json b/src/shared/chat-fixtures/opencode/inputs/v2-entries.json
new file mode 100644
index 000000000..740e4e8f2
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/v2-entries.json
@@ -0,0 +1,291 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "projectID": "prj_fixture",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000,
+ "busy": 1780000000000,
+ "idle": 1780000000000
+ },
+ "title": "Fixture session",
+ "location": {
+ "directory": "/srv/demo"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_1",
+ "time": {
+ "created": 1780000001000
+ },
+ "text": "SYSTEM TEXT NEVER SHOWN",
+ "type": "system"
+ },
+ {
+ "id": "msg_2",
+ "time": {
+ "created": 1780000002000
+ },
+ "text": "SYNTHETIC TEXT NEVER SHOWN",
+ "description": "file read",
+ "type": "synthetic"
+ },
+ {
+ "id": "msg_3",
+ "time": {
+ "created": 1780000003000
+ },
+ "skill": "skl_fixture",
+ "name": "demo",
+ "text": "SKILL TEXT NEVER SHOWN",
+ "type": "skill"
+ },
+ {
+ "id": "msg_4",
+ "time": {
+ "created": 1780000004000
+ },
+ "agent": "plan",
+ "previous": "build",
+ "type": "agent-switched"
+ },
+ {
+ "id": "msg_5",
+ "time": {
+ "created": 1780000005000
+ },
+ "model": {
+ "id": "other",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "type": "model-switched"
+ },
+ {
+ "id": "msg_6",
+ "time": {
+ "created": 1780000006000
+ },
+ "location": {
+ "directory": "/srv/other"
+ },
+ "type": "location-switched"
+ },
+ {
+ "id": "msg_7",
+ "time": {
+ "created": 1780000007000
+ },
+ "text": "",
+ "files": [],
+ "type": "user"
+ },
+ {
+ "id": "msg_8",
+ "time": {
+ "created": 1780000008000
+ },
+ "shellID": "sh_fixture",
+ "command": "git status",
+ "status": "exited",
+ "exit": 0,
+ "output": {
+ "output": "On branch main\nnothing to commit",
+ "cursor": 0,
+ "size": 33,
+ "truncated": false
+ },
+ "type": "shell"
+ },
+ {
+ "id": "msg_9",
+ "time": {
+ "created": 1780000009000
+ },
+ "shellID": "sh_fixture2",
+ "command": "sleep 9",
+ "status": "running",
+ "type": "shell"
+ },
+ {
+ "id": "msg_10",
+ "time": {
+ "created": 1780000010000
+ },
+ "status": "completed",
+ "reason": "auto",
+ "summary": "Summary of the work so far.",
+ "type": "compaction"
+ },
+ {
+ "id": "msg_11",
+ "time": {
+ "created": 1780000011000
+ },
+ "status": "running",
+ "reason": "manual",
+ "summary": "PARTIAL SUMMARY NEVER SHOWN",
+ "type": "compaction"
+ },
+ {
+ "id": "msg_12",
+ "time": {
+ "created": 1780000012000
+ },
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "partial"
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "error": {
+ "type": "provider.error",
+ "message": " rate limited ",
+ "status": 429
+ },
+ "type": "assistant"
+ },
+ {
+ "id": "msg_13",
+ "time": {
+ "created": 1780000013000
+ },
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "content": [],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "error": {
+ "type": "aborted",
+ "message": ""
+ },
+ "type": "assistant"
+ },
+ {
+ "id": "msg_14",
+ "time": {
+ "created": 1780000014000
+ },
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "kept"
+ },
+ {
+ "type": "image",
+ "url": "x"
+ },
+ "nope",
+ {
+ "type": "text",
+ "text": 7
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "error": "boom",
+ "type": "assistant"
+ },
+ {
+ "id": "msg_15",
+ "time": {
+ "created": 1780000015000
+ },
+ "text": "UNKNOWN TYPE NEVER SHOWN",
+ "type": "hologram"
+ },
+ {
+ "id": "msg_16",
+ "time": {
+ "created": 1780000016000
+ },
+ "type": "user"
+ },
+ {
+ "id": "msg_17",
+ "time": {
+ "created": 1780000017000
+ },
+ "type": "assistant",
+ "model": {
+ "id": "last-model",
+ "providerID": "opencode",
+ "variant": "default"
+ }
+ },
+ {
+ "id": "msg_18",
+ "time": {
+ "created": 1780000018000
+ },
+ "shellID": "sh_fixture3",
+ "status": "exited",
+ "type": "shell"
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/v2-tools.json b/src/shared/chat-fixtures/opencode/inputs/v2-tools.json
new file mode 100644
index 000000000..16c2cccc2
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/v2-tools.json
@@ -0,0 +1,224 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "projectID": "prj_fixture",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000,
+ "busy": 1780000000000,
+ "idle": 1780000000000
+ },
+ "title": "Fixture session",
+ "location": {
+ "directory": "/srv/demo"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_1",
+ "time": {
+ "created": 1780000001000
+ },
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_fixture64",
+ "name": "bash",
+ "executed": false,
+ "state": {
+ "status": "streaming",
+ "input": "{\"command\":\"ls"
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_fixture65",
+ "name": "bash",
+ "executed": false,
+ "state": {
+ "status": "running",
+ "input": {
+ "command": "sleep 5"
+ },
+ "metadata": {}
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_fixture66",
+ "name": "grep",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "pattern": "TODO",
+ "path": "src"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "a\nb"
+ },
+ {
+ "type": "text",
+ "text": "c\nd"
+ }
+ ],
+ "metadata": {
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_fixture67",
+ "name": "read",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "path": "shot.png"
+ },
+ "content": [
+ {
+ "type": "file",
+ "uri": "media:00",
+ "mime": "image/png"
+ }
+ ]
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_fixture68",
+ "name": "bash",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "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 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"
+ }
+ ],
+ "metadata": {
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_fixture69",
+ "name": "bash",
+ "executed": false,
+ "state": {
+ "status": "error",
+ "input": {
+ "command": "false"
+ },
+ "error": {
+ "type": "tool.failed",
+ "message": "exit 1\nmore"
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_fixture70",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {},
+ "content": [
+ {
+ "type": "text",
+ "text": "unnamed"
+ }
+ ],
+ "metadata": {
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_fixture_stateless",
+ "name": "bash"
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "type": "assistant"
+ }
+ ]
+}
diff --git a/src/shared/chat-fixtures/opencode/inputs/v2-turns.json b/src/shared/chat-fixtures/opencode/inputs/v2-turns.json
new file mode 100644
index 000000000..38d989135
--- /dev/null
+++ b/src/shared/chat-fixtures/opencode/inputs/v2-turns.json
@@ -0,0 +1,183 @@
+{
+ "info": {
+ "id": "ses_0a1b2c3d4ffeSynthetic000001",
+ "projectID": "prj_fixture",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 0,
+ "output": 0,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1780000000000,
+ "updated": 1780000000000,
+ "busy": 1780000000000,
+ "idle": 1780000000000
+ },
+ "title": "Fixture session",
+ "location": {
+ "directory": "/srv/demo"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_1",
+ "time": {
+ "created": 1780000001000
+ },
+ "text": "Read `note.txt` — özet lütfen 🧪",
+ "files": [],
+ "type": "user"
+ },
+ {
+ "id": "msg_2",
+ "time": {
+ "created": 1780000002000
+ },
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_fixture63",
+ "name": "read",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "path": "note.txt"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Read file note.txt, lines 1-1\n1: hello fixture"
+ }
+ ],
+ "metadata": {
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1780000000000,
+ "ran": 1780000000001,
+ "completed": 1780000000002
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "type": "assistant"
+ },
+ {
+ "id": "msg_3",
+ "time": {
+ "created": 1780000003000
+ },
+ "agent": "build",
+ "model": {
+ "id": "demo-model",
+ "providerID": "opencode",
+ "variant": "default"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "thinking it over"
+ },
+ {
+ "type": "text",
+ "text": "It holds **one** line."
+ },
+ {
+ "type": "text",
+ "text": "Second block."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "type": "assistant"
+ },
+ {
+ "id": "msg_4",
+ "time": {
+ "created": 1780000004000
+ },
+ "outcome": "succeeded",
+ "type": "idle"
+ },
+ {
+ "id": "msg_5",
+ "time": {
+ "created": 1780000005000
+ },
+ "text": "and with a variant?",
+ "files": [],
+ "type": "user"
+ },
+ {
+ "id": "msg_6",
+ "time": {
+ "created": 1780000006000
+ },
+ "agent": "build",
+ "model": {
+ "id": "demo-model-2",
+ "providerID": "opencode",
+ "variant": "high"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Yes."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 12,
+ "output": 8,
+ "reasoning": 0,
+ "cache": {
+ "read": 0,
+ "write": 0
+ }
+ },
+ "type": "assistant"
+ }
+ ]
+}