diff --git a/changelog.d/319.md b/changelog.d/319.md new file mode 100644 index 00000000..ff0fe4ee --- /dev/null +++ b/changelog.d/319.md @@ -0,0 +1,9 @@ +### Added + +- **OpenCode V2** session logs: sessions stored in the new `session_v2`/`session_message` + database tables are now parsed for prompts, models, tokens, tools, file edits, and inline + image attachments, alongside the classic V1 tables. Migrated sessions that appear in both + formats are counted once, and on the Timeline each session carries its title from the + database (#319) +- `subagent` tool calls now count as investigation activity in the Curiosity view, and OpenCode + subagent sessions are recognized as automated turns instead of user turns (#319) diff --git a/cspell.json b/cspell.json index 3ce4bcae..0af0a454 100644 --- a/cspell.json +++ b/cspell.json @@ -51,6 +51,7 @@ "extjs", "falsey", "fastapi", + "filediff", "finalizable", "foxpro", "fpath", diff --git a/docs/content/getting-started/supported-tools.md b/docs/content/getting-started/supported-tools.md index d063b31b..81b07766 100644 --- a/docs/content/getting-started/supported-tools.md +++ b/docs/content/getting-started/supported-tools.md @@ -34,6 +34,10 @@ Reads session history from OpenAI's Codex terminal agent. Captures prompts, comp Parses session logs from the open-source OpenCode terminal tool that supports multiple LLM backends. +Both OpenCode 1 and OpenCode 2 are supported. The reader detects V1 SQLite tables or V2's inline message format automatically, capturing prompts, assistant responses, model and reasoning-effort selections, token counts, tool calls, and file edits. Migrated sessions that remain in both formats are counted once, using the V2 copy. + +Databases are discovered in the standard OpenCode data directories, including `~/.local/share/opencode/`, `$XDG_DATA_HOME/opencode/`, and platform-specific application data directories. Channel-specific databases such as `opencode-nightly.db` are also included. Legacy V1 JSON storage remains supported when a database or SQLite runtime support is unavailable. All database connections are read-only. + ## GitHub Copilot for Xcode Reads Copilot Chat conversation logs from Apple's Xcode IDE. Sessions are parsed from SQLite databases stored in the GitHub Copilot configuration directory. @@ -54,7 +58,7 @@ Coding Moments counts image attachments on user turns and loads the original ima | GitHub Copilot CLI and App | User-event attachments and image variables, matched to the corresponding conversation turn | | Claude | Inline image content, including image-only turns and merged subagent transcripts | | Codex | User image content and local image attachments; mirrored event records count only once | -| OpenCode | Image file parts in legacy JSON storage or current SQLite databases | +| OpenCode | V1 image file parts in JSON storage or SQLite, and V2 user file attachments | | Xcode | Stored image references on user turns | Image extraction runs in the existing parse worker, not on the extension-host thread. Raw image payloads are not stored in the analytics cache. Extraction returns at most four images per turn, with a 10 MB limit per image. Local PNG, JPEG, GIF, WebP, BMP, and AVIF images are supported. Reconstructing raw VS Code JSON or JSONL state is limited to 50 MB per session file. diff --git a/src/core/curiosity-activity.test.ts b/src/core/curiosity-activity.test.ts index 811cb815..6f147343 100644 --- a/src/core/curiosity-activity.test.ts +++ b/src/core/curiosity-activity.test.ts @@ -11,7 +11,7 @@ import { detectCuriosity } from './curiosity'; describe('Recorded Curiosity tools', () => { it.each([ ['functions.view', true], ['functions.web_fetch', true], ['apply_patch', true], - ['Agent', true], ['spawn_agent', true], ['multi_tool_use.parallel', true], + ['Agent', true], ['spawn_agent', true], ['subagent', true], ['multi_tool_use.parallel', true], ['bash', false], ['task_complete', false], ['unknown_read_tool', false], ])('checks evidence eligibility before reading arguments: %s', (name, eligible) => { expect(hasRecordedToolEvidence(name)).toBe(eligible); @@ -59,6 +59,9 @@ describe('Recorded Curiosity tools', () => { it('uses recorded roles for investigation evidence, never agent names or prompt keywords', () => { expect(recordedInvestigation('functions.task', { agent_type: 'research' })).toBe('research'); expect(recordedInvestigation('Agent', { subagent_type: 'Explore' })).toBe('explore'); + expect(recordedInvestigation('subagent', { agent: 'explore' })).toBe('explore'); + expect(recordedInvestigation('subagent', { agent: 'RESEARCH' })).toBe('research'); + expect(recordedInvestigation('subagent', { agent: 'general', prompt: 'Research the web.' })).toBeUndefined(); expect(recordedInvestigation('spawn_agent', { agent_type: 'general-purpose', prompt: 'Research the web.' })).toBeUndefined(); expect(recordedInvestigation('unknown_research_agent', { agent_type: 'research' })).toBeUndefined(); }); diff --git a/src/core/curiosity-activity.ts b/src/core/curiosity-activity.ts index 41f41b82..7a895d48 100644 --- a/src/core/curiosity-activity.ts +++ b/src/core/curiosity-activity.ts @@ -39,7 +39,7 @@ const NEUTRAL_TOOLS = new Set([ 'list_bash', 'list_powershell', 'task_complete', ]); const CLARIFICATION_TOOLS = new Set(['ask_user', 'askuserquestion', 'vscode_askquestions']); -const INVESTIGATION_TOOLS = new Set(['task', 'agent', 'spawn_agent']); +const INVESTIGATION_TOOLS = new Set(['task', 'agent', 'spawn_agent', 'subagent']); export function toolIdentity(name: string): string { return name.slice(name.lastIndexOf('.') + 1).toLowerCase(); @@ -88,7 +88,7 @@ function record(value: unknown): Record | undefined { export function recordedInvestigation(name: string, args: unknown): 'research' | 'explore' | undefined { if (!INVESTIGATION_TOOLS.has(toolIdentity(name))) return undefined; const data = record(args); - const role = data?.agent_type ?? data?.subagent_type; + const role = data?.agent_type ?? data?.subagent_type ?? data?.agent; if (typeof role !== 'string') return undefined; const normalized = role.toLowerCase(); return normalized === 'research' || normalized === 'explore' ? normalized : undefined; diff --git a/src/core/parser-opencode.test.ts b/src/core/parser-opencode.test.ts index 292e5fb4..75e684c3 100644 --- a/src/core/parser-opencode.test.ts +++ b/src/core/parser-opencode.test.ts @@ -11,9 +11,10 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { DatabaseSync } from 'node:sqlite'; -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { EditLocIndex } from './edit-loc-diff'; -import { parseOpenCodeSessions } from './parser-opencode'; +import { findOpenCodeDirs, loadOpenCodeSession, parseOpenCodeSessions } from './parser-opencode'; +import type { SessionSource } from './cache'; function withStorage( rawSession: object, @@ -51,6 +52,385 @@ function sqlString(value: string): string { return `'${value.replaceAll("'", "''")}'`; } +function withV2Database(run: (database: DatabaseSync, dbPath: string) => void): void { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-v2-test-')); + const dbPath = path.join(root, 'opencode.db'); + const database = new DatabaseSync(dbPath); + try { + database.exec(` + CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, path TEXT, title TEXT, slug TEXT, + agent TEXT, model TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, + time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session_v2 VALUES ('ses_v2', 'project', '/repo/project', NULL, 'Project', 'project', + 'build', '{"id":"gpt-5","providerID":"openai"}', 1700000000000, 1700000010000); + `); + run(database, dbPath); + } finally { + database.close(); + fs.rmSync(root, { recursive: true, force: true }); + } +} + +function insertV2Message(database: DatabaseSync, id: string, type: string, seq: number, data: object | string, + sessionId = 'ses_v2', created = 1700000000000 + seq * 1000): void { + database.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)') + .run(id, sessionId, type, seq, created, created, typeof data === 'string' ? data : JSON.stringify(data)); +} + +describe('OpenCode V2 databases', () => { + it('reads inline prompts, assistant content, models, tokens, tools, and source details', () => { + withV2Database((database, dbPath) => { + insertV2Message(database, 'user', 'user', 1, { text: 'Update the app', files: [] }); + insertV2Message(database, 'assistant', 'assistant', 2, { + agent: 'plan', model: { id: 'gpt-5', providerID: 'openai', variant: 'high' }, + time: { created: 1700000002000, completed: 1700000004000 }, + tokens: { input: 100, output: 20, cache: { read: 30, write: 5 } }, finish: 'stop', + content: [ + { type: 'reasoning', text: 'Private reasoning is not response text.' }, + { type: 'tool', name: 'read', state: { status: 'completed', input: { filePath: 'src/app.ts' } } }, + { type: 'tool', name: 'edit', state: { status: 'completed', input: { filePath: 'src/app.ts', oldString: 'old', newString: 'new\nline' } } }, + { type: 'tool', name: 'patch', state: { status: 'completed', input: { patchText: '*** Begin Patch\n*** Add File: src/new.ts\n+export {};\n*** End Patch' } } }, + { type: 'tool', name: 'subagent', state: { status: 'completed', input: { agent: 'explore' } } }, + { type: 'text', text: 'Updated the app.' }, + ], + }); + const editLocIndex: EditLocIndex = new Map(); + const sources = new Map(); + const originalDatabase = fs.readFileSync(dbPath); + const sessions = parseOpenCodeSessions(dbPath, editLocIndex, sources); + expect(sessions).toHaveLength(1); + expect(sessions[0]).toMatchObject({ sessionId: 'ses_v2', harness: 'OpenCode', workspaceName: 'project', workspaceRootPath: '/repo/project' }); + expect(sessions[0].requests[0]).toMatchObject({ + requestId: 'user', messageText: 'Update the app', + modelId: 'gpt-5', agentName: 'plan', agentMode: 'plan', reasoningEffort: 'high', answerEvidence: 'final', + promptTokens: 135, completionTokens: 20, cacheReadTokens: 30, cacheWriteTokens: 5, + totalElapsed: 3000, toolsUsed: ['read', 'edit', 'patch', 'subagent'], + referencedFiles: ['src/app.ts'], editedFiles: ['src/app.ts', 'src/new.ts'], investigationDelegations: ['explore'], + }); + expect(sessions[0].requests[0].responseText).toContain('Updated the app.'); + expect(sessions[0].requests[0].responseText).not.toContain('Private reasoning'); + expect(editLocIndex.get('user')?.get('src/app.ts')).toEqual({ added: 2, removed: 1 }); + expect(editLocIndex.get('user')?.get('src/new.ts')).toEqual({ added: 1, removed: 0 }); + expect(sources.get('ses_v2')).toMatchObject({ kind: 'opencode-db', filePath: dbPath }); + expect(loadOpenCodeSession(dbPath, 'ses_v2')).toEqual(sessions[0]); + expect(fs.readFileSync(dbPath)).toEqual(originalDatabase); + }); + }); + + it('uses sequence order, ignores control events, and captures the full agentic turn', () => { + withV2Database((database, dbPath) => { + insertV2Message(database, 'z-user', 'user', 1, { text: 'Explain it' }, 'ses_v2', 1700000001000); + insertV2Message(database, 'b-step', 'assistant', 2, { + model: { id: 'gpt-5', providerID: 'openai' }, tokens: { input: 10, output: 3 }, + content: [{ type: 'tool', name: 'read', state: { input: { filePath: 'app.ts' } } }], finish: 'tool-calls', + }, 'ses_v2', 1700000001000); + insertV2Message(database, 'system', 'system', 3, { text: 'Not a user prompt' }); + insertV2Message(database, 'compact', 'compaction', 4, { summary: 'Not an assistant response', tokens: { input: 900, output: 900 } }); + insertV2Message(database, 'a-final', 'assistant', 5, { + model: { id: 'gpt-5', providerID: 'openai' }, tokens: { input: 100, output: 7, cache: { read: 50, write: 0 } }, + time: { created: 1700000005000, completed: 1700000006000 }, + content: [{ type: 'text', text: 'The answer.' }], finish: 'stop', + }); + insertV2Message(database, 'next-user', 'user', 6, { text: 'Next question' }); + const session = parseOpenCodeSessions(dbPath)[0]; + expect(session.requests).toHaveLength(2); + expect(session.requests[0]).toMatchObject({ messageText: 'Explain it', responseText: 'The answer.', + promptTokens: 160, completionTokens: 10, cacheReadTokens: 50, totalElapsed: 5000, answerEvidence: 'final' }); + expect(session.requests[1]).toMatchObject({ messageText: 'Next question', promptTokens: null, completionTokens: null, answerEvidence: 'missing' }); + expect(session.lastMessageDate).toBe(1700000006000); + }); + }); + + it('keeps explicit zero tokens and skips malformed messages and unsuccessful edits', () => { + withV2Database((database, dbPath) => { + insertV2Message(database, 'bad-json', 'user', 1, '{'); + insertV2Message(database, 'bad-shape', 'assistant', 2, 'null'); + insertV2Message(database, 'user', 'user', 3, { text: 'Try editing' }); + insertV2Message(database, 'assistant', 'assistant', 4, { tokens: { input: 0, output: 0 }, content: [ + { type: 'tool', name: 'edit', state: { status: 'error', input: { filePath: 'failed.ts', oldString: 'old', newString: 'new' } } }, + { type: 'tool', name: 'patch', state: { status: 'running', input: { patchText: '*** Begin Patch\n*** Add File: running.ts\n+new\n*** End Patch' } } }, + ] }); + const editLocIndex: EditLocIndex = new Map(); + const sessions = parseOpenCodeSessions(dbPath, editLocIndex); + expect(sessions).toHaveLength(1); + expect(sessions[0].requests).toHaveLength(1); + expect(sessions[0].requests[0]).toMatchObject({ promptTokens: 0, completionTokens: 0, editedFiles: [] }); + expect(editLocIndex.size).toBe(0); + }); + }); + + it('uses recorded tool diffs rather than estimating repeated replacements and patches', () => { + withV2Database((database, dbPath) => { + insertV2Message(database, 'user', 'user', 1, { text: 'Replace repeated text' }); + insertV2Message(database, 'assistant', 'assistant', 2, { content: [ + { type: 'tool', name: 'edit', state: { + status: 'completed', input: { filePath: 'app.ts', oldString: 'old', newString: 'new', replaceAll: true }, + metadata: { filediff: { file: 'app.ts', additions: 3, deletions: 3 } }, + } }, + { type: 'tool', name: 'patch', state: { + status: 'completed', input: { patchText: '*** Begin Patch\n*** Update File: app.ts\n-old\n+new\n*** End Patch' }, + metadata: { files: [{ file: 'app.ts', additions: 2, deletions: 2 }] }, + } }, + { type: 'tool', name: 'edit', state: { + status: 'error', input: { filePath: 'failed.ts' }, metadata: { filediff: { file: 'failed.ts', additions: 9, deletions: 9 } }, + } }, + ] }); + const edits: EditLocIndex = new Map(); + expect(parseOpenCodeSessions(dbPath, edits)[0].requests[0].editedFiles).toEqual(['app.ts']); + expect(edits.get('user')?.get('app.ts')).toEqual({ added: 5, removed: 5 }); + }); + }); + + it('prefers V2 copies of migrated sessions while retaining V1-only sessions', () => { + withV2Database((database, dbPath) => { + database.exec(` + CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, title TEXT, slug TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + CREATE TABLE part (id TEXT PRIMARY KEY, session_id TEXT, message_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session VALUES ('ses_v2', 'project', '/repo/project', 'Project', 'project', 1, 2); + INSERT INTO session VALUES ('ses_v1', 'project', '/repo/legacy', 'Legacy', 'legacy', 1, 2); + INSERT INTO message VALUES ('user', 'ses_v2', 1, 2, '{"role":"user","summary":{"title":"Old copy"}}'); + INSERT INTO message VALUES ('legacy-user', 'ses_v1', 1, 2, '{"role":"user","summary":{"title":"V1 only"}}'); + `); + insertV2Message(database, 'user', 'user', 1, { text: 'Current copy' }); + const sessions = parseOpenCodeSessions(dbPath); + expect(sessions).toHaveLength(2); + expect(sessions.find(session => session.sessionId === 'ses_v2')?.requests[0].messageText).toBe('Current copy'); + expect(sessions.find(session => session.sessionId === 'ses_v1')?.requests[0].messageText).toBe('V1 only'); + expect(loadOpenCodeSession(dbPath, 'ses_v2')?.requests[0].messageText).toBe('Current copy'); + expect(loadOpenCodeSession(dbPath, 'ses_v1')?.requests[0].messageText).toBe('V1 only'); + database.exec("DELETE FROM session_message WHERE session_id = 'ses_v2'"); + expect(parseOpenCodeSessions(dbPath).map(session => session.sessionId)).toEqual(['ses_v1']); + expect(loadOpenCodeSession(dbPath, 'ses_v2')).toBeNull(); + }); + }); + + it('discovers V2 channel databases in configured data roots', () => { + withV2Database((database, dbPath) => { + insertV2Message(database, 'user', 'user', 1, { text: 'Nightly session' }); + const root = path.dirname(dbPath); + const base = path.join(root, 'opencode'); + fs.mkdirSync(base); + const nightly = path.join(base, 'opencode-nightly.db'); + fs.copyFileSync(dbPath, nightly); + vi.stubEnv('HOME', root); + vi.stubEnv('USERPROFILE', root); + vi.stubEnv('XDG_DATA_HOME', root); + vi.stubEnv('LOCALAPPDATA', path.join(root, 'local-appdata')); + try { + expect(findOpenCodeDirs()).toEqual([nightly]); + expect(parseOpenCodeSessions(nightly)[0].requests[0].messageText).toBe('Nightly session'); + } finally { + vi.unstubAllEnvs(); + } + }); + }); + + it('uses the V2 path when the session directory is empty', () => { + withV2Database((database, dbPath) => { + database.exec("UPDATE session_v2 SET directory = '', path = '/repo/alternate'"); + insertV2Message(database, 'user', 'user', 1, { text: 'Path session' }); + expect(parseOpenCodeSessions(dbPath)[0]).toMatchObject({ workspaceRootPath: '/repo/alternate', workspaceName: 'alternate' }); + }); + }); + + it('skips V1 query when V2 has the requested session', () => { + withV2Database((database, dbPath) => { + // Create V1 tables with the same session ID — V1 should be skipped entirely. + database.exec(` + CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, title TEXT, slug TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + CREATE TABLE part (id TEXT PRIMARY KEY, session_id TEXT, message_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session VALUES ('ses_v2', 'v1project', '/repo/v1', 'V1 Copy', 'v1', 1, 2); + INSERT INTO message VALUES ('v1-user', 'ses_v2', 1, 2, '{"role":"user","summary":{"title":"V1 stale"}}'); + `); + insertV2Message(database, 'user', 'user', 1, { text: 'V2 current' }); + const loaded = loadOpenCodeSession(dbPath, 'ses_v2'); + expect(loaded?.requests[0].messageText).toBe('V2 current'); + }); + }); + + it('handles V2 messages with null content, null files, and non-user/assistant roles', () => { + withV2Database((database, dbPath) => { + // User with null files — should still produce a text part. + insertV2Message(database, 'user', 'user', 1, { text: 'Hello', files: null as unknown as [] }); + // Assistant with null content — should produce no parts, no response text. + insertV2Message(database, 'assistant', 'assistant', 2, { content: null as unknown as [] }); + // Non-user/assistant roles — should be ignored. + insertV2Message(database, 'system', 'system', 3, { text: 'System message' }); + insertV2Message(database, 'tool', 'tool_result', 4, { text: 'Tool output' }); + const session = parseOpenCodeSessions(dbPath)[0]; + expect(session.requests).toHaveLength(1); + expect(session.requests[0].messageText).toBe('Hello'); + expect(session.requests[0].responseText).toBe(''); + }); + }); + + it('filters to a single session when loadOpenCodeSession is called with a sessionId', () => { + withV2Database((database, dbPath) => { + // Ensure ses_v2 has messages so it parses as a valid session. + insertV2Message(database, 'user', 'user', 1, { text: 'Update the app' }); + insertV2Message(database, 'assistant', 'assistant', 2, { + model: { id: 'gpt-5', providerID: 'openai' }, tokens: { input: 10, output: 5 }, + content: [{ type: 'text', text: 'Updated.' }], finish: 'stop', + }); + // Insert a second session to verify filtering. + database.exec(` + INSERT INTO session_v2 VALUES ('ses_other', 'project', '/repo/other', NULL, 'Other', 'other', + 'build', '{"id":"gpt-5","providerID":"openai"}', 1700000020000, 1700000030000); + `); + insertV2Message(database, 'other-user', 'user', 1, { text: 'Other session prompt' }, 'ses_other'); + insertV2Message(database, 'other-assistant', 'assistant', 2, { + model: { id: 'gpt-5', providerID: 'openai' }, tokens: { input: 10, output: 5 }, + content: [{ type: 'text', text: 'Other answer.' }], finish: 'stop', + }, 'ses_other'); + const allSessions = parseOpenCodeSessions(dbPath); + expect(allSessions).toHaveLength(2); + // loadOpenCodeSession with a specific ID should return only that session. + const filtered = loadOpenCodeSession(dbPath, 'ses_v2'); + expect(filtered).not.toBeNull(); + expect(filtered!.sessionId).toBe('ses_v2'); + expect(filtered!.requests[0].messageText).toBe('Update the app'); + const other = loadOpenCodeSession(dbPath, 'ses_other'); + expect(other).not.toBeNull(); + expect(other!.sessionId).toBe('ses_other'); + expect(other!.requests[0].messageText).toBe('Other session prompt'); + }); + }); + + it('returns empty / null when the V2 database has zero sessions', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-empty-v2-')); + const dbPath = path.join(root, 'opencode.db'); + const database = new DatabaseSync(dbPath); + try { + database.exec(` + CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, path TEXT, title TEXT, slug TEXT, + agent TEXT, model TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, + time_created INTEGER, time_updated INTEGER, data TEXT); + `); + expect(parseOpenCodeSessions(dbPath)).toEqual([]); + expect(loadOpenCodeSession(dbPath, 'nonexistent')).toBeNull(); + } finally { + database.close(); + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it.each([true, false])('marks child sessions as subagent (session_v2 parent_id column: %s)', withParentColumn => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-v2-child-')); + const dbPath = path.join(root, 'opencode.db'); + const database = new DatabaseSync(dbPath); + try { + database.exec(` + CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT, ${withParentColumn ? 'parent_id TEXT, ' : ''}directory TEXT, path TEXT, title TEXT, slug TEXT, + agent TEXT, model TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, + time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session_v2 VALUES ('ses_root', 'project', ${withParentColumn ? 'NULL, ' : ''}'/repo/project', NULL, 'Root', 'root', + 'build', '{"id":"gpt-5","providerID":"openai"}', 1, 2); + INSERT INTO session_v2 VALUES ('ses_child', 'project', ${withParentColumn ? "'ses_root', " : ''}'/repo/project', NULL, 'Child', 'child', + 'build', '{"id":"gpt-5","providerID":"openai"}', 1, 2); + `); + const insert = database.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)'); + for (const id of ['ses_root', 'ses_child']) { + insert.run(`${id}_user`, id, 'user', 1, 1, 1, JSON.stringify({ text: 'Prompt', files: [] })); + insert.run(`${id}_assistant`, id, 'assistant', 2, 2, 2, JSON.stringify({ content: [{ type: 'text', text: 'Answer' }], finish: 'stop' })); + } + const sessions = parseOpenCodeSessions(dbPath); + const kindsOf = (id: string) => (sessions.find(session => session.sessionId === id)?.requests ?? []).map(request => request.nonHumanKind); + expect(kindsOf('ses_root')).toEqual([undefined]); + expect(kindsOf('ses_child')).toEqual(withParentColumn ? ['subagent'] : [undefined]); + } finally { + database.close(); + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it('uses the session title as display name unless it repeats the first prompt', () => { + withV2Database((database, dbPath) => { + // Fixture title 'Project' differs from the prompt → kept. + insertV2Message(database, 'user', 'user', 1, { text: 'Update the app' }); + insertV2Message(database, 'assistant', 'assistant', 2, { content: [{ type: 'text', text: 'Done.' }] }); + // A title that is the first prompt itself (an auto title) → dropped. + database.exec("INSERT INTO session_v2 VALUES ('ses_copy', 'project', '/repo/copy', NULL, 'Do the thing', 'copy', 'build', NULL, 1, 2)"); + insertV2Message(database, 'copy-user', 'user', 1, { text: 'Do the thing' }, 'ses_copy'); + insertV2Message(database, 'copy-assistant', 'assistant', 2, { content: [{ type: 'text', text: 'Done.' }] }, 'ses_copy'); + const sessions = parseOpenCodeSessions(dbPath); + expect(sessions.find(session => session.sessionId === 'ses_v2')?.displayName).toBe('Project'); + expect(sessions.find(session => session.sessionId === 'ses_copy')?.displayName).toBeUndefined(); + }); + }); +}); + +describe('findOpenCodeDirs', () => { + it('returns an empty array when HOME has no V2 databases or legacy storage', () => { + const emptyHome = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-empty-home-')); + vi.stubEnv('HOME', emptyHome); + vi.stubEnv('USERPROFILE', emptyHome); + vi.stubEnv('XDG_DATA_HOME', emptyHome); + vi.stubEnv('LOCALAPPDATA', emptyHome); + try { + expect(findOpenCodeDirs()).toEqual([]); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(emptyHome, { recursive: true, force: true }); + } + }); +}); + +describe('OpenCode V1-only database', () => { + it('parses V1 tables when no V2 tables exist', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-v1-only-test-')); + const dbPath = path.join(root, 'opencode.db'); + const userData = JSON.stringify({ role: 'user', summary: { title: 'V1 only session' } }); + const assistantData = JSON.stringify({ role: 'assistant', modelID: 'gpt-4', tokens: { input: 50, output: 10 } }); + try { + const database = new DatabaseSync(dbPath); + database.exec(` + CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, title TEXT, slug TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + CREATE TABLE part (id TEXT PRIMARY KEY, session_id TEXT, message_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session VALUES ('v1only', 'proj', '/repo/v1', 'V1 Only', 'v1only', 1700000000000, 1700000002000); + INSERT INTO message VALUES ('u1', 'v1only', 1700000000000, 1700000000000, ${sqlString(userData)}); + INSERT INTO message VALUES ('a1', 'v1only', 1700000001000, 1700000001000, ${sqlString(assistantData)}); + `); + database.close(); + const sessions = parseOpenCodeSessions(dbPath); + expect(sessions).toHaveLength(1); + expect(sessions[0].sessionId).toBe('v1only'); + expect(sessions[0].requests[0].messageText).toBe('V1 only session'); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it('uses the session title as display name', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-v1-title-test-')); + const dbPath = path.join(root, 'opencode.db'); + const userData = JSON.stringify({ role: 'user', summary: { title: 'Please fix the login bug in src/auth.ts' } }); + const assistantData = JSON.stringify({ role: 'assistant', modelID: 'gpt-4', tokens: { input: 50, output: 10 } }); + try { + const database = new DatabaseSync(dbPath); + database.exec(` + CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, title TEXT, slug TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + CREATE TABLE part (id TEXT PRIMARY KEY, session_id TEXT, message_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session VALUES ('titled', 'proj', '/repo/v1', 'Fix the login bug', 'titled', 1700000000000, 1700000002000); + INSERT INTO message VALUES ('u1', 'titled', 1700000000000, 1700000000000, ${sqlString(userData)}); + INSERT INTO message VALUES ('a1', 'titled', 1700000001000, 1700000001000, ${sqlString(assistantData)}); + `); + database.close(); + const sessions = parseOpenCodeSessions(dbPath); + expect(sessions).toHaveLength(1); + expect(sessions[0].displayName).toBe('Fix the login bug'); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); + describe('parseOpenCodeSessions', () => { it('ends a turn’s agent time at its last assistant message', () => { withStorage({ id: 'sess-elapsed', directory: '/Users/me/proj', time: { created: 1700000000000 } }, [ diff --git a/src/core/parser-opencode.ts b/src/core/parser-opencode.ts index 2fbbb30f..14776767 100644 --- a/src/core/parser-opencode.ts +++ b/src/core/parser-opencode.ts @@ -5,10 +5,12 @@ /* OpenCode session parser * - * Data layout (macOS): + * V1 JSON layout (macOS): * ~/.local/share/opencode/storage/session/global/.json -- session metadata * ~/.local/share/opencode/storage/message//.json -- message metadata * ~/.local/share/opencode/storage/part//.json -- content parts (text, tool, step-start/finish) + * SQLite: opencode.db (and channel-specific databases) stores V1 session/message/part + * tables or V2 session_v2/session_message tables with inline content. Both can coexist. * * Sessions have: id, slug, version, projectID, directory, title, time.created/updated * Messages have: id, sessionID, role (user|assistant), time, agent, model {providerID, modelID}, tokens, cost @@ -23,6 +25,7 @@ import { canonicalizeReasoningEffort, extractReasoningEffortFromModelId } from ' import { warnCore } from './log'; import { EditLocIndex } from './edit-loc-diff'; import { markNonHuman } from './human-turns'; +import { isPromptText } from './session-workspace-meta'; import { openCodeMessageNonHumanKind } from './parser-turn-kinds'; import { addFileEditLoc, @@ -69,6 +72,10 @@ interface OcMessage { summary?: { title?: string; diffs?: OcFileDiff[] }; variant?: string; model?: { providerID?: string; modelID?: string }; + seq?: number; + text?: string; + files?: unknown[]; + content?: unknown[]; } interface OcFileDiff { @@ -91,12 +98,14 @@ interface OcPart { auto?: boolean; mime?: string; url?: string; + data?: unknown; tool?: string; callID?: string; state?: { status?: string; input?: Record; output?: string }; tokens?: { input?: number; output?: number; reasoning?: number }; cost?: number; reason?: string; + fileDiffs?: OcFileDiff[]; } interface OpenCodeAssistantData { @@ -107,6 +116,8 @@ interface OpenCodeAssistantData { editedFiles: string[]; referencedFiles: string[]; modelId: string; + agent: string; + variant?: string; totalElapsed: number | null; lastTs: number | null; /** Token totals over the request's model calls; `null` when no call logged tokens. */ @@ -134,7 +145,10 @@ const READ_TOOLS = new Set(['read', 'glob', 'grep', 'ls', 'find']); /** The subset of `node:sqlite` this parser uses, so the module stays optional at build time. */ interface SqliteDatabase { - prepare(sql: string): { all(...parameters: string[]): unknown[] }; + prepare(sql: string): { + all(...parameters: string[]): unknown[]; + iterate(...parameters: string[]): Iterable; + }; close(): void; } @@ -271,10 +285,21 @@ function applyOpenCodePart( const toolLower = part.tool.toLowerCase(); const toolSucceeded = part.state?.status === undefined || part.state.status === 'completed'; if (!toolSucceeded && WRITE_TOOLS.has(toolLower)) return; - if (toolLower === 'patch' || toolLower === 'apply_patch') { - const patch = typeof input.patch === 'string' ? input.patch - : typeof input.input === 'string' ? input.input - : ''; + const recordedLocs: FileEditLocMap = new Map(); + if (WRITE_TOOLS.has(toolLower)) { + for (const diff of part.fileDiffs ?? []) { + if (diff.file && typeof diff.additions === 'number' && typeof diff.deletions === 'number') { + addFileEditLoc(recordedLocs, diff.file, diff.additions, diff.deletions); + } + } + mergeFileEditLoc(data.editLocs, recordedLocs); + data.editedFiles.push(...recordedLocs.keys()); + } + if ((toolLower === 'patch' || toolLower === 'apply_patch') && recordedLocs.size === 0) { + const patch = typeof input.patchText === 'string' ? input.patchText + : typeof input.patch === 'string' ? input.patch + : typeof input.input === 'string' ? input.input + : ''; const patchEdits = parseApplyPatch(patch); mergeFileEditLoc(data.editLocs, patchEdits); for (const file of patchEdits.keys()) data.editedFiles.push(file); @@ -290,15 +315,18 @@ function applyOpenCodePart( if (WRITE_TOOLS.has(toolLower)) { data.editedFiles.push(filePath); - const previous = typeof input.old_string === 'string' ? input.old_string - : typeof input.old_str === 'string' ? input.old_str - : ''; - const next = typeof input.new_string === 'string' ? input.new_string - : typeof input.new_str === 'string' ? input.new_str - : ''; - if (previous || next) { + const previous = typeof input.oldString === 'string' ? input.oldString + : typeof input.old_string === 'string' ? input.old_string + : typeof input.old_str === 'string' ? input.old_str + : ''; + const next = typeof input.newString === 'string' ? input.newString + : typeof input.new_string === 'string' ? input.new_string + : typeof input.new_str === 'string' ? input.new_str + : ''; + // Recorded diffs capture replace-all and overwrite behavior that inputs alone cannot. + if (!recordedLocs.has(filePath) && (previous || next)) { recordContentReplacement(data.editLocs, filePath, previous, next); - } else { + } else if (!recordedLocs.has(filePath)) { const written = typeof input.content === 'string' ? input.content : typeof input.code === 'string' ? input.code : ''; @@ -310,9 +338,10 @@ function applyOpenCodePart( // Write tools store the code in various input fields; also check state.output. const content = typeof input.content === 'string' ? input.content : typeof input.code === 'string' ? input.code - : typeof input.new_string === 'string' ? input.new_string - : typeof part.state?.output === 'string' ? part.state.output - : null; + : typeof input.newString === 'string' ? input.newString + : typeof input.new_string === 'string' ? input.new_string + : typeof part.state?.output === 'string' ? part.state.output + : null; if (content) { const ext = filePath.split('.').pop() || 'unknown'; textParts.push(`\n\`\`\`${ext}\n${content}\n\`\`\`\n`); @@ -358,6 +387,7 @@ function collectAssistantData( editedFiles: [], referencedFiles: [], modelId: '', + agent: '', totalElapsed: null, lastTs, tokens: null, @@ -369,17 +399,18 @@ function collectAssistantData( const assistantMsg = assistantMessages[0]; if (!assistantMsg) return data; - // The turn's work ends with its last assistant message, not its first (tool loops log several). - const ends = assistantMessages.map(message => message.time?.completed || message.time?.created || 0).filter(ts => ts > 0); - const assistantTs = ends.length > 0 ? Math.max(...ends) : null; - if (assistantTs && (!data.lastTs || assistantTs > data.lastTs)) data.lastTs = assistantTs; - if (userTs && assistantTs) data.totalElapsed = assistantTs - userTs; - - data.modelId = assistantMsg.modelID || ''; addOpenCodeTokens(data, assistantMessages); const textParts: string[] = []; for (const message of assistantMessages) { + const assistantTs = message.time?.completed || message.time?.created || null; + if (assistantTs && (!data.lastTs || assistantTs > data.lastTs)) data.lastTs = assistantTs; + // Multi-round turn: totalElapsed measures from the user message to the *last* + // assistant message, yielding a more accurate total turn duration. + if (userTs && assistantTs) data.totalElapsed = assistantTs - userTs; + data.modelId = message.modelID || data.modelId; + data.agent = message.agent || data.agent; + data.variant = message.variant ?? data.variant; const parts = partsByMsg.get(message.id) || []; const hasText = parts.some(part => part.type === 'text' && part.text?.trim()); data.answerEvidence = hasText && (message.finish === 'stop' || message.finish === 'end_turn') ? 'final' @@ -411,6 +442,14 @@ function getOpenCodeWorkspace(rawSession: OcSession): { wsId: string; wsName: st }; } +/** The session's title as logged, as its display name — unless it is the first prompt itself, an auto title that + * would just repeat what the timeline shows anyway. */ +function openCodeDisplayName(title: string | undefined, firstPrompt: string): string | undefined { + const name = title?.trim(); + if (!name) return undefined; + return isPromptText(name, firstPrompt) ? undefined : name; +} + function buildOpenCodeRequest( msg: OcMessage, partsByMsg: Map, @@ -442,8 +481,8 @@ function buildOpenCodeRequest( variableKinds: imageCount > 0 ? { image: imageCount } : {}, responseText: assistantData.responseText, replyText: assistantData.replyText, - agentName: msg.agent || 'OpenCode', - agentMode: msg.agent || 'build', + agentName: msg.agent || assistantData.agent || 'OpenCode', + agentMode: msg.agent || assistantData.agent || 'build', modelId: assistantData.modelId, toolsUsed: assistantData.toolsUsed, investigationDelegations: assistantData.investigationDelegations, @@ -460,8 +499,8 @@ function buildOpenCodeRequest( // null: no cache usage was reported. 0: it was reported with no cache reads or writes (caching off). cacheReadTokens: tokens?.cacheReported ? tokens.cacheRead : null, cacheWriteTokens: tokens?.cacheReported ? tokens.cacheWrite : null, - // OpenCode stores reasoning effort as "variant" on user messages - reasoningEffort: canonicalizeReasoningEffort(msg.variant) + // V1 stores variants on user messages; V2 records them on assistant models. + reasoningEffort: canonicalizeReasoningEffort(msg.variant ?? assistantData.variant) ?? extractReasoningEffortFromModelId(assistantData.modelId), ...(assistantData.contextUsage ? { contextUsage: assistantData.contextUsage } : {}), }); @@ -522,7 +561,8 @@ function buildOpenCodeSession( ): Session | null { if (!rawSession.id) return null; - rawMessages.sort((a, b) => (a.time?.created || 0) - (b.time?.created || 0)); + rawMessages.sort((a, b) => a.seq !== undefined && b.seq !== undefined + ? a.seq - b.seq : (a.time?.created || 0) - (b.time?.created || 0)); if (rawMessages.length === 0) return null; const { wsId, wsName } = getOpenCodeWorkspace(rawSession); @@ -538,6 +578,7 @@ function buildOpenCodeSession( const userTs = msg.time?.created || null; if (userTs && (!firstTs || userTs < firstTs)) firstTs = userTs; + if (userTs && (!lastTs || userTs > lastTs)) lastTs = userTs; const assistantMessages = answers.get(msg.id) ?? []; const assistantData = collectAssistantData(assistantMessages, partsByMsg, userTs, lastTs); @@ -550,6 +591,7 @@ function buildOpenCodeSession( if (requests.length === 0) return null; markOpenCodeTurns(requests, partsByMsg, Boolean(rawSession.parentID)); + const displayName = openCodeDisplayName(rawSession.title, requests[0].messageText); return createSession({ sessionId: rawSession.id, workspaceId: wsId, @@ -562,6 +604,7 @@ function buildOpenCodeSession( hasDevcontainer: detectDevcontainerFromRequests(requests, rawSession.directory), workspaceRootPath: rawSession.directory || undefined, ...(rawSession.parentID && rawSession.parentID !== rawSession.id ? { parentSessionId: rawSession.parentID } : {}), + ...(displayName ? { displayName } : {}), }); } @@ -609,6 +652,8 @@ interface OcDbDataRow { created?: number; completed?: number; data: string; + type?: string; + seq?: number; } function decodeOpenCodeMessage(row: OcDbDataRow): OcMessage | null { @@ -616,11 +661,15 @@ function decodeOpenCodeMessage(row: OcDbDataRow): OcMessage | null { const data: unknown = JSON.parse(row.data); if (!isRecord(data)) return null; const time = isRecord(data.time) ? data.time : {}; + const model = isRecord(data.model) ? data.model : {}; return { ...data, id: row.id, sessionID: row.sessionID, - role: typeof data.role === 'string' ? data.role : '', + role: row.type ?? (typeof data.role === 'string' ? data.role : ''), + seq: row.seq, + modelID: typeof model.id === 'string' ? model.id : data.modelID, + variant: typeof model.variant === 'string' ? model.variant : data.variant, time: { created: typeof time.created === 'number' ? time.created : row.created, completed: typeof time.completed === 'number' ? time.completed : row.completed, @@ -647,35 +696,38 @@ function decodeOpenCodePart(row: OcDbDataRow): OcPart | null { } } -function parseOpenCodeDatabase(dbPath: string, editLocIndex?: EditLocIndex, sessionId?: string): Session[] { - assertTrustedPath(dbPath); - const sqlite = loadSqlite(); - if (!sqlite) return []; - let database: SqliteDatabase; - try { - database = new sqlite.DatabaseSync(dbPath, { readOnly: true }); - } catch (error) { - warnCore('parser-opencode', 'Could not open OpenCode database', error); - return []; - } - +function readOpenCodeV1Database(database: SqliteDatabase, editLocIndex: EditLocIndex | undefined, + sessionId: string | undefined, excludeIds: string[]): Session[] { const parameters = sessionId === undefined ? [] : [sessionId]; const sessionFilter = sessionId === undefined ? '' : ' WHERE id = ?'; const dataFilter = sessionId === undefined ? '' : ' WHERE session_id = ?'; // Older databases have no `session.parent_id`; selecting it there would fail the whole query. const parentColumn = queryOpenCodeDatabase<{ name?: unknown }>(database, 'PRAGMA table_info(session)') .some(column => column.name === 'parent_id') ? 'parent_id AS parentID, ' : ''; + // Use parameterized NOT IN to exclude V2 session IDs — avoids a wasteful + // `NOT IN (SELECT id FROM session_v2)` subquery on every query. + let sessionExclusion = ''; + if (excludeIds.length > 0) { + const placeholders = excludeIds.map(() => '?').join(','); + sessionExclusion = `${sessionFilter ? ' AND' : ' WHERE'} id NOT IN (${placeholders})`; + parameters.push(...excludeIds); + } + let dataExclusion = ''; + if (excludeIds.length > 0) { + const placeholders = excludeIds.map(() => '?').join(','); + dataExclusion = `${dataFilter ? ' AND' : ' WHERE'} session_id NOT IN (${placeholders})`; + } const rawSessions = queryOpenCodeDatabase(database, `SELECT id, project_id AS projectID, ${parentColumn}directory, title, slug, ` - + `time_created AS created, time_updated AS updated FROM session${sessionFilter} ORDER BY time_created`, ...parameters); + + `time_created AS created, time_updated AS updated FROM session${sessionFilter}${sessionExclusion} ORDER BY time_created`, ...parameters); + if (rawSessions.length === 0) return []; const messageRows = queryOpenCodeDatabase(database, 'SELECT id, session_id AS sessionID, time_created AS created, ' - + `time_updated AS completed, data FROM message${dataFilter} ORDER BY session_id, time_created, id`, ...parameters); + + `time_updated AS completed, data FROM message${dataFilter}${dataExclusion} ORDER BY session_id, time_created, id`, ...parameters); const partRows = queryOpenCodeDatabase(database, 'SELECT id, session_id AS sessionID, message_id AS messageID, ' - + `time_created AS created, time_updated AS completed, data FROM part${dataFilter} ` + + `time_created AS created, time_updated AS completed, data FROM part${dataFilter}${dataExclusion} ` + 'ORDER BY session_id, time_created, id', ...parameters); - database.close(); const messagesBySession = new Map(); for (const message of messageRows.map(decodeOpenCodeMessage)) { if (!message) continue; @@ -719,6 +771,109 @@ function parseOpenCodeDatabase(dbPath: string, editLocIndex?: EditLocIndex, sess return sessions; } +function openCodeDatabaseTables(database: SqliteDatabase): Set { + return new Set(queryOpenCodeDatabase<{ name: string }>(database, + "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('session', 'message', 'part', 'session_v2', 'session_message')", + ).map(row => row.name)); +} + +function openCodeV2Parts(message: OcMessage): OcPart[] { + const values: unknown[] = message.role === 'user' + ? [{ type: 'text', text: message.text }, ...(Array.isArray(message.files) + ? message.files.filter(isRecord).map(file => ({ ...file, type: 'file' })) : [])] + : message.role === 'assistant' && Array.isArray(message.content) ? message.content : []; + return values.filter(isRecord).map((value, index) => { + const state = isRecord(value.state) ? value.state : {}; + const source = isRecord(value.source) ? value.source : {}; + const metadata = isRecord(state.metadata) ? state.metadata : {}; + const files: unknown[] = Array.isArray(metadata.files) ? metadata.files : []; + const fileDiffs = [metadata.filediff, ...files] + .filter(isRecord).map(diff => ({ + file: typeof diff.file === 'string' ? diff.file : undefined, + additions: typeof diff.additions === 'number' ? diff.additions : undefined, + deletions: typeof diff.deletions === 'number' ? diff.deletions : undefined, + })); + return { + id: `${message.id}:${index}`, sessionID: message.sessionID, messageID: message.id, + type: typeof value.type === 'string' ? value.type : '', + text: value.type === 'text' && typeof value.text === 'string' ? value.text : undefined, + tool: typeof value.name === 'string' ? value.name : undefined, + mime: typeof value.mime === 'string' ? value.mime : undefined, + data: value.data, + fileDiffs, + url: typeof source.uri === 'string' ? source.uri : undefined, + // Tool output can be very large and is not needed for analytics. + state: { status: typeof state.status === 'string' ? state.status : undefined, + input: isRecord(state.input) ? state.input : {} }, + }; + }); +} + +function readOpenCodeV2Database(database: SqliteDatabase, editLocIndex?: EditLocIndex, sessionId?: string): Session[] { + const parameters = sessionId === undefined ? [] : [sessionId]; + const filter = sessionId === undefined ? '' : ' WHERE id = ?'; + // Older databases have no `session_v2.parent_id`; selecting it there would fail the whole query. + const parentColumn = queryOpenCodeDatabase<{ name?: unknown }>(database, 'PRAGMA table_info(session_v2)') + .some(column => column.name === 'parent_id') ? 'parent_id AS parentID, ' : ''; + const rows = queryOpenCodeDatabase(database, + `SELECT id, project_id AS projectID, ${parentColumn}coalesce(nullif(directory, ''), path) AS directory, title, slug, ` + + `time_created AS created, time_updated AS updated FROM session_v2${filter} ORDER BY time_created`, ...parameters); + const sessions: Session[] = []; + for (const row of rows) { + if (!/^[\w-]+$/.test(row.id)) continue; + const messages: OcMessage[] = []; + const partsByMsg = new Map(); + try { + // Stream one session at a time; retaining every tool output can exhaust the worker heap. + const messageRows = database.prepare('SELECT id, session_id AS sessionID, type, seq, ' + + "time_created AS created, data FROM session_message WHERE session_id = ? AND type IN ('user', 'assistant') ORDER BY seq, id").iterate(row.id); + for (const messageRow of messageRows) { + const message = decodeOpenCodeMessage(messageRow as OcDbDataRow); + if (!message || (message.role !== 'user' && message.role !== 'assistant')) continue; + partsByMsg.set(message.id, openCodeV2Parts(message)); + message.content = undefined; + message.files = undefined; + messages.push(message); + } + } catch (error) { + warnCore('parser-opencode', 'Could not read OpenCode V2 messages', error); + continue; + } + const session = buildOpenCodeSession({ ...row, parentID: row.parentID ?? undefined, time: { created: row.created, updated: row.updated } }, messages, partsByMsg, editLocIndex); + if (session) sessions.push(session); + } + return sessions; +} + +function parseOpenCodeDatabase(dbPath: string, editLocIndex?: EditLocIndex, sessionId?: string): Session[] { + assertTrustedPath(dbPath); + const sqlite = loadSqlite(); + if (!sqlite) return []; + let database: SqliteDatabase | undefined; + try { + database = new sqlite.DatabaseSync(dbPath, { readOnly: true }); + const tables = openCodeDatabaseTables(database); + const hasV2 = tables.has('session_v2') && tables.has('session_message'); + const sessions = hasV2 ? readOpenCodeV2Database(database, editLocIndex, sessionId) : []; + // Skip V1 query for a specific session when V2 already has it — avoids a wasteful + // `NOT IN (SELECT id FROM session_v2)` subquery that would return zero rows. + if (sessionId === undefined || !hasV2 || sessions.every(s => s.sessionId !== sessionId)) { + if (tables.has('session') && tables.has('message') && tables.has('part')) { + const excludeIds = hasV2 + ? queryOpenCodeDatabase<{ id: string }>(database, 'SELECT id FROM session_v2').map(r => r.id) + : []; + sessions.push(...readOpenCodeV1Database(database, editLocIndex, sessionId, excludeIds)); + } + } + return sessions; + } catch (error) { + warnCore('parser-opencode', 'Could not read OpenCode database', error); + return []; + } finally { + database?.close(); + } +} + export function loadOpenCodeSession(source: string, sessionId: string): Session | null { if (!/^[\w-]+$/.test(sessionId)) { warnCore('parser-opencode', 'Invalid OpenCode session ID'); @@ -763,6 +918,16 @@ export function readOpenCodeImageReferences(source: string, sessionId: string, r let database: SqliteDatabase | undefined; try { database = new sqlite.DatabaseSync(source, { readOnly: true }); + const tables = openCodeDatabaseTables(database); + if (tables.has('session_v2') && tables.has('session_message') + && database.prepare('SELECT id FROM session_v2 WHERE id = ?').all(sessionId).length > 0) { + const rows = queryOpenCodeDatabase(database, + "SELECT id, session_id AS sessionID, type, data FROM session_message WHERE session_id = ? AND id = ? AND type = 'user'", + sessionId, requestId); + const message = rows[0] && decodeOpenCodeMessage(rows[0]); + return message ? imageReferencesFromContent(openCodeV2Parts(message)) : []; + } + if (!tables.has('message') || !tables.has('part')) return []; const rows = database.prepare( 'SELECT part.data FROM part JOIN message ON message.id = part.message_id AND message.session_id = part.session_id ' + "WHERE part.session_id = ? AND part.message_id = ? AND json_extract(message.data, '$.role') = 'user' " diff --git a/src/core/session-images.test.ts b/src/core/session-images.test.ts index 66f065b7..433f7875 100644 --- a/src/core/session-images.test.ts +++ b/src/core/session-images.test.ts @@ -14,7 +14,7 @@ import { collectExternalHarnessesAsync } from './parser-harnesses'; import { parseCLIEventsFile, parseCLIEventsFileAsync } from './parser-vscode-cli'; import { parseClaudeSessions } from './parser-claude'; import { parseCodexSessions } from './parser-codex'; -import { parseOpenCodeSessions } from './parser-opencode'; +import { parseOpenCodeSessions, readOpenCodeImageReferences, findOpenCodeDirs } from './parser-opencode'; import { parseSessionFile, processWorkspaceEntryAsync } from './parser-vscode'; import { extractSourceImages, loadSourceSession } from './session-images'; import { Analyzer } from './analyzer'; @@ -457,12 +457,85 @@ describe('harness-aware image loading', () => { expect(extractSourceImages(source, 'oc-db', "' OR 1=1 --")).toEqual([]); const prepare = vi.spyOn(DatabaseSync.prototype, 'prepare'); expect(loadSourceSession(source, 'oc-db')?.requests[0].variableKinds.image).toBe(1); - // One schema probe (does `session.parent_id` exist?), then three row queries, each limited to the session. + // One schema probe (parent_id check), a V2 table probe, then three row queries, each limited to the session. const statements = prepare.mock.calls.map(([sql]) => sql); expect(statements.filter(sql => sql.startsWith('PRAGMA '))).toEqual(['PRAGMA table_info(session)']); const rowQueries = statements.filter(sql => !sql.startsWith('PRAGMA ')); - expect(rowQueries).toHaveLength(3); - expect(rowQueries.every(sql => / WHERE (?:id|session_id) = \?/.test(sql))).toBe(true); + expect(rowQueries).toHaveLength(4); + const sessionQueries = rowQueries.filter(sql => !sql.includes('sqlite_master')); + expect(sessionQueries).toHaveLength(3); + expect(sessionQueries.every(sql => / WHERE (?:id|session_id) = \?/.test(sql))).toBe(true); + }); + + it('counts and loads V2 inline file attachments with targeted, user-only reads', () => { + const file = path.join(root, 'opencode.db'); + const database = new DatabaseSync(file); + database.exec(` + CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, path TEXT, title TEXT, slug TEXT, + agent TEXT, model TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, + time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session_v2 VALUES ('oc-v2', 'project', '', NULL, 'Project', 'project', 'build', NULL, 1, 2); + `); + const attachment = { mime: 'image/png', data: base64, source: { type: 'inline' } }; + const localImage = path.join(root, 'screenshot.png'); + fs.writeFileSync(localImage, Buffer.from(alternateBase64, 'base64')); + const localAttachment = { mime: 'image/png', data: '', source: { type: 'uri', uri: pathToFileURL(localImage).href } }; + const insert = database.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, 1, 1, ?)'); + insert.run('user', 'oc-v2', 'user', 1, JSON.stringify({ text: 'Screenshot', files: [attachment, localAttachment] })); + insert.run('assistant', 'oc-v2', 'assistant', 2, JSON.stringify({ files: [attachment] })); + insert.run('other-user', 'other-session', 'user', 1, JSON.stringify({ files: [attachment] })); + database.close(); + const session = parseOpenCodeSessions(file, undefined, sources)[0]; + expect(session.requests[0].variableKinds.image).toBe(2); + const source = sources.get('oc-v2')!; + expect(extractSourceImages(source, 'oc-v2', 'user')).toEqual([image, alternateImage]); + expect(extractSourceImages(source, 'oc-v2', 'assistant')).toEqual([]); + expect(extractSourceImages(source, 'wrong-session', 'user')).toEqual([]); + expect(extractSourceImages(source, 'oc-v2', "' OR 1=1 --")).toEqual([]); + const prepare = vi.spyOn(DatabaseSync.prototype, 'prepare'); + expect(loadSourceSession(source, 'oc-v2')?.requests[0].variableKinds.image).toBe(2); + // One V2 table probe, one parent_id schema probe, then two row queries, each limited to the session. + const dataQueries = prepare.mock.calls.map(([sql]) => sql) + .filter(sql => !sql.includes('sqlite_master')) + .filter(sql => !sql.startsWith('PRAGMA ')); + expect(dataQueries).toHaveLength(2); + expect(dataQueries.every(sql => / WHERE (?:id|session_id) = \?/.test(sql))).toBe(true); + expect(JSON.stringify([...sources])).not.toContain(base64); + }); + + it('reads V2 inline image attachments directly via readOpenCodeImageReferences', () => { + const file = path.join(root, 'opencode-v2.db'); + const database = new DatabaseSync(file); + database.exec(` + CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT, directory TEXT, path TEXT, title TEXT, slug TEXT, + agent TEXT, model TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, + time_created INTEGER, time_updated INTEGER, data TEXT); + INSERT INTO session_v2 VALUES ('v2-direct', 'project', '', NULL, 'Direct', 'direct', 'build', NULL, 1, 2); + `); + const insert = database.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, 1, 1, ?)'); + const inlineAttachment = { mime: 'image/png', data: base64, source: { type: 'inline' } }; + insert.run('v2-user', 'v2-direct', 'user', 1, JSON.stringify({ text: 'Direct V2 image', files: [inlineAttachment] })); + insert.run('v2-assistant', 'v2-direct', 'assistant', 2, JSON.stringify({ text: 'Reply' })); + insert.run('other-session', 'other-v2', 'user', 1, JSON.stringify({ text: 'Wrong session', files: [inlineAttachment] })); + database.close(); + const references = readOpenCodeImageReferences(file, 'v2-direct', 'v2-user'); + expect(references).toHaveLength(1); + expect(references[0].data).toBe(base64); + expect(readOpenCodeImageReferences(file, 'v2-direct', 'v2-assistant')).toEqual([]); + expect(readOpenCodeImageReferences(file, 'nonexistent', 'v2-user')).toEqual([]); + expect(readOpenCodeImageReferences(file, 'v2-direct', "' OR 1=1 --")).toEqual([]); + }); + + it('returns empty array from findOpenCodeDirs when HOME and XDG_DATA_HOME point to empty directories', () => { + const emptyDir = path.join(root, 'empty-data'); + fs.mkdirSync(emptyDir, { recursive: true }); + vi.stubEnv('HOME', emptyDir); + vi.stubEnv('USERPROFILE', emptyDir); + vi.stubEnv('XDG_DATA_HOME', emptyDir); + vi.stubEnv('LOCALAPPDATA', emptyDir); + expect(findOpenCodeDirs()).toEqual([]); }); it('registers loadable external sources during cold parsing and asynchronous refresh', async () => {