Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): close plugin approval cleanup races
Yuewei-LL24792dc495fc
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex fab3da2221..43fd9f8ebb 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -3326,7 +3326,7 @@ describe('GhostManager · Host approval receipt', () => {expect(fs.existsSync(snapshotRoot)).toBe(false);});- it('prunes skill snapshots left behind by superseded approval revisions', async () => {+ it('retains skill snapshots left behind by superseded approval revisions', async () => {await manager.install(await makeCindy('skill-v1.cindy', skillManifest(), skillFiles()));const firstSnapshot = manager.list()[0].approvedSkillRoot!;const snapshotParent = path.dirname(firstSnapshot);@@ -3342,9 +3342,9 @@ describe('GhostManager · Host approval receipt', () => {const secondSnapshot = manager.list()[0].approvedSkillRoot!;expect(secondSnapshot).not.toBe(firstSnapshot);- expect(await fs.promises.readdir(snapshotParent)).toEqual([- path.basename(secondSnapshot),- ]);+ expect(new Set(await fs.promises.readdir(snapshotParent))).toEqual(+ new Set([path.basename(firstSnapshot), path.basename(secondSnapshot)]),+ );});it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex e38d3dd92e..4b16a0d2ec 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -97,4 +97,36 @@ describe('GhostInstallReceiptStore cleanup', () => {);expect(await fs.promises.readFile(externalReceipt, 'utf8')).toBe('{}');});++ it('retains stale snapshots instead of using unsafe pathname-based recursive cleanup', async () => {+ const parent = path.join(stateRoot, 'skill-snapshots', 'hello');+ const movedParent = path.join(stateRoot, 'skill-snapshots', 'hello-moved');+ const external = path.join(workDir, 'external-prune-target');+ await fs.promises.mkdir(path.join(parent, 'stale'), { recursive: true });+ await fs.promises.mkdir(path.join(external, 'stale'), { recursive: true });+ await fs.promises.writeFile(path.join(external, 'stale', 'sentinel.txt'), 'keep');+ const verifiedParent = await fs.promises.realpath(parent);++ const realReaddir = fs.promises.readdir;+ let swapped = false;+ vi.spyOn(fs.promises, 'readdir').mockImplementation(async (target, options) => {+ const entries = await realReaddir(target, options as never);+ if (!swapped && path.resolve(String(target)) === path.resolve(verifiedParent)) {+ swapped = true;+ await fs.promises.rename(parent, movedParent);+ await fs.promises.symlink(external, parent, process.platform === 'win32' ? 'junction' : 'dir');+ }+ return entries as never;+ });++ await (store as unknown as {+ pruneStaleSkillSnapshots(receipt: { id: string; revision: string }): Promise<void>;+ }).pruneStaleSkillSnapshots({ id: 'hello', revision: 'current' });++ expect(swapped).toBe(false);+ expect(await fs.promises.readFile(path.join(external, 'stale', 'sentinel.txt'), 'utf8')).toBe(+ 'keep',+ );+ expect(fs.existsSync(path.join(parent, 'stale'))).toBe(true);+ });});diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 4e4d950741..7f0c6e4d05 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -850,6 +850,9 @@ export class GhostInstallReceiptStore {* best-effort:批准事实已经落盘,回收失败只记为待清理状态,不回滚安装。*/private async pruneStaleSkillSnapshots(receipt: GhostInstallReceipt): Promise<void> {+ void receipt;+ return;+ /* Pathname-based recursive deletion cannot close the parent-swap TOCTOU// 父段遏制先行:`<id>` 段被换成 junction 时,readdir 会列出外部目录的条目、// 随后的逐项 recursive rm 就会把**外部目录的内容**删掉(Windows 实测可复现)。// 回收是 best-effort:父段可疑就整体跳过,绝不带着可疑父段动盘。@@ -860,21 +863,47 @@ export class GhostInstallReceiptStore {return;}if (!parent) return;+ let verifiedParent: string;+ try {+ const [realRoot, realParent] = await Promise.all([+ fs.promises.realpath(this.rootDir()),+ fs.promises.realpath(parent),+ ]);+ if (!isPathInsideDir(realRoot, realParent)) return;+ verifiedParent = realParent;+ } catch {+ return;+ }let entries: fs.Dirent[];try {- entries = await fs.promises.readdir(parent, { withFileTypes: true });+ entries = await fs.promises.readdir(verifiedParent, { withFileTypes: true });} catch {return;}await Promise.all(entries.filter((entry) => entry.name !== receipt.revision)- .map((entry) =>- fs.promises- .rm(path.join(parent, entry.name), { recursive: true, force: true })- .catch(() => undefined),- ),- );+ .map(async (entry) => {+ try {+ // Re-validate the managed parent immediately before each destructive+ // child removal: another process may have swapped the lexical+ // snapshot parent for a symlink/junction after the initial check.+ const [realRoot, currentParent] = await Promise.all([+ fs.promises.realpath(this.rootDir()),+ fs.promises.realpath(parent),+ ]);+ if (currentParent !== verifiedParent || !isPathInsideDir(realRoot, currentParent)) {+ return;+ }+ await fs.promises.rm(path.join(currentParent, entry.name), {+ recursive: true,+ force: true,+ });+ } catch {+ // Best-effort cleanup; a later receipt reconciliation can retry.+ }+ }),+ ); */}}diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex ab0caafc0d..db37f9df1b 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -942,6 +942,7 @@ export class GhostNodeRuntimeBroker {/** 同 key 在途启动去重:重试退避窗口内的并发请求共享同一次启动,不双开进程。 */private readonly startingWorkers = new Map<string, Promise<WorkerEntry>>();+ private readonly startingWorkerScopes = new Map<string, unknown>();/** stop(ghostId) 置入:在途重试检测到后立即中止,不继续拉新进程。 */private readonly stoppedGhosts = new Set<string>();@@ -971,12 +972,14 @@ export class GhostNodeRuntimeBroker {this.assertOwnerScopeUsable(ghost.manifest.id, existing.ownerScopeSnapshot);return existing;}+ this.startingWorkerScopes.set(key, ownerScopeSnapshot);const starting = this.startWorkerWithRetry(ghost, entryRel, key, ownerScopeSnapshot);this.startingWorkers.set(key, starting);try {return await starting;} finally {this.startingWorkers.delete(key);+ this.startingWorkerScopes.delete(key);}}@@ -1420,6 +1423,14 @@ export class GhostNodeRuntimeBroker {}this.stopWorker(key, entry);}+ if (!hasCurrentWorker) {+ for (const [key, scope] of this.startingWorkerScopes) {+ if (key.startsWith(`${ghostId}::`) && isGhostOwnerScopeUsable(this.deps.ownerScope, scope)) {+ hasCurrentWorker = true;+ break;+ }+ }+ }if (!hasCurrentWorker) this.deps.ownerScope?.onInvalidated?.(ghostId);return false;}diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 2fb68bd24f..9ed17c0d01 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -745,6 +745,7 @@ describe('PluginMarketService migration and defaultInstall', () => {{ghostId: 'cindy-github',version: item.currentRelease.version,+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,officialCindyGithub: true,},);diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 2fb2abc8eb..f444bd5ce1 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -457,6 +457,7 @@ function canBackfillOfficialCindyGithubTrust(record.installed &&record.source === 'market' &&record.manifestDigest !== undefined &&+ installed.approval.state === 'approved' &&!hasCindyOfficialTrustMetadata(installed.dir) &&serverRecordMatchesInstalledGhost(record.pluginId, installed, record));@@ -2040,6 +2041,7 @@ export class PluginMarketService {await installOrUpdateMarketGhostPackage(tempPath, {ghostId: 'cindy-github',version: currentRecord.version,+ expectedInstalledApproval: ghostInstallApprovalToken(currentInstalled.approval),officialCindyGithub: true,});});