Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
[CHOO-3384] Console: refuse a database migrated by a newer build (#728)
Louis Amaudruz7242b5491658
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 50877317d..fd3831dba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2139,6 +2139,18 @@ version of their own to them without also giving them a release of their own.agent"; it was the only place Console showed that name.#### Fixed+- **Console no longer opens to a blank window on a database a newer build+ has changed.** Stable and Canary share one database, so after Canary added a+ migration, an older build found tables it was not written for, applied+ nothing, and failed its first query with nothing on screen. Console now+ refuses a database carrying a migration it does not know, before changing+ anything, and says why: open the build that last used it, download a newer+ release (a build that cannot start cannot update itself), or move the data+ folder aside to start empty. Migrations are tracked one by one, so a+ migration applied out of order is applied rather than skipped. Any other+ startup failure now shows the error and a Reload button instead of a blank+ window. drizzle-kit now defaults to the dev data folder's database rather+ than the installed app's.- **Giving a machine a Vertex AI login no longer pre-fills a project.** TheGoogle Cloud project field started out filled with one organisation's ownproject, so anyone else who kept it got a sign-in failure with nothing todiff --git a/console/agents/risky-areas/database.md b/console/agents/risky-areas/database.mdindex 91ec87077..65921b735 100644--- a/console/agents/risky-areas/database.md+++ b/console/agents/risky-areas/database.md@@ -17,6 +17,10 @@- database path is resolved by main-process db path helpers- `SWITCHDASH_DB_FILE` overrides the default location+- drizzle-kit (`push`, `migrate`, `studio`) opens the database in the dev data folder:+ `SWITCH_CONSOLE_USER_DATA_DIR` when it names one, `switchdash-dev` otherwise, and+ `SWITCHDASH_DB_FILE` over both; never point it at `switchdash`, which stable and Canary+ share and which refuses to open once it has a migration the app does not know- database initialization happens in `src/main/db/initialize.ts`## Development Workflowdiff --git a/console/apps/switch-console-desktop/drizzle.config.ts b/console/apps/switch-console-desktop/drizzle.config.tsindex f7d35181b..607d9b5cd 100644--- a/console/apps/switch-console-desktop/drizzle.config.ts+++ b/console/apps/switch-console-desktop/drizzle.config.ts@@ -1,13 +1,23 @@import { resolve } from 'node:path';import { defineConfig } from 'drizzle-kit';+import { checkedFolderName, USER_DATA_DIR_ENV } from './src/main/app/user-data-dir';import { defaultDbFilePath, resolveDefaultUserDataPath } from './src/main/db/default-path';+import { DEV_USER_DATA_DIR_NAME } from './src/shared/app-identity';+// The database `pnpm dev` uses — in the worktree's own data folder when+// SWITCH_CONSOLE_USER_DATA_DIR names one — never the installed app's: stable+// and Canary share `switchdash`, and a schema pushed or migrated into it from a+// branch leaves the installed app unable to open it. Not userDataDirName() or+// USER_DATA_DIR_NAME: outside the Vite build both resolve to `switchdash`.function resolveDbUrl(): string {const explicit = process.env.SWITCHDASH_DB_FILE?.trim();if (explicit) {return resolve(explicit);}- return defaultDbFilePath(resolveDefaultUserDataPath());+ const named = process.env[USER_DATA_DIR_ENV];+ return defaultDbFilePath(+ resolveDefaultUserDataPath(named ? checkedFolderName(named) : DEV_USER_DATA_DIR_NAME)+ );}export default defineConfig({diff --git a/console/apps/switch-console-desktop/src/main/db/client.ts b/console/apps/switch-console-desktop/src/main/db/client.tsindex bb67af0fb..ded31660f 100644--- a/console/apps/switch-console-desktop/src/main/db/client.ts+++ b/console/apps/switch-console-desktop/src/main/db/client.ts@@ -18,8 +18,9 @@ const databasePath = resolveDatabasePath();*/export const databaseExistedAtStart = existsSync(databasePath);+// WAL is switched on by initializeDatabase, not here: switching writes to the+// file, and a database from a newer build must be refused before anything does.export const sqlite = new Database(databasePath);-sqlite.pragma('journal_mode = WAL');sqlite.pragma('busy_timeout = 5000');export const db = drizzle(sqlite, { schema });diff --git a/console/apps/switch-console-desktop/src/main/db/default-path.ts b/console/apps/switch-console-desktop/src/main/db/default-path.tsindex 33960da7f..d49a8114b 100644--- a/console/apps/switch-console-desktop/src/main/db/default-path.ts+++ b/console/apps/switch-console-desktop/src/main/db/default-path.ts@@ -10,31 +10,26 @@ export const CURRENT_DB_FILENAME = 'switchdash.db';// see resolveDefaultDatabasePath() in ./database-file.ts.export const LEGACY_DB_FILENAMES = ['emdash4.db', 'emdash3.db'] as const;-const USER_DATA_DIR_NAME = 'switchdash';-/**- * Returns the platform-specific default userData directory without requiring- * the Electron `app` module. This is pinned to the shared `switchdash` directory- * regardless of product identity.- *- * Pass this result as `userDataPath` to `resolveDatabasePath()` when running- * outside of Electron (e.g. drizzle-kit CLI).+ * Returns the platform-specific path of the userData directory `dirName`+ * without requiring the Electron `app` module, for code running outside+ * Electron (e.g. drizzle-kit CLI).*/-export function resolveDefaultUserDataPath(): string {+export function resolveDefaultUserDataPath(dirName: string): string {const home = process.env.HOME ?? homedir();const platform = process.platform;if (platform === 'darwin') {- return join(home, 'Library', 'Application Support', USER_DATA_DIR_NAME);+ return join(home, 'Library', 'Application Support', dirName);}if (platform === 'win32') {const appData = process.env.APPDATA ?? join(home, 'AppData', 'Roaming');- return join(appData, USER_DATA_DIR_NAME);+ return join(appData, dirName);}const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(home, '.config');- return join(xdgConfig, USER_DATA_DIR_NAME);+ return join(xdgConfig, dirName);}/**diff --git a/console/apps/switch-console-desktop/src/main/db/drizzle-config.test.ts b/console/apps/switch-console-desktop/src/main/db/drizzle-config.test.tsnew file mode 100644index 000000000..7a3159c1d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/drizzle-config.test.ts@@ -0,0 +1,92 @@+/**+ * drizzle-kit `push`, `migrate` and `studio` open the database the config+ * names. Defaulting to the installed app's `switchdash` folder let a schema+ * from a branch land in the database stable and Canary open (CHOO-3384), and+ * ignoring a worktree's own data folder does the same to every other dev+ * worktree, which share `switchdash-dev`.+ */+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { CURRENT_DB_FILENAME } from './default-path';++const appDir = fileURLToPath(new URL('../../..', import.meta.url));++beforeEach(() => {+ vi.stubEnv('SWITCHDASH_DB_FILE', '');+ vi.stubEnv('SWITCH_CONSOLE_USER_DATA_DIR', '');+});++afterEach(() => {+ vi.unstubAllEnvs();+ vi.resetModules();+});++async function configuredUrl(): Promise<string> {+ const { default: config } = await import('../../../drizzle.config');+ return (config as { dbCredentials: { url: string } }).dbCredentials.url;+}++it("opens the dev database by default, never the installed app's", async () => {+ const url = await configuredUrl();++ expect(url.endsWith(join('switchdash-dev', CURRENT_DB_FILENAME))).toBe(true);+});++// drizzle-kit loads the config outside the Vite build, where DEV is unset, so+// USER_DATA_DIR_NAME is `switchdash`: a config built on it passes every test+// here under Vitest and opens the installed app's database. Only drizzle-kit's+// own loader shows it.+it('opens the dev database when drizzle-kit itself loads the config', () => {+ const scratch = mkdtempSync(join(tmpdir(), 'drizzle-config-'));+ try {+ const probe = join(scratch, 'probe.config.ts');+ writeFileSync(+ probe,+ `import config from ${JSON.stringify(join(appDir, 'drizzle.config.ts').replaceAll('\\', '/'))};\n` ++ `console.log('DB_URL=' + config.dbCredentials.url);\n` ++ `export default config;\n`+ );+ const bin = join(dirname(createRequire(import.meta.url).resolve('drizzle-kit')), 'bin.cjs');++ // `check` reads the migrations folder and never opens the database.+ const run = spawnSync(process.execPath, [bin, 'check', `--config=${probe}`], {+ cwd: appDir,+ encoding: 'utf8',+ env: { ...process.env, SWITCHDASH_DB_FILE: '', SWITCH_CONSOLE_USER_DATA_DIR: '' },+ });++ const url = /^DB_URL=(.*)$/m.exec(run.stdout)?.[1];+ expect(url, run.stderr || run.stdout).toBeDefined();+ expect(url!.endsWith(join('switchdash-dev', CURRENT_DB_FILENAME))).toBe(true);+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+}, 60_000);++it("opens the worktree's own data folder when SWITCH_CONSOLE_USER_DATA_DIR names one", async () => {+ vi.stubEnv('SWITCH_CONSOLE_USER_DATA_DIR', 'switchdash-wt1');++ const url = await configuredUrl();++ expect(url.endsWith(join('switchdash-wt1', CURRENT_DB_FILENAME))).toBe(true);+});++it('refuses a SWITCH_CONSOLE_USER_DATA_DIR that is a path, as the app does', async () => {+ vi.stubEnv('SWITCH_CONSOLE_USER_DATA_DIR', '../elsewhere');++ await expect(configuredUrl()).rejects.toThrow(+ /SWITCH_CONSOLE_USER_DATA_DIR must be a folder name/+ );+});++it('opens SWITCHDASH_DB_FILE when it is set, over SWITCH_CONSOLE_USER_DATA_DIR', async () => {+ vi.stubEnv('SWITCHDASH_DB_FILE', '/tmp/scratch/switchdash.db');+ vi.stubEnv('SWITCH_CONSOLE_USER_DATA_DIR', 'switchdash-wt1');++ expect(await configuredUrl()).toBe(resolve('/tmp/scratch/switchdash.db'));+});diff --git a/console/apps/switch-console-desktop/src/main/db/initialize.ts b/console/apps/switch-console-desktop/src/main/db/initialize.tsindex 74a8d421e..2ddcf42d1 100644--- a/console/apps/switch-console-desktop/src/main/db/initialize.ts+++ b/console/apps/switch-console-desktop/src/main/db/initialize.ts@@ -11,7 +11,7 @@ const sqlFiles = import.meta.glob('@root/drizzle/*.sql', {eager: true,}) as Record<string, string>;-type JournalEntry = { idx: number; when: number; tag: string; breakpoints: boolean };+export type JournalEntry = { idx: number; when: number; tag: string; breakpoints: boolean };/*** Bundled migration SQL that the journal does not list.@@ -40,7 +40,49 @@ function migrationTagFromKey(key: string): string | null {return base?.endsWith('.sql') ? base.slice(0, -'.sql'.length) : null;}+/**+ * The database has migrations applied that this build does not know about: it+ * was last opened by a newer build, or one that diverged from this one —+ * Canary or a build from source, which share the stable channel's data+ * directory, or a stable hotfix tagged off main (CHOO-3384).+ *+ * Opening it anyway means booting on a schema this build was not written for:+ * the first query that touches a changed table fails, and the renderer is left+ * on a blank window. Refusing with a clear message is the only safe outcome, as+ * downgrading a schema is not something the migrations can do.+ */+export class DatabaseFromNewerBuildError extends Error {+ readonly unknownMigrations: number;+ /** The file that was refused — not always in the data folder (SWITCHDASH_DB_FILE). */+ readonly databasePath: string;++ constructor(unknownTimestamps: number[], newestKnown: number, databasePath: string) {+ super(+ `The database was last opened by a newer or different version of the app: it has ` ++ `${unknownTimestamps.length} migration(s) this version does not know about ` ++ `(ledger timestamps ${unknownTimestamps.join(', ')}; newest known ${newestKnown}).`+ );+ this.name = 'DatabaseFromNewerBuildError';+ this.unknownMigrations = unknownTimestamps.length;+ this.databasePath = databasePath;+ }+}+function runBundledMigrations(connection: BetterSqlite3.Database): void {+ applyMigrations(connection, (journal as { entries: JournalEntry[] }).entries, sqlFiles);+}++/**+ * Applies `entries` (journal order) from `sqlFiles` to `connection`.+ *+ * Exported so tests can run the runner against an older journal — the way an+ * older build sees a database — without rebuilding the bundle.+ */+export function applyMigrations(+ connection: BetterSqlite3.Database,+ entries: JournalEntry[],+ sqlFiles: Record<string, string>+): void {const migrationLog = log.child({ component: 'db-migration' });const startedAt = Date.now();const applied: string[] = [];@@ -53,8 +95,6 @@ function runBundledMigrations(connection: BetterSqlite3.Database): void {)`);- const entries = (journal as { entries: JournalEntry[] }).entries;-const orphans = orphanedMigrationTags(Object.keys(sqlFiles),entries.map((entry) => entry.tag)@@ -74,10 +114,34 @@ function runBundledMigrations(connection: BetterSqlite3.Database): void {Object.keys(sqlFiles).map((key) => [migrationTagFromKey(key), key] as const));- const lastRow = connection- .prepare('SELECT created_at FROM __drizzle_migrations ORDER BY created_at DESC LIMIT 1')- .get() as { created_at: number } | undefined;- const lastTimestamp = lastRow?.created_at ?? 0;+ // Each ledger row is matched to its journal entry by timestamp, rather than+ // treating the newest timestamp as "everything up to here is applied". A+ // high-water mark cannot see a migration from a build that diverged from this+ // one (a stable hotfix stamped after Canary's newest looks like the newer+ // build), and it skips an entry stamped below a migration applied out of+ // order — both boot the app on a schema it was not written for.+ const appliedTimestamps = new Set(+ (+ connection.prepare('SELECT created_at FROM __drizzle_migrations').all() as {+ created_at: number;+ }[]+ ).map((row) => Number(row.created_at))+ );+ const knownTimestamps = new Set(entries.map((entry) => entry.when));+ const unknownTimestamps = [...appliedTimestamps]+ .filter((timestamp) => !knownTimestamps.has(timestamp))+ .sort((a, b) => a - b);+ if (unknownTimestamps.length) {+ const newestKnown = Math.max(0, ...knownTimestamps);+ migrationLog.error('Database was migrated by a newer or different build', {+ event: 'db_migration_newer_schema',+ databasePath: connection.name,+ unknownTimestamps,+ newestKnown,+ unknownMigrations: unknownTimestamps.length,+ });+ throw new DatabaseFromNewerBuildError(unknownTimestamps, newestKnown, connection.name);+ }// Apply migrations with foreign keys disabled. SQLite's table-recreation// pattern (CREATE __new / copy / DROP / RENAME) used to drop columns that are@@ -90,7 +154,7 @@ function runBundledMigrations(connection: BetterSqlite3.Database): void {// fact, so which one was being applied is recorded as it happens.connection.transaction(() => {for (const entry of entries) {- if (entry.when <= lastTimestamp) continue;+ if (appliedTimestamps.has(entry.when)) continue;const sqlKey = sqlByTag.get(entry.tag);if (!sqlKey) throw new Error(`Missing bundled SQL for migration: ${entry.tag}`);@@ -214,6 +278,9 @@ export async function initializeDatabase(// This keeps the module importable in non-Electron environments (Vitest).const conn = connection ?? (await import('./client')).sqlite;runBundledMigrations(conn);+ // After the migrations, which refuse a database from a newer build before+ // writing to it: switching the journal mode writes the file header.+ conn.pragma('journal_mode = WAL');ensureSearchIndex(conn);dropFileIndex(conn);return conn;diff --git a/console/apps/switch-console-desktop/src/main/db/open-failure-dialog.test.ts b/console/apps/switch-console-desktop/src/main/db/open-failure-dialog.test.tsnew file mode 100644index 000000000..9c8c336e8--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/open-failure-dialog.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from 'vitest';+import { SWITCH_CONSOLE_RELEASES_URL } from '@shared/urls';+import { DatabaseFromNewerBuildError } from './initialize';+import { databaseOpenFailureDialog } from './open-failure-dialog';++const DATA_PATH = '/Users/someone/Library/Application Support/switchdash';+const DB_PATH = `${DATA_PATH}/switchdash.db`;++describe('databaseOpenFailureDialog', () => {+ const newerBuild = new DatabaseFromNewerBuildError([1790300000000], 1790248865722, DB_PATH);++ it('names the newer build as the cause, and the build that last used it as the remedy', () => {+ const { title, body } = databaseOpenFailureDialog(+ newerBuild,+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(title).toBe('Switch Console could not open its database');+ expect(body).toContain('last opened by a newer or different build');+ expect(body).toContain('open the build that last used it');+ expect(body).toContain('It has not been changed.');+ expect(body).not.toContain('another copy of the app already running');+ });++ // The reporter of CHOO-3384 had never knowingly run another build, so naming+ // one is not enough on its own: the box has to say where the data is and+ // what moving it aside costs.+ it('names the folder to move aside when there is no build to go back to', () => {+ const { body } = databaseOpenFailureDialog(+ newerBuild,+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(body).toContain('To start empty instead, quit and move this folder aside');+ expect(body).toContain('will not carry over');+ expect(body.split('\n')).toContain(DATA_PATH);+ });++ // A database put elsewhere with SWITCHDASH_DB_FILE: moving the data folder+ // aside would leave the refused file exactly where it is.+ it('names the database file instead when it is not in the data folder', () => {+ const elsewhere = '/tmp/scratch/switchdash.db';+ const { body } = databaseOpenFailureDialog(+ new DatabaseFromNewerBuildError([1790300000000], 1790248865722, elsewhere),+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(body).toContain('move this database file aside, with the -wal and -shm files');+ expect(body.split('\n')).toContain(elsewhere);+ expect(body).not.toContain(DATA_PATH);+ expect(body).not.toContain('move this folder aside');+ });++ // The updater starts after the database opens, so a build that refuses its+ // database never updates itself; the box has to say where a newer one is.+ it('says where to download a newer release, and that it will not update itself', () => {+ const { body } = databaseOpenFailureDialog(+ newerBuild,+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(body).toContain(+ `download a release newer than that build from ${SWITCH_CONSOLE_RELEASES_URL}`+ );+ expect(body).toContain('cannot update itself while it cannot start');+ });++ it('does not blame Canary alone, since a build from source writes the same folder', () => {+ const { body } = databaseOpenFailureDialog(+ newerBuild,+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(body).toContain('or one built from source');+ });++ // Canary is ahead of stable, so the newest stable release does not carry+ // Canary's migrations either: telling a stable user to update cannot work.+ it('does not tell the user that updating to the latest release will fix it', () => {+ const { body } = databaseOpenFailureDialog(+ newerBuild,+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(body).not.toMatch(/latest release/i);+ });++ it('keeps the generic causes for any other failure', () => {+ const { body } = databaseOpenFailureDialog(+ new Error('SQLITE_BUSY: database is locked'),+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(body).toContain('another copy of the app already running');+ expect(body).not.toContain('newer or different build');+ expect(body).not.toContain(DATA_PATH);+ });++ it('ends with the log path and the raw error', () => {+ const { body } = databaseOpenFailureDialog(+ newerBuild,+ 'Switch Console',+ DATA_PATH,+ '/logs/main.log'+ );++ expect(body).toContain('Full details are in the log: /logs/main.log');+ expect(body.split('\n').at(-1)).toBe(`Error: ${newerBuild.message}`);+ });++ it('leaves out the log line when there is no log file', () => {+ const { body } = databaseOpenFailureDialog('boom', 'Switch Console', DATA_PATH, undefined);++ expect(body).not.toContain('Full details are in the log');+ expect(body.split('\n').at(-1)).toBe('Error: boom');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/db/open-failure-dialog.ts b/console/apps/switch-console-desktop/src/main/db/open-failure-dialog.tsnew file mode 100644index 000000000..342ef3fb0--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/open-failure-dialog.ts@@ -0,0 +1,52 @@+import { dirname, resolve } from 'node:path';+import { SWITCH_CONSOLE_RELEASES_URL } from '@shared/urls';+import { DatabaseFromNewerBuildError } from './initialize';++function newerBuildCause(error: DatabaseFromNewerBuildError, dataPath: string): string {+ // SWITCHDASH_DB_FILE can put the database anywhere, and moving aside the+ // folder it happens to sit in (or a data folder it is not in) is wrong.+ const inDataFolder = resolve(dirname(error.databasePath)) === resolve(dataPath);+ return [+ 'The database was last opened by a newer or different build of the app (a Canary build, or one built from source, which share this folder), so this version cannot read it. It has not been changed.',+ // The updater runs after the database opens, so a refused build never+ // updates itself: without this, waiting for an update would wait forever.+ `To keep what is in it, open the build that last used it, or download a release newer than that build from ${SWITCH_CONSOLE_RELEASES_URL}. This version cannot update itself while it cannot start.`,+ inDataFolder+ ? 'To start empty instead, quit and move this folder aside; what was saved in it will not carry over:'+ : 'To start empty instead, quit and move this database file aside, with the -wal and -shm files beside it; what was saved in it will not carry over:',+ inDataFolder ? dataPath : error.databasePath,+ ].join('\n');+}++const GENERIC_CAUSE =+ 'The usual causes are another copy of the app already running, a full disk, or the database file having been moved or made read-only. Closing the other copy and reopening is worth trying first.';++/**+ * The box shown when the database cannot be opened at boot.+ *+ * The one failure with no UI to fall back on: the app is about to quit, so+ * whatever the user needs to act has to be in this box. Name the cause and+ * remedy, where the log is, then the raw error under its own heading.+ */+export function databaseOpenFailureDialog(+ error: unknown,+ productName: string,+ dataPath: string,+ logPath: string | null | undefined+): { title: string; body: string } {+ const cause =+ error instanceof DatabaseFromNewerBuildError ? newerBuildCause(error, dataPath) : GENERIC_CAUSE;+ return {+ title: `${productName} could not open its database`,+ body: [+ `${productName} cannot start without it, so it is closing.`,+ '',+ cause,+ logPath ? `\nFull details are in the log: ${logPath}` : '',+ '',+ `Error: ${error instanceof Error ? error.message : String(error)}`,+ ]+ .filter((line) => line !== '')+ .join('\n'),+ };+}diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.tsindex ab2311463..bb564523b 100644--- a/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/journal-registration.test.ts@@ -76,16 +76,15 @@ describe('migration journal registration', () => {});/**- * The runner skips with `entry.when <= lastTimestamp`, where `lastTimestamp`- * is the highest `created_at` in the ledger — not a record of which- * migrations ran. So an entry whose `when` is below a preceding entry's can- * never be applied on any machine: it is skipped on every boot, silently,- * while migration reports success and the table it creates is simply absent.+ * The ledger records a migration by its `when` and nothing else, so `when` is+ * a migration's identity: two entries sharing one would make the runner treat+ * the second as applied the moment the first is. Order matters too — drizzle+ * stamps `created_at` from `when`, and every build already released has+ * assumed a journal whose timestamps rise with its index.*- * Two branches landing migrations out of order is enough to cause it, which- * is the same class of merge accident that produced the 0045/0046 renumber.- * Keying the ledger per migration would remove the dependency entirely; until- * then the precondition is at least asserted rather than assumed.+ * Two branches landing migrations out of order is enough to break either,+ * which is the same class of merge accident that produced the 0045/0046+ * renumber.*/it('orders journal entries by strictly increasing timestamp', () => {const whens = journal.entries.map((entry) => entry.when);diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/newer-build-database.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/newer-build-database.test.tsnew file mode 100644index 000000000..c10a6658d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/newer-build-database.test.ts@@ -0,0 +1,277 @@+/**+ * A build must refuse a database migrated by a build it does not match+ * (CHOO-3384), and must never skip a migration it has not applied.+ *+ * Every build on a machine writes the same data directory: stable, Canary and+ * any build packaged from source (only `pnpm dev` and drizzle-kit keep to the+ * dev data folder). 0051_workspaces (Canary 0.39, and main) rebuilds+ * `agents` without `server_id`. Stable 0.38.2 skipped every migration at or+ * below the newest applied timestamp, so on such a database it applied+ * nothing, reported success and booted on the newer schema; `getAgents`+ * selected `agents.server_id` and the renderer was left on a blank window.+ *+ * The old build is simulated by running the real runner against the journal+ * truncated before 0051 — exactly what a 0.38.2 bundle contains. A stable+ * hotfix cut from that point is simulated by adding a migration stamped after+ * everything on main, which is what `db:generate` on a release branch produces.+ */++import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import Database from 'better-sqlite3';+import { afterEach, describe, expect, it } from 'vitest';+import {+ applyMigrations,+ DatabaseFromNewerBuildError,+ initializeDatabase,+ type JournalEntry,+} from '@main/db/initialize';+import journal from '@root/drizzle/meta/_journal.json';++const drizzleDir = fileURLToPath(new URL('../../../../../drizzle', import.meta.url));+const sqlFiles = Object.fromEntries(+ readdirSync(drizzleDir)+ .filter((name) => name.endsWith('.sql'))+ .map((name) => [`/drizzle/${name}`, readFileSync(`${drizzleDir}/${name}`, 'utf8')])+);+const allEntries = journal.entries as JournalEntry[];+const cut = allEntries.findIndex((entry) => entry.tag === '0051_workspaces');+const olderEntries = allEntries.slice(0, cut);+const olderSqlFiles = sqlFilesFor(olderEntries);+const newestKnown = Math.max(...allEntries.map((entry) => entry.when));++const hotfix: JournalEntry = {+ idx: cut,+ when: newestKnown + 1000,+ tag: '0051_stable_hotfix',+ breakpoints: true,+};+const hotfixSqlFiles = {+ '/drizzle/0051_stable_hotfix.sql': 'CREATE TABLE `stable_hotfix` (`id` integer PRIMARY KEY);',+};++function sqlFilesFor(entries: JournalEntry[]): Record<string, string> {+ return Object.fromEntries(+ Object.entries(sqlFiles).filter(([key]) =>+ entries.some((entry) => key.endsWith(`/${entry.tag}.sql`))+ )+ );+}++function schemaAndLedger(db: Database.Database): unknown {+ return {+ schema: db.prepare('SELECT type, name, sql FROM sqlite_master ORDER BY type, name').all(),+ ledger: db.prepare('SELECT id, hash, created_at FROM __drizzle_migrations ORDER BY id').all(),+ };+}++function refusal(run: () => unknown): DatabaseFromNewerBuildError {+ try {+ run();+ } catch (error) {+ expect(error).toBeInstanceOf(DatabaseFromNewerBuildError);+ return error as DatabaseFromNewerBuildError;+ }+ throw new Error('expected the runner to refuse the database');+}++function columns(db: Database.Database, table: string): string[] {+ return (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map(+ (column) => column.name+ );+}++describe('database migrated by a newer build', () => {+ let db: Database.Database;++ afterEach(() => db?.close());++ it('finds 0051 in the journal, so the older build below is really older', () => {+ expect(cut).toBeGreaterThan(0);+ expect(olderEntries.length).toBe(cut);+ });++ it('is refused by the older build instead of booting on the newer schema', () => {+ db = new Database(':memory:');+ applyMigrations(db, allEntries, sqlFiles); // a newer build (Canary, or one from main)++ const error = refusal(() => applyMigrations(db, olderEntries, olderSqlFiles));+ expect(error.message).toMatch(/last opened by a newer or different version/);+ });++ it('counts how many migrations the older build does not know', () => {+ db = new Database(':memory:');+ applyMigrations(db, allEntries, sqlFiles);++ const error = refusal(() => applyMigrations(db, olderEntries, olderSqlFiles));+ expect(error.unknownMigrations).toBe(allEntries.length - olderEntries.length);+ });++ // The dialog tells the user what to move aside, and SWITCHDASH_DB_FILE can+ // put the database outside the data folder: it needs the file it refused.+ it('names the database file it refused', () => {+ const dir = mkdtempSync(join(tmpdir(), 'newer-build-'));+ const path = join(dir, 'switchdash.db');+ try {+ db = new Database(path);+ applyMigrations(db, allEntries, sqlFiles);++ const error = refusal(() => applyMigrations(db, olderEntries, olderSqlFiles));+ expect(error.databasePath).toBe(path);+ } finally {+ db.close();+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('leaves the schema and the ledger exactly as it found them when it refuses', () => {+ db = new Database(':memory:');+ applyMigrations(db, allEntries, sqlFiles);+ const before = schemaAndLedger(db);++ refusal(() => applyMigrations(db, olderEntries, olderSqlFiles));++ expect(schemaAndLedger(db)).toEqual(before);+ });++ it('still upgrades a database from an older build, and reopens it as a no-op', () => {+ db = new Database(':memory:');+ applyMigrations(db, olderEntries, olderSqlFiles);+ expect(() => applyMigrations(db, allEntries, sqlFiles)).not.toThrow();+ expect(() => applyMigrations(db, allEntries, sqlFiles)).not.toThrow();+ const { n } = db.prepare('SELECT COUNT(*) AS n FROM __drizzle_migrations').get() as {+ n: number;+ };+ expect(n).toBe(allEntries.length);+ });+});++/**+ * Stable releases can be tagged from any commit, so a stable hotfix can carry a+ * migration main never had. drizzle-kit stamps it with the time it was+ * generated — after everything Canary has — so comparing the newest timestamps+ * says the hotfix build is the newer one. It is not: it does not know 0051.+ */+describe('database migrated by a build that diverged from this one', () => {+ let db: Database.Database;++ afterEach(() => db?.close());++ it('is refused by a stable hotfix whose own migration is stamped after Canary’s', () => {+ db = new Database(':memory:');+ applyMigrations(db, allEntries, sqlFiles); // Canary, with 0051+ const before = schemaAndLedger(db);++ const error = refusal(() =>+ applyMigrations(db, [...olderEntries, hotfix], { ...olderSqlFiles, ...hotfixSqlFiles })+ );++ expect(error.unknownMigrations).toBe(allEntries.length - olderEntries.length);+ expect(schemaAndLedger(db)).toEqual(before);+ });++ it('is refused when an unknown migration sits between known ones, not only after them', () => {+ db = new Database(':memory:');+ applyMigrations(db, allEntries, sqlFiles);+ db.prepare('INSERT INTO __drizzle_migrations (hash, created_at) VALUES (?, ?)').run(+ 'from-another-branch',+ allEntries[1].when + 1+ );++ expect(refusal(() => applyMigrations(db, allEntries, sqlFiles)).unknownMigrations).toBe(1);+ });++ it('applies a migration stamped before the newest applied one instead of skipping it', () => {+ // The stable hotfix is merged back into main after 0051: main's journal is+ // [..., 0051, hotfix]. A database the hotfix build migrated has the hotfix+ // but not 0051, and the hotfix's timestamp is the higher of the two.+ db = new Database(':memory:');+ applyMigrations(db, [...olderEntries, hotfix], { ...olderSqlFiles, ...hotfixSqlFiles });+ expect(columns(db, 'agents')).toContain('server_id');++ applyMigrations(db, [...allEntries, { ...hotfix, idx: allEntries.length }], {+ ...sqlFiles,+ ...hotfixSqlFiles,+ });++ expect(columns(db, 'agents')).not.toContain('server_id');+ expect(columns(db, 'workspaces')).toContain('server_id');+ const { n } = db.prepare('SELECT COUNT(*) AS n FROM __drizzle_migrations').get() as {+ n: number;+ };+ expect(n).toBe(allEntries.length + 1);+ });+});++/** Through the entry point the app calls, with the migrations the bundle carries. */+describe('initializeDatabase on a database from a newer build', () => {+ let db: Database.Database;++ afterEach(() => db?.close());++ it('rejects before the post-migration steps touch anything', async () => {+ db = new Database(':memory:');+ await initializeDatabase(db);+ db.prepare('INSERT INTO __drizzle_migrations (hash, created_at) VALUES (?, ?)').run(+ 'from-a-newer-build',+ newestKnown + 1+ );+ db.prepare("DELETE FROM kv WHERE key IN ('fts_version', 'file_index_version')").run();+ const before = schemaAndLedger(db);++ await expect(initializeDatabase(db)).rejects.toBeInstanceOf(DatabaseFromNewerBuildError);++ expect(schemaAndLedger(db)).toEqual(before);+ expect(+ db.prepare("SELECT key FROM kv WHERE key IN ('fts_version', 'file_index_version')").all()+ ).toEqual([]);+ });++ // The dialog promises the database "has not been changed". Switching to WAL+ // rewrites the file header, so it has to wait until the database is accepted.+ it('leaves a refused database file byte-for-byte as it was, journal mode included', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'newer-build-'));+ const path = join(dir, 'switchdash.db');+ try {+ db = new Database(path);+ db.pragma('journal_mode = DELETE');+ applyMigrations(db, allEntries, sqlFiles);+ db.prepare('INSERT INTO __drizzle_migrations (hash, created_at) VALUES (?, ?)').run(+ 'from-a-newer-build',+ newestKnown + 1+ );+ db.close();+ const before = readFileSync(path);++ db = new Database(path);+ await expect(initializeDatabase(db)).rejects.toBeInstanceOf(DatabaseFromNewerBuildError);+ expect(db.pragma('journal_mode', { simple: true })).toBe('delete');+ db.close();++ expect(readFileSync(path).equals(before)).toBe(true);+ } finally {+ db.close();+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('switches a database it accepts to WAL', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'newer-build-'));+ try {+ db = new Database(join(dir, 'switchdash.db'));+ await initializeDatabase(db);+ expect(db.pragma('journal_mode', { simple: true })).toBe('wal');+ } finally {+ db.close();+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('opens a database this build migrated itself', async () => {+ db = new Database(':memory:');+ await initializeDatabase(db);+ await expect(initializeDatabase(db)).resolves.toBe(db);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex 7567041e4..1e74f30e6 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -48,6 +48,7 @@ import { updateService } from './core/updates/update-service';import { viewStateService } from './core/view-state/view-state-service';import { reconcileAllWorkspaces } from './core/workspaces/reconcile-workspaces';import { initializeDatabase } from './db/initialize';+import { databaseOpenFailureDialog } from './db/open-failure-dialog';import { logAppExit, logAppStart, registerAppDiagnostics } from './lib/app-diagnostics';import {getLogFilePath,@@ -139,23 +140,13 @@ void app.whenReady().then(async () => {}} catch (error) {log.error('Failed to initialize database:', error);- // The one failure with no UI to fall back on: the app is about to quit, so- // whatever the user needs to act has to be in this box. Name the likely- // causes and where the log is, then the raw error under its own heading.- const logPath = getLogFilePath();- dialog.showErrorBox(- `${PRODUCT_NAME} could not open its database`,- [- `${PRODUCT_NAME} cannot start without it, so it is closing.`,- '',- 'The usual causes are another copy of the app already running, a full disk, or the database file having been moved or made read-only. Closing the other copy and reopening is worth trying first.',- logPath ? `\nFull details are in the log: ${logPath}` : '',- '',- `Error: ${error instanceof Error ? error.message : String(error)}`,- ]- .filter((line) => line !== '')- .join('\n')+ const { title, body } = databaseOpenFailureDialog(+ error,+ PRODUCT_NAME,+ app.getPath('userData'),+ getLogFilePath());+ dialog.showErrorBox(title, body);app.quit();return;}diff --git a/console/apps/switch-console-desktop/src/renderer/bootstrap-failure.tsx b/console/apps/switch-console-desktop/src/renderer/bootstrap-failure.tsxnew file mode 100644index 000000000..40c44fbbd--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/bootstrap-failure.tsx@@ -0,0 +1,25 @@+import { createRoot, type Root } from 'react-dom/client';+import { ErrorFallback, reloadAfterCrash } from './lib/components/error-boundary';+import { describeFailure } from './lib/errors/describe-failure';++/**+ * Bootstrap runs before the app mounts, so nothing else is on screen when it+ * fails: logging alone leaves a blank window, and the error reaches only the+ * log file, which the user has no reason to open (CHOO-3384).+ */+export function renderBootstrapFailure(container: HTMLElement, error: unknown): Root {+ const { headline, detail } = describeFailure(+ error,+ 'Reloading may recover it. If it keeps happening, the error below says why.'+ );+ const root = createRoot(container);+ root.render(+ <ErrorFallback+ title="Switch Console could not start"+ hint={headline}+ message={detail ?? 'No further detail was reported.'}+ onReload={reloadAfterCrash}+ />+ );+ return root;+}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsxindex 6b1f5f217..6427b3fbe 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsx@@ -18,12 +18,22 @@ type ErrorBoundaryProps = {* with it, so the raw message stays — demoted out of the lead sentence, but* present, and selectable so it can be pasted into a bug report.*/-function ErrorFallback({ message, onReload }: { message: string; onReload: () => void }) {+export function ErrorFallback({+ title,+ hint,+ message,+ onReload,+}: {+ title: string;+ hint: string;+ message: string;+ onReload: () => void;+}) {return (<div className="flex h-screen w-screen items-center justify-center bg-background p-6"><div className="bg-card text-card-foreground max-w-xl rounded-md border border-border p-6 shadow-sm">- <h1 className="mb-2 text-lg font-semibold">Switch Console hit an error and stopped</h1>- <p className="text-muted-foreground mb-4 text-sm">Reloading usually recovers it.</p>+ <h1 className="mb-2 text-lg font-semibold">{title}</h1>+ <p className="text-muted-foreground mb-4 text-sm">{hint}</p><p className="text-muted-foreground mb-4 font-mono text-xs break-all select-text">{message}</p>@@ -35,6 +45,15 @@ function ErrorFallback({ message, onReload }: { message: string; onReload: () =>);}+/** Drops the saved view state first, in case restoring it is what failed. */+export function reloadAfterCrash(): void {+ void rpc.viewState.reset().finally(() => {+ try {+ window.location.reload();+ } catch {}+ });+}+export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {state: ErrorBoundaryState = { hasError: false, error: null };@@ -58,17 +77,16 @@ export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoun});}- handleReload = () => {- void rpc.viewState.reset().finally(() => {- try {- window.location.reload();- } catch {}- });- };-render() {if (!this.state.hasError) return this.props.children as React.ReactElement;const message = this.state.error?.message || 'No further detail was reported.';- return <ErrorFallback message={message} onReload={this.handleReload} />;+ return (+ <ErrorFallback+ title="Switch Console hit an error and stopped"+ hint="Reloading usually recovers it."+ message={message}+ onReload={reloadAfterCrash}+ />+ );}}diff --git a/console/apps/switch-console-desktop/src/renderer/main.tsx b/console/apps/switch-console-desktop/src/renderer/main.tsxindex 2dabea9d1..3b236206a 100644--- a/console/apps/switch-console-desktop/src/renderer/main.tsx+++ b/console/apps/switch-console-desktop/src/renderer/main.tsx@@ -18,6 +18,7 @@ import { initSoundPlayer } from '@renderer/utils/soundPlayer';import { setAgentProviderCatalogue } from '@shared/core/providers/agent-provider-registry';import type { NavigationSnapshot, SidebarSnapshot } from '@shared/view-state';import { App } from './App';+import { renderBootstrapFailure } from './bootstrap-failure';import { ErrorBoundary } from './lib/components/error-boundary';import { appState } from './lib/stores/app-state';@@ -66,4 +67,5 @@ async function bootstrap() {bootstrap().catch((error: unknown) => {log.error('Renderer bootstrap failed:', error);+ renderBootstrapFailure(document.getElementById('root') ?? document.body, error);});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/bootstrap-failure.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/bootstrap-failure.test.tsxnew file mode 100644index 000000000..5f4298e98--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/bootstrap-failure.test.tsx@@ -0,0 +1,56 @@+/**+ * A renderer whose bootstrap fails shows why, instead of a blank window+ * (CHOO-3384: a schema mismatch failed the first query, and the only trace of+ * it was a line in the log).+ */+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { afterEach, expect, it } from 'vitest';+import { renderBootstrapFailure } from '@renderer/bootstrap-failure';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(error: unknown): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ await act(async () => {+ root = renderBootstrapFailure(container!, error);+ });+ return container;+}++it('says the app could not start and shows the error it failed on', async () => {+ const el = await render(+ new Error('no such column: "server_id" - should this be a string literal in single-quotes?')+ );++ expect(el.querySelector('h1')?.textContent).toBe('Switch Console could not start');+ expect(el.textContent).toContain('no such column: "server_id"');+});++it('offers a reload', async () => {+ const el = await render(new Error('boom'));++ const button = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Reload');+ expect(button).toBeDefined();+});++it('shows a thrown value that is not an Error', async () => {+ const el = await render('RpcError: database is locked');++ expect(el.textContent).toContain('RpcError: database is locked');+});++it('says so when the failure carried no message', async () => {+ const el = await render(new Error(''));++ expect(el.textContent).toContain('No further detail was reported.');+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/error-boundary.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/error-boundary.test.tsxnew file mode 100644index 000000000..315420236--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/error-boundary.test.tsx@@ -0,0 +1,70 @@+/**+ * A component that throws after the app has mounted is caught by the+ * boundary, which shows the crash screen with the error and a Reload that+ * drops the saved view state first.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';++const { reset } = vi.hoisted(() => ({+ // Never settles, so clicking Reload does not reload the test page.+ reset: vi.fn(() => new Promise<void>(() => {})),+}));++vi.mock('@renderer/lib/ipc', () => ({ rpc: { viewState: { reset } } }));+vi.mock('@renderer/lib/telemetry/report', () => ({ report: vi.fn() }));++import { ErrorBoundary } from '@renderer/lib/components/error-boundary';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+ reset.mockClear();+});++function Throws({ message }: { message: string }): never {+ throw new Error(message);+}++async function renderCrash(message: string): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ // React reports a caught render error to the console as well; it is expected.+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ await act(async () => {+ root!.render(+ <ErrorBoundary>+ <Throws message={message} />+ </ErrorBoundary>+ );+ });+ } finally {+ consoleError.mockRestore();+ }+ return container;+}++it('shows the crash screen with the error the component threw', async () => {+ const el = await renderCrash('Cannot read properties of undefined');++ expect(el.querySelector('h1')?.textContent).toBe('Switch Console hit an error and stopped');+ expect(el.textContent).toContain('Reloading usually recovers it.');+ expect(el.textContent).toContain('Cannot read properties of undefined');+});++it('drops the saved view state when Reload is pressed', async () => {+ const el = await renderCrash('boom');++ const button = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Reload');+ await act(async () => button!.click());++ expect(reset).toHaveBeenCalledOnce();+});diff --git a/console/apps/switch-console-desktop/src/shared/app-identity.ts b/console/apps/switch-console-desktop/src/shared/app-identity.tsindex f2b136615..125a6aa25 100644--- a/console/apps/switch-console-desktop/src/shared/app-identity.ts+++ b/console/apps/switch-console-desktop/src/shared/app-identity.ts@@ -40,7 +40,10 @@ export const APP_ID = isCanary ? 'com.switchdash.canary' : 'com.switchdash.stablexport const PRODUCT_NAME = isCanary ? 'Switch Console Canary' : 'Switch Console';export const OS_APP_NAME = 'Switchdash';export const APP_NAME_LOWER = isCanary ? 'switch-console-canary' : 'switch-console';-export const USER_DATA_DIR_NAME = isDev ? 'switchdash-dev' : 'switchdash';+// Named on its own for code outside the Vite build (drizzle-kit), where isDev is+// always false and USER_DATA_DIR_NAME is `switchdash`, the installed app's.+export const DEV_USER_DATA_DIR_NAME = 'switchdash-dev';+export const USER_DATA_DIR_NAME = isDev ? DEV_USER_DATA_DIR_NAME : 'switchdash';export const UPDATE_CHANNEL = isCanary ? 'v1-canary' : 'v1-stable';export const ARTIFACT_PREFIX = isCanary ? 'switch-console-canary' : 'switch-console';export const IS_CANARY = isCanary;