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(desktop): 修复安装版与 passive dev 共用数据时无法启动 (#1664)

Dash8823c09f6069
diff --git a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts
index 64814705d2..f7f58adaf1 100644
--- a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';
import {
acquireSchemaMigrationWriterLease,
+ acquireSchemaStartupLease,
SchemaMigrationReaderLeaseLifecycle,
} from '../schemaMigrationLease';
@@ -46,4 +47,66 @@ describe('shared-passive schema lease worker takeover wiring', () => {
rmSync(dir, { recursive: true, force: true });
}
});
+
+ it('packaged fallback acquires a reader and does not acquire a writer', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'cindy-schema-packaged-fallback-'));
+ const dbFilePath = path.join(dir, 'shared.db');
+ const passiveLifecycle = new SchemaMigrationReaderLeaseLifecycle();
+ const packagedLifecycle = new SchemaMigrationReaderLeaseLifecycle();
+ try {
+ expect(passiveLifecycle.ensure(dbFilePath)).toEqual({
+ acquired: true,
+ newlyAcquired: true,
+ });
+ const result = acquireSchemaStartupLease({
+ dbFilePath,
+ packaged: true,
+ sharedPassive: false,
+ readerLifecycle: packagedLifecycle,
+ });
+ expect(result.acquired).toBe(true);
+ if (!result.acquired) throw new Error(result.reason);
+ expect(result.kind).toBe('reader');
+ expect(acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({
+ acquired: false,
+ reason: 'readers-active',
+ activeReaderCount: 2,
+ });
+ result.lease.release();
+ expect(acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({
+ acquired: false,
+ reason: 'readers-active',
+ activeReaderCount: 1,
+ });
+ } finally {
+ packagedLifecycle.release();
+ passiveLifecycle.release();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+ it('allows another reader to join while preserving writer exclusion', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'cindy-schema-packaged-reader-'));
+ const dbFilePath = path.join(dir, 'shared.db');
+ const passiveLifecycle = new SchemaMigrationReaderLeaseLifecycle();
+ const packagedLifecycle = new SchemaMigrationReaderLeaseLifecycle();
+ try {
+ expect(passiveLifecycle.ensure(dbFilePath)).toEqual({
+ acquired: true,
+ newlyAcquired: true,
+ });
+ expect(packagedLifecycle.ensure(dbFilePath)).toEqual({
+ acquired: true,
+ newlyAcquired: true,
+ });
+ expect(acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({
+ acquired: false,
+ reason: 'readers-active',
+ activeReaderCount: 2,
+ });
+ } finally {
+ packagedLifecycle.release();
+ passiveLifecycle.release();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
});
diff --git a/apps/desktop/src/main/localDb/__tests__/schemaStartupPolicy.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaStartupPolicy.test.ts
index 8b092dd59e..0ea3a778fb 100644
--- a/apps/desktop/src/main/localDb/__tests__/schemaStartupPolicy.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/schemaStartupPolicy.test.ts
@@ -53,6 +53,25 @@ describe('runSchemaStartupPolicy', () => {
expect(prepare).not.toHaveBeenCalled();
});
+ it('fails closed when packaged read-only invariants require schema cleanup', async () => {
+ const cleanup = vi.fn();
+ const result = await runSchemaStartupPolicy({
+ sharedPassive: false,
+ readOnly: true,
+ checkCompatibility: () => ({ compatible: true, marker: 'exact' }),
+ checkReadOnlyInvariants: () => ({ compatible: false }),
+ prepareRuntimeManifest: vi.fn(),
+ runMigrations: vi.fn(async () => undefined),
+ handleSchemaDrift: vi.fn(async () => undefined),
+ cleanupSchemaDdl: cleanup,
+ });
+
+ expect(result).toEqual({
+ ready: false,
+ compatibility: { compatible: false, marker: 'exact' },
+ });
+ expect(cleanup).not.toHaveBeenCalled();
+ });
it('prepares identity intent before primary schema maintenance', async () => {
const events: string[] = [];
const result = await runSchemaStartupPolicy({
diff --git a/apps/desktop/src/main/localDb/index.ts b/apps/desktop/src/main/localDb/index.ts
index 0cd5607653..ee26bd2510 100644
--- a/apps/desktop/src/main/localDb/index.ts
+++ b/apps/desktop/src/main/localDb/index.ts
@@ -41,7 +41,7 @@ import { tryRestoreWithFallback, backupDb, restrictLegacyBackupPermissions } fro
import { detectSchemaDrift } from './schemaDriftDetector';
import { repairSchemaDriftWithBackup } from './schemaDriftRepair';
import { reconcileKnownEquivalentMigrationHashes } from './schemaDriftCompatibility';
-import { cleanupStaleOrcaLeadIndex } from './orcaStaleIndexCleanup';
+import { cleanupStaleOrcaLeadIndex, hasStaleOrcaLeadIndex } from './orcaStaleIndexCleanup';
import { reconcileStrandedOrcaLeads } from './orcaStrandedLeadReconcile';
import { initializeCodexHistoryPromptState } from './codexHistoryPromptInit';
import { dialogueWorkspaceRootDir } from './dialogueWorkspace';
@@ -55,11 +55,15 @@ import {
} from './migrationRunner';
import {
acquireSchemaMigrationWriterLease,
+ acquireSchemaStartupLease,
SchemaMigrationReaderLeaseLifecycle,
type SchemaMigrationLease,
} from './schemaMigrationLease';
import { runSchemaStartupPolicy } from './schemaStartupPolicy';
-import { buildSharedDbCompatibilityMessage } from './sharedDbCompatibilityMessage';
+import {
+ buildPackagedReadOnlyCompatibilityMessage,
+ buildSharedDbCompatibilityMessage,
+} from './sharedDbCompatibilityMessage';
import { shouldShowNativeFatalDialog, type EnsureReadyErrorCode } from './fatalDialogPolicy';
import { createLogger } from '../logger';
@@ -146,33 +150,40 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {
const filePath = dbPath(userId);
const passiveSharedUserData = !app.isPackaged && process.env.XDT_PASSIVE_SHARED_USER_DATA === '1';
+ // A packaged release may be launched while a shared passive dev instance is still
+ // open. The passive reader lease must continue to block schema writes, but an
+ // already-compatible database does not need any startup DDL; let the release use
+ // the existing schema in read-only startup mode instead of failing before opening
+ // the database. If compatibility is not exact, the policy below still fails
+ // closed and the user gets the normal update/isolated recovery path.
let startupWriterLease: SchemaMigrationLease | null = null;
let readerLeaseAcquiredThisCall = false;
- if (passiveSharedUserData) {
- const leaseResult = schemaMigrationReaderLeaseLifecycle.ensure(filePath);
- if (!leaseResult.acquired) {
- const message =
- 'passive dev 暂时无法打开共享数据库:另一个实例正在执行 schema migration。' +
- '请稍后重试,或改用 --isolated。';
- showFatalDialog('passive dev 等待数据库迁移', message, 'MIGRATE_FAILED');
- return { ready: false, error: { code: 'MIGRATE_FAILED', message } };
- }
- readerLeaseAcquiredThisCall = leaseResult.newlyAcquired;
- } else {
- const leaseResult = acquireSchemaMigrationWriterLease(filePath);
- if (!leaseResult.acquired) {
- const readerHint = leaseResult.activeReaderCount
- ? `(当前有 ${leaseResult.activeReaderCount} 个 passive 实例)`
- : '';
- const message =
- `当前不能执行数据库 schema 启动维护${readerHint}。` +
+ const startupLease = acquireSchemaStartupLease({
+ dbFilePath: filePath,
+ packaged: app.isPackaged,
+ sharedPassive: passiveSharedUserData,
+ readerLifecycle: schemaMigrationReaderLeaseLifecycle,
+ });
+ if (!startupLease.acquired) {
+ const readerHint = startupLease.activeReaderCount
+ ? `(当前有 ${startupLease.activeReaderCount} 个 passive 实例)`
+ : '';
+ const waitingForWriter = startupLease.reason === 'writer-active';
+ const message = waitingForWriter
+ ? '另一个实例正在执行数据库 schema migration,当前实例无法同时启动维护。请等待迁移完成后重试,或改用 --isolated 启动独立数据。'
+ : `当前不能执行数据库 schema 启动维护${readerHint}。` +
'请先关闭共享该 userData 的 passive dev 后重试,或让这些实例使用 --isolated。';
- showFatalDialog('数据库 schema 正被其它实例使用', message, 'MIGRATE_FAILED');
- return { ready: false, error: { code: 'MIGRATE_FAILED', message } };
- }
- startupWriterLease = leaseResult.lease;
+ showFatalDialog(
+ waitingForWriter ? '数据库 schema 正在维护' : '数据库 schema 正被其它实例使用',
+ message,
+ 'MIGRATE_FAILED',
+ );
+ return { ready: false, error: { code: 'MIGRATE_FAILED', message } };
}
+ const schemaMaintenanceReadOnly = startupLease.kind === 'reader' && !passiveSharedUserData;
+ readerLeaseAcquiredThisCall = startupLease.kind === 'reader' && startupLease.newlyAcquired;
+ if (startupLease.kind === 'writer') startupWriterLease = startupLease.lease;
const releaseSchemaLeasesAfterFailure = (): void => {
startupWriterLease?.release();
@@ -196,19 +207,15 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {
const message = err instanceof Error ? err.message : String(err);
const errCode = (err as { code?: string }).code ?? '';
if (errCode === 'SQLITE_CORRUPT' || /corrupt/i.test(message)) {
- if (passiveSharedUserData) {
- const passiveMessage =
- 'passive dev 检测到共享数据库损坏,但不会在其它实例可能运行时自动恢复。' +
- '请关闭 passive 实例后用 primary 启动恢复,或改用 --isolated。';
- showFatalDialog(
- 'passive dev 无法恢复共享数据库',
- passiveMessage,
- 'DB_CORRUPT_NO_BACKUP',
- );
+ if (passiveSharedUserData || schemaMaintenanceReadOnly) {
+ const readOnlyStartupMessage =
+ '共享数据库当前由其它实例使用,Cindy 不会在其运行期间自动恢复或修改 schema。' +
+ '请关闭共享该 userData 的 passive 实例后重试,或改用 --isolated。';
+ showFatalDialog('共享数据库无法恢复', readOnlyStartupMessage, 'DB_CORRUPT_NO_BACKUP');
releaseSchemaLeasesAfterFailure();
return {
ready: false,
- error: { code: 'DB_CORRUPT_NO_BACKUP', message: passiveMessage },
+ error: { code: 'DB_CORRUPT_NO_BACKUP', message: readOnlyStartupMessage },
};
}
const restored = tryRestoreWithFallback(filePath);
@@ -280,7 +287,9 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {
try {
const schemaStartup = await runSchemaStartupPolicy({
sharedPassive: passiveSharedUserData,
+ readOnly: schemaMaintenanceReadOnly,
checkCompatibility: () => checkMigrationCompatibility(db, getDrizzleDir(), filePath),
+ checkReadOnlyInvariants: () => ({ compatible: !hasStaleOrcaLeadIndex(db) }),
prepareRuntimeManifest: () => {
const prepared = prepareMigrationRuntimeManifest(
filePath,
@@ -303,10 +312,14 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {
});
if (!schemaStartup.ready) {
const compatibility = schemaStartup.compatibility;
- const message = buildSharedDbCompatibilityMessage(compatibility);
+ const message = schemaMaintenanceReadOnly
+ ? buildPackagedReadOnlyCompatibilityMessage(compatibility)
+ : buildSharedDbCompatibilityMessage(compatibility);
log.error(
JSON.stringify({
- event: 'localDb.ensureReady.passiveMigrationMismatch',
+ event: schemaMaintenanceReadOnly
+ ? 'localDb.ensureReady.packagedReadOnlyCompatibilityMismatch'
+ : 'localDb.ensureReady.passiveMigrationMismatch',
userId,
dbPath: filePath,
databaseVersion: compatibility.databaseVersion,
@@ -315,13 +328,19 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {
}),
);
closeDb({ preserveSchemaMigrationLease: !readerLeaseAcquiredThisCall });
- showFatalDialog('当前开发版与本地数据版本不兼容', message, 'MIGRATE_FAILED');
+ showFatalDialog(
+ schemaMaintenanceReadOnly ? '安装版无法打开本地数据' : '当前开发版与本地数据版本不兼容',
+ message,
+ 'MIGRATE_FAILED',
+ );
return { ready: false, error: { code: 'MIGRATE_FAILED', message } };
}
if (schemaStartup.compatibility) {
log.info(
JSON.stringify({
- event: 'localDb.ensureReady.passiveMigrationCompatible',
+ event: schemaMaintenanceReadOnly
+ ? 'localDb.ensureReady.packagedReadOnlyCompatible'
+ : 'localDb.ensureReady.passiveMigrationCompatible',
userId,
dbPath: filePath,
schemaVersion: schemaStartup.compatibility.databaseVersion,
@@ -731,9 +750,7 @@ function showFatalDialog(title: string, detail: string, code: EnsureReadyErrorCo
// MIGRATE_FAILED 由 renderer 的 LocalDbFatalScreen 全屏接管(可安装已暂存更新),
// 不再弹阻塞式原生对话框;错误详情随 ensureReady 的 invoke reply 回渲染层。
if (!shouldShowNativeFatalDialog(code)) {
- log.error(
- JSON.stringify({ event: 'localDb.fatal.rendererOwned', code, title, detail }),
- );
+ log.error(JSON.stringify({ event: 'localDb.fatal.rendererOwned', code, title, detail }));
return;
}
try {
diff --git a/apps/desktop/src/main/localDb/orcaStaleIndexCleanup.ts b/apps/desktop/src/main/localDb/orcaStaleIndexCleanup.ts
index 3b6260cfe1..3523dc1101 100644
--- a/apps/desktop/src/main/localDb/orcaStaleIndexCleanup.ts
+++ b/apps/desktop/src/main/localDb/orcaStaleIndexCleanup.ts
@@ -26,6 +26,22 @@ const log = createLogger('orca-stale-index-cleanup');
const STALE_INDEX_NAME = 'uniq_orca_workflows_lead_session_id';
const MIN_SCHEMA_VERSION = 36;
+export function hasStaleOrcaLeadIndex(db: Database.Database): boolean {
+ try {
+ const versionRow = db
+ .prepare(`SELECT value FROM migration_meta WHERE key='schema_version'`)
+ .get() as { value: string } | undefined;
+ const version = versionRow ? parseInt(versionRow.value, 10) : -1;
+ if (!Number.isFinite(version) || version < MIN_SCHEMA_VERSION) return false;
+ return Boolean(
+ db.prepare(`SELECT 1 FROM sqlite_master WHERE type='index' AND name=?`).get(STALE_INDEX_NAME),
+ );
+ } catch {
+ // Read-only startup cannot repair this invariant, so an unreadable catalog is unsafe.
+ return true;
+ }
+}
+
/**
* 同步执行:在 `ensureReady` 的 runMigrations + schemaDriftRepair 之后调用。
* 不抛错 —— 任何异常都被吞掉记日志,不让兜底清理把启动卡死。
diff --git a/apps/desktop/src/main/localDb/schemaMigrationLease.ts b/apps/desktop/src/main/localDb/schemaMigrationLease.ts
index f7b334dbae..ceb9f629cf 100644
--- a/apps/desktop/src/main/localDb/schemaMigrationLease.ts
+++ b/apps/desktop/src/main/localDb/schemaMigrationLease.ts
@@ -22,6 +22,76 @@ export type AcquireSchemaMigrationLeaseResult =
export type EnsureSchemaMigrationReaderLeaseResult =
{ acquired: true; newlyAcquired: boolean } | { acquired: false; reason: 'writer-active' };
+export type SchemaStartupLeaseResult =
+ | {
+ acquired: true;
+ kind: 'reader' | 'writer';
+ lease: SchemaMigrationLease;
+ newlyAcquired: boolean;
+ }
+ | {
+ acquired: false;
+ reason: 'writer-active' | 'readers-active';
+ activeReaderCount?: number;
+ };
+
+export interface AcquireSchemaStartupLeaseOptions {
+ dbFilePath: string;
+ packaged: boolean;
+ sharedPassive: boolean;
+ readerLifecycle?: SchemaMigrationReaderLeaseLifecycle;
+}
+
+/**
+ * Select the startup lease without deciding how the caller presents failures.
+ * Packaged instances may join existing readers, but only as a reader; this keeps
+ * the actual fallback branch small and directly testable without Electron.
+ */
+export function acquireSchemaStartupLease(
+ options: AcquireSchemaStartupLeaseOptions,
+): SchemaStartupLeaseResult {
+ const readerLifecycle = options.readerLifecycle ?? new SchemaMigrationReaderLeaseLifecycle();
+ if (options.sharedPassive) {
+ const result = readerLifecycle.ensure(options.dbFilePath);
+ return result.acquired
+ ? {
+ acquired: true,
+ kind: 'reader',
+ lease: readerLifecycleLease(readerLifecycle, result),
+ newlyAcquired: result.newlyAcquired,
+ }
+ : result;
+ }
+
+ const writer = acquireSchemaMigrationWriterLease(options.dbFilePath);
+ if (writer.acquired) {
+ return { acquired: true, kind: 'writer', lease: writer.lease, newlyAcquired: true };
+ }
+ if (!options.packaged || writer.reason !== 'readers-active') return writer;
+
+ const packagedReader = readerLifecycle.ensure(options.dbFilePath);
+ return packagedReader.acquired
+ ? {
+ acquired: true,
+ kind: 'reader',
+ lease: readerLifecycleLease(readerLifecycle, packagedReader),
+ newlyAcquired: packagedReader.newlyAcquired,
+ }
+ : packagedReader;
+}
+
+function readerLifecycleLease(
+ lifecycle: SchemaMigrationReaderLeaseLifecycle,
+ result: EnsureSchemaMigrationReaderLeaseResult,
+): SchemaMigrationLease {
+ return {
+ kind: 'reader',
+ release: () => {
+ if ('newlyAcquired' in result && result.newlyAcquired) lifecycle.release();
+ },
+ };
+}
+
interface LeaseOwner {
pid: number;
token: string;
diff --git a/apps/desktop/src/main/localDb/schemaStartupPolicy.ts b/apps/desktop/src/main/localDb/schemaStartupPolicy.ts
index bea0cdd83c..b407785c89 100644
--- a/apps/desktop/src/main/localDb/schemaStartupPolicy.ts
+++ b/apps/desktop/src/main/localDb/schemaStartupPolicy.ts
@@ -1,17 +1,24 @@
/**
* localDb schema 启动阶段的确定性编排。
*
- * shared passive 只允许先做兼容性核对,绝不执行 migration、drift repair 或其它
- * schema DDL;primary / packaged 则按既有顺序完成维护并发布 runtime manifest。
+ * shared passive 与 packaged readOnly 只允许先做兼容性/只读不变量核对,绝不执行
+ * migration、drift repair 或其它 schema DDL;primary / packaged writer 则按既有顺序
+ * 完成维护并发布 runtime manifest。
*/
export interface SchemaCompatibilityResult {
compatible: boolean;
}
+export interface SchemaReadOnlyInvariantCheck {
+ compatible: boolean;
+}
+
interface RunSchemaStartupPolicyOptions<T extends SchemaCompatibilityResult> {
sharedPassive: boolean;
+ readOnly?: boolean;
checkCompatibility: () => T;
+ checkReadOnlyInvariants?: () => SchemaReadOnlyInvariantCheck;
prepareRuntimeManifest: () => void;
runMigrations: () => Promise<void>;
handleSchemaDrift: () => Promise<void>;
@@ -24,8 +31,17 @@ export type SchemaStartupPolicyResult<T extends SchemaCompatibilityResult> =
export async function runSchemaStartupPolicy<T extends SchemaCompatibilityResult>(
options: RunSchemaStartupPolicyOptions<T>,
): Promise<SchemaStartupPolicyResult<T>> {
- if (options.sharedPassive) {
+ if (options.sharedPassive || options.readOnly) {
const compatibility = options.checkCompatibility();
+ if (options.readOnly) {
+ if (!compatibility.compatible || !options.checkReadOnlyInvariants) {
+ return { ready: false, compatibility: { ...compatibility, compatible: false } };
+ }
+ const invariant = options.checkReadOnlyInvariants();
+ if (!invariant.compatible) {
+ return { ready: false, compatibility: { ...compatibility, compatible: false } };
+ }
+ }
return compatibility.compatible
? { ready: true, compatibility }
: { ready: false, compatibility };
diff --git a/apps/desktop/src/main/localDb/sharedDbCompatibilityMessage.ts b/apps/desktop/src/main/localDb/sharedDbCompatibilityMessage.ts
index f7c23ef9dc..e2338d203c 100644
--- a/apps/desktop/src/main/localDb/sharedDbCompatibilityMessage.ts
+++ b/apps/desktop/src/main/localDb/sharedDbCompatibilityMessage.ts
@@ -1,14 +1,24 @@
/**
- * 共享 userData 的 passive dev 遇到 migration 兼容性失败时的恢复说明。
+ * shared userData 的 passive dev 与 packaged read-only 启动遇到 migration 兼容性失败时的恢复说明。
*
* 只有 checkout 存在待迁移 schema 时才能建议切换为 primary 执行 migration;
* 历史记录或运行时身份不一致必须改用兼容 checkout 或隔离数据库。
*/
-import type {
- MigrationCompatibilityIssue,
- MigrationCompatibilityReport,
-} from './migrationRunner';
+import type { MigrationCompatibilityIssue, MigrationCompatibilityReport } from './migrationRunner';
+
+export function buildPackagedReadOnlyCompatibilityMessage(
+ compatibility: MigrationCompatibilityReport,
+): string {
+ const issueSummary = compatibility.issues
+ .slice(0, 3)
+ .map((issue) => issue.kind)
+ .join(', ');
+ return (
+ '当前安装版无法安全打开共享数据库。请关闭其它开发实例后重试,或安装包含该本地数据 schema 的更新版本。' +
+ `(详情:${issueSummary || '未知原因'})`
+ );
+}
function hasIssue(
issues: readonly MigrationCompatibilityIssue[],