diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 18c0946144d4a..01cbfd18fa370 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -101,6 +101,10 @@ function candidate( } const PI_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("pi"), model: "default" }; +const OPENCODE_MODEL_SELECTION = { + instanceId: ProviderInstanceId.make("opencode"), + model: "zai-coding-plan/glm-5.4", +}; // Pi threads are owned by their session file path, not the session UUID. const nativeId = ({ source }: ReturnType) => @@ -456,6 +460,32 @@ it.effect("rechecks ownership after the import reaches the commit transaction", }).pipe(Effect.scoped, Effect.provide(persistence)), ); +// An imported OpenCode thread continues the OpenCode session it was read from. +it.effect("binds an imported OpenCode thread to its OpenCode session", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const source = candidate(OPENCODE_MODEL_SELECTION, "ses_opencode", "opencode"); + const threadId = importId(source); + const importer = yield* makeImporter([source]); + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + const records = yield* projections.getThreadRecords(threadId, ["providerThreads"]); + expect(records.thread).toMatchObject({ + providerInstanceId: "opencode", + modelSelection: { instanceId: "opencode", model: "zai-coding-plan/glm-5.4" }, + }); + expect(records.providerThreads[0]).toMatchObject({ + driver: "opencode", + nativeThreadRef: { driver: "opencode", nativeId: "ses_opencode", strength: "strong" }, + }); + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ + providerName: "opencode", + adapterKey: "opencode", + resumeCursor: { threadId: "ses_opencode" }, + }); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + it.effect( "retries failed commits and runtime persistence without replaying committed history", () => @@ -1025,6 +1055,12 @@ it.effect("repeated imports reach linked-worktree sessions behind the scan budge enabled: false, config: {}, }, + // Keeps the default OpenCode instance off the developer's real OpenCode history. + [ProviderInstanceId.make("opencode")]: { + driver: ProviderDriverKind.make("opencode"), + enabled: false, + config: {}, + }, }, }), Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Effect.succeed([]) }), diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 0fcab0d7ad4c3..bd2da1c3d335d 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; import * as NodeSqlite from "node:sqlite"; import * as NodeZlib from "node:zlib"; import { describe, expect, it } from "@effect/vitest"; @@ -29,6 +30,7 @@ import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ServerConfig from "../config.ts"; import * as ProcessRunner from "../processRunner.ts"; @@ -89,13 +91,37 @@ const layerRuntimeRepository = (imported: ScannerTestInput["importedTranscripts" ), }); +// Stand in for the configured OpenCode executable so tests never consult a developer's sessions. +const scannerProcessRunner = Layer.effect( + ProcessRunner.ProcessRunner, + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + return ProcessRunner.ProcessRunner.of({ + run: (input) => { + if (input.command !== "fixture-opencode") return runner.run(input); + expect(input.args).toEqual(["debug", "paths", "db"]); + const dataHome = input.env?.XDG_DATA_HOME; + if (!dataHome) throw new Error("Missing fixture data home"); + const file = input.env?.OPENCODE_DB ?? input.env?.FIXTURE_CHANNEL_DB ?? "opencode.db"; + const target = file === ":memory:" ? file : NodePath.resolve(dataHome, "opencode", file); + return Effect.succeed({ + stdout: target + "\r\n", + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }); + }, + }); + }), +).pipe(Layer.provide(ProcessRunner.layer)); + const layerScannerTest = (input: ScannerTestInput) => - (input.processRunner === undefined - ? AgentSessionScanner.layer - : Layer.effect(AgentSessionScanner.AgentSessionScanner, AgentSessionScanner.make).pipe( - Layer.provide(input.processRunner), - ) - ).pipe( + Layer.effect(AgentSessionScanner.AgentSessionScanner, AgentSessionScanner.make).pipe( + Layer.provide(input.processRunner ?? scannerProcessRunner), Layer.provide( Layer.mergeAll( ServerSettings.layerTest({ @@ -108,6 +134,12 @@ const layerScannerTest = (input: ScannerTestInput) => driver: ProviderDriverKind.make("codex"), config: { homePath: input.codexHomePath }, }, + // Keeps the default OpenCode instance off the developer's real OpenCode history. + [ProviderInstanceId.make("opencode")]: { + driver: ProviderDriverKind.make("opencode"), + enabled: false, + config: {}, + }, // Keeps the default Pi instance off the developer's real ~/.pi. [ProviderInstanceId.make("pi")]: { driver: ProviderDriverKind.make("pi"), @@ -4177,4 +4209,806 @@ describe("parseAgentSessionTranscript", () => { : { title: thread.title, texts: thread.messages.map((message) => message.text) }, ).toEqual(expected); }); + + // OpenCode keeps every session in one database, so these fixtures build it as OpenCode 2 does. + const writeOpenCodeDatabase = Effect.fn("AgentSessionScanner.test.writeOpenCodeDatabase")( + function* (input: { + readonly dataHome: string; + // OpenCode's default file name, unless OPENCODE_DB names another. + readonly file?: string; + readonly sessions: ReadonlyArray<{ + readonly id: string; + readonly directory: string; + readonly title?: string | null; + readonly model?: string | null; + readonly parentId?: string | null; + readonly archived?: number | null; + readonly timeUpdated: number; + // A message's kind is its own column, and its data holds everything else, as OpenCode 2 keeps them. + readonly messages: ReadonlyArray<{ readonly type: string; readonly data: unknown }>; + }>; + readonly legacy?: boolean; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = path.join(input.dataHome, "opencode"); + yield* fileSystem.makeDirectory(directory, { recursive: true }); + yield* Effect.sync(() => { + const database = new NodeSqlite.DatabaseSync( + path.join(directory, input.file ?? "opencode.db"), + ); + try { + if (input.legacy) { + // OpenCode 1 kept sessions in another table, which has nothing to import here. + database.exec("CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT)"); + database.exec("INSERT INTO session VALUES ('ses_legacy', '/nowhere')"); + return; + } + database.exec( + `CREATE TABLE session_v2 (id TEXT PRIMARY KEY, directory TEXT, title TEXT, model TEXT, + parent_id TEXT, time_archived INTEGER, time_created INTEGER, time_updated INTEGER)`, + ); + database.exec( + `CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, + time_created INTEGER, time_updated INTEGER, data TEXT)`, + ); + const session = database.prepare( + "INSERT INTO session_v2 VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + ); + const message = database.prepare( + "INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)", + ); + // One transaction, so a fixture of many sessions or messages is written quickly. + database.exec("BEGIN"); + for (const entry of input.sessions) { + session.run( + entry.id, + entry.directory, + entry.title ?? null, + entry.model ?? null, + entry.parentId ?? null, + entry.archived ?? null, + entry.timeUpdated - 60_000, + entry.timeUpdated, + ); + for (const [seq, item] of entry.messages.entries()) { + message.run( + `${entry.id}-${seq}`, + entry.id, + item.type, + seq + 1, + entry.timeUpdated, + entry.timeUpdated, + JSON.stringify(item.data), + ); + } + } + database.exec("COMMIT"); + } finally { + database.close(); + } + }); + }, + ); + + // OpenCode archives a session by stamping it, and keeps its messages. + const archiveOpenCodeSession = Effect.fn("AgentSessionScanner.test.archiveOpenCodeSession")( + function* (input: { readonly dataHome: string; readonly id: string; readonly at: number }) { + const path = yield* Path.Path; + yield* Effect.sync(() => { + const database = new NodeSqlite.DatabaseSync( + path.join(input.dataHome, "opencode", "opencode.db"), + ); + try { + database + .prepare("UPDATE session_v2 SET time_archived = ? WHERE id = ?") + .run(input.at, input.id); + } finally { + database.close(); + } + }); + }, + ); + + // Appends one message without touching the session's own row. + const appendOpenCodeMessage = Effect.fn("AgentSessionScanner.test.appendOpenCodeMessage")( + function* (input: { + readonly dataHome: string; + readonly sessionId: string; + readonly seq: number; + readonly at: number; + readonly message: { readonly type: string; readonly data: unknown }; + }) { + const path = yield* Path.Path; + yield* Effect.sync(() => { + const database = new NodeSqlite.DatabaseSync( + path.join(input.dataHome, "opencode", "opencode.db"), + ); + try { + database + .prepare("INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)") + .run( + `${input.sessionId}-${input.seq}`, + input.sessionId, + input.message.type, + input.seq, + input.at, + input.at, + JSON.stringify(input.message.data), + ); + } finally { + database.close(); + } + }); + }, + ); + + const openCodeInstanceWith = ( + dataHome: string, + variables: ReadonlyArray, + ): NonNullable => ({ + [ProviderInstanceId.make("opencode")]: { + driver: ProviderDriverKind.make("opencode"), + enabled: true, + environment: [ + { name: "XDG_DATA_HOME", value: dataHome, sensitive: false }, + ...variables.map(([name, value]) => ({ name, value, sensitive: false })), + ], + config: { binaryPath: "fixture-opencode" }, + }, + }); + + const openCodeInstance = (dataHome: string): NonNullable => + openCodeInstanceWith(dataHome, []); + + const glmModel = JSON.stringify({ id: "glm-5.4", providerID: "zai-coding-plan" }); + + it.effect("lists and reads OpenCode sessions kept in the OpenCode 2 database", () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const otherWorkspace = yield* makeTempDir("t3code-workspace-other-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { + id: "ses_recent", + directory: workspace, + title: "GLM refactor", + model: glmModel, + timeUpdated: at, + messages: [ + { + type: "user", + data: { time: { created: at - 60_000 }, text: "Plan the change" }, + }, + { + type: "assistant", + data: { + time: { created: at - 30_000 }, + model: { id: "glm-5.4", providerID: "zai-coding-plan" }, + content: [ + { type: "reasoning", text: "Hidden reasoning" }, + { + type: "tool", + tool: "bash", + state: { status: "completed", output: "Tool output" }, + }, + { type: "text", text: "Active answer" }, + ], + }, + }, + { type: "idle", data: { time: { created: at }, outcome: "succeeded" } }, + ], + }, + // A child session is a subagent's, and an archived session is finished with. + { + id: "ses_child", + directory: workspace, + parentId: "ses_recent", + timeUpdated: at, + messages: [{ type: "user", data: { text: "Child prompt" } }], + }, + { + id: "ses_archived", + directory: workspace, + archived: at, + timeUpdated: at, + messages: [{ type: "user", data: { text: "Archived prompt" } }], + }, + { + id: "ses_other", + directory: otherWorkspace, + timeUpdated: at, + messages: [{ type: "user", data: { text: "Other prompt" } }], + }, + ], + }); + const input = { + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + providerInstances: openCodeInstance(dataHome), + }; + + const scan = yield* runScan(input); + // The child and archived sessions are not counted, so each folder offers one conversation. + expect(scan.candidates.map((entry) => [entry.sources, entry.threadCount])).toEqual([ + [["opencode"], 1], + [["opencode"], 1], + ]); + + const threads = yield* runRecentThreads(input); + expect(threads).toHaveLength(1); + expect(threads[0]).toMatchObject({ + source: "opencode", + providerInstanceId: "opencode", + providerSessionId: "ses_recent", + title: "GLM refactor", + model: "zai-coding-plan/glm-5.4", + omittedMessageCount: 0, + }); + // Reasoning, tool output and bookkeeping entries stay out of the history. + expect(threads[0]?.messages.map((message) => [message.role, message.text])).toEqual([ + ["user", "Plan the change"], + ["assistant", "Active answer"], + ]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect( + "reports an unchanged OpenCode session as already imported, with a stable identity", + () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + const messages = [ + { type: "user", data: { time: { created: at }, text: "Plan the change" } }, + { + type: "assistant", + data: { time: { created: at }, content: [{ type: "text", text: "Done" }] }, + }, + ]; + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { id: "ses_recent", directory: workspace, title: null, timeUpdated: at, messages }, + ], + }); + const input = { + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + providerInstances: openCodeInstance(dataHome), + }; + const outcomes = yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const first = Array.from(yield* scanner.recentThreads(workspace).pipe(Stream.runCollect)); + expect(first).toHaveLength(1); + const outcome = first[0]; + if (outcome?._tag !== "Importable") return []; + return Array.from( + yield* scanner.recentThreads(workspace, [outcome.source]).pipe(Stream.runCollect), + ); + }).pipe(Effect.provide(layerScannerTest(input))); + expect(outcomes).toEqual([ + { + _tag: "AlreadyImported", + source: expect.objectContaining({ + provider: "opencode", + providerInstanceId: "opencode", + providerSessionId: "ses_recent", + // The path key names the database and the session. The size is the sequence number + // of the last message, and the time is the session's own. + filePath: expect.stringMatching(/opencode\.db#ses_recent$/), + size: messages.length, + mtimeMs: at, + }), + }, + ]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect( + "finds nothing to import from a database that predates OpenCode 2's session tables", + () => + Effect.gen(function* () { + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + yield* writeOpenCodeDatabase({ dataHome, sessions: [], legacy: true }); + const scan = yield* runScan({ + claudeHomePath, + codexHomePath, + providerInstances: openCodeInstance(dataHome), + }); + expect(scan.candidates).toEqual([]); + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + providerInstances: openCodeInstance(dataHome), + }); + expect(threads).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect( + "does not file local history under an OpenCode provider that uses an external server", + () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { + id: "ses_recent", + directory: workspace, + timeUpdated: at, + messages: [ + { type: "user", data: { text: "Plan the change" } }, + { type: "assistant", data: { content: [{ type: "text", text: "Done" }] } }, + ], + }, + ], + }); + // Both providers name the same database. The external one is listed first, so without + // the rule it would claim the conversation before the local one. + const providers: NonNullable = { + [ProviderInstanceId.make("opencode-remote")]: { + driver: ProviderDriverKind.make("opencode"), + enabled: true, + environment: [{ name: "XDG_DATA_HOME", value: dataHome, sensitive: false }], + config: { binaryPath: "fixture-opencode", serverUrl: "http://127.0.0.1:4096" }, + }, + [ProviderInstanceId.make("opencode-local")]: { + driver: ProviderDriverKind.make("opencode"), + enabled: true, + environment: [{ name: "XDG_DATA_HOME", value: dataHome, sensitive: false }], + config: { binaryPath: "fixture-opencode" }, + }, + }; + const input = { + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + providerInstances: providers, + }; + + const scan = yield* runScan(input); + expect(scan.candidates.map((entry) => [entry.sources, entry.threadCount])).toEqual([ + [["opencode"], 1], // counted once + ]); + const outcomes = yield* runRecentThreadOutcomes(input); + expect(outcomes).toHaveLength(1); + expect(outcomes[0]).toMatchObject({ + _tag: "Importable", + thread: { providerInstanceId: "opencode-local", providerSessionId: "ses_recent" }, + }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("skips an OpenCode session past a limit instead of importing part of its history", () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + const megabyte = "x".repeat(1024 * 1024); + // One JavaScript character, but three bytes in UTF-8 and two in UTF-16. + const wideMegabyte = "界".repeat(1024 * 1024); + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + // One row past the record limit. Bookkeeping rows count toward it. + { + id: "ses_many", + directory: workspace, + timeUpdated: at, + messages: Array.from({ length: 100_001 }, () => ({ + type: "idle", + data: { outcome: "succeeded" }, + })), + }, + // One message past the limit on visible history. The limit counts two bytes per + // character, as the transcript reader does, so 16 MiB of text is already too much. + { + id: "ses_large", + directory: workspace, + timeUpdated: at, + // A user row keeps its text in one field and an assistant row in parts, as OpenCode does. + messages: Array.from({ length: 16 }, (_, index) => ({ + type: index % 2 === 0 ? "user" : "assistant", + data: + index % 2 === 0 + ? { text: megabyte } + : { content: [{ type: "text", text: megabyte }] }, + })), + }, + // The same with wide characters. Counting characters instead of bytes would let + // this one through at half the budget. + { + id: "ses_wide", + directory: workspace, + timeUpdated: at, + messages: Array.from({ length: 17 }, (_, index) => ({ + type: index % 2 === 0 ? "user" : "assistant", + data: + index % 2 === 0 + ? { text: wideMegabyte } + : { content: [{ type: "text", text: wideMegabyte }] }, + })), + }, + { + id: "ses_small", + directory: workspace, + timeUpdated: at, + messages: [ + { type: "user", data: { text: "Plan the change" } }, + { type: "assistant", data: { content: [{ type: "text", text: "Done" }] } }, + ], + }, + ], + }); + const input = { + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + providerInstances: openCodeInstance(dataHome), + }; + // Sessions are read newest first, then by name: large, many, small, wide. + const outcomes = yield* runRecentThreadOutcomes(input); + expect(outcomes.map((outcome) => outcome._tag)).toEqual([ + "Skipped", + "Skipped", + "Importable", + "Skipped", + ]); + expect(outcomes[2]).toMatchObject({ thread: { providerSessionId: "ses_small" } }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reports a cut-off scan once OpenCode sessions pass the per-source cap", () => + Effect.gen(function* () { + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = Date.parse("2026-08-24T12:00:00.000Z") - 60 * 60 * 1000; + yield* writeOpenCodeDatabase({ + dataHome, + sessions: Array.from({ length: 5001 }, (_, index) => ({ + id: `ses_${String(index).padStart(4, "0")}`, + directory: workspace, + timeUpdated: at - index, + messages: [{ type: "user", data: { text: `Prompt ${index}` } }], + })), + }); + const scan = yield* runScan({ + claudeHomePath, + codexHomePath, + providerInstances: openCodeInstance(dataHome), + }); + expect(scan.truncated).toBe(true); + expect(scan.candidates.map((entry) => entry.threadCount)).toEqual([5000]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("charges the exact stored bytes of OpenCode rows before accepting a session", () => + Effect.gen(function* () { + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + for (const [id, char] of [ + ["ascii", "x"], + ["wide", "界"], + ["emoji", "😀"], + ] as const) { + const file = id + ".db"; + const messages = [ + { type: "user", data: { text: char.repeat(32) } }, + { type: "assistant", data: { content: [{ type: "text", text: "Done" }] } }, + ]; + yield* writeOpenCodeDatabase({ + dataHome, + file, + sessions: [{ id, directory: workspace, timeUpdated: 1, messages }], + }); + const bytes = messages.reduce( + (sum, row) => sum + Buffer.byteLength(JSON.stringify(row.data)), + 0, + ); + const db = NodePath.join(dataHome, "opencode", file); + const atLimit = AgentSessionScanner.readOpenCodeSession(db, id, bytes); + expect(atLimit.bytesRead).toBe(bytes); + expect(atLimit.session).not.toBeNull(); + expect(AgentSessionScanner.readOpenCodeSession(db, id, bytes - 1)).toEqual({ + bytesRead: bytes, + session: null, + }); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reads only the database that OPENCODE_DB names", () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const workWorkspace = yield* makeTempDir("t3code-workspace-work-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + // A default database and a separate one, as a user who keeps work and personal histories + // apart has them. OpenCode opens only the one OPENCODE_DB names. + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { + id: "ses_default", + directory: workspace, + timeUpdated: at, + messages: [{ type: "user", data: { text: "Personal prompt" } }], + }, + ], + }); + yield* writeOpenCodeDatabase({ + dataHome, + file: " work.db", + sessions: [ + { + id: "ses_work", + directory: workWorkspace, + timeUpdated: at, + messages: [{ type: "user", data: { text: "Work prompt" } }], + }, + ], + }); + const providerInstances = openCodeInstanceWith(dataHome, [["OPENCODE_DB", " work.db"]]); + const homesOnly = { claudeHomePath, codexHomePath }; + + const scan = yield* runScan({ ...homesOnly, providerInstances }); + expect(scan.candidates.map((entry) => [entry.sources, entry.threadCount])).toEqual([ + [["opencode"], 1], + ]); + const work = yield* runRecentThreadOutcomes({ + ...homesOnly, + providerInstances, + workspaceRoot: workWorkspace, + }); + expect(work).toMatchObject([ + { _tag: "Importable", thread: { providerSessionId: "ses_work" } }, + ]); + const personal = yield* runRecentThreadOutcomes({ + ...homesOnly, + providerInstances, + workspaceRoot: workspace, + }); + expect(personal).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("finds nothing where OPENCODE_DB names a database that exists only in memory", () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { + id: "ses_default", + directory: workspace, + timeUpdated: nowMs - 60 * 60 * 1000, + messages: [{ type: "user", data: { text: "Personal prompt" } }], + }, + ], + }); + const scan = yield* runScan({ + claudeHomePath, + codexHomePath, + providerInstances: openCodeInstanceWith(dataHome, [["OPENCODE_DB", ":memory:"]]), + }); + expect(scan.candidates).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reads only the database reported by the configured OpenCode binary", () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { + id: "ses_default", + directory: workspace, + timeUpdated: at, + messages: [{ type: "user", data: { text: "Default prompt" } }], + }, + ], + }); + // A build on another channel keeps its history in its own file beside the default. + yield* writeOpenCodeDatabase({ + dataHome, + file: "opencode-local.db", + sessions: [ + { + id: "ses_local", + directory: workspace, + timeUpdated: at - 1000, + messages: [{ type: "user", data: { text: "Channel prompt" } }], + }, + ], + }); + const homesOnly = { claudeHomePath, codexHomePath }; + + const selectedSessions = (variables: ReadonlyArray) => + runRecentThreads({ + ...homesOnly, + workspaceRoot: workspace, + providerInstances: openCodeInstanceWith(dataHome, variables), + }).pipe(Effect.map((threads) => threads.map((thread) => thread.providerSessionId))); + expect(yield* selectedSessions([])).toEqual(["ses_default"]); + expect(yield* selectedSessions([["FIXTURE_CHANNEL_DB", "opencode-local.db"]])).toEqual([ + "ses_local", + ]); + const missingBinary = openCodeInstance(dataHome); + const id = ProviderInstanceId.make("opencode"); + const unreadable = yield* runScan({ + ...homesOnly, + providerInstances: { + [id]: { + ...missingBinary[id]!, + config: { binaryPath: NodePath.join(dataHome, "missing-binary") }, + }, + }, + }); + expect(unreadable.candidates).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("does not import an OpenCode session that was archived after it was listed", () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { + id: "ses_recent", + directory: workspace, + timeUpdated: at, + messages: [ + { type: "user", data: { time: { created: at }, text: "Plan the change" } }, + { + type: "assistant", + data: { time: { created: at }, content: [{ type: "text", text: "Done" }] }, + }, + ], + }, + ], + }); + const input = { + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + providerInstances: openCodeInstance(dataHome), + }; + const outcomes = yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const first = Array.from(yield* scanner.recentThreads(workspace).pipe(Stream.runCollect)); + expect(first.map((outcome) => outcome._tag)).toEqual(["Importable"]); + // The page keeps what it listed. The session is archived in OpenCode before its history + // is asked for again. + yield* archiveOpenCodeSession({ dataHome, id: "ses_recent", at: at + 1000 }); + return Array.from(yield* scanner.recentThreads(workspace).pipe(Stream.runCollect)); + }).pipe(Effect.provide(layerScannerTest(input))); + expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("offers an imported OpenCode session again once it gains a message", () => + Effect.gen(function* () { + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + const dataHome = yield* makeTempDir("t3code-opencode-home-"); + const at = nowMs - 60 * 60 * 1000; + yield* writeOpenCodeDatabase({ + dataHome, + sessions: [ + { + id: "ses_recent", + directory: workspace, + timeUpdated: at, + messages: [ + { type: "user", data: { time: { created: at }, text: "Plan the change" } }, + { + type: "assistant", + data: { time: { created: at }, content: [{ type: "text", text: "Done" }] }, + }, + ], + }, + ], + }); + const input = { + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + providerInstances: openCodeInstance(dataHome), + }; + const imported = yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const first = Array.from(yield* scanner.recentThreads(workspace).pipe(Stream.runCollect)); + const outcome = first[0]; + return outcome?._tag === "Importable" ? Option.some(outcome.source) : Option.none(); + }).pipe(Effect.provide(layerScannerTest(input))); + const source = Option.getOrThrow(imported); + // The new message leaves the session's own row alone, so only its last sequence shows it. + yield* appendOpenCodeMessage({ + dataHome, + sessionId: "ses_recent", + seq: 3, + at: at + 1000, + message: { + type: "user", + data: { time: { created: at + 1000 }, text: "And one more thing" }, + }, + }); + // The page was reopened in between, so the sessions are listed again. + const outcomes = yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + return Array.from( + yield* scanner.recentThreads(workspace, [source]).pipe(Stream.runCollect), + ); + }).pipe(Effect.provide(layerScannerTest(input))); + expect(outcomes).toMatchObject([ + { + _tag: "Importable", + source: { size: 3 }, + thread: { + messages: expect.arrayContaining([ + expect.objectContaining({ role: "user", text: "And one more thing" }), + ]), + }, + }, + ]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }); diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 745d60e6f2c26..f0f74cada2d93 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -42,6 +42,7 @@ import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.t import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { OpenCodeSettings } from "@t3tools/provider-opencode/settings"; import { piHome, resolvePiSessionsDir } from "@t3tools/provider-pi/server/usage"; import * as ServerSettings from "../serverSettings.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; @@ -70,6 +71,18 @@ class CodexStateReadError extends Schema.TaggedError()("Cod return `Could not read Codex projects from ${this.databasePath}.`; } } + +class OpenCodeStateReadError extends Schema.TaggedError()( + "OpenCodeStateReadError", + { + databasePath: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Could not read OpenCode sessions from ${this.databasePath}.`; + } +} const METADATA_READ_BYTES = 8 * 1024; const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024; const MAX_CODEX_SESSION_INDEX_BYTES = 1024 * 1024; @@ -127,6 +140,8 @@ const TranscriptRecord = Schema.Struct({ id: Schema.optional(Schema.String), parentId: Schema.optional(Schema.NullOr(Schema.String)), name: Schema.optional(Schema.String), + // An OpenCode session record names the model the session ran on. + model: Schema.optional(Schema.String), timestamp: Schema.optional(Schema.String), cwd: Schema.optional(Schema.String), sessionId: Schema.optional(Schema.String), @@ -159,6 +174,7 @@ const CodexSessionIndexEntry = Schema.Struct({ const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings); const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings); +const decodeOpenCodeSettings = Schema.decodeUnknownOption(OpenCodeSettings); const decodeTranscriptRecord = Schema.decodeUnknownOption(Schema.fromJsonString(TranscriptRecord)); const decodeTranscriptValue = Schema.decodeUnknownOption(TranscriptRecord); const decodePiEntryLinks = Schema.decodeUnknownOption( @@ -199,6 +215,7 @@ const isCompressedTranscript = (filePath: string) => filePath.endsWith(COMPRESSED_TRANSCRIPT_SUFFIX); // Codex records a chat's project only here; moving a chat leaves its rollout cwd unchanged. const CODEX_STATE_DATABASE = "state_5.sqlite"; +const MAX_OPENCODE_SESSION_ROWS = MAX_TRANSCRIPTS_PER_SOURCE; const decodeCodexSessionIndexEntry = Schema.decodeUnknownOption( Schema.fromJsonString(CodexSessionIndexEntry), ); @@ -266,6 +283,7 @@ interface RawCandidate { readonly filePath: string; readonly mtimeMs: number | null; readonly projectRoots?: ReadonlyArray | undefined; + readonly openCode?: OpenCodeSession | undefined; }>; } @@ -276,8 +294,28 @@ interface TranscriptCandidate { readonly homePath: string; readonly identity: TranscriptIdentity; readonly projectRoots?: ReadonlyArray | undefined; + readonly openCode?: OpenCodeSession | undefined; } +/** + * An OpenCode session stands in for a transcript file. Its path key names the database and the + * session, because OpenCode keeps every session in one database. + */ +interface OpenCodeSession { + readonly databasePath: string; + readonly sessionId: string; + readonly directory: string; + /** + * The database file's identity, with the session's own size and time in place of the file's. The + * size is the session's last message sequence, which OpenCode indexes, and the time is the + * session's own. + */ + readonly identity: ReturnType; +} + +const openCodeTranscriptPath = (databasePath: string, sessionId: string) => + `${databasePath}#${sessionId}`; + interface MetadataReadBudget { bytesRemaining: number; operationsRemaining: number; @@ -493,7 +531,8 @@ function activePiBranch( return branch.toReversed(); } -function isPiConversationRecord( +// Pi and OpenCode keep a conversation as plain message records in order. +function isConversationMessageRecord( record: DecodedTranscriptRecord, ): record is DecodedTranscriptRecord & { readonly message: typeof TranscriptMessage.Type & { readonly role: "user" | "assistant" }; @@ -529,18 +568,25 @@ function parseAgentSessionRecords( const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs)); // Claude filenames are session IDs. Codex rollout filenames include extra // timestamp text, so only transcript metadata can provide a resumable ID. + // Pi and OpenCode name a session in its session record. + const sessionRecord = + input.source === "pi" || input.source === "opencode" + ? records.find((record) => record.type === "session") + : undefined; let providerSessionId = input.source === "codex" ? "" - : input.source === "pi" - ? records.find((record) => record.type === "session")?.id?.trim() || input.fallbackSessionId + : sessionRecord !== undefined + ? sessionRecord.id?.trim() || input.fallbackSessionId : (claudeFields.sessionId ?? input.fallbackSessionId); // Pi titles a session by its latest session_info on any branch; an empty name clears it. const title = - input.source === "pi" + input.source === "pi" || input.source === "opencode" ? records.findLast((record) => record.type === "session_info")?.name?.trim() || null : (claudeFields.title ?? null); - let model = claudeFields.model ?? null; + let model = + claudeFields.model ?? + (input.source === "opencode" ? sessionRecord?.model?.trim() || null : null); let derivedTitle: string | undefined; // Names a session whose only request was a bare command, such as `/review`. let bareCommandTitle: string | undefined; @@ -642,8 +688,8 @@ function parseAgentSessionRecords( let recordIndex = -1; for (const record of input.source === "pi" ? activePiBranch(records) : records) { recordIndex += 1; - if (input.source === "pi") { - if (!isPiConversationRecord(record)) continue; + if (input.source === "pi" || input.source === "opencode") { + if (!isConversationMessageRecord(record)) continue; const text = extractText(record.message.content); if (text.length === 0) continue; retainMessage({ @@ -910,6 +956,239 @@ function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdent ); } +interface OpenCodeSessionRow { + readonly id: string; + readonly directory: string; + readonly timeUpdated: number; + /** The sequence number of the newest message. It changes when the session gains or loses one. */ + readonly lastSeq: number; +} + +interface OpenCodeSessionSnapshot { + readonly records: ReadonlyArray; + readonly directory: string; + readonly timeUpdated: number; + readonly lastSeq: number; + readonly historyBytes: number; +} + +/** + * The outcome of reading a session. `bytesRead` counts the message rows read and is charged to the + * import budget whether or not the session could be used. `session` is null when the session + * cannot be imported whole, because it is no longer eligible or ran past a limit. + */ +interface OpenCodeSessionRead { + readonly bytesRead: number; + readonly session: OpenCodeSessionSnapshot | null; +} + +const textField = (value: unknown): string => (typeof value === "string" ? value : ""); + +const numberField = (value: unknown): number | null => + typeof value === "number" && Number.isFinite(value) ? value : null; + +const parseJsonField = (value: unknown): Record | null => { + let parsed = value; + if (typeof value === "string") { + try { + parsed = JSON.parse(value); + } catch { + return null; + } + } + return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) + ? (parsed as Record) + : null; +}; + +// OpenCode stores a model as a JSON object; M3 names it `provider/model`. +function openCodeModelReference(value: unknown): string | null { + const model = parseJsonField(value); + const id = textField(model?.id).trim(); + const providerId = textField(model?.providerID).trim(); + return id.length === 0 ? null : providerId.length === 0 ? id : `${providerId}/${id}`; +} + +// OpenCode 2 keeps a message's kind in its own column, a user message's text in one field and an +// assistant's in parts. Only text is shown. +function parseOpenCodeMessage( + kind: unknown, + data: unknown, +): { + readonly role: "user" | "assistant"; + readonly text: string; + readonly createdAt: string | undefined; + readonly model: string | null; +} | null { + const message = parseJsonField(data); + if (message === null) return null; + const type = typeof kind === "string" && kind.length > 0 ? kind : message.type; + const created = parseJsonField(message.time)?.created; + const createdAt = + typeof created === "number" && Number.isFinite(created) + ? DateTime.formatIso(DateTime.makeUnsafe(created)) + : typeof created === "string" + ? created + : undefined; + const model = openCodeModelReference(message.model); + if (type === "user") { + const text = textField(message.text).trim(); + return text.length === 0 ? null : { role: "user", text, createdAt, model }; + } + if (type !== "assistant" || !Array.isArray(message.content)) return null; + const text = message.content + .flatMap((part) => { + const block = parseJsonField(part); + return block?.type === "text" ? [textField(block.text)] : []; + }) + .filter((part) => part.trim().length > 0) + .join("\n") + .trim(); + return text.length === 0 ? null : { role: "assistant", text, createdAt, model }; +} + +/** + * Top-level, unarchived sessions as OpenCode 2 keeps them, newest first, up to one past the cap. + * No message is read here: a session's last sequence comes from OpenCode's unique index on + * (session_id, seq), so listing costs the same however large the histories are. + */ +function listOpenCodeSessions(databasePath: string): ReadonlyArray { + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + const rows = database + .prepare( + `SELECT s.id AS id, s.directory AS directory, s.time_updated AS timeUpdated, + COALESCE((SELECT MAX(m.seq) FROM session_message m + WHERE m.session_id = s.id), 0) AS lastSeq + FROM session_v2 s + WHERE s.parent_id IS NULL AND s.time_archived IS NULL + ORDER BY s.time_updated DESC + LIMIT ?`, + ) + .all(MAX_OPENCODE_SESSION_ROWS + 1) as ReadonlyArray>; + return rows.flatMap((row): OpenCodeSessionRow[] => { + const id = textField(row.id).trim(); + const directory = textField(row.directory).trim(); + const timeUpdated = numberField(row.timeUpdated); + const lastSeq = numberField(row.lastSeq); + return id.length === 0 || directory.length === 0 || timeUpdated === null || lastSeq === null + ? [] + : [{ id, directory, timeUpdated, lastSeq }]; + }); + } finally { + database.close(); + } +} + +/** + * A session's visible messages as transcript records, in the shape the Pi parser reads. One read + * transaction covers the eligibility check and the messages, so a session archived since it was + * listed is left out. The first message row past `maxBytes` ends the read, and the session is left + * out rather than imported in part. + */ +export function readOpenCodeSession( + databasePath: string, + sessionId: string, + maxBytes: number, +): OpenCodeSessionRead { + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); + try { + database.exec("PRAGMA busy_timeout = 100"); + database.exec("BEGIN"); + try { + const session = database + .prepare( + "SELECT directory, title, model, time_updated FROM session_v2 WHERE id = ? AND parent_id IS NULL AND time_archived IS NULL", + ) + .get(sessionId) as Record | undefined; + const directory = textField(session?.directory).trim(); + const timeUpdated = session === undefined ? null : numberField(session.time_updated); + if (session === undefined || directory.length === 0 || timeUpdated === null) { + return { bytesRead: 0, session: null }; + } + // The same measure the session list uses, so an unchanged session keeps its identity. + const lastSeq = + numberField( + database + .prepare("SELECT MAX(seq) AS lastSeq FROM session_message WHERE session_id = ?") + .get(sessionId)?.lastSeq, + ) ?? 0; + // Rows arrive one at a time and are dropped once their text is kept. A session can hold + // gigabytes of tool output that is never shown, and reading it whole would take the server + // down with it. Past any limit only part of the history is left, and it must not pass as + // the whole. + const rows = database + .prepare( + "SELECT type, data, octet_length(data) AS bytes FROM session_message WHERE session_id = ? ORDER BY seq LIMIT ?", + ) + .iterate(sessionId, MAX_IMPORT_RECORDS + 1); + const messages: Array = []; + let historyBytes = 0; + let bytesRead = 0; + let lastModel: string | null = null; + let count = 0; + let partial = false; + for (const row of rows) { + count += 1; + bytesRead += Number(row.bytes); + if (count > MAX_IMPORT_RECORDS || bytesRead > maxBytes) { + partial = true; + break; + } + const message = parseOpenCodeMessage(row.type, row.data); + if (message === null) continue; + // The transcript reader's accounting: two bytes per UTF-16 code unit, plus a little for + // the record. Counting characters would let twice the budget in. + historyBytes += 64 + message.text.length * 2; + if (historyBytes > MAX_IMPORT_HISTORY_BYTES) { + partial = true; + break; + } + lastModel = message.model ?? lastModel; + const decoded = decodeTranscriptValue({ + type: "message", + timestamp: message.createdAt, + message: { role: message.role, content: message.text }, + }); + if (Option.isSome(decoded)) messages.push(decoded.value); + } + if (partial) return { bytesRead, session: null }; + const title = textField(session.title).trim(); + const header: Record = { type: "session", id: sessionId }; + const model = openCodeModelReference(session.model) ?? lastModel; + if (model !== null) header.model = model; + const records: Array = []; + for (const record of [ + header, + ...(title.length === 0 ? [] : [{ type: "session_info", name: title }]), + ]) { + const decoded = decodeTranscriptValue(record); + if (Option.isSome(decoded)) records.push(decoded.value); + } + return { + bytesRead, + session: { + records: [...records, ...messages], + directory, + timeUpdated, + lastSeq, + historyBytes, + }, + }; + } finally { + // Only a read happened. Ending the transaction releases its snapshot. + try { + database.exec("ROLLBACK"); + } catch { + // The read itself failed; that error is the one reported. + } + } + } finally { + database.close(); + } +} + /** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1010,6 +1289,27 @@ export const make = Effect.gen(function* () { return `path:${normalizeProjectPathForComparison(realPath)}`; }); + // An OpenCode binary knows its own channel. Another channel's sessions cannot be resumed by it. + const openCodeDatabase = Effect.fn("AgentSessionScanner.openCodeDatabase")(function* ( + binaryPath: string, + environment: NodeJS.ProcessEnv, + ) { + const result = yield* processRunner + .run({ + command: expandHomePath(binaryPath, homeDir), + args: ["debug", "paths", "db"], + env: environment, + timeout: "10 seconds", + maxOutputBytes: 32 * 1024, + }) + .pipe(Effect.option); + if (Option.isNone(result) || result.value.code !== 0 || result.value.stdoutInvalidUtf8) { + return null; + } + const databasePath = result.value.stdout.replace(/\r?\n$/, ""); + return path.isAbsolute(databasePath) && !/[\r\n\0]/.test(databasePath) ? databasePath : null; + }); + /** Stats a directory that may be offered as a project, or none when it is missing or excluded. */ const projectDirectoryStats = Effect.fn("AgentSessionScanner.projectDirectoryStats")(function* ( directory: string, @@ -1398,7 +1698,7 @@ export const make = Effect.gen(function* () { } else if ( source === "pi" && decoded.value.type === "message" && - !isPiConversationRecord(decoded.value) + !isConversationMessageRecord(decoded.value) ) { // Tool output can dwarf the conversation; keep only the tree links. const { message: _message, ...links } = decoded.value; @@ -1770,6 +2070,105 @@ export const make = Effect.gen(function* () { return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining }; }); + // One query lists every session in a database, so no budget is spent per session. For OpenCode + // a home is one database file, chosen where the homes are listed. + const discoverOpenCodeTranscripts = Effect.fn("AgentSessionScanner.discoverOpenCodeTranscripts")( + function* ( + databasePath: string, + providerInstanceId: ProviderInstanceId, + _operationBudget: number, + ) { + const stats = yield* statOption(databasePath); + if (Option.isNone(stats) || stats.value.type !== "File") { + return { transcripts: [], truncated: false, operationsUsed: 1 }; + } + const fileIdentity = transcriptIdentity(databasePath, stats.value); + const sessions = yield* Effect.try({ + try: () => listOpenCodeSessions(databasePath), + catch: (cause) => new OpenCodeStateReadError({ databasePath, cause }), + }).pipe( + Effect.catch((cause) => + // A database from another OpenCode version has no such table, so there is nothing to import. + Effect.logDebug("Could not list OpenCode sessions", { databasePath, cause }).pipe( + Effect.as(null), + ), + ), + ); + return { + // One session past the per-source cap is listed on purpose. The shared check that follows + // then reports the scan as cut off, instead of letting older sessions vanish silently. + transcripts: (sessions ?? []).map((session): TranscriptCandidate => { + const filePath = openCodeTranscriptPath(databasePath, session.id); + // A session changes when it gains or loses a message, so its last message's sequence + // number and its own time stand in for the file's size and time. The file's identity + // still ties it to this database. + const identity = { + ...fileIdentity, + filePath, + size: session.lastSeq, + mtimeMs: session.timeUpdated, + }; + return { + filePath, + mtimeMs: session.timeUpdated, + providerInstanceId, + homePath: databasePath, + identity, + openCode: { + databasePath, + sessionId: session.id, + directory: session.directory, + identity, + }, + }; + }), + truncated: false, + operationsUsed: 1, + }; + }, + ); + + // An OpenCode session is read from its database where the other transcripts are read from a file. + // `maxBytes` is what is left of the import budget, and the read stops at it. + const readOpenCodeTranscript = Effect.fn("AgentSessionScanner.readOpenCodeTranscript")(function* ( + session: OpenCodeSession & { readonly filePath: string }, + maxBytes: number, + ) { + const stats = yield* statOption(session.databasePath); + if (Option.isNone(stats) || stats.value.type !== "File") return null; + const fileIdentity = transcriptIdentity(session.databasePath, stats.value); + const read = yield* Effect.try({ + try: () => readOpenCodeSession(session.databasePath, session.sessionId, maxBytes), + catch: (cause) => new OpenCodeStateReadError({ databasePath: session.databasePath, cause }), + }).pipe( + Effect.catch((cause) => + Effect.logWarning("Could not read an OpenCode session", { + filePath: session.filePath, + cause, + }).pipe(Effect.as(null)), + ), + ); + if (read === null) return null; + const snapshot = read.session; + if (snapshot === null) return { bytesRead: read.bytesRead, snapshot: null }; + return { + bytesRead: read.bytesRead, + snapshot: { + records: snapshot.records, + droppedMessageCount: 0, + cwd: Option.some(snapshot.directory), + claudeFields: emptyClaudeFields, + historyBytes: snapshot.historyBytes, + identity: { + ...fileIdentity, + filePath: session.filePath, + size: snapshot.lastSeq, + mtimeMs: snapshot.timeUpdated, + }, + }, + }; + }); + const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* ( source: AgentSessionSource, transcripts: ReadonlyArray, @@ -1794,15 +2193,18 @@ export const make = Effect.gen(function* () { // Unchanged imported transcripts keep their import cwd, so they never spend the read budget. // Codex is excluded: its first record carries the cwd and the subagent marker, and // rollouts imported before subagents were skipped must still be excluded by it. + // An OpenCode session's row names its folder, so no file is opened for it. const rolloutCwd = - (source === "codex" - ? undefined - : importedByFile.get(`${transcript.providerInstanceId}\0${transcript.filePath}`) - )?.find( - (imported) => - imported.source.provider === source && - sameTranscriptIdentity(imported.source, transcript.identity), - )?.cwd ?? (yield* readCwd(source, transcript, budget)); + source === "opencode" && transcript.openCode !== undefined + ? transcript.openCode.directory + : ((source === "codex" + ? undefined + : importedByFile.get(`${transcript.providerInstanceId}\0${transcript.filePath}`) + )?.find( + (imported) => + imported.source.provider === source && + sameTranscriptIdentity(imported.source, transcript.identity), + )?.cwd ?? (yield* readCwd(source, transcript, budget))); if (rolloutCwd === null || rolloutCwd === false) continue; const cwd = yield* projectCwd(rolloutCwd, transcript.projectRoots); const key = `${transcript.providerInstanceId}\0${cwd}`; @@ -1857,7 +2259,7 @@ export const make = Effect.gen(function* () { let truncated = false; let metadataTruncated = false; - for (const source of ["claudeAgent", "codex", "pi"] as const) { + for (const source of ["claudeAgent", "codex", "pi", "opencode"] as const) { const instances: Array<{ readonly instanceId: ProviderInstanceId; readonly config: ProviderInstanceConfig; @@ -1895,7 +2297,23 @@ export const make = Effect.gen(function* () { }; let homePath: string; - if (source === "pi") { + if (source === "opencode") { + // An instance set to use an external server resumes through that server, so a local + // conversation filed under it could not be continued. Such an instance is not searched. + const config = decodeOpenCodeSettings(instance.config ?? {}); + if (Option.isNone(config) || config.value.serverUrl.trim().length > 0) continue; + const environment = yield* mergeProviderInstanceEnvironment( + instance.environment, + hostEnvironment, + ).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir)); + const databasePath = yield* openCodeDatabase(config.value.binaryPath, environment); + if (databasePath === null) continue; + const homeKey = `${source}\0${yield* directoryIdentity(databasePath)}`; + if (seenHomes.has(homeKey)) continue; + seenHomes.add(homeKey); + homes.push({ homePath: databasePath, providerInstanceId: instanceId }); + continue; + } else if (source === "pi") { const environment = yield* mergeProviderInstanceEnvironment( instance.environment, hostEnvironment, @@ -1940,7 +2358,9 @@ export const make = Effect.gen(function* () { ? discoverClaudeTranscripts : source === "codex" ? discoverCodexTranscripts - : discoverPiTranscripts; + : source === "opencode" + ? discoverOpenCodeTranscripts + : discoverPiTranscripts; const shares = splitOperationBudget(MAX_DISCOVERY_OPERATIONS_PER_SOURCE, homes.length); const discovered: Array<{ readonly transcripts: ReadonlyArray; @@ -2262,14 +2682,18 @@ export const make = Effect.gen(function* () { const completed = completedByFile.get( `${candidate.providerInstanceId}\0${transcript.filePath}`, ); - if (completed === undefined && (transcriptsRemaining === 0 || bytesRemaining === 0)) { + // An OpenCode read ends on the first row past the budget, so the remainder can be negative. + if (completed === undefined && (transcriptsRemaining === 0 || bytesRemaining <= 0)) { return Option.some({ _tag: "Skipped" }); } - const stats = yield* statOption(transcript.filePath); + // An OpenCode session's size and time are its own; its database file only shows it is there. + const openCode = candidate.source === "opencode" ? transcript.openCode : undefined; + const stats = yield* statOption(openCode?.databasePath ?? transcript.filePath); if (Option.isNone(stats) || stats.value.type !== "File") { return Option.some({ _tag: "Skipped" }); } - const identity = transcriptIdentity(transcript.filePath, stats.value); + const identity = + openCode?.identity ?? transcriptIdentity(transcript.filePath, stats.value); const completedSource = completed?.find( (source) => source.provider === candidate.source && sameTranscriptIdentity(source, identity), @@ -2283,16 +2707,31 @@ export const make = Effect.gen(function* () { source: completedSource, }); } + // An OpenCode session's size is a sequence number, not a byte count. Its bytes are + // counted as its rows are read, and the read stops at what is left of the budget. if ( transcriptsRemaining === 0 || - identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES || - identity.size > bytesRemaining + (openCode === undefined && + (identity.size > MAX_IMPORTED_TRANSCRIPT_BYTES || identity.size > bytesRemaining)) ) { return Option.some({ _tag: "Skipped" }); } transcriptsRemaining -= 1; - bytesRemaining -= identity.size; - const snapshot = yield* readTranscript(transcript.filePath, identity, candidate.source); + const snapshot = + openCode === undefined + ? yield* Effect.gen(function* () { + bytesRemaining -= identity.size; + return yield* readTranscript(transcript.filePath, identity, candidate.source); + }) + : yield* Effect.gen(function* () { + const read = yield* readOpenCodeTranscript( + { ...openCode, filePath: transcript.filePath }, + Math.max(0, Math.min(MAX_IMPORTED_TRANSCRIPT_BYTES, bytesRemaining)), + ); + // Charged whether or not the session could be used. + bytesRemaining -= read?.bytesRead ?? 0; + return read?.snapshot ?? null; + }); if (snapshot === null) { return Option.some({ _tag: "Skipped" }); } @@ -2321,12 +2760,14 @@ export const make = Effect.gen(function* () { { source: candidate.source, providerInstanceId: candidate.providerInstanceId, - fallbackSessionId: path.basename( - transcript.filePath, - isCompressedTranscript(transcript.filePath) - ? COMPRESSED_TRANSCRIPT_SUFFIX - : ".jsonl", - ), + fallbackSessionId: + openCode?.sessionId ?? + path.basename( + transcript.filePath, + isCompressedTranscript(transcript.filePath) + ? COMPRESSED_TRANSCRIPT_SUFFIX + : ".jsonl", + ), lastActiveAtMs: transcript.mtimeMs, }, inheritedRecords === null @@ -2357,7 +2798,7 @@ export const make = Effect.gen(function* () { } const source: AgentSessionImportSource = { - ...identity, + ...("identity" in snapshot ? snapshot.identity : identity), provider: parsedThread.source, providerInstanceId: parsedThread.providerInstanceId, providerSessionId: parsedThread.providerSessionId, diff --git a/apps/web/src/components/onboarding/WelcomePage.tsx b/apps/web/src/components/onboarding/WelcomePage.tsx index bf2de9eace9d0..a3748e31c88ee 100644 --- a/apps/web/src/components/onboarding/WelcomePage.tsx +++ b/apps/web/src/components/onboarding/WelcomePage.tsx @@ -47,7 +47,6 @@ import { useLocalStorage } from "../../hooks/useLocalStorage"; import { usePersistEnvironmentProviderInstanceMutation } from "../../hooks/useSettings"; import { useCloudLinkState } from "../../cloud/cloudLinkState"; import { hasCloudPublicConfig } from "../../cloud/publicConfig"; -import { PRIVACY_POLICY_URL } from "../../legalLinks"; import { workspaceAreaProps } from "../../lib/workspaceFocus"; import { retryClerkLoad, useClerkLoadFailed } from "../clerk/clerkLoadFailure"; import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; @@ -1933,6 +1932,7 @@ const IMPORT_SOURCE_NAMES: Record = { claudeAgent: "Claude Code", codex: "Codex", pi: "Pi", + opencode: "OpenCode", }; function useImportSourcesLabel() { return new Intl.ListFormat(useLocale(), { type: "conjunction" }).format( @@ -1960,7 +1960,7 @@ function ImportRowMeta({ ? gt("now", { $context: "relative time" }) : relative.value; return ( - + {AgentSessionSource.literals.map((source) => ( {sources?.includes(source) ? ( diff --git a/docs/user/welcome-page.md b/docs/user/welcome-page.md index 9907073d05bfa..34581a2a6e931 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -2,7 +2,7 @@ M3 Code shows a Welcome page when you open a new installation. Existing workspaces skip it. It shows what M3 Code found on the computer you are using, -on one page: your agents, projects from your Claude Code, Codex, and Pi history, +on one page: your agents, projects from your Claude Code, Codex, OpenCode, and Pi history, and the phone app. Only an agent is needed to start chatting. To see the page again, go to **Settings → About → Welcome page** and select @@ -64,7 +64,7 @@ app with a code from **Settings → Sharing & access**. ## Projects -M3 Code finds directories that Claude Code, Codex or Pi has used. Git repositories +M3 Code finds directories that Claude Code, Codex, OpenCode or Pi has used. Git repositories are listed first, newest activity on top. When the remote is on GitHub, the group shows the repository as `owner/name`. Clones with the same remote share one group. Directories that are not git repositories sit under "Other folders". @@ -82,13 +82,23 @@ anything under `Downloads` are not offered. A large or malformed history can reach the scan limit. M3 Code keeps the projects it found and warns when projects or conversations may be missing. -Imported projects include Claude, Codex and Pi conversations active within the last +Imported projects include Claude, Codex, OpenCode and Pi conversations active within the last 30 days. You can continue those conversations in M3 Code. Pi is off by default: open **Add more agents** and select **Turn on** next to Pi, and the page looks for its sessions too. Pi sessions are read from each enabled Pi provider's session directory, which follows `PI_CODING_AGENT_SESSION_DIR` and `PI_CODING_AGENT_DIR` in its environment. A -Pi conversation imports its active branch, the one Pi reopens. +Pi conversation imports its active branch, the one Pi reopens. OpenCode +conversations are read from the database of each enabled OpenCode provider. +M3 Code asks the configured OpenCode executable for its database with +`debug paths db`, using that provider's environment. This selects the same +file the provider uses, including a custom `OPENCODE_DB` or channel build. +The lookup can create OpenCode's `log` and `repos` directories and write `opencode.log`. +If the command cannot report a local file, the provider's history is skipped. +Only conversations that OpenCode 2 stored are read. An OpenCode +provider set to use an external server (**Server URL**) is not searched, +because its conversations live on that server. A session archived in OpenCode +after the page listed it is left out. Conversation import is best effort. M3 Code keeps the first user prompt and the newest remaining visible user and assistant messages, with 200 messages total. diff --git a/packages/contracts/src/agentSessions.ts b/packages/contracts/src/agentSessions.ts index 93e0e36e4fbd4..7c75eeb0bfe72 100644 --- a/packages/contracts/src/agentSessions.ts +++ b/packages/contracts/src/agentSessions.ts @@ -2,7 +2,7 @@ import * as Schema from "effect/Schema"; import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; -export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex", "pi"]); +export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex", "pi", "opencode"]); export type AgentSessionSource = typeof AgentSessionSource.Type; export const AgentSessionImportSource = Schema.Struct({