Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): drain download consumers before cache cleanup
Dash8c1ee4d872a4
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/downloadCache.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/downloadCache.test.tsindex 43bf9dfc4d..e5f783a409 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/downloadCache.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadCache.test.ts@@ -28,7 +28,12 @@ it('shares quota across plugins, protects reserved/pinned files, and revokes eviconst retainedToken = await cache.issue(a, 'owner', 'p', 'approved');cache.release(b);await fs.writeFile(path.join(b, 'artifact'), Buffer.alloc(80000));+ // Filesystem timestamp resolution differs across CI hosts. Establish LRU+ // order explicitly instead of assuming these writes occur in distinct ticks.+ const newer = new Date(Date.now() + 60000);+ await fs.utimes(path.join(b, 'artifact'), newer, newer);await cache.reserve(root, c, 4000);+ await expect(fs.stat(a)).rejects.toMatchObject({ code: 'ENOENT' });await expect(cache.acquire(retainedToken, 'owner', 'p', 'approved')).rejects.toThrow();await expect(cache.acquire(token, 'owner', 'p', 'approved')).rejects.toThrow();cache.release(c);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.tsnew file mode 100644index 0000000000..1256a39ca3--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadLifecycle.test.ts@@ -0,0 +1,61 @@+import { it, expect } from 'vitest';+import fs from 'node:fs';+import path from 'node:path';+import ts from 'typescript';++const source = fs.readFileSync(path.join(__dirname, '..', 'index.ts'), 'utf8');++it('uninstall waits for actual Node exit before removing plugin files and cache', () => {+ const start = source.indexOf('async function uninstallGhostAndCleanupLocked(');+ const body = source.slice(start, source.indexOf('\n}', start));+ const wait = body.indexOf('await getGhostNodeRuntimeBroker().stopAndWait(id)');+ expect(wait).toBeGreaterThan(0);+ expect(body.indexOf('await manager.uninstall(')).toBeGreaterThan(wait);+ expect(body.indexOf('await pluginDownloads.removePlugin(')).toBeGreaterThan(wait);+});++it('quit awaits download drain and Node exit before removing captured anonymous roots', async () => {+ const start = source.indexOf("onQuit('plugin-downloads'");+ const end = source.indexOf("'async');", start) + "'async');".length;+ const js = ts.transpile(source.slice(start, end), { target: ts.ScriptTarget.ES2022 });+ const events: string[] = [];+ let quit!: () => Promise<void>;+ let finish!: () => void;+ const exited = new Promise<void>((resolve) => {+ finish = resolve;+ });+ new Function(+ 'onQuit',+ 'pluginDownloads',+ 'anonymousDownloadRoots',+ 'getGhostNodeRuntimeBroker',+ js,+ )(+ (_name: string, fn: () => Promise<void>, phase: string) => {+ expect(phase).toBe('async');+ quit = fn;+ },+ {+ stopAndWait: async () => {+ events.push('drained');+ },+ removePlugin: async (...args: string[]) => {+ expect(args).toEqual(['p', '/captured-anonymous/p', 'old-scope']);+ events.push('removed');+ },+ },+ new Map([['p', { root: '/captured-anonymous/p', scope: 'old-scope' }]]),+ () => ({+ stopAndWait: async () => {+ events.push('stopping');+ await exited;+ },+ }),+ );+ const work = quit();+ await Promise.resolve();+ expect(events).toEqual(['drained', 'stopping']);+ finish();+ await work;+ expect(events).toEqual(['drained', 'stopping', 'removed']);+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.tsindex 0dc74d894f..dd3dd4b6c5 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts@@ -4,6 +4,66 @@ import os from 'node:os';import path from 'node:path';import { PluginDownloadSlot } from '../downloadSlot';import type { InstalledGhost } from '../../../shared/ghost';+it('shutdown drains cancelled downloads and rejects new downloads and Node handoffs', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'download-shutdown-')));+ let started!: () => void, finish!: () => void;+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ const drained = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => 'anonymous',+ send() {},+ getGhost: () =>+ ({+ enabled: true,+ approval: {},+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ }) as unknown as InstalledGhost,+ download: async (options) => {+ started();+ await new Promise<void>((resolve) =>+ options.signal!.addEventListener('abort', () => resolve(), { once: true }),+ );+ await drained;+ throw Error('aborted');+ },+ });+ const request = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ try {+ const work = slot.handle('p', request);+ await ready;+ let stopped = false;+ const stop = slot.stopAndWait().then(() => {+ stopped = true;+ });+ await Promise.resolve();+ expect(stopped).toBe(false);+ expect(await slot.handle('p', { ...request, id: 'later' })).toMatchObject({ ok: false });+ expect(+ await slot.withNodeDownloads('p', {}, async () => {+ throw Error('must not run');+ }),+ ).toMatchObject({ ok: false });+ finish();+ await stop;+ await work;+ await slot.removePlugin('p');+ await expect(fs.stat(path.join(root, 'p'))).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ finish();+ await fs.rm(root, { recursive: true, force: true });+ }+});it('restricts redirects, rejects arbitrary paths and isolates owner delivery', async () => {const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));let scope = 'a';diff --git a/apps/desktop/src/main/cindy-brain/downloadSlot.ts b/apps/desktop/src/main/cindy-brain/downloadSlot.tsindex 97c2856e6d..bf5210f2d2 100644--- a/apps/desktop/src/main/cindy-brain/downloadSlot.ts+++ b/apps/desktop/src/main/cindy-brain/downloadSlot.ts@@ -14,6 +14,7 @@ export interface PluginDownloadDeps {download(options: DownloadOptions): Promise<DownloadResult>;}export class PluginDownloadSlot {+ private stopped = false;private cache = new PluginDownloadCache();private active = new Map<string,@@ -24,6 +25,11 @@ export class PluginDownloadSlot {this.cache.revokeAll();for (const item of this.active.values()) item.controller.abort();}+ async stopAndWait() {+ this.stopped = true;+ this.abortAll();+ await Promise.allSettled([...this.active.values()].map((item) => item.promise));+ }async removePlugin(id: string, root = this.deps.root(id), scope = this.deps.scope()) {const work = [...this.active].filter(([key]) => {const parts = JSON.parse(key);@@ -43,6 +49,7 @@ export class PluginDownloadSlot {payload: Record<string, unknown>,run: (payload: unknown) => Promise<unknown>,) {+ if (this.stopped) return { ok: false, errorCode: 'INVALID_REQUEST', message: '下载服务已停止' };if (payload.downloadTokens === undefined) return run(payload);const releases: Array<() => void> = [];try {@@ -79,6 +86,7 @@ export class PluginDownloadSlot {downloads[name] = lease.path;}if (+ this.stopped ||this.deps.scope() !== scope ||!this.deps.getGhost(id)?.enabled ||JSON.stringify(this.deps.getGhost(id)?.approval) !== approval@@ -105,6 +113,7 @@ export class PluginDownloadSlot {callerActive: () => boolean = () => true,): Promise<unknown> {try {+ if (this.stopped) throw Error('Download service stopped');if (!value || typeof value !== 'object') throw Error('Invalid download request');const p = value as Record<string, unknown>;if (typeof p.id !== 'string' || !/^[\w-]{1,100}$/.test(p.id))@@ -135,6 +144,7 @@ export class PluginDownloadSlot {throw Error('Download requires node and network.hosts declarations');const approval = JSON.stringify(ghost.approval);const current = () =>+ !this.stopped &&callerActive() &&this.deps.scope() === scope &&this.deps.getGhost(id)?.enabled === true &&diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex da4225a2ab..0b300e1ceb 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -78,6 +78,7 @@ import {type GhostLibraryOverview,} from '../../shared/ghost.js';import { getAppCapabilities } from '../appCapabilities.js';+import { onQuit } from '../lifecycle.js';import { getRemoteOauthContext } from '../plugin-oauth/context.js';import { withGhostSkillProjectionReconcile } from '../authBoundaryQuarantine.js';import {@@ -2675,8 +2676,15 @@ export function getGhostIOSSimulatorSlot(): GhostIOSSimulatorSlot {}let cindySlotSingleton: GhostCindySlot | null = null;+// Capture only roots actually used without an owner; login before quit must not+// redirect cleanup into the newly active account's persistent cache.+const anonymousDownloadRoots = new Map<string, { root: string; scope: string }>();const pluginDownloads = new PluginDownloadSlot({- getGhost: findAvailableGhost, root: id => ownerScopedUserDataPath('plugin-downloads', id),+ getGhost: findAvailableGhost, root: id => {+ const root = ownerScopedUserDataPath('plugin-downloads', id);+ if (!getActiveAppSession().dataOwnerId) anonymousDownloadRoots.set(id, { root, scope: activeOwnerScopeKey() });+ return root;+ },scope: activeOwnerScopeKey, send: sendToGhostLogic, download: createDownloader(),});let networkSlotSingleton: GhostNetworkSlot | null = null;@@ -6478,7 +6486,7 @@ async function uninstallGhostAndCleanupLocked(const libraryDisplayName =manager.list().find((g) => g.manifest.id === id)?.manifest.name ?? id;runtime.stop(id);- getGhostNodeRuntimeBroker().stop(id);+ await getGhostNodeRuntimeBroker().stopAndWait(id);getGhostAgentSlot().clearGhost(id);getGhostErrandSlot().clearGhost(id);getGhostSubscriptionGateway().dropGhost(id);@@ -6859,6 +6867,13 @@ export function registerGhostIpc(): void {runtime.destroyAll();getGhostNodeRuntimeBroker().destroyAll();});+ onQuit('plugin-downloads', async () => {+ await pluginDownloads.stopAndWait();+ await Promise.all([...anonymousDownloadRoots].map(async ([id, { root, scope }]) => {+ await getGhostNodeRuntimeBroker().stopAndWait(id);+ await pluginDownloads.removePlugin(id, root, scope);+ }));+ }, 'async');// Stable-owner 后处理序列:先完成内置插件对账,再恢复常驻插件和旧账号凭证。// 旧凭证迁移保持 best-effort,不阻塞其他插件;任一迁移异常会把本 owner scope