π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(database): establish cross-runtime local database (#17682)
Innei57cc104b7b1c
diff --git a/apps/desktop/drizzle.local.config.ts b/apps/desktop/drizzle.local.config.tsnew file mode 100644index 00000000000..7d031fbb1a3--- /dev/null+++ b/apps/desktop/drizzle.local.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from 'drizzle-kit';++export default defineConfig({+ dialect: 'sqlite',+ out: './src/main/database/migrations/drizzle',+ schema: './src/main/database/schema.ts',+ strict: true,+});diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 4c4fe038bd5..6ec0f4d358b 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -15,6 +15,7 @@"build:main": "cross-env NODE_OPTIONS=--max-old-space-size=8192 npm run build:main:raw","build:main:raw": "vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.renderer.config.ts","build:run-unpack": "electron .",+ "db:generate:local": "drizzle-kit generate --config drizzle.local.config.ts","dev": "node scripts/dev.mjs","dev:react-devtools": "cross-env DESKTOP_REACT_DEVTOOLS=1 npm run dev","dev:static": "cross-env DESKTOP_RENDERER_STATIC=1 npm run dev",@@ -86,6 +87,8 @@"cookie": "^1.1.1","cross-env": "^10.1.0","diff": "^8.0.4",+ "drizzle-kit": "^0.31.10",+ "drizzle-orm": "^0.45.2","electron": "41.3.0","electron-builder": "26.14.0","electron-is": "^3.0.0",diff --git a/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts b/apps/desktop/src/main/controllers/LocalDatabaseCtr.tsnew file mode 100644index 00000000000..ddd8a682d30--- /dev/null+++ b/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts@@ -0,0 +1,57 @@+import type {+ DesktopLocalDatabaseBatchOperation,+ DesktopLocalDatabaseEntry,+ DesktopLocalDatabaseKey,+ DesktopLocalDatabasePrefix,+ DesktopLocalDatabaseSet,+} from '@lobechat/electron-client-ipc';++import LocalDatabaseService from '@/services/LocalDatabaseSrv';++import { ControllerModule, IpcMethod } from './index';++export default class LocalDatabaseController extends ControllerModule {+ static override readonly groupName = 'localDatabase';++ private get service() {+ return this.app.getService(LocalDatabaseService);+ }++ @IpcMethod()+ initialize(): void {+ this.service.initialize();+ }++ @IpcMethod()+ async batch(operations: DesktopLocalDatabaseBatchOperation[]): Promise<void> {+ await this.service.batch(operations);+ }++ @IpcMethod()+ async delete({ collection, key }: DesktopLocalDatabaseKey): Promise<void> {+ await this.service.delete(collection, key);+ }++ @IpcMethod()+ async deleteByPrefix({ collection, prefix }: DesktopLocalDatabasePrefix): Promise<void> {+ await this.service.deleteByPrefix(collection, prefix);+ }++ @IpcMethod()+ async entriesByPrefix({+ collection,+ prefix,+ }: DesktopLocalDatabasePrefix): Promise<DesktopLocalDatabaseEntry[]> {+ return this.service.entriesByPrefix(collection, prefix);+ }++ @IpcMethod()+ async get({ collection, key }: DesktopLocalDatabaseKey): Promise<string | undefined> {+ return this.service.get(collection, key);+ }++ @IpcMethod()+ async set({ collection, key, value }: DesktopLocalDatabaseSet): Promise<void> {+ await this.service.set(collection, key, value);+ }+}diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.tsindex daef4d32da1..8fad5959ccd 100644--- a/apps/desktop/src/main/controllers/registry.ts+++ b/apps/desktop/src/main/controllers/registry.ts@@ -11,6 +11,7 @@ import GatewayConnectionCtr from './GatewayConnectionCtr';import GitCtr from './GitCtr';import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';import ImessageBridgeCtr from './ImessageBridgeCtr';+import LocalDatabaseCtr from './LocalDatabaseCtr';import LocalFileCtr from './LocalFileCtr';import McpCtr from './McpCtr';import McpInstallCtr from './McpInstallCtr';@@ -39,6 +40,7 @@ export const controllerIpcConstructors = [DevtoolsCtr,GatewayConnectionCtr,GitCtr,+ LocalDatabaseCtr,LocalFileCtr,ImessageBridgeCtr,McpCtr,diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex 8cdcfab3b7b..4edef2c1f83 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -23,7 +23,7 @@ import {} from '@/modules/binaries';import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';import { ScreenCaptureManager } from '@/modules/screenCapture/ScreenCaptureManager';-import type { IServiceModule } from '@/services';+import type { IServiceModule, ServiceLifecycle, ServiceModule } from '@/services';import { createLogger } from '@/utils/logger';import { BrowserManager } from './browser/BrowserManager';@@ -294,7 +294,7 @@ export class App {};getService<T>(serviceClass: Class<T>): T {- return this.services.get(serviceClass);+ return this.services.get(serviceClass) as T;}getController<T>(controllerClass: Class<T>): T {@@ -390,7 +390,7 @@ export class App {/*** all services in app*/- private services = new Map<Class<any>, any>();+ private services = new Map<Class<any>, ServiceModule & ServiceLifecycle>();private ipcServer: ElectronIPCServer;private ipcServerEventMap: IPCEventMap = new Map();@@ -471,6 +471,10 @@ export class App {}// Execute cleanup operations+ for (const service of this.services.values()) {+ service.destroy?.();+ }+this.staticFileServerManager.destroy();};}diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.tsindex 600c4dfb8dd..22ff8dc12db 100644--- a/apps/desktop/src/main/core/__tests__/App.test.ts+++ b/apps/desktop/src/main/core/__tests__/App.test.ts@@ -1,6 +1,8 @@+import { app as electronApp } from 'electron';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// Import after mocks are set up+import LocalDatabaseService from '../../services/LocalDatabaseSrv';import { App } from '../App';const mockPathExistsSync = vi.fn();@@ -191,4 +193,19 @@ describe('App', () => {expect(storagePath).toBe('/mock/storage/path');});});++ describe('service lifecycle', () => {+ it('destroys registered services before quitting', () => {+ appInstance = new App();+ const databaseService = appInstance.getService(LocalDatabaseService);+ const destroy = vi.spyOn(databaseService, 'destroy');+ const beforeQuitHandler = vi+ .mocked(electronApp.on)+ .mock.calls.findLast(([event]) => (event as string) === 'before-quit')?.[1] as () => void;++ beforeQuitHandler();++ expect(destroy).toHaveBeenCalledOnce();+ });+ });});diff --git a/apps/desktop/src/main/database/client.ts b/apps/desktop/src/main/database/client.tsnew file mode 100644index 00000000000..c5064b9e094--- /dev/null+++ b/apps/desktop/src/main/database/client.ts@@ -0,0 +1,64 @@+import { DatabaseSync } from 'node:sqlite';++import { drizzle } from 'drizzle-orm/sqlite-proxy';++import { runLocalDatabaseMigrations } from './migrations/runner';+import { localDatabaseSchema } from './schema';++const configureDatabase = (database: DatabaseSync) => {+ database.exec(`+ PRAGMA busy_timeout = 5000;+ PRAGMA journal_mode = WAL;+ PRAGMA synchronous = NORMAL;+ `);+};++const createDrizzleDatabase = (database: DatabaseSync) =>+ drizzle(+ async (query, params, method) => {+ const statement = database.prepare(query);++ switch (method) {+ case 'all': {+ statement.setReturnArrays(true);+ return { rows: statement.all(...params) as never[] };+ }++ case 'get': {+ statement.setReturnArrays(true);+ return { rows: statement.get(...params) as never };+ }++ case 'run': {+ statement.run(...params);+ return { rows: [] };+ }++ case 'values': {+ statement.setReturnArrays(true);+ return { rows: statement.all(...params) as never[] };+ }+ }+ },+ { schema: localDatabaseSchema },+ );++export type LocalDrizzleDatabase = ReturnType<typeof createDrizzleDatabase>;++export interface LocalDatabaseRuntime {+ database: DatabaseSync;+ db: LocalDrizzleDatabase;+}++export const createLocalDatabaseRuntime = (databasePath: string): LocalDatabaseRuntime => {+ const database = new DatabaseSync(databasePath);++ try {+ configureDatabase(database);+ runLocalDatabaseMigrations(database);+ return { database, db: createDrizzleDatabase(database) };+ } catch (error) {+ database.close();+ throw error;+ }+};diff --git a/apps/desktop/src/main/database/migrations/drizzle/0000_initialize_local_records.sql b/apps/desktop/src/main/database/migrations/drizzle/0000_initialize_local_records.sqlnew file mode 100644index 00000000000..2014277aafb--- /dev/null+++ b/apps/desktop/src/main/database/migrations/drizzle/0000_initialize_local_records.sql@@ -0,0 +1,4 @@+CREATE TABLE `local_records` (+ `id` text PRIMARY KEY NOT NULL,+ `value` text NOT NULL+);diff --git a/apps/desktop/src/main/database/migrations/drizzle/meta/0000_snapshot.json b/apps/desktop/src/main/database/migrations/drizzle/meta/0000_snapshot.jsonnew file mode 100644index 00000000000..c43752558f9--- /dev/null+++ b/apps/desktop/src/main/database/migrations/drizzle/meta/0000_snapshot.json@@ -0,0 +1,42 @@+{+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "dialect": "sqlite",+ "enums": {},+ "id": "4337dd0f-12c1-4d06-9a8c-a030df8bb86f",+ "internal": {+ "indexes": {}+ },+ "prevId": "00000000-0000-0000-0000-000000000000",+ "tables": {+ "local_records": {+ "name": "local_records",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "version": "6",+ "views": {}+}diff --git a/apps/desktop/src/main/database/migrations/drizzle/meta/_journal.json b/apps/desktop/src/main/database/migrations/drizzle/meta/_journal.jsonnew file mode 100644index 00000000000..a2cf7ae290a--- /dev/null+++ b/apps/desktop/src/main/database/migrations/drizzle/meta/_journal.json@@ -0,0 +1,13 @@+{+ "dialect": "sqlite",+ "entries": [+ {+ "idx": 0,+ "version": "6",+ "when": 1785251399985,+ "tag": "0000_initialize_local_records",+ "breakpoints": true+ }+ ],+ "version": "7"+}diff --git a/apps/desktop/src/main/database/migrations/index.ts b/apps/desktop/src/main/database/migrations/index.tsnew file mode 100644index 00000000000..1258fbf43b8--- /dev/null+++ b/apps/desktop/src/main/database/migrations/index.ts@@ -0,0 +1,27 @@+import type { LocalDatabaseMigration } from './types';++const migrationModules = import.meta.glob('./drizzle/*.sql', {+ eager: true,+ import: 'default',+ query: '?raw',+}) as Record<string, string>;++const migrationName = (path: string) =>+ path+ .split('/')+ .at(-1)!+ .replace(/\.sql$/, '');++/** Generated Drizzle migrations, ordered by their immutable numeric filename prefix. */+export const localDatabaseMigrations: readonly LocalDatabaseMigration[] = Object.entries(+ migrationModules,+)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([path, source], index) => ({+ name: migrationName(path),+ statements: source+ .split('--> statement-breakpoint')+ .map((statement) => statement.trim())+ .filter(Boolean),+ version: index + 1,+ }));diff --git a/apps/desktop/src/main/database/migrations/runner.test.ts b/apps/desktop/src/main/database/migrations/runner.test.tsnew file mode 100644index 00000000000..77ffb1872f9--- /dev/null+++ b/apps/desktop/src/main/database/migrations/runner.test.ts@@ -0,0 +1,115 @@+import { DatabaseSync } from 'node:sqlite';++import { afterEach, describe, expect, it } from 'vitest';++import { runLocalDatabaseMigrations } from './runner';+import type { LocalDatabaseMigration } from './types';++describe('runLocalDatabaseMigrations', () => {+ let database: DatabaseSync | undefined;++ afterEach(() => {+ database?.close();+ database = undefined;+ });++ it('applies pending migrations exactly once and records their versions', () => {+ database = new DatabaseSync(':memory:');+ const migrations = [+ {+ name: 'create_items',+ statements: ['CREATE TABLE items (id TEXT PRIMARY KEY NOT NULL)'],+ version: 1,+ },+ {+ name: 'seed_item',+ statements: ["INSERT INTO items (id) VALUES ('seed')"],+ version: 2,+ },+ ] satisfies readonly LocalDatabaseMigration[];++ runLocalDatabaseMigrations(database, migrations);+ runLocalDatabaseMigrations(database, migrations);++ expect(database.prepare('SELECT id FROM items').all()).toEqual([{ id: 'seed' }]);+ expect(database.prepare('SELECT version FROM __local_database_migrations').all()).toEqual([+ { version: 1 },+ { version: 2 },+ ]);+ });++ it('rolls back a failed migration without reverting earlier versions', () => {+ database = new DatabaseSync(':memory:');+ const migrations = [+ {+ name: 'create_stable_table',+ statements: ['CREATE TABLE stable_items (id TEXT PRIMARY KEY NOT NULL)'],+ version: 1,+ },+ {+ name: 'create_invalid_table',+ statements: [+ 'CREATE TABLE rolled_back_items (id TEXT PRIMARY KEY NOT NULL)',+ 'INSERT INTO missing_table (id) VALUES (1)',+ ],+ version: 2,+ },+ ] satisfies readonly LocalDatabaseMigration[];++ expect(() => runLocalDatabaseMigrations(database!, migrations)).toThrow();++ expect(+ database+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stable_items'")+ .get(),+ ).toEqual({ name: 'stable_items' });+ expect(+ database+ .prepare(+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'rolled_back_items'",+ )+ .get(),+ ).toBeUndefined();+ expect(database.prepare('SELECT version FROM __local_database_migrations').all()).toEqual([+ { version: 1 },+ ]);+ });++ it('rejects edits to an already applied migration', () => {+ database = new DatabaseSync(':memory:');+ const migration = {+ name: 'create_items',+ statements: ['CREATE TABLE items (id TEXT PRIMARY KEY NOT NULL)'],+ version: 1,+ } satisfies LocalDatabaseMigration;+ runLocalDatabaseMigrations(database, [migration]);++ expect(() =>+ runLocalDatabaseMigrations(database!, [+ { ...migration, statements: ['CREATE TABLE changed_items (id TEXT PRIMARY KEY NOT NULL)'] },+ ]),+ ).toThrow('differs from the application manifest');+ });++ it('rejects gaps in applied migration history', () => {+ database = new DatabaseSync(':memory:');+ const migrations = [+ {+ name: 'create_items',+ statements: ['CREATE TABLE items (id TEXT PRIMARY KEY NOT NULL)'],+ version: 1,+ },+ {+ name: 'add_item_value',+ statements: ['ALTER TABLE items ADD COLUMN value TEXT'],+ version: 2,+ },+ ] satisfies readonly LocalDatabaseMigration[];+ runLocalDatabaseMigrations(database, migrations);+ database.prepare('DELETE FROM __local_database_migrations WHERE version = 1').run();++ expect(() => runLocalDatabaseMigrations(database!, migrations)).toThrow(+ 'migration history is not contiguous',+ );+ });+});diff --git a/apps/desktop/src/main/database/migrations/runner.ts b/apps/desktop/src/main/database/migrations/runner.tsnew file mode 100644index 00000000000..d1b217a95b9--- /dev/null+++ b/apps/desktop/src/main/database/migrations/runner.ts@@ -0,0 +1,113 @@+import { createHash } from 'node:crypto';+import type { DatabaseSync } from 'node:sqlite';++import { localDatabaseMigrations } from './index';+import type { LocalDatabaseMigration } from './types';++interface AppliedMigration {+ checksum: string;+ name: string;+ version: number;+}++const MIGRATIONS_TABLE = '__local_database_migrations';++const migrationChecksum = (migration: LocalDatabaseMigration) =>+ createHash('sha256')+ .update(JSON.stringify([migration.version, migration.name, migration.statements]))+ .digest('hex');++const validateManifest = (migrations: readonly LocalDatabaseMigration[]) => {+ for (const [index, migration] of migrations.entries()) {+ const expectedVersion = index + 1;++ if (migration.version !== expectedVersion) {+ throw new Error(+ `Local database migration sequence is invalid: expected version ${expectedVersion}, received ${migration.version}`,+ );+ }++ if (migration.statements.length === 0) {+ throw new Error(`Local database migration ${migration.version} has no statements`);+ }+ }+};++const initializeMigrationTable = (database: DatabaseSync) => {+ database.exec(`+ CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (+ version INTEGER PRIMARY KEY NOT NULL,+ name TEXT NOT NULL,+ checksum TEXT NOT NULL,+ applied_at INTEGER NOT NULL+ );+ `);+};++const readAppliedMigrations = (database: DatabaseSync): AppliedMigration[] =>+ database+ .prepare(`SELECT version, name, checksum FROM ${MIGRATIONS_TABLE} ORDER BY version ASC`)+ .all() as unknown as AppliedMigration[];++const validateAppliedMigrations = (+ appliedMigrations: AppliedMigration[],+ migrations: readonly LocalDatabaseMigration[],+) => {+ for (const [index, applied] of appliedMigrations.entries()) {+ const expectedVersion = index + 1;++ if (applied.version !== expectedVersion) {+ throw new Error(+ `Local database migration history is not contiguous: expected version ${expectedVersion}, received ${applied.version}`,+ );+ }++ const migration = migrations[applied.version - 1];++ if (!migration) {+ throw new Error(+ `Local database version ${applied.version} is newer than this application supports`,+ );+ }++ if (applied.name !== migration.name || applied.checksum !== migrationChecksum(migration)) {+ throw new Error(+ `Local database migration ${applied.version} (${applied.name}) differs from the application manifest`,+ );+ }+ }+};++const applyMigration = (database: DatabaseSync, migration: LocalDatabaseMigration) => {+ database.exec('BEGIN IMMEDIATE');++ try {+ for (const statement of migration.statements) database.exec(statement);++ database+ .prepare(+ `INSERT INTO ${MIGRATIONS_TABLE} (version, name, checksum, applied_at) VALUES (?, ?, ?, ?)`,+ )+ .run(migration.version, migration.name, migrationChecksum(migration), Date.now());+ database.exec('COMMIT');+ } catch (error) {+ if (database.isTransaction) database.exec('ROLLBACK');+ throw error;+ }+};++export const runLocalDatabaseMigrations = (+ database: DatabaseSync,+ migrations: readonly LocalDatabaseMigration[] = localDatabaseMigrations,+): void => {+ validateManifest(migrations);+ initializeMigrationTable(database);++ const appliedMigrations = readAppliedMigrations(database);+ validateAppliedMigrations(appliedMigrations, migrations);+ const appliedVersions = new Set(appliedMigrations.map(({ version }) => version));++ for (const migration of migrations) {+ if (!appliedVersions.has(migration.version)) applyMigration(database, migration);+ }+};diff --git a/apps/desktop/src/main/database/migrations/types.ts b/apps/desktop/src/main/database/migrations/types.tsnew file mode 100644index 00000000000..0c2c36e652c--- /dev/null+++ b/apps/desktop/src/main/database/migrations/types.ts@@ -0,0 +1,8 @@+export interface LocalDatabaseMigration {+ /** Stable human-readable identifier recorded in the database. */+ name: string;+ /** Ordered SQL statements applied atomically for this version. */+ statements: readonly string[];+ /** Immutable, monotonically increasing schema version. */+ version: number;+}diff --git a/apps/desktop/src/main/database/schema.ts b/apps/desktop/src/main/database/schema.tsnew file mode 100644index 00000000000..81018be8fcc--- /dev/null+++ b/apps/desktop/src/main/database/schema.ts@@ -0,0 +1,8 @@+import { sqliteTable, text } from 'drizzle-orm/sqlite-core';++export const localRecords = sqliteTable('local_records', {+ id: text('id').primaryKey().notNull(),+ value: text('value').notNull(),+});++export const localDatabaseSchema = { localRecords };diff --git a/apps/desktop/src/main/services/LocalDatabaseSrv.ts b/apps/desktop/src/main/services/LocalDatabaseSrv.tsnew file mode 100644index 00000000000..4e1306c1fcb--- /dev/null+++ b/apps/desktop/src/main/services/LocalDatabaseSrv.ts@@ -0,0 +1,110 @@+import path from 'node:path';++import type {+ DesktopLocalDatabaseBatchOperation,+ DesktopLocalDatabaseEntry,+} from '@lobechat/electron-client-ipc';+import { and, asc, eq, gte, lt } from 'drizzle-orm';++import { createLocalDatabaseRuntime, type LocalDatabaseRuntime } from '@/database/client';+import { localRecords } from '@/database/schema';+import { createLogger } from '@/utils/logger';++import { ServiceModule } from './index';++const logger = createLogger('services:LocalDatabaseSrv');+const DATABASE_FILENAME = 'local-database.sqlite3';+const PREFIX_UPPER_BOUND = '\u{10FFFF}';++const collectionPrefix = (collection: string) => `${collection.length}:${collection}`;+const storageKey = (collection: string, key: string) => `${collectionPrefix(collection)}${key}`;+const prefixRange = (collection: string, prefix: string) => {+ const lowerBound = storageKey(collection, prefix);+ return { lowerBound, upperBound: `${lowerBound}${PREFIX_UPPER_BOUND}` };+};++export default class LocalDatabaseService extends ServiceModule {+ private runtime: LocalDatabaseRuntime | null = null;++ initialize(): void {+ if (this.runtime) return;++ const databasePath = path.join(this.app.appStoragePath, DATABASE_FILENAME);+ this.runtime = createLocalDatabaseRuntime(databasePath);+ logger.info('Local database initialized');+ }++ async batch(operations: DesktopLocalDatabaseBatchOperation[]): Promise<void> {+ if (operations.length === 0) return;++ await this.getRuntime().db.transaction(async (tx) => {+ for (const operation of operations) {+ const id = storageKey(operation.collection, operation.key);++ if (operation.type === 'delete') {+ await tx.delete(localRecords).where(eq(localRecords.id, id)).run();+ } else {+ await tx+ .insert(localRecords)+ .values({ id, value: operation.value })+ .onConflictDoUpdate({ set: { value: operation.value }, target: localRecords.id })+ .run();+ }+ }+ });+ }++ async delete(collection: string, key: string): Promise<void> {+ await this.getRuntime()+ .db.delete(localRecords)+ .where(eq(localRecords.id, storageKey(collection, key)))+ .run();+ }++ async deleteByPrefix(collection: string, prefix: string): Promise<void> {+ const { lowerBound, upperBound } = prefixRange(collection, prefix);+ await this.getRuntime()+ .db.delete(localRecords)+ .where(and(gte(localRecords.id, lowerBound), lt(localRecords.id, upperBound)))+ .run();+ }++ async entriesByPrefix(collection: string, prefix: string): Promise<DesktopLocalDatabaseEntry[]> {+ const { lowerBound, upperBound } = prefixRange(collection, prefix);+ const rows = await this.getRuntime()+ .db.select({ id: localRecords.id, value: localRecords.value })+ .from(localRecords)+ .where(and(gte(localRecords.id, lowerBound), lt(localRecords.id, upperBound)))+ .orderBy(asc(localRecords.id));+ const keyOffset = collectionPrefix(collection).length;++ return rows.map(({ id, value }) => ({ key: id.slice(keyOffset), value }));+ }++ async get(collection: string, key: string): Promise<string | undefined> {+ const [row] = await this.getRuntime()+ .db.select({ value: localRecords.value })+ .from(localRecords)+ .where(eq(localRecords.id, storageKey(collection, key)))+ .limit(1);+ return row?.value;+ }++ async set(collection: string, key: string, value: string): Promise<void> {+ await this.getRuntime()+ .db.insert(localRecords)+ .values({ id: storageKey(collection, key), value })+ .onConflictDoUpdate({ set: { value }, target: localRecords.id })+ .run();+ }++ destroy = (): void => {+ this.runtime?.database.close();+ this.runtime = null;+ };++ private getRuntime(): LocalDatabaseRuntime {+ this.initialize();+ return this.runtime!;+ }+}diff --git a/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts b/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.tsnew file mode 100644index 00000000000..77ae6644325--- /dev/null+++ b/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts@@ -0,0 +1,86 @@+import { mkdtemp, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import LocalDatabaseService from '../LocalDatabaseSrv';++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({ info: vi.fn() }),+}));++describe('LocalDatabaseService', () => {+ let storagePath: string;+ let service: LocalDatabaseService;++ beforeEach(async () => {+ storagePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-local-database-'));+ service = new LocalDatabaseService({ appStoragePath: storagePath } as App);+ });++ afterEach(async () => {+ service.destroy();+ await rm(storagePath, { force: true, recursive: true });+ });++ it('isolates collections and supports prefix queries and deletes', async () => {+ await service.set('first', 'scope-a::1', 'first-1');+ await service.set('first', 'scope-a::2', 'first-2');+ await service.set('first', 'scope-b::1', 'first-3');+ await service.set('second', 'scope-a::1', 'second-1');++ await expect(service.entriesByPrefix('first', 'scope-a::')).resolves.toEqual([+ { key: 'scope-a::1', value: 'first-1' },+ { key: 'scope-a::2', value: 'first-2' },+ ]);++ await service.deleteByPrefix('first', 'scope-a::');++ await expect(service.entriesByPrefix('first', '')).resolves.toEqual([+ { key: 'scope-b::1', value: 'first-3' },+ ]);+ await expect(service.get('second', 'scope-a::1')).resolves.toBe('second-1');+ });++ it('preserves keys when collection names contain key-like delimiters', async () => {+ await service.set('cache:1', ':scope::1', 'first');+ await service.set('cache', '1:scope::1', 'second');++ await expect(service.entriesByPrefix('cache:1', ':scope::')).resolves.toEqual([+ { key: ':scope::1', value: 'first' },+ ]);+ await expect(service.entriesByPrefix('cache', '1:scope::')).resolves.toEqual([+ { key: '1:scope::1', value: 'second' },+ ]);+ });++ it('commits mixed batch operations atomically', async () => {+ await service.set('cache', 'legacy', 'old');+ await service.batch([+ { collection: 'cache', key: 'replacement', type: 'set', value: 'new' },+ { collection: 'cache', key: 'legacy', type: 'delete' },+ ]);++ await expect(service.get('cache', 'legacy')).resolves.toBeUndefined();+ await expect(service.get('cache', 'replacement')).resolves.toBe('new');+ });++ it('rolls back the entire batch when one operation fails', async () => {+ await expect(+ service.batch([+ { collection: 'cache', key: 'first', type: 'set', value: 'written-before-error' },+ {+ collection: 'cache',+ key: 'invalid',+ type: 'set',+ value: null as unknown as string,+ },+ ]),+ ).rejects.toThrow();++ await expect(service.get('cache', 'first')).resolves.toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/services/index.ts b/apps/desktop/src/main/services/index.tsindex 7e156902732..0586fa2beb8 100644--- a/apps/desktop/src/main/services/index.ts+++ b/apps/desktop/src/main/services/index.ts@@ -6,4 +6,8 @@ export class ServiceModule {}}-export type IServiceModule = typeof ServiceModule;+export interface ServiceLifecycle {+ destroy?: () => void;+}++export type IServiceModule = new (app: App) => ServiceModule & ServiceLifecycle;diff --git a/package.json b/package.jsonindex 8c262cc81f7..7d0487f2b6b 100644--- a/package.json+++ b/package.json@@ -349,7 +349,6 @@"d3-dsv": "^3.0.1","dayjs": "^1.11.21","debug": "^4.4.3",- "dexie": "^3.2.7","diff": "^8.0.4","discord-api-types": "^0.38.49","drizzle-orm": "^0.45.2",diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.tsindex 7a23c9f269a..c47a6f80152 100644--- a/packages/electron-client-ipc/src/types/index.ts+++ b/packages/electron-client-ipc/src/types/index.ts@@ -5,6 +5,7 @@ export * from './dataSync';export * from './git';export * from './heterogeneousAgent';export * from './imessageBridge';+export * from './localDatabase';export * from './localSystem';export * from './mcpInstall';export * from './notification';diff --git a/packages/electron-client-ipc/src/types/localDatabase.ts b/packages/electron-client-ipc/src/types/localDatabase.tsnew file mode 100644index 00000000000..7c186e0dcc1--- /dev/null+++ b/packages/electron-client-ipc/src/types/localDatabase.ts@@ -0,0 +1,21 @@+export interface DesktopLocalDatabaseKey {+ collection: string;+ key: string;+}++export interface DesktopLocalDatabasePrefix {+ collection: string;+ prefix: string;+}++export interface DesktopLocalDatabaseEntry {+ key: string;+ value: string;+}++export interface DesktopLocalDatabaseSet extends DesktopLocalDatabaseKey {+ value: string;+}++export type DesktopLocalDatabaseBatchOperation =+ (DesktopLocalDatabaseKey & { type: 'delete' }) | (DesktopLocalDatabaseSet & { type: 'set' });diff --git a/src/libs/localDatabase/ARCHITECTURE.md b/src/libs/localDatabase/ARCHITECTURE.mdnew file mode 100644index 00000000000..13abc9d2397--- /dev/null+++ b/src/libs/localDatabase/ARCHITECTURE.md@@ -0,0 +1,62 @@+# Local Database Architecture++The local database is a runtime-neutral persistence boundary. SWR cache persistence is its first+consumer, but the database contract and adapters do not depend on SWR.++```text+Repository / feature+ β+ βΌ+LocalDatabaseAdapter+ ββββββ΄βββββββββββββββ+ βΌ βΌ+IndexedDB Electron IPC+ β+ βΌ+ Drizzle query builder+ β+ βΌ+ node:sqlite+```++## Ownership++| Layer | Responsibility |+| -------------------------------- | --------------------------------------------------------------------- |+| `src/libs/localDatabase` | Runtime-neutral contract, adapter registration, IndexedDB adapter |+| `src/libs/swr/localDataCache.ts` | SWR-specific repository and cache-key semantics |+| `apps/desktop/src/main/database` | SQLite client, Drizzle schema, and migration execution |+| `LocalDatabaseSrv` | Collection-scoped reads and writes expressed through Drizzle builders |+| Electron IPC | Serialization and process-boundary transport only |++## Migration invariants++- Migration manifests are append-only and ordered by increasing integer version.+- A released migration is immutable. Schema corrections use a new migration.+- Every SQLite migration runs in its own `BEGIN IMMEDIATE` transaction.+- Applied SQLite migrations record their version, stable name, checksum, and timestamp.+- Startup rejects unknown newer versions and checksum drift instead of silently mutating history.+- IndexedDB upgrades run inside the browser-provided version-change transaction.+- Data backfills do not belong in schema migrations. Add a resumable, idempotent process when a+ future collection requires retained data.++## Adding a SQLite migration++1. Update `apps/desktop/src/main/database/schema.ts`.+2. Run `pnpm run db:generate:local` from `apps/desktop`.+3. Review the generated SQL, snapshot, and journal under `database/migrations/drizzle`.+4. Give the generated file a stable, descriptive name before the migration is released.+5. Keep statements idempotent where SQLite supports it.+6. Add a migration-runner regression test for the observable schema or data transition.+7. Run the desktop service tests, desktop type check, and main-process production build.++During development, delete and regenerate the latest unreleased migration artifacts when the schema+changes. Delete the local cache database when testing a replacement draft migration. After release,+the migration becomes immutable and all changes require a new version.++## Adding an IndexedDB migration++1. Append a higher version to `indexedDBMigrations.ts`.+2. Keep the migration synchronous so it remains inside `onupgradeneeded`'s active transaction.+3. Use the supplied version-change transaction for data-preserving object-store transformations.+4. Add a regression test for both the upgrade boundary and the resulting store behavior.diff --git a/src/libs/localDatabase/electronAdapter.test.ts b/src/libs/localDatabase/electronAdapter.test.tsnew file mode 100644index 00000000000..97f5738ae80--- /dev/null+++ b/src/libs/localDatabase/electronAdapter.test.ts@@ -0,0 +1,94 @@+import type {+ DesktopLocalDatabaseBatchOperation,+ DesktopLocalDatabaseKey,+ DesktopLocalDatabasePrefix,+ DesktopLocalDatabaseSet,+} from '@lobechat/electron-client-ipc';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createElectronLocalDatabaseAdapter } from './electronAdapter';++const mocks = vi.hoisted(() => ({+ batch: vi.fn(),+ delete: vi.fn(),+ deleteByPrefix: vi.fn(),+ entriesByPrefix: vi.fn(),+ get: vi.fn(),+ initialize: vi.fn(),+ set: vi.fn(),+}));++vi.mock('@/utils/electron/ipc', () => ({+ ensureElectronIpc: () => ({ localDatabase: mocks }),+}));++describe('createElectronLocalDatabaseAdapter', () => {+ const records = new Map<string, string>();+ const recordKey = (collection: string, key: string) => `${collection}\u0000${key}`;++ beforeEach(() => {+ records.clear();+ vi.clearAllMocks();++ mocks.initialize.mockResolvedValue(undefined);+ mocks.get.mockImplementation(async ({ collection, key }: DesktopLocalDatabaseKey) =>+ records.get(recordKey(collection, key)),+ );+ mocks.set.mockImplementation(async ({ collection, key, value }: DesktopLocalDatabaseSet) => {+ records.set(recordKey(collection, key), value);+ });+ mocks.delete.mockImplementation(async ({ collection, key }: DesktopLocalDatabaseKey) => {+ records.delete(recordKey(collection, key));+ });+ mocks.deleteByPrefix.mockImplementation(+ async ({ collection, prefix }: DesktopLocalDatabasePrefix) => {+ const storagePrefix = recordKey(collection, prefix);+ for (const key of records.keys()) if (key.startsWith(storagePrefix)) records.delete(key);+ },+ );+ mocks.entriesByPrefix.mockImplementation(+ async ({ collection, prefix }: DesktopLocalDatabasePrefix) => {+ const collectionPrefix = recordKey(collection, '');+ const storagePrefix = recordKey(collection, prefix);+ return [...records.entries()]+ .filter(([key]) => key.startsWith(storagePrefix))+ .map(([key, value]) => ({ key: key.slice(collectionPrefix.length), value }));+ },+ );+ mocks.batch.mockImplementation(async (operations: DesktopLocalDatabaseBatchOperation[]) => {+ for (const operation of operations) {+ const key = recordKey(operation.collection, operation.key);+ if (operation.type === 'delete') records.delete(key);+ else records.set(key, operation.value);+ }+ });+ });++ it('preserves structured values across the serialized IPC boundary', async () => {+ const adapter = createElectronLocalDatabaseAdapter();+ const value = {+ createdAt: new Date('2026-07-28T00:00:00.000Z'),+ optional: undefined,+ };++ await adapter.initialize();+ await adapter.set('cache', 'item', value);++ await expect(adapter.get('cache', 'item')).resolves.toEqual(value);+ });++ it('supports prefix queries and atomic batch payloads through IPC', async () => {+ const adapter = createElectronLocalDatabaseAdapter();++ await adapter.batch([+ { collection: 'cache', key: 'scope::1', type: 'set', value: { id: 1 } },+ { collection: 'cache', key: 'scope::2', type: 'set', value: { id: 2 } },+ { collection: 'cache', key: 'other::1', type: 'set', value: { id: 3 } },+ ]);++ await expect(adapter.entriesByPrefix('cache', 'scope::')).resolves.toEqual([+ { key: 'scope::1', value: { id: 1 } },+ { key: 'scope::2', value: { id: 2 } },+ ]);+ });+});diff --git a/src/libs/localDatabase/electronAdapter.ts b/src/libs/localDatabase/electronAdapter.tsnew file mode 100644index 00000000000..643a26311f7--- /dev/null+++ b/src/libs/localDatabase/electronAdapter.ts@@ -0,0 +1,49 @@+import type { DesktopLocalDatabaseEntry } from '@lobechat/electron-client-ipc';+import superjson from 'superjson';++import { ensureElectronIpc } from '@/utils/electron/ipc';++import type { LocalDatabaseAdapter, LocalDatabaseBatchOperation } from './types';++const serializeBatchOperation = (operation: LocalDatabaseBatchOperation) => {+ if (operation.type === 'delete') return operation;++ return { ...operation, value: superjson.stringify(operation.value) };+};++export const createElectronLocalDatabaseAdapter = (): LocalDatabaseAdapter => ({+ batch: async (operations) => {+ await ensureElectronIpc().localDatabase.batch(operations.map(serializeBatchOperation));+ },+ delete: async (collection, key) => {+ await ensureElectronIpc().localDatabase.delete({ collection, key });+ },+ deleteByPrefix: async (collection, prefix) => {+ await ensureElectronIpc().localDatabase.deleteByPrefix({ collection, prefix });+ },+ entriesByPrefix: async <T>(collection: string, prefix: string) => {+ const entries = await ensureElectronIpc().localDatabase.entriesByPrefix({+ collection,+ prefix,+ });++ return entries.map(({ key, value }: DesktopLocalDatabaseEntry) => ({+ key,+ value: superjson.parse<T>(value),+ }));+ },+ get: async <T>(collection: string, key: string) => {+ const value = await ensureElectronIpc().localDatabase.get({ collection, key });+ return value === undefined ? undefined : superjson.parse<T>(value);+ },+ initialize: async () => {+ await ensureElectronIpc().localDatabase.initialize();+ },+ set: async (collection, key, value) => {+ await ensureElectronIpc().localDatabase.set({+ collection,+ key,+ value: superjson.stringify(value),+ });+ },+});diff --git a/src/libs/localDatabase/index.test.ts b/src/libs/localDatabase/index.test.tsnew file mode 100644index 00000000000..7e0c6dcf35b--- /dev/null+++ b/src/libs/localDatabase/index.test.ts@@ -0,0 +1,76 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { localDatabase, type LocalDatabaseAdapter, registerLocalDatabaseAdapter } from './index';++describe('localDatabase', () => {+ const collection = 'database-test';+ const otherCollection = 'database-test-other';++ beforeEach(async () => {+ await localDatabase.deleteByPrefix(collection, '');+ await localDatabase.deleteByPrefix(otherCollection, '');+ });++ it('stores values independently across collections', async () => {+ await localDatabase.set(collection, 'shared-key', { source: 'first' });+ await localDatabase.set(otherCollection, 'shared-key', { source: 'second' });++ await expect(localDatabase.get(collection, 'shared-key')).resolves.toEqual({ source: 'first' });+ await expect(localDatabase.get(otherCollection, 'shared-key')).resolves.toEqual({+ source: 'second',+ });+ });++ it('queries and deletes keys by prefix within one collection', async () => {+ await localDatabase.batch([+ { collection, key: 'scope-a::1', type: 'set', value: 1 },+ { collection, key: 'scope-a::2', type: 'set', value: 2 },+ { collection, key: 'scope-b::1', type: 'set', value: 3 },+ ]);++ await expect(localDatabase.entriesByPrefix(collection, 'scope-a::')).resolves.toEqual([+ { key: 'scope-a::1', value: 1 },+ { key: 'scope-a::2', value: 2 },+ ]);++ await localDatabase.deleteByPrefix(collection, 'scope-a::');++ await expect(localDatabase.entriesByPrefix(collection, '')).resolves.toEqual([+ { key: 'scope-b::1', value: 3 },+ ]);+ });++ it('commits mixed writes and deletes as one batch', async () => {+ await localDatabase.set(collection, 'legacy', { value: 'old' });+ await localDatabase.batch([+ { collection, key: 'replacement', type: 'set', value: { value: 'new' } },+ { collection, key: 'legacy', type: 'delete' },+ ]);++ await expect(localDatabase.get(collection, 'legacy')).resolves.toBeUndefined();+ await expect(localDatabase.get(collection, 'replacement')).resolves.toEqual({ value: 'new' });+ });++ it('routes database operations through a registered runtime adapter', async () => {+ const adapter: LocalDatabaseAdapter = {+ batch: vi.fn().mockResolvedValue(undefined),+ delete: vi.fn().mockResolvedValue(undefined),+ deleteByPrefix: vi.fn().mockResolvedValue(undefined),+ entriesByPrefix: vi.fn().mockResolvedValue([]),+ get: vi.fn().mockResolvedValue({ source: 'electron' }),+ initialize: vi.fn().mockResolvedValue(undefined),+ set: vi.fn().mockResolvedValue(undefined),+ };+ const unregister = registerLocalDatabaseAdapter(adapter);++ try {+ await expect(localDatabase.get('runtime', 'key')).resolves.toEqual({ source: 'electron' });+ await localDatabase.set('runtime', 'key', { value: 1 });++ expect(adapter.get).toHaveBeenCalledWith('runtime', 'key');+ expect(adapter.set).toHaveBeenCalledWith('runtime', 'key', { value: 1 });+ } finally {+ unregister();+ }+ });+});diff --git a/src/libs/localDatabase/index.ts b/src/libs/localDatabase/index.tsnew file mode 100644index 00000000000..0d26a87598f--- /dev/null+++ b/src/libs/localDatabase/index.ts@@ -0,0 +1,39 @@+import { createIndexedDBLocalDatabaseAdapter } from './indexedDBAdapter';+import type { LocalDatabaseAdapter, LocalDatabaseBatchOperation } from './types';++export type {+ LocalDatabaseAdapter,+ LocalDatabaseBatchOperation,+ LocalDatabaseEntry,+} from './types';++let activeAdapter: LocalDatabaseAdapter = createIndexedDBLocalDatabaseAdapter();++/**+ * Replace the local database implementation before application initialization.+ * Electron can register a SQLite IPC adapter from its renderer entry point.+ */+export const registerLocalDatabaseAdapter = (adapter: LocalDatabaseAdapter): (() => void) => {+ const previousAdapter = activeAdapter;+ activeAdapter = adapter;++ return () => {+ if (activeAdapter === adapter) activeAdapter = previousAdapter;+ };+};++/** Runtime-neutral local database used by persistence repositories. */+export const localDatabase = {+ batch: (operations: LocalDatabaseBatchOperation[]): Promise<void> =>+ activeAdapter.batch(operations),+ delete: (collection: string, key: string): Promise<void> => activeAdapter.delete(collection, key),+ deleteByPrefix: (collection: string, prefix: string): Promise<void> =>+ activeAdapter.deleteByPrefix(collection, prefix),+ entriesByPrefix: <T>(collection: string, prefix: string) =>+ activeAdapter.entriesByPrefix<T>(collection, prefix),+ get: <T>(collection: string, key: string): Promise<T | undefined> =>+ activeAdapter.get<T>(collection, key),+ initialize: (): Promise<void> => activeAdapter.initialize(),+ set: (collection: string, key: string, value: unknown): Promise<void> =>+ activeAdapter.set(collection, key, value),+};diff --git a/src/libs/localDatabase/indexedDBAdapter.ts b/src/libs/localDatabase/indexedDBAdapter.tsnew file mode 100644index 00000000000..3fbffe035c1--- /dev/null+++ b/src/libs/localDatabase/indexedDBAdapter.ts@@ -0,0 +1,181 @@+import {+ INDEXED_DB_NAME,+ INDEXED_DB_RECORD_STORE,+ INDEXED_DB_VERSION,+ runIndexedDBMigrations,+} from './indexedDBMigrations';+import type {+ LocalDatabaseAdapter,+ LocalDatabaseBatchOperation,+ LocalDatabaseEntry,+} from './types';++interface IndexedDBRecord {+ key: string;+ value: unknown;+}++const COLLECTION_SEPARATOR = '\u0000';++const collectionPrefix = (collection: string) => `${collection}${COLLECTION_SEPARATOR}`;+const storageKey = (collection: string, key: string) => `${collectionPrefix(collection)}${key}`;+const storageRange = (collection: string, prefix: string) => {+ const lowerBound = storageKey(collection, prefix);+ return IDBKeyRange.bound(lowerBound, `${lowerBound}\uFFFF`);+};++const requestResult = <T>(request: IDBRequest<T>): Promise<T> =>+ new Promise((resolve, reject) => {+ request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));+ request.onsuccess = () => resolve(request.result);+ });++const transactionCompletion = (transaction: IDBTransaction): Promise<void> =>+ new Promise((resolve, reject) => {+ transaction.onabort = () =>+ reject(transaction.error ?? new Error('IndexedDB transaction aborted'));+ transaction.onerror = () =>+ reject(transaction.error ?? new Error('IndexedDB transaction failed'));+ transaction.oncomplete = () => resolve();+ });++const openDatabase = (onVersionChange: () => void): Promise<IDBDatabase> =>+ new Promise((resolve, reject) => {+ const request = indexedDB.open(INDEXED_DB_NAME, INDEXED_DB_VERSION);+ let settled = false;++ request.onblocked = () => {+ settled = true;+ reject(new Error('IndexedDB upgrade was blocked by another LobeHub tab'));+ };+ request.onerror = () => {+ settled = true;+ reject(request.error ?? new Error('Unable to open the local database'));+ };+ request.onupgradeneeded = (event) => {+ runIndexedDBMigrations(+ request.result,+ request.transaction!,+ event.oldVersion,+ event.newVersion ?? INDEXED_DB_VERSION,+ );+ };+ request.onsuccess = () => {+ const database = request.result;+ if (settled) {+ database.close();+ return;+ }++ database.onversionchange = () => {+ database.close();+ onVersionChange();+ };+ settled = true;+ resolve(database);+ };+ });++export const createIndexedDBLocalDatabaseAdapter = (): LocalDatabaseAdapter => {+ let databasePromise: Promise<IDBDatabase> | null = null;++ const getDatabase = () => {+ if (!databasePromise) {+ const opening = openDatabase(() => {+ if (databasePromise === opening) databasePromise = null;+ });+ databasePromise = opening;+ void opening.catch(() => {+ if (databasePromise === opening) databasePromise = null;+ });+ }++ return databasePromise;+ };++ const runTransaction = async <T>(+ mode: IDBTransactionMode,+ operation: (store: IDBObjectStore) => IDBRequest<T>,+ ): Promise<T> => {+ const database = await getDatabase();+ const transaction = database.transaction(INDEXED_DB_RECORD_STORE, mode);+ const completion = transactionCompletion(transaction);+ let request: IDBRequest<T>;++ try {+ request = operation(transaction.objectStore(INDEXED_DB_RECORD_STORE));+ } catch (error) {+ transaction.abort();+ await completion.catch(() => undefined);+ throw error;+ }++ const [result] = await Promise.all([requestResult(request), completion]);+ return result;+ };++ return {+ batch: async (operations: LocalDatabaseBatchOperation[]): Promise<void> => {+ if (operations.length === 0) return;++ const database = await getDatabase();+ const transaction = database.transaction(INDEXED_DB_RECORD_STORE, 'readwrite');+ const completion = transactionCompletion(transaction);+ const store = transaction.objectStore(INDEXED_DB_RECORD_STORE);++ try {+ for (const operation of operations) {+ const key = storageKey(operation.collection, operation.key);+ if (operation.type === 'delete') store.delete(key);+ else store.put({ key, value: operation.value } satisfies IndexedDBRecord);+ }+ } catch (error) {+ transaction.abort();+ await completion.catch(() => undefined);+ throw error;+ }++ await completion;+ },++ delete: async (collection: string, key: string): Promise<void> => {+ await runTransaction('readwrite', (store) => store.delete(storageKey(collection, key)));+ },++ deleteByPrefix: async (collection: string, prefix: string): Promise<void> => {+ await runTransaction('readwrite', (store) => store.delete(storageRange(collection, prefix)));+ },++ entriesByPrefix: async <T>(+ collection: string,+ prefix: string,+ ): Promise<LocalDatabaseEntry<T>[]> => {+ const records = await runTransaction<IndexedDBRecord[]>('readonly', (store) =>+ store.getAll(storageRange(collection, prefix)),+ );+ const keyOffset = collectionPrefix(collection).length;++ return records.map((record) => ({+ key: record.key.slice(keyOffset),+ value: record.value as T,+ }));+ },++ get: async <T>(collection: string, key: string): Promise<T | undefined> => {+ const record = await runTransaction<IndexedDBRecord | undefined>('readonly', (store) =>+ store.get(storageKey(collection, key)),+ );+ return record?.value as T | undefined;+ },++ initialize: async (): Promise<void> => {+ await getDatabase();+ },++ set: async (collection: string, key: string, value: unknown): Promise<void> => {+ await runTransaction('readwrite', (store) =>+ store.put({ key: storageKey(collection, key), value } satisfies IndexedDBRecord),+ );+ },+ };+};diff --git a/src/libs/localDatabase/indexedDBMigrations.test.ts b/src/libs/localDatabase/indexedDBMigrations.test.tsnew file mode 100644index 00000000000..9a9666ce475--- /dev/null+++ b/src/libs/localDatabase/indexedDBMigrations.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it, vi } from 'vitest';++import { runIndexedDBMigrations } from './indexedDBMigrations';++describe('runIndexedDBMigrations', () => {+ it('replaces the legacy Dexie store during the version 10 to 11 upgrade', () => {+ const database = {+ createObjectStore: vi.fn(),+ deleteObjectStore: vi.fn(),+ objectStoreNames: ['cache'],+ } as unknown as IDBDatabase;++ runIndexedDBMigrations(database, {} as IDBTransaction, 10, 11);++ expect(database.deleteObjectStore).toHaveBeenCalledWith('cache');+ expect(database.createObjectStore).toHaveBeenCalledWith('records', { keyPath: 'key' });+ });++ it('does not replay migrations that are already reflected by the database version', () => {+ const database = {+ createObjectStore: vi.fn(),+ deleteObjectStore: vi.fn(),+ objectStoreNames: ['records'],+ } as unknown as IDBDatabase;++ runIndexedDBMigrations(database, {} as IDBTransaction, 11, 11);++ expect(database.deleteObjectStore).not.toHaveBeenCalled();+ expect(database.createObjectStore).not.toHaveBeenCalled();+ });+});diff --git a/src/libs/localDatabase/indexedDBMigrations.ts b/src/libs/localDatabase/indexedDBMigrations.tsnew file mode 100644index 00000000000..f9905d7be89--- /dev/null+++ b/src/libs/localDatabase/indexedDBMigrations.ts@@ -0,0 +1,56 @@+export const INDEXED_DB_NAME = 'lobehub-local-data';+export const INDEXED_DB_RECORD_STORE = 'records';++interface IndexedDBMigrationContext {+ database: IDBDatabase;+ transaction: IDBTransaction;+}++interface IndexedDBMigration {+ migrate: (context: IndexedDBMigrationContext) => void;+ name: string;+ version: number;+}++/**+ * Dexie version 1 maps to IndexedDB version 10. Version 11 establishes the+ * runtime-neutral schema and intentionally discards the former SWR cache.+ */+const replaceDexieCacheSchema = {+ migrate: ({ database }) => {+ for (const storeName of Array.from(database.objectStoreNames)) {+ database.deleteObjectStore(storeName);+ }+ database.createObjectStore(INDEXED_DB_RECORD_STORE, { keyPath: 'key' });+ },+ name: 'replace_dexie_cache_schema',+ version: 11,+} satisfies IndexedDBMigration;++/** Append-only browser migration manifest. Released entries are immutable. */+export const indexedDBMigrations = [replaceDexieCacheSchema] as const;+export const INDEXED_DB_VERSION = indexedDBMigrations.at(-1)!.version;++const validateManifest = (migrations: readonly IndexedDBMigration[]) => {+ for (let index = 1; index < migrations.length; index += 1) {+ if (migrations[index].version <= migrations[index - 1].version) {+ throw new Error('IndexedDB migrations must be ordered by increasing version');+ }+ }+};++export const runIndexedDBMigrations = (+ database: IDBDatabase,+ transaction: IDBTransaction,+ oldVersion: number,+ newVersion: number,+ migrations: readonly IndexedDBMigration[] = indexedDBMigrations,+): void => {+ validateManifest(migrations);++ for (const migration of migrations) {+ if (migration.version > oldVersion && migration.version <= newVersion) {+ migration.migrate({ database, transaction });+ }+ }+};diff --git a/src/libs/localDatabase/types.ts b/src/libs/localDatabase/types.tsnew file mode 100644index 00000000000..07eaa526386--- /dev/null+++ b/src/libs/localDatabase/types.ts@@ -0,0 +1,33 @@+export interface LocalDatabaseEntry<T = unknown> {+ key: string;+ value: T;+}++export type LocalDatabaseBatchOperation =+ | {+ collection: string;+ key: string;+ type: 'delete';+ }+ | {+ collection: string;+ key: string;+ type: 'set';+ value: unknown;+ };++/**+ * Runtime-independent local key/value database contract.+ *+ * Collections are logical namespaces rather than physical tables, allowing+ * both IndexedDB and SQLite IPC implementations to expose identical behavior.+ */+export interface LocalDatabaseAdapter {+ batch: (operations: LocalDatabaseBatchOperation[]) => Promise<void>;+ delete: (collection: string, key: string) => Promise<void>;+ deleteByPrefix: (collection: string, prefix: string) => Promise<void>;+ entriesByPrefix: <T>(collection: string, prefix: string) => Promise<LocalDatabaseEntry<T>[]>;+ get: <T>(collection: string, key: string) => Promise<T | undefined>;+ initialize: () => Promise<void>;+ set: (collection: string, key: string, value: unknown) => Promise<void>;+}diff --git a/src/libs/swr/localDataCache.ts b/src/libs/swr/localDataCache.tsindex df12e78f24c..e8149f4a4b6 100644--- a/src/libs/swr/localDataCache.ts+++ b/src/libs/swr/localDataCache.ts@@ -1,47 +1,21 @@/**- * IndexedDB local-first data cache- *- * A scope-partitioned key/value store used as the IndexedDB *tier* of the- * unified SWR cache provider (see `localStorageProvider.ts`). It backs large,- * important business entities (messages, topics, tasks, documents, agents)- * whose history blows past the ~5MB localStorage origin quota.- *- * Why IndexedDB rather than the localStorage SWR provider for these:- * - localStorage has a ~5MB per-origin quota; large entity data exceeds it and- * a quota error there wipes the *entire* SWR cache. IndexedDB offers- * hundreds of MB and stores each entry as an independent row.- *- * The provider reads from this tier at boot (async) and writes through on every- * cache update β consumers never touch it directly.- *- * Every key is partitioned by identity scope (`${userId}:${workspaceId}`) so- * different users / workspaces sharing a browser origin never collide.+ * SWR cache repository backed by the runtime-neutral local database.*/-import type { Table } from 'dexie';+import { localDatabase } from '@/libs/localDatabase';interface CacheRow {data: unknown;- /** Composite key: `${scope}::${serializedSWRKey}` */- key: string;updatedAt: number;- /** App cache version; mismatching rows are ignored on load. */version?: string;}-export interface ScopeEntry {- data: unknown;- /** The SWR key (scope prefix stripped). */+export interface ScopeEntry extends CacheRow {key: string;- updatedAt: number;- version?: string;}-export interface LocalDataCachePutEntry {- data: unknown;+export interface LocalDataCachePutEntry extends CacheRow {/** Full composite key, including the identity scope prefix. */key: string;- updatedAt: number;- version?: string;}export interface LocalDataCacheBatch {@@ -49,101 +23,54 @@ export interface LocalDataCacheBatch {putEntries: LocalDataCachePutEntry[];}-const DB_NAME = 'lobehub-local-data';-const STORE_NAME = 'cache';--const isAvailable = () => typeof indexedDB !== 'undefined';--// Lazily-created singleton Dexie instance. Kept out of module scope so SSR-// imports never touch IndexedDB.-let dbPromise: Promise<Table<CacheRow, string>> | null = null;--const getTable = async () => {- if (!isAvailable()) return null;- if (!dbPromise) {- dbPromise = (async () => {- const { default: Dexie } = await import('dexie');- const db = new Dexie(DB_NAME);- db.version(1).stores({ [STORE_NAME]: 'key, updatedAt' });- return db.table<CacheRow, string>(STORE_NAME);- })();- }- return dbPromise;-};+const CACHE_COLLECTION = 'swr-cache';const scopePrefix = (scope: string) => `${scope}::`;-/**- * Build the composite IndexedDB key from the identity scope and the SWR key.- */+/** Build the composite persistence key from the identity scope and SWR key. */export const buildLocalDataKey = (scope: string, swrKey: unknown): string =>`${scopePrefix(scope)}${typeof swrKey === 'string' ? swrKey : JSON.stringify(swrKey)}`;export const localDataCache = {/**- * Atomically replace persisted cache rows.- *- * Unlike the best-effort single-row helpers below, migration callers need a- * rejection when the transaction cannot commit so they can keep and retry- * the legacy source rows on the next boot.+ * Atomically replace persisted cache rows. Migration callers receive a+ * rejection when the transaction cannot commit so source rows remain+ * available for a later retry.*/- applyBatch: async ({ deleteKeys, putEntries }: LocalDataCacheBatch): Promise<void> => {- const table = await getTable();- if (!table) return;-- await table.db.transaction('rw', table, async () => {- if (putEntries.length > 0) {- await table.bulkPut(- putEntries.map((entry) => ({- data: entry.data,- key: entry.key,- updatedAt: entry.updatedAt,- version: entry.version,- })),- );- }- if (deleteKeys.length > 0) await table.bulkDelete(deleteKeys);- });- },+ applyBatch: ({ deleteKeys, putEntries }: LocalDataCacheBatch): Promise<void> =>+ localDatabase.batch([+ ...putEntries.map(({ key, ...value }) => ({+ collection: CACHE_COLLECTION,+ key,+ type: 'set' as const,+ value,+ })),+ ...deleteKeys.map((key) => ({ collection: CACHE_COLLECTION, key, type: 'delete' as const })),+ ]),- /**- * Remove every entry belonging to a scope. Useful on logout / account switch.- */clearScope: async (scope: string): Promise<void> => {try {- const table = await getTable();- if (!table) return;- await table.where('key').startsWith(scopePrefix(scope)).delete();+ await localDatabase.deleteByPrefix(CACHE_COLLECTION, scopePrefix(scope));} catch {- // best-effort; ignore+ // Cache persistence is best-effort.}},delete: async (key: string): Promise<void> => {try {- const table = await getTable();- if (!table) return;- await table.delete(key);+ await localDatabase.delete(CACHE_COLLECTION, key);} catch {- // best-effort; ignore+ // Cache persistence is best-effort.}},- /**- * Return every entry belonging to a scope, with the scope prefix stripped- * back to the original SWR key. Used to hydrate the in-memory SWR cache.- */entriesByScope: async (scope: string): Promise<ScopeEntry[]> => {try {- const table = await getTable();- if (!table) return [];const prefix = scopePrefix(scope);- const rows = await table.where('key').startsWith(prefix).toArray();- return rows.map((row) => ({- data: row.data,- key: row.key.slice(prefix.length),- updatedAt: row.updatedAt,- version: row.version,+ const entries = await localDatabase.entriesByPrefix<CacheRow>(CACHE_COLLECTION, prefix);+ return entries.map(({ key, value }) => ({+ ...value,+ key: key.slice(prefix.length),}));} catch {return [];@@ -152,9 +79,7 @@ export const localDataCache = {get: async <T>(key: string): Promise<T | undefined> => {try {- const table = await getTable();- if (!table) return undefined;- const row = await table.get(key);+ const row = await localDatabase.get<CacheRow>(CACHE_COLLECTION, key);return row?.data as T | undefined;} catch {return undefined;@@ -163,11 +88,9 @@ export const localDataCache = {set: async (key: string, data: unknown, version?: string): Promise<void> => {try {- const table = await getTable();- if (!table) return;- await table.put({ data, key, updatedAt: Date.now(), version });+ await localDatabase.set(CACHE_COLLECTION, key, { data, updatedAt: Date.now(), version });} catch {- // best-effort; ignore+ // Cache persistence is best-effort.}},};diff --git a/src/spa/entry.desktop.tsx b/src/spa/entry.desktop.tsxindex 23c8f4df7bf..3ed712c2d00 100644--- a/src/spa/entry.desktop.tsx+++ b/src/spa/entry.desktop.tsx@@ -4,12 +4,15 @@ import { RouterProvider } from 'react-router/dom';import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';import { bootTiming } from '@/libs/bootTiming';+import { registerLocalDatabaseAdapter } from '@/libs/localDatabase';+import { createElectronLocalDatabaseAdapter } from '@/libs/localDatabase/electronAdapter';import { createAppRouter } from '@/utils/router';import { startAppInitialization } from './initialize/bootstrap';import { desktopRoutes } from './router/desktopRouter.config';import { createSPARoot } from './runtime';+registerLocalDatabaseAdapter(createElectronLocalDatabaseAdapter());bootTiming.mark('bundle-eval');startAppInitialization();diff --git a/src/spa/entry.popup.tsx b/src/spa/entry.popup.tsxindex 7215a55fb93..762501ff4b0 100644--- a/src/spa/entry.popup.tsx+++ b/src/spa/entry.popup.tsx@@ -4,12 +4,15 @@ import { RouterProvider } from 'react-router/dom';import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';import { bootTiming } from '@/libs/bootTiming';+import { registerLocalDatabaseAdapter } from '@/libs/localDatabase';+import { createElectronLocalDatabaseAdapter } from '@/libs/localDatabase/electronAdapter';import { createAppRouter } from '@/utils/router';import { startAppInitialization } from './initialize/bootstrap';import { popupRoutes } from './router/popupRouter.config';import { createSPARoot } from './runtime';+registerLocalDatabaseAdapter(createElectronLocalDatabaseAdapter());bootTiming.mark('bundle-eval');startAppInitialization();