A desktop coding agent with free access to frontier models.
TypeScript
fix: chats made in an older app version come over once
ogsamrat6374ab70a001
diff --git a/apps/server/src/engine-v2-migration.ts b/apps/server/src/engine-v2-migration.tsindex 8505975f..233c57df 100644--- a/apps/server/src/engine-v2-migration.ts+++ b/apps/server/src/engine-v2-migration.ts@@ -25,17 +25,25 @@ export function engineV2Root(runtimeStorageDir: string): string {type Sqlite = { exec(sql: string): void; all(sql: string): unknown[]; close(): void };-async function openReadOnly(path: string): Promise<Sqlite> {+async function openDb(path: string, readOnly: boolean): Promise<Sqlite> {if (typeof process.versions.bun === "string") {const { Database } = await import("bun:sqlite");- const db = new Database(path, { readonly: true, create: false });+ const db = new Database(path, readOnly ? { readonly: true, create: false } : { readwrite: true, create: false });return { exec: (sql) => db.run(sql), all: (sql) => db.query(sql).all(), close: () => db.close() };}const { DatabaseSync } = await importNodeSqlite();- const db = new DatabaseSync(path, { readOnly: true });+ const db = new DatabaseSync(path, { readOnly, enableForeignKeyConstraints: false });return { exec: (sql) => db.exec(sql), all: (sql) => db.prepare(sql).all(), close: () => db.close() };}+const openReadOnly = (path: string) => openDb(path, true);++function ids(rows: unknown[]): string[] {+ return rows.flatMap((row) => row && typeof (row as { id?: unknown }).id === "string" ? [(row as { id: string }).id] : []);+}++const quote = (value: string) => `'${value.replace(/'/g, "''")}'`;+/*** Seeds `<v2Root>/opencode.db` from the 1.x store once (only while the 2.x store does not exist yet).* Returns what it did, or null when there was nothing to do.@@ -63,6 +71,75 @@ export async function seedV2StoreFromV1(v2Root: string, v1Db: string, now = newreturn { backup, sessions };}+/**+ * Brings over the 1.x chats an existing 2.x store does not have yet: chats made in a 1.x app after the store was+ * seeded (for example 3.7.6 -> 3.7.5 -> 3.7.8). A chat the 2.x store has, or that came over before (and may since+ * have been deleted there), is never touched. The chats go into the store's 1.x tables, which then hold only them,+ * and the 2.x engine's own migration converts them on its next start; the 1.x store stays untouched and a+ * consistent copy of it is kept as a backup. Returns the chats brought over, or null when there were none.+ */+export async function importMissingV1Chats(v2Root: string, v1Db: string, now = new Date()): Promise<{ backup: string; sessions: string[] } | null> {+ const target = join(v2Root, "opencode.db");+ if (!existsSync(target) || !existsSync(v1Db)) return null;+ const known = readMigratedSessions(v2Root);+ const store = await openDb(target, false);+ try {+ const tables = new Set(store.all("SELECT name FROM sqlite_master WHERE type = 'table'").map((row) => (row as { name: string }).name));+ if (!tables.has("session_v2") || !tables.has("kv")) return null;+ for (const id of ids(store.all("SELECT id FROM session_v2"))) known.add(id);+ const source = await openReadOnly(v1Db);+ let missing: string[];+ let backup: string;+ try {+ const v1Tables = new Set(source.all("SELECT name FROM sqlite_master WHERE type = 'table'").map((row) => (row as { name: string }).name));+ if (!["session", "message", "part"].every((name) => v1Tables.has(name))) return null;+ missing = ids(source.all("SELECT id FROM session")).filter((id) => !known.has(id));+ if (missing.length === 0) return null;+ backup = join(dirname(v2Root), `v1-store-backup-${now.toISOString().replace(/[:.]/g, "-")}`, "opencode.db");+ await mkdir(dirname(backup), { recursive: true, mode: 0o700 });+ source.exec(`VACUUM INTO ${quote(backup)}`);+ } finally {+ source.close();+ }+ store.exec(`ATTACH DATABASE ${quote(backup)} AS v1`);+ try {+ const wanted = missing.map(quote).join(",");+ store.exec("BEGIN IMMEDIATE");+ try {+ for (const table of ["session", "message", "part"]) {+ if (!tables.has(table)) {+ const [ddl] = store.all(`SELECT sql FROM v1.sqlite_master WHERE type = 'table' AND name = ${quote(table)}`) as { sql: string }[];+ store.exec(ddl!.sql);+ }+ const key = table === "session" ? "id" : "session_id";+ // Only the chats being brought over stay in the 1.x tables: the engine's migration converts every row there.+ store.exec(`DELETE FROM main.${table} WHERE ${key} NOT IN (${wanted})`);+ const own = new Set(store.all(`PRAGMA main.table_info(${table})`).map((row) => (row as { name: string }).name));+ const columns = store.all(`PRAGMA v1.table_info(${table})`).map((row) => (row as { name: string }).name).filter((name) => own.has(name));+ const list = columns.map((name) => `"${name}"`).join(", ");+ store.exec(`INSERT OR IGNORE INTO main.${table} (${list}) SELECT ${list} FROM v1.${table} WHERE ${key} IN (${wanted})`);+ }+ // Converts the 1.x tables on the next start; a set phase keeps the engine from clearing the store's events.+ const at = now.getTime();+ store.exec(`INSERT INTO kv (key, value, time_created, time_updated) VALUES ('migration.v1-v2', '{"phase":"sessions"}', ${at}, ${at})+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, time_updated = excluded.time_updated`);+ store.exec("COMMIT");+ } catch (error) {+ store.exec("ROLLBACK");+ throw error;+ }+ } finally {+ store.exec("DETACH DATABASE v1");+ }+ const previous = (() => { try { return JSON.parse(readFileSync(join(v2Root, MIGRATED_SESSIONS_FILE), "utf8")) as Record<string, unknown>; } catch { return {}; } })();+ const sessions = [...readMigratedSessions(v2Root), ...missing];+ await writeFile(join(v2Root, MIGRATED_SESSIONS_FILE), `${JSON.stringify({ from: MIGRATED_FROM, ...previous, sessions, lastImport: { at: now.toISOString(), backup, sessions: missing } })}\n`, { mode: 0o600 });+ return { backup, sessions: missing };+ } finally {+ store.close();+ }+}+/** The chats that came from the 1.x store (empty when none did). */export function readMigratedSessions(v2Root: string): Set<string> {try {diff --git a/apps/server/src/engine-v2-next.test.ts b/apps/server/src/engine-v2-next.test.tsindex 92b09910..013929e7 100644--- a/apps/server/src/engine-v2-next.test.ts+++ b/apps/server/src/engine-v2-next.test.ts@@ -6,7 +6,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { assertSessionPluginActive, OMNIRUSH_SESSION_PLUGIN_ID } from "./engine-v2-preview.js";-import { readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";+import { importMissingV1Chats, readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";import { pluginDirectories } from "./managed-opencode-v2.js";import sessionPlugin from "./opencode-plugins/omnirush-session-next.js";import { startsV1Chat } from "./server.js";@@ -253,3 +253,73 @@ test("the 2.x engine's agent prompt: its own tool names, no todo list; nothing eexpect(instructions).toContain("smaller patch (or edit) calls");for (const word of ["apply_patch", "bash tool", "task tool", "todo list"]) expect(instructions.includes(word)).toBe(false);});++test("1.x chats made after the 2.x store was seeded come over once; chats the 2.x store has or had stay as they are", () => withDir(async (dir) => {+ const v1 = join(dir, "v1", "opencode.db");+ await Bun.write(join(dir, "v1", ".keep"), "");+ const old = new Database(v1, { create: true });+ old.run("CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT NOT NULL)");+ old.run("CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, directory TEXT NOT NULL, title TEXT NOT NULL, extra_v1 TEXT)");+ old.run("CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL)");+ old.run("CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL)");+ // ses_a came over at the seed and goes on in 2.x; ses_d came over and was deleted there; ses_c was made in 1.x later.+ for (const id of ["ses_a", "ses_c", "ses_d"]) {+ old.run(`INSERT INTO session VALUES ('${id}', 'p1', '/w', '${id} in 1.x', 'x')`);+ old.run(`INSERT INTO message VALUES ('msg_${id}', '${id}', 1, 1, '{}')`);+ old.run(`INSERT INTO part VALUES ('prt_${id}', 'msg_${id}', '${id}', 1, 1, '{}')`);+ }+ old.close();+ const root = join(dir, "v2", "state");+ const seeded = await seedV2StoreFromV1(root, v1, new Date("2026-10-25T00:00:00Z"));+ expect(seeded?.sessions.sort()).toEqual(["ses_a", "ses_c", "ses_d"]);+ // As 3.7.6 left it: the seed list without ses_c (made in 3.7.5 afterwards), the engine's migration done.+ await Bun.write(join(root, "v1-migrated-sessions.json"), JSON.stringify({ from: "1.18.32", at: "2026-10-25", backup: seeded!.backup, sessions: ["ses_a", "ses_d"] }));+ const store = new Database(join(root, "opencode.db"));+ store.run("CREATE TABLE session_v2 (id TEXT PRIMARY KEY, title TEXT)");+ store.run("CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL)");+ store.run("INSERT INTO session_v2 VALUES ('ses_a', 'continued in 2.x'), ('ses_b', 'made in 2.x')");+ store.run("INSERT INTO kv VALUES ('migration.v1-v2', '{\"phase\":\"completed\"}', 1, 1)");+ store.run("DELETE FROM session WHERE id = 'ses_c'");+ store.close();++ const imported = await importMissingV1Chats(root, v1, new Date("2026-10-26T00:00:00Z"));+ expect(imported?.sessions).toEqual(["ses_c"]);+ expect(existsSync(imported!.backup)).toBe(true);+ const after = new Database(join(root, "opencode.db"), { readonly: true });+ expect(after.query("SELECT id, title FROM session").all()).toEqual([{ id: "ses_c", title: "ses_c in 1.x" }]);+ expect(after.query("SELECT session_id FROM message").all()).toEqual([{ session_id: "ses_c" }]);+ expect(after.query("SELECT session_id FROM part").all()).toEqual([{ session_id: "ses_c" }]);+ expect(after.query("SELECT id, title FROM session_v2 ORDER BY id").all()).toEqual([{ id: "ses_a", title: "continued in 2.x" }, { id: "ses_b", title: "made in 2.x" }]);+ expect(after.query("SELECT value FROM kv WHERE key = 'migration.v1-v2'").get()).toEqual({ value: "{\"phase\":\"sessions\"}" });+ after.close();+ expect(readMigratedSessions(root)).toEqual(new Set(["ses_a", "ses_d", "ses_c"]));+ // Once over, never again; nothing to do without a 1.x store.+ expect(await importMissingV1Chats(root, v1)).toBeNull();+ expect(await importMissingV1Chats(root, join(dir, "missing.db"))).toBeNull();+}));++test("a 2.x store made without a 1.x store gets the 1.x tables for chats a 1.x app made later", () => withDir(async (dir) => {+ const v1 = join(dir, "v1", "opencode.db");+ await Bun.write(join(dir, "v1", ".keep"), "");+ const old = new Database(v1, { create: true });+ old.run("CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT NOT NULL)");+ old.run("CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, data TEXT NOT NULL)");+ old.run("CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL, data TEXT NOT NULL)");+ old.run("INSERT INTO session VALUES ('ses_new', '/w'), ('ses_twice', '/w')");+ old.run("INSERT INTO message VALUES ('msg_1', 'ses_new', '{}')");+ old.close();+ const root = join(dir, "v2", "state");+ await Bun.write(join(root, ".keep"), "");+ const store = new Database(join(root, "opencode.db"), { create: true });+ store.run("CREATE TABLE session_v2 (id TEXT PRIMARY KEY)");+ store.run("CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL)");+ // A chat 3.7.5 copied from the 2.x store into 1.x keeps its id: it is already here.+ store.run("INSERT INTO session_v2 VALUES ('ses_twice')");+ store.close();+ expect((await importMissingV1Chats(root, v1))?.sessions).toEqual(["ses_new"]);+ const after = new Database(join(root, "opencode.db"), { readonly: true });+ expect(after.query("SELECT id FROM session").all()).toEqual([{ id: "ses_new" }]);+ expect(after.query("SELECT id FROM message").all()).toEqual([{ id: "msg_1" }]);+ expect(after.query("SELECT value FROM kv").get()).toEqual({ value: "{\"phase\":\"sessions\"}" });+ after.close();+}));diff --git a/apps/server/src/engine-v2-preview.ts b/apps/server/src/engine-v2-preview.tsindex 1a76912f..68f842ca 100644--- a/apps/server/src/engine-v2-preview.ts+++ b/apps/server/src/engine-v2-preview.ts@@ -27,7 +27,7 @@ import { CLOUD_MCP_NAME, cloudMcpEntry, desiredV2Mcp, v2McpGate } from "./engineimport { runtimeMcpMap } from "./runtime-opencode-config-store.js";import { engineDataDir } from "./engine-data-home.js";import { computerUseEngineEnv } from "./computer-use/desktop.js";-import { engineV2Root, readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";+import { engineV2Root, importMissingV1Chats, readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";import type { ServerConfig } from "./types.js";import { boxServiceFor } from "./box/desktop.js";import { omnirushBoxNextPluginPath } from "./omnirush-extensions-plugin-path.js";@@ -525,8 +525,10 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Picif (!enabled || !allowRunning) return;await mkdir(workspaceDir, { recursive: true });// First start next to a 1.x store: back it up and seed the 2.x store from a copy (the 1.x store is kept).+ // Later, 1.x chats the 2.x store does not have yet (made in a 1.x app after it was seeded) are brought over too.try {- await seedV2StoreFromV1(rootDir, join(engineDataDir(process.env), "opencode.db"));+ const v1Db = join(engineDataDir(process.env), "opencode.db");+ if (!await seedV2StoreFromV1(rootDir, v1Db)) await importMissingV1Chats(rootDir, v1Db);} catch (error) {lastError = `1.x chats were not brought over: ${errorMessage(error)}`;}