Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(plugins): pass Electron SQLite binding to library workers

zqchrisd72a28ac12ae
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryDbWorkerNative.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryDbWorkerNative.test.ts
new file mode 100644
index 0000000000..2d77fcf3b3
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryDbWorkerNative.test.ts
@@ -0,0 +1,73 @@
+/** Real worker + native SQLite regression. Existing core tests bypass worker startup;
+ * they cannot catch a dropped nativeBinding between Main and the worker constructor. */
+import { afterAll, beforeAll, expect, it } from 'vitest';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+import { build } from 'esbuild';
+import { LibrarySqlService } from '../librarySqlService.js';
+
+const moduleRequire = createRequire(import.meta.url);
+const modulePath = moduleRequire.resolve('better-sqlite3');
+const bindingPath = moduleRequire.resolve('better-sqlite3/build/Release/better_sqlite3.node');
+let dir: string;
+let workerPath: string;
+beforeAll(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'cindy-library-native-'));
+ workerPath = path.join(dir, 'libraryDbWorker.mjs');
+ await build({
+ entryPoints: [fileURLToPath(new URL('../libraryDbWorker.ts', import.meta.url))],
+ outfile: workerPath,
+ bundle: true,
+ platform: 'node',
+ format: 'esm',
+ target: 'node22',
+ });
+});
+afterAll(async () => {
+ if (dir) await rm(dir, { recursive: true, force: true });
+});
+
+it('uses the host-selected native binding in a real worker and preserves the default Node path', async () => {
+ for (const nativeBinding of [bindingPath, undefined]) {
+ const service = new LibrarySqlService({
+ workerScriptPath: () => workerPath,
+ betterSqliteModulePath: () => modulePath,
+ betterSqliteNativeBinding: () => nativeBinding,
+ });
+ try {
+ const db = path.join(dir, nativeBinding ? 'explicit.sqlite' : 'default.sqlite');
+ expect(await service.open(db)).toMatchObject({ ok: true });
+ expect(await service.exec(db, 'CREATE TABLE example (value TEXT)')).toMatchObject({
+ ok: true,
+ });
+ expect(await service.exec(db, 'INSERT INTO example VALUES (?)', ['saved'])).toMatchObject({
+ ok: true,
+ });
+ expect(await service.exec(db, 'SELECT value FROM example')).toMatchObject({
+ ok: true,
+ rows: [{ value: 'saved' }],
+ });
+ } finally {
+ await service.dispose();
+ }
+ }
+});
+
+it('does not silently use the root addon when the host-selected binding cannot load', async () => {
+ const service = new LibrarySqlService({
+ workerScriptPath: () => workerPath,
+ betterSqliteModulePath: () => modulePath,
+ betterSqliteNativeBinding: () => path.join(dir, 'missing-electron-binding.node'),
+ });
+ try {
+ expect(await service.open(path.join(dir, 'unavailable.sqlite'))).toMatchObject({
+ ok: false,
+ code: 'DB_ERROR',
+ });
+ } finally {
+ await service.dispose();
+ }
+});
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 483ee2019c..1634ffdec3 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -487,6 +487,7 @@ import { setGhostLibraryFileResolver } from './runtime/electronSandboxAdapter.js
import {
createBetterSqliteDatabase,
resolveBetterSqliteModuleEntry,
+ resolveBetterSqliteNativeBinding,
} from '../localDb/betterSqliteFactory.js';
import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';
import { getSessionFsSnapshot, getSessionRowSnapshot } from '../localDb/ipc/sessions.js';
@@ -6030,6 +6031,7 @@ export function getGhostLibrarySlot(): GhostLibrarySlot {
getDiskFreeBytes: (root) => statfsFreeBytes(root),
workerScriptPath: defaultLibraryDbWorkerPath,
betterSqliteModulePath: () => resolveBetterSqliteModuleEntry() ?? 'better-sqlite3',
+ betterSqliteNativeBinding: resolveBetterSqliteNativeBinding,
log,
syncAgentReadonlyExtraDir: syncMivoLibraryExtraDirFromSlot,
showItemInFolder: (absPath) => {
diff --git a/apps/desktop/src/main/cindy-brain/libraryDbCore.ts b/apps/desktop/src/main/cindy-brain/libraryDbCore.ts
index 4906be494f..2f0c2c6d8b 100644
--- a/apps/desktop/src/main/cindy-brain/libraryDbCore.ts
+++ b/apps/desktop/src/main/cindy-brain/libraryDbCore.ts
@@ -38,7 +38,7 @@ export interface SqliteDatabase {
backup(destination: string): Promise<void>;
transaction<T>(fn: () => T): () => T;
}
-export type SqliteDatabaseConstructor = new (path: string, options?: { readonly?: boolean }) => SqliteDatabase;
+export type SqliteDatabaseConstructor = new (path: string, options?: { readonly?: boolean; nativeBinding?: string }) => SqliteDatabase;
/** 语句门白名单(见文件头第 2 条论证)。 */
const ALLOWED_FIRST_WORDS = new Set([
@@ -141,6 +141,8 @@ export type LibraryDbResult<T> = { ok: true } & T | { ok: false; code: LibraryDb
*/
export function createLibraryDbCore(opts: {
DatabaseCtor: SqliteDatabaseConstructor;
+ /** Trusted host startup configuration, never part of plugin SQL requests. */
+ nativeBinding?: string;
onLog?: (msg: string, meta?: Record<string, unknown>) => void;
}) {
const open: OpenDatabases = {};
@@ -151,7 +153,7 @@ export function createLibraryDbCore(opts: {
async function openDatabase(dbPath: string): Promise<LibraryDbResult<{ opened: true }>> {
if (open[dbPath]) return { ok: true, opened: true };
- const db = new opts.DatabaseCtor(dbPath);
+ const db = new opts.DatabaseCtor(dbPath, opts.nativeBinding ? { nativeBinding: opts.nativeBinding } : undefined);
// 与主库同水位的关键 pragma;cache/mmap 收小(per-plugin 多库并存)。
db.pragma('journal_mode = WAL');
db.pragma('synchronous = NORMAL');
diff --git a/apps/desktop/src/main/cindy-brain/libraryDbWorker.ts b/apps/desktop/src/main/cindy-brain/libraryDbWorker.ts
index 405b908206..483e97b8e7 100644
--- a/apps/desktop/src/main/cindy-brain/libraryDbWorker.ts
+++ b/apps/desktop/src/main/cindy-brain/libraryDbWorker.ts
@@ -19,6 +19,7 @@ import {
interface LibraryDbWorkerStartup {
betterSqliteModulePath?: string;
+ betterSqliteNativeBinding?: string;
}
const workerPort = parentPort;
@@ -39,6 +40,7 @@ function loadDatabaseConstructor(modulePath: string | undefined): SqliteDatabase
const core = createLibraryDbCore({
DatabaseCtor: loadDatabaseConstructor(startup.betterSqliteModulePath),
+ nativeBinding: startup.betterSqliteNativeBinding,
onLog: () => {
/* worker 侧静默;错误经 RPC 结果回传,不落日志(不含用户内容) */
},
diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.ts
index 35480a12a6..de955cb4c9 100644
--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts
@@ -207,6 +207,8 @@ export interface GhostLibrarySlotDeps {
getDiskFreeBytes?(root: string): Promise<number | null>;
workerScriptPath(): string;
betterSqliteModulePath(): string;
+ /** Host-selected Electron ABI binding; never supplied by the plugin. */
+ betterSqliteNativeBinding?(): string | undefined;
log?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
warn: (msg: string, meta?: Record<string, unknown>) => void;
@@ -666,6 +668,7 @@ export class GhostLibrarySlot {
const sql = this.deps.createSqlService({
workerScriptPath: this.deps.workerScriptPath,
betterSqliteModulePath: this.deps.betterSqliteModulePath,
+ betterSqliteNativeBinding: this.deps.betterSqliteNativeBinding,
log: this.deps.log,
});
const record = 'record' in resolution ? resolution.record : undefined;
diff --git a/apps/desktop/src/main/cindy-brain/librarySqlService.ts b/apps/desktop/src/main/cindy-brain/librarySqlService.ts
index e74275cdc7..274d3e8824 100644
--- a/apps/desktop/src/main/cindy-brain/librarySqlService.ts
+++ b/apps/desktop/src/main/cindy-brain/librarySqlService.ts
@@ -27,6 +27,8 @@ export interface LibrarySqlServiceDeps {
workerScriptPath(): string;
/** better-sqlite3 模块绝对路径(生产 = resolveBetterSqliteModuleEntry)。 */
betterSqliteModulePath(): string;
+ /** Separate Electron native binding selected by Main (Node/package default when absent). */
+ betterSqliteNativeBinding?(): string | undefined;
/** 进程内执行体(单测注入;缺省时拉真 worker)。 */
createCore?: (DatabaseCtor: SqliteDatabaseConstructor) => ReturnType<typeof createLibraryDbCore>;
/** 进程内构造器(仅当 createCore 提供时使用;测试直连 require 结果)。 */
@@ -62,7 +64,10 @@ export class LibrarySqlService {
if (this.core) throw new Error('in-process mode has no worker');
if (!this.worker) {
const worker = new Worker(this.deps.workerScriptPath(), {
- workerData: { betterSqliteModulePath: this.deps.betterSqliteModulePath() },
+ workerData: {
+ betterSqliteModulePath: this.deps.betterSqliteModulePath(),
+ betterSqliteNativeBinding: this.deps.betterSqliteNativeBinding?.(),
+ },
});
this.worker = worker;
worker.on('message', (reply: WorkerReply) => {