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(ghost): 安装事务 rename 失败时清理 journal 与隔离标记,并对 Windows 瞬时 EPERM 有界重试(#5026)

ficowang351361019522
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 3d3ea7e998..dcd1590514 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -216,8 +216,20 @@ export interface GhostManagerOptions {
log?: GhostManagerLogger;
/** Test-only stable snapshot mutation seam; production defaults to the worker. */
mutateSnapshot?: ConstructorParameters<typeof GhostInstallReceiptStore>[1];
+ /**
+ * 安装/更新事务里目录整体 rename 的瞬时错误重试策略(#5026)。Windows 上刚解包的目录
+ * 在短窗口内会被杀软扫描或目录监视持有句柄,staging→final 的 rename 吃 EPERM/EBUSY/
+ * EACCES;缺省仅 win32 启用有界退避重试(其它平台的 EPERM 通常是永久性权限问题)。
+ * 只重试 rename 本身,不改事务顺序、安装布局、receipt 与 journal 格式。测试可覆盖。
+ */
+ renameRetry?: { enabled?: boolean; delaysMs?: readonly number[] };
}
+/** Windows 目录句柄竞争的典型瞬时错误码;其它错误码原样上抛,不重试。 */
+const TRANSIENT_RENAME_ERROR_CODES: ReadonlySet<string> = new Set(['EPERM', 'EBUSY', 'EACCES']);
+/** 有界退避:累计约 3s,覆盖 #5026 实测的 5–10s 内非单调句柄释放窗口的大部分场景。 */
+const DEFAULT_RENAME_RETRY_DELAYS_MS: readonly number[] = [100, 200, 400, 800, 1600];
+
/** install / update 的失败分类 —— IPC 层据此映射错误码。 */
export type InstallRejection =
| { code: 'source-not-found'; reason: string }
@@ -533,6 +545,35 @@ export class GhostManager {
return `${this.receiptStore.rootDir()}\u0000${id}`;
}
+ /**
+ * 事务目录 rename(staging→final / final→backup / backup→final)。瞬时错误按
+ * `options.renameRetry` 有界重试;重试耗尽或非瞬时错误照常抛出,由各调用点的
+ * 既有回滚/journal 逻辑处理。不做任何 rm/复制,失败时源目录保持原样。
+ */
+ private async renameManagedDir(from: string, to: string, stage: string, id: string): Promise<void> {
+ const retry = this.options.renameRetry;
+ const enabled = retry?.enabled ?? process.platform === 'win32';
+ const delays = enabled ? (retry?.delaysMs ?? DEFAULT_RENAME_RETRY_DELAYS_MS) : [];
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ await fs.promises.rename(from, to);
+ if (attempt > 0) {
+ this.options.log?.info?.('ghost transaction rename succeeded after transient retry', {
+ id, stage, attempts: attempt + 1,
+ });
+ }
+ return;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (attempt >= delays.length || !code || !TRANSIENT_RENAME_ERROR_CODES.has(code)) throw error;
+ this.options.log?.warn('ghost transaction rename hit transient error; retrying', {
+ id, stage, code, attempt: attempt + 1, delayMs: delays[attempt],
+ });
+ await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
+ }
+ }
+ }
+
constructor(private readonly options: GhostManagerOptions) {
this.receiptStore = new GhostInstallReceiptStore(
() => this.stateRootDir(),
@@ -2711,7 +2752,27 @@ export class GhostManager {
this.untrustedApprovals.delete(this.isolationKey(manifest.id));
throw error;
}
- await fs.promises.rename(stagingDir, finalDir);
+ try {
+ await this.renameManagedDir(stagingDir, finalDir, 'install placement', manifest.id);
+ } catch (error) {
+ // rename 没成功就没有发布任何字节(#5026):此时若留下 install journal 与内存
+ // 隔离标记,之后每次审批检查都会判 invalid、插件停在停用态,且用户手工放入
+ // 目录也没有正常入口恢复。只有确认 finalDir 确实不存在才能清;万一目录已
+ // 出现(rename 半途成功),保留 journal 交给启动恢复,与更新路径的口径一致。
+ if (!fs.existsSync(finalDir)) {
+ try {
+ await this.receiptStore.clearPendingMutation(manifest.id);
+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ } catch (clearError) {
+ // Keep the in-process quarantine while the durable journal remains.
+ this.options.log?.warn('ghost install journal cleanup failed after placement error', {
+ id: manifest.id,
+ error: clearError instanceof Error ? clearError.message : String(clearError),
+ });
+ }
+ }
+ throw error;
+ }
try {
receipt = createGhostInstallReceipt({
manifest: approvedManifest,
@@ -2984,7 +3045,7 @@ export class GhostManager {
};
// 换目录:旧版先挪去备份位,新版 rename 失败即滚回,保证任何时刻都有一份完整版本在位。
try {
- await fs.promises.rename(finalDir, backupDir);
+ await this.renameManagedDir(finalDir, backupDir, 'update backup', manifest.id);
} catch (err) {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
await clearUpdateQuarantineAfterRollback();
@@ -3017,10 +3078,10 @@ export class GhostManager {
);
});
try {
- await fs.promises.rename(stagingDir, finalDir);
+ await this.renameManagedDir(stagingDir, finalDir, 'update placement', manifest.id);
} catch (err) {
let rolledBack = true;
- await fs.promises.rename(backupDir, finalDir).catch((rollbackErr) => {
+ await this.renameManagedDir(backupDir, finalDir, 'update rollback', manifest.id).catch((rollbackErr) => {
rolledBack = false;
(this.options.log?.error ?? this.options.log?.warn)?.call(
this.options.log,
@@ -3096,7 +3157,7 @@ export class GhostManager {
if (sideEffectRolledBack) {
directoryRolledBack = true;
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
- await fs.promises.rename(backupDir, finalDir).catch((rollbackErr) => {
+ await this.renameManagedDir(backupDir, finalDir, 'update receipt rollback', manifest.id).catch((rollbackErr) => {
directoryRolledBack = false;
(this.options.log?.error ?? this.options.log?.warn)?.call(
this.options.log,
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index b93c8ca083..8e1811cd12 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -1547,6 +1547,114 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
});
});
+describe('GhostManager · 安装事务目录 rename 失败(#5026)', () => {
+ const pendingMarkerPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);
+ const managerWithRenameRetry = (renameRetry: { enabled: boolean; delaysMs?: number[] }) =>
+ new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ renameRetry,
+ mutateSnapshot: async (request) => {
+ const { parentDir, ...workerRequest } = request;
+ await runGhostSnapshotWorkerRequest(workerRequest, parentDir);
+ },
+ });
+
+ it('新装 rename 持续 EPERM:事务失败后清掉 journal 与隔离标记,插件可重新安装', async () => {
+ const local = managerWithRenameRetry({ enabled: false });
+ const finalDir = path.join(rootDir, 'hello');
+ const realRename = fs.promises.rename;
+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (path.resolve(String(to)) === path.resolve(finalDir)) {
+ throw Object.assign(new Error('EPERM: operation not permitted, rename'), { code: 'EPERM' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ await expectRejection(await local.install(await makeCindy('a.cindy', goodManifest())), 'io');
+ } finally {
+ spy.mockRestore();
+ }
+ // 没有发布任何字节:journal 与隔离标记都不能留下,否则审批检查持续 invalid、
+ // 插件永远停用且没有正常入口恢复(#5026)。
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(fs.existsSync(finalDir)).toBe(false);
+ expect(local.list()).toEqual([]);
+ expect(fs.readdirSync(rootDir).filter((name) => name.startsWith('.cindy-installing-'))).toEqual([]);
+
+ // 环境恢复后同一插件能正常装上并获得批准。
+ const result = await local.install(await makeCindy('b.cindy', goodManifest()));
+ expect('rejection' in result).toBe(false);
+ expect(local.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('新装 rename 吃到瞬时 EPERM 时有界重试,窗口过去后安装成功', async () => {
+ const local = managerWithRenameRetry({ enabled: true, delaysMs: [1, 1, 1] });
+ const finalDir = path.join(rootDir, 'hello');
+ const realRename = fs.promises.rename;
+ let placementAttempts = 0;
+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (path.resolve(String(to)) === path.resolve(finalDir)) {
+ placementAttempts += 1;
+ if (placementAttempts <= 2) {
+ throw Object.assign(new Error('EPERM: operation not permitted, rename'), { code: 'EPERM' });
+ }
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ const result = await local.install(await makeCindy('a.cindy', goodManifest()));
+ expect('rejection' in result).toBe(false);
+ } finally {
+ spy.mockRestore();
+ }
+ expect(placementAttempts).toBe(3);
+ expect(local.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('非瞬时错误码不重试,重试耗尽后仍如实返回 io 拒绝', async () => {
+ const local = managerWithRenameRetry({ enabled: true, delaysMs: [1, 1] });
+ const finalDir = path.join(rootDir, 'hello');
+ const realRename = fs.promises.rename;
+ let placementAttempts = 0;
+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (path.resolve(String(to)) === path.resolve(finalDir)) {
+ placementAttempts += 1;
+ throw Object.assign(new Error('EXDEV: cross-device link'), { code: 'EXDEV' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ await expectRejection(await local.install(await makeCindy('a.cindy', goodManifest())), 'io');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(placementAttempts).toBe(1);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+
+ const exhausted = managerWithRenameRetry({ enabled: true, delaysMs: [1, 1] });
+ placementAttempts = 0;
+ const spy2 = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (path.resolve(String(to)) === path.resolve(finalDir)) {
+ placementAttempts += 1;
+ throw Object.assign(new Error('EBUSY: resource busy'), { code: 'EBUSY' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ await expectRejection(await exhausted.install(await makeCindy('c.cindy', goodManifest())), 'io');
+ } finally {
+ spy2.mockRestore();
+ }
+ expect(placementAttempts).toBe(3);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+});
+
describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {
const pendingMarkerPath = (id = 'hello') =>
path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);