diff --git a/packages/desktop/src/main/storage/database.test.ts b/packages/desktop/src/main/storage/database.test.ts index 9dddad1b478..abacdf6d656 100644 --- a/packages/desktop/src/main/storage/database.test.ts +++ b/packages/desktop/src/main/storage/database.test.ts @@ -1,10 +1,13 @@ import { describe, expect, test } from "bun:test" +import { copyFileSync, mkdtempSync, rmSync, symlinkSync } from "node:fs" +import { tmpdir } from "node:os" import { DatabaseSync } from "node:sqlite" import path from "node:path" import { sql } from "drizzle-orm" import { drizzle } from "drizzle-orm/node-sqlite" import { migrate, openDatabase } from "./database" import { migrations } from "./migration.gen" +import { readWindowSnapshot } from "./window-snapshot" const tables = (db: ReturnType) => db @@ -60,6 +63,42 @@ describe("database", () => { native.close() }) + // Symlinks need elevated privileges on Windows. + test.each(["symlink", "copy"].filter((link) => link === "copy" || process.platform !== "win32"))( + "moves aside a drafts.sqlite that is the CLI database (%s) without writing to it", + (link) => { + const root = mkdtempSync(path.join(tmpdir(), "opencode-drafts-cli-")) + const cli = path.join(root, "opencode.db") + const drafts = path.join(root, "drafts.sqlite") + const seeded = new DatabaseSync(cli) + seeded.exec( + "CREATE TABLE session_v2 (id TEXT PRIMARY KEY); CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL); INSERT INTO migration VALUES ('20261010180456_project_time_archived', 0)", + ) + seeded.close() + + if (link === "symlink") symlinkSync(cli, drafts) + + if (link === "copy") copyFileSync(cli, drafts) + + readWindowSnapshot(root, ["settings"]) + const database = openDatabase(drafts) + + expect(tables(database.db)).toEqual(expected) + expect(database.moved).toStartWith(`${drafts}.cli-`) + database.close() + const moved = drizzle({ client: new DatabaseSync(database.moved ?? "") }) + const original = drizzle({ client: new DatabaseSync(cli) }) + + for (const db of [moved, original]) { + expect(tables(db)).toEqual(["migration", "session_v2"]) + expect(db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20261010180456_project_time_archived" }]) + db.$client.close() + } + + rmSync(root, { recursive: true, force: true }) + }, + ) + test("a failed migration rolls back the journal without losing existing data", () => { const native = new DatabaseSync(":memory:") native.exec("CREATE TABLE state (value TEXT); INSERT INTO state VALUES ('kept')") diff --git a/packages/desktop/src/main/storage/database.ts b/packages/desktop/src/main/storage/database.ts index 8d11d15f990..de235462844 100644 --- a/packages/desktop/src/main/storage/database.ts +++ b/packages/desktop/src/main/storage/database.ts @@ -1,20 +1,34 @@ +import { renameSync } from "node:fs" import { DatabaseSync } from "node:sqlite" import { drizzle } from "drizzle-orm/node-sqlite" -import { migrateDatabase } from "./migration" +import { isCliDatabase, migrateDatabase } from "./migration" export type Database = ReturnType export function openDatabase(filename: string) { - const native = new DatabaseSync(filename) + const opened = openOwnDatabase(filename) // WAL keeps readers off the writer. NORMAL fsyncs at checkpoints only, which survives an app // crash but not power loss; the right trade for UI state and far cheaper on Windows. - native.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA temp_store=MEMORY") - const db = drizzle({ client: native }) + opened.native.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA temp_store=MEMORY") + const db = drizzle({ client: opened.native }) migrate(db) - return { db, close: () => native.close() } + return { db, moved: opened.moved, close: () => opened.native.close() } } export function migrate(db: Database) { return migrateDatabase(db.$client) } + +// A drafts.sqlite symlinked or copied from the CLI's opencode.db can't hold desktop tables. Renaming it moves +// only this directory entry, so a symlink's target and the CLI data in it stay untouched. +function openOwnDatabase(filename: string) { + const native = new DatabaseSync(filename) + + if (!isCliDatabase(native)) return { native } + native.close() + const moved = `${filename}.cli-${Date.now()}` + renameSync(filename, moved) + + return { native: new DatabaseSync(filename), moved } +} diff --git a/packages/desktop/src/main/storage/index.ts b/packages/desktop/src/main/storage/index.ts index 79ce2592212..91f7893bde2 100644 --- a/packages/desktop/src/main/storage/index.ts +++ b/packages/desktop/src/main/storage/index.ts @@ -25,6 +25,9 @@ export const layer = Layer.effect( runFork(Effect.logError("storage flush failed", { error })), ) + if (storage.moved) + yield* Effect.logWarning("drafts.sqlite was the OpenCode CLI database; moved it aside", { to: storage.moved }) + yield* importLegacyStores(storage.db, userData).pipe( Effect.tap((result) => result.removed.length === 0 @@ -65,6 +68,7 @@ export function make(filename: string, onError?: (error: unknown) => void) { return { db: database.db, + moved: database.moved, state, drafts, flush() { diff --git a/packages/desktop/src/main/storage/migration.ts b/packages/desktop/src/main/storage/migration.ts index ae7eb7f27a5..97c3bcb869b 100644 --- a/packages/desktop/src/main/storage/migration.ts +++ b/packages/desktop/src/main/storage/migration.ts @@ -3,6 +3,9 @@ import { migrations } from "./migration.gen" /** The desktop journal, usable by the early preload read without loading Drizzle or Effect. */ export function migrateDatabase(db: DatabaseSync) { + // Check before writing anything: desktop tables written into the CLI database break the CLI's own migrations. + if (isCliDatabase(db)) throw new Error("drafts.sqlite is the OpenCode CLI database") + db.exec("CREATE TABLE IF NOT EXISTS migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)") const applied = new Set(db.prepare("SELECT id FROM migration").all().map((row) => row.id)) @@ -31,3 +34,11 @@ export function migrateDatabase(db: DatabaseSync) { return pending.map((migration) => migration.id) } + +/** The CLI's opencode.db, reached through a symlink or a copy. Both apps define `blob` and `migration`, so they can't share one file. */ +export function isCliDatabase(db: DatabaseSync) { + return ( + db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('session', 'session_v2')").get() !== + undefined + ) +}