Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): 开放可取消下载与进度接口
Dashf543f1ef5c0b
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.tsnew file mode 100644index 0000000000..4f665ea396--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts@@ -0,0 +1,33 @@+import { it, expect } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { PluginDownloadSlot } from '../downloadSlot';+import type { InstalledGhost } from '../../../shared/ghost';+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';const events:unknown[]=[];+ const ghost={enabled:true,approval:{state:'approved'},manifest:{node:{},network:{hosts:['github.com']}}} as unknown as InstalledGhost;+ let calls=0;+ const slot=new PluginDownloadSlot({root:()=>root,scope:()=>scope,getGhost:()=>ghost,send:(_,e)=>events.push(e),download:async o=>{+ calls++;expect(()=>o.validateUrl!('https://evil.invalid/file')).toThrow();+ expect(()=>o.validateUrl!('http://github.com/file')).toThrow();+ o.onProgress?.({loaded:1,total:2,percent:50,speedBps:1});+ scope='b';return {path:o.targetPath,size:2,sha256:o.sha256,fromCache:false,durationMs:1,resumedFromBytes:0};+ }});+ const req={kind:'start',id:'x',url:'https://github.com/file',sha256:'a'.repeat(64),bytes:2};+ try{+ expect(await slot.handle('p',{...req,targetPath:'/tmp/arbitrary'})).toMatchObject({ok:false});+ expect(calls).toBe(0);+ expect(await slot.handle('p',req)).toMatchObject({ok:false});+ expect(calls).toBe(1);+ expect(events.filter((x:any)=>x.data.phase==='completed')).toHaveLength(0);+ }finally{await fs.rm(root,{recursive:true,force:true});}+});+it('cancel reaches only the matching active request',async()=>{+ const root=await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(),'plugin-download-test-')));+ const ghost={enabled:true,approval:{},manifest:{node:{},network:{hosts:['github.com']}}} as unknown as InstalledGhost;+ let started!:()=>void;const ready=new Promise<void>(r=>started=r);+ const slot=new PluginDownloadSlot({root:()=>root,scope:()=> 'a',getGhost:()=>ghost,send:()=>{},download:async o=>new Promise((_,reject)=>{started();o.signal!.addEventListener('abort',()=>reject(Error('aborted')));})});+ try{const work=slot.handle('p',{kind:'start',id:'x',url:'https://github.com/file',sha256:'a'.repeat(64),bytes:2});await ready;await slot.handle('p',{kind:'cancel',id:'x'});expect(await work).toMatchObject({ok:false,message:'下载已取消'});}finally{await fs.rm(root,{recursive:true,force:true});}+});diff --git a/apps/desktop/src/main/cindy-brain/downloadSlot.ts b/apps/desktop/src/main/cindy-brain/downloadSlot.tsnew file mode 100644index 0000000000..bad5a4f92e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/downloadSlot.ts@@ -0,0 +1,71 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import { ghostNetworkHostMatches, type InstalledGhost } from '../../shared/ghost.js';+import type { DownloadOptions, DownloadResult } from '../downloader/index.js';++/** Verified public artifacts, in the requesting plugin's host-managed cache only. */+export interface PluginDownloadDeps {+ getGhost(id: string): InstalledGhost | null;+ root(id: string): string;+ scope(): string;+ send(id: string, event: unknown): void;+ download(options: DownloadOptions): Promise<DownloadResult>;+}+export class PluginDownloadSlot {+ private active = new Map<string, { controller: AbortController; promise: Promise<unknown>; fingerprint: string }>();+ constructor(private deps: PluginDownloadDeps) {}+ abortAll() { for (const item of this.active.values()) item.controller.abort(); }+ async handle(id: string, value: unknown, callerActive: () => boolean = () => true): Promise<unknown> {+ try {+ 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)) throw Error('Invalid download id');+ const scope = this.deps.scope(), key = JSON.stringify([scope,id,p.id]);+ if (p.kind === 'cancel') { this.active.get(key)?.controller.abort(); return { ok: true }; }+ if (p.kind !== 'start' || Object.keys(p).some(k=>!['type','kind','id','url','sha256','bytes'].includes(k))) throw Error('Invalid download request');+ if (typeof p.url !== 'string' || p.url.length > 8192 || typeof p.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(p.sha256) || !Number.isSafeInteger(p.bytes) || (p.bytes as number)<1 || (p.bytes as number)>2**31) throw Error('URL, SHA-256 and exact size (up to 2 GiB) are required');+ const ghost = this.deps.getGhost(id);+ if (!ghost?.enabled || !ghost.manifest.node || !ghost.manifest.network?.hosts.length) throw Error('Download requires node and network.hosts declarations');+ const approval = JSON.stringify(ghost.approval);+ const current = () => callerActive() && this.deps.scope() === scope && this.deps.getGhost(id)?.enabled === true && JSON.stringify(this.deps.getGhost(id)?.approval) === approval;+ const validateUrl = (raw: string) => {+ if (!current()) throw Error('Download owner or plugin changed');+ const u = new URL(raw);+ if (u.protocol !== 'https:' || u.port || u.username || u.password || !ghost.manifest.network!.hosts.some(h=>ghostNetworkHostMatches(h,u.hostname))) throw Error('Download URL is outside declared HTTPS hosts');+ };+ validateUrl(p.url);+ const fingerprint = JSON.stringify([p.url,p.sha256,p.bytes]);+ const existing = this.active.get(key);+ if (existing) { if(existing.fingerprint!==fingerprint) throw Error('Download id already in use'); return existing.promise; }+ if (this.active.size >= 8) throw Error('Too many active downloads');+ const controller = new AbortController();+ const emit = (data: Record<string, unknown>) => { if(current()) this.deps.send(id,{type:'event',name:'download-progress',data:{id:p.id,...data}}); };+ const promise = (async()=>{+ // Distinct operations cannot share the first caller's signal or progress callback.+ const root = this.deps.root(id), dir = path.join(root,createHash('sha256').update(JSON.stringify([scope,p.id,fingerprint])).digest('hex'));+ await fs.mkdir(dir,{recursive:true});+ if(await fs.realpath(dir)!==path.resolve(dir)) throw Error('Download cache must not contain symbolic links');+ const targetPath = path.join(dir,'artifact');+ for(const file of [targetPath,targetPath+'.part',targetPath+'.meta.json']) {+ try { if(!(await fs.lstat(file)).isFile()) throw Error('Unsafe download cache entry'); } catch(e) { if((e as NodeJS.ErrnoException).code!=='ENOENT') throw e; }+ }+ if(!current() || controller.signal.aborted) throw Error('Download cancelled');+ emit({phase:'queued',loaded:0,total:p.bytes,speedBps:0});+ const watch = setInterval(()=>{if(!current())controller.abort();},250);+ try {+ const result=await this.deps.download({url:p.url as string,targetPath,sha256:p.sha256 as string,expectedSize:p.bytes as number,maxBytes:p.bytes as number,validateUrl,signal:controller.signal,+ logger:{debug(){},info(){},warn(){},error(){}},+ onProgress:e=>emit({phase:'downloading',...e}),onVerifying:()=>emit({phase:'verifying',loaded:p.bytes,total:p.bytes,speedBps:0}),+ onRetry:e=>emit({phase:'retrying',attempt:e.attempt,delayMs:e.delayMs}),+ });+ if(!current() || controller.signal.aborted) throw Error('Download cancelled');+ emit({phase:'completed',loaded:result.size,total:result.size,speedBps:0,fromCache:result.fromCache});+ return {ok:true,path:result.path,bytes:result.size,sha256:result.sha256,fromCache:result.fromCache};+ } finally { clearInterval(watch); }+ })().catch(()=>{emit({phase:controller.signal.aborted?'cancelled':'failed'});return {ok:false,message:controller.signal.aborted?'下载已取消':'下载失败,请重试(网络、权限或文件校验未通过)'};}).finally(()=>this.active.delete(key));+ this.active.set(key,{controller,promise,fingerprint});+ return promise;+ } catch(e) { return {ok:false,message:(e as Error).message}; }+ }+}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 8c46a25c73..5d0867c6fb 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1,3 +1,5 @@+import { PluginDownloadSlot } from './downloadSlot.js';+import { download as downloadPluginArtifact } from '../downloader/index.js';import { registerGhostCardRemoteProvider, persistGhostCardWithRemoteChange } from './cardRemoteResource.js';import { openDeviceAuthorizationCard, openPluginAuthorizationCard } from '../plugin-oauth/deviceCard.js';import { t as authorizationText } from '../i18n.js';@@ -1032,6 +1034,7 @@ export function suspendCindyAccountGhosts(): void {* setup writes, and post-dispatch cleanup cannot cross into the next owner.*/export async function interruptGhostCallsForAccountBoundary(): Promise<void> {+ pluginDownloads.abortAll();cancelActiveGhostOauthFlow();await getBotAuthorizationService()?.dispose();getGhostSetupInteractionBridge()?.cleanupAll('session_aborted');@@ -2672,6 +2675,10 @@ export function getGhostIOSSimulatorSlot(): GhostIOSSimulatorSlot {}let cindySlotSingleton: GhostCindySlot | null = null;+const pluginDownloads = new PluginDownloadSlot({+ getGhost: findAvailableGhost, root: id => ownerScopedUserDataPath('plugin-downloads', id),+ scope: activeOwnerScopeKey, send: sendToGhostLogic, download: downloadPluginArtifact,+});let networkSlotSingleton: GhostNetworkSlot | null = null;let notifySlotSingleton: GhostNotifySlot | null = null;let connectionAudienceResolverSingleton: ConnectionAudienceResolver | null = null;@@ -7135,6 +7142,7 @@ export function registerGhostIpc(): void {return getGhostCindySlot().handleModelRequest(id, payload);}// fetch-request = network 槽代理 HTTP(invoke 返回值即响应,机制同上)。+ if (type === 'download-request') return pluginDownloads.handle(id, payload, () => !event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id);if (type === 'fetch-request') {return getGhostNetworkSlot().handleFetchRequest(id, payload);}diff --git a/apps/desktop/src/main/downloader/transport.ts b/apps/desktop/src/main/downloader/transport.tsindex 9fd1c486d6..9a88438920 100644--- a/apps/desktop/src/main/downloader/transport.ts+++ b/apps/desktop/src/main/downloader/transport.ts@@ -127,7 +127,8 @@ export async function executeOnce(ctx: TransportContext): Promise<TransportResul// ── Step 3: HTTP request via Electron net (auto-respects system proxy) ──return await new Promise<TransportResult>((resolve, reject) => {- const request = net.request({ url: opts.url, method: 'GET', redirect: 'follow' });+ opts.validateUrl?.(opts.url);+ const request = net.request({ url: opts.url, method: 'GET', redirect: opts.validateUrl ? 'manual' : 'follow', ...(opts.validateUrl ? { useSessionCookies: false, credentials: 'omit' as const } : {}) });Object.entries(headers).forEach(([k, v]) => request.setHeader(k, v));let connectTimer: ReturnType<typeof setTimeout> | null = null;@@ -182,7 +183,20 @@ export async function executeOnce(ctx: TransportContext): Promise<TransportResul}, timeout.idleMs);};+ let redirectCount = 0;+ if (opts.validateUrl) request.on('redirect', (_status, _method, redirectUrl) => {+ try {+ if (++redirectCount > 5) throw new Error('Too many redirects');+ opts.validateUrl!(redirectUrl);+ request.followRedirect();+ } catch {+ safeReject(new DownloadError('INVALID_ARG', 'Download redirect rejected'));+ request.abort();+ }+ });request.on('response', (response) => {+ if (settled) return;+if (connectTimer !== null) { clearTimeout(connectTimer); connectTimer = null; }const status = response.statusCode;@@ -271,6 +285,11 @@ export async function executeOnce(ctx: TransportContext): Promise<TransportResul});response.on('data', (chunk: Buffer) => {+ if (settled) return;+ if (opts.maxBytes !== undefined && tracker.getLoaded() + chunk.length > opts.maxBytes) {+ safeReject(new DownloadError('INVALID_ARG', 'Download exceeds declared size'));+ writeStream.destroy(); request.abort(); return;+ }resetIdleTimer();// 1. Persist to disk. Electron's IncomingMessage isn't a Node Readable// stream (no pause/resume/destroy on it directly), so we can't apply@@ -305,6 +324,8 @@ export async function executeOnce(ctx: TransportContext): Promise<TransportResul});response.on('end', () => {+ if (settled) { writeStream.destroy(); return; }+ try { opts.onVerifying?.(); } catch { /* observer only */ }// close the stream and finalizewriteStream.end(() => {(async () => {@@ -312,6 +333,8 @@ export async function executeOnce(ctx: TransportContext): Promise<TransportResulconst finalHash = await hasher.digest();const finalSize = tracker.getLoaded();+ if (settled || opts.signal?.aborted) return;+ if (opts.expectedSize !== undefined && finalSize !== opts.expectedSize) { safeReject(new DownloadError('CHECKSUM', 'Downloaded size mismatch')); return; }if (finalHash !== opts.sha256) {// Corrupt body — wipe both .part and .meta so a future attempt// starts truly fresh (CHECKSUM is not retried inside withRetry).diff --git a/apps/desktop/src/main/downloader/types.ts b/apps/desktop/src/main/downloader/types.tsindex 58974ca2ec..23e49145e6 100644--- a/apps/desktop/src/main/downloader/types.ts+++ b/apps/desktop/src/main/downloader/types.ts@@ -13,6 +13,12 @@ export interface DownloadOptions {/** Absolute target file path on disk. The downloader writes `${targetPath}.part`* during the transfer and renames to `targetPath` after SHA256 passes. */targetPath: string;+ /** Optional caller policy, checked before dispatch and every redirect. */+ validateUrl?: (url: string) => void;+ /** Maximum bytes allowed on disk, including resumed bytes. */+ maxBytes?: number;+ /** Called after all bytes arrive, before checksum verification. */+ onVerifying?: () => void;/** 64-char lowercase hex SHA256 (uppercase accepted, lowercased internally). */sha256: string;/** Optional. When provided, Content-Length must match for fresh downloads. */diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex a144a3401d..864c4d36a6 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -61,6 +61,10 @@ contextBridge.exposeInMainWorld('cindy', {ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'host-request' }),fetch: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fetch-request' }),+ downloads: {+ start: (req: Record<string, unknown>): Promise<unknown> => ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'download-request', kind: 'start' }),+ cancel: (req: Record<string, unknown>): Promise<unknown> => ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'download-request', kind: 'cancel' }),+ },fs: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fs-request' }),library: (req: Record<string, unknown>): Promise<unknown> =>diff --git a/docs/dev-rules/plugin-download-api.md b/docs/dev-rules/plugin-download-api.mdnew file mode 100644index 0000000000..2a82f7aefa--- /dev/null+++ b/docs/dev-rules/plugin-download-api.md@@ -0,0 +1,22 @@+# 插件文件下载接口++逻辑页使用 `cindy.downloads.start({id,url,sha256,bytes})`,取消使用+`cindy.downloads.cancel({id})`。返回结构为+`{ok:true,path,bytes,sha256,fromCache}` 或 `{ok:false,message}`。++插件必须声明 node 与 network.hosts;仅允许已声明 HTTPS 主机,重定向每跳重新检查。+本接口用于匿名公开文件,不携带 Cookie、账号凭证或自定义请求头;带授权请求继续使用 fetch 槽。+SHA-256 与精确字节数必填,单文件最大 2 GiB。目标由宿主管理,不接受本机目标路径。+成功路径可传给本插件 Node 进程读取。缓存由账号、插件、请求身份隔离;id 相同且内容相同可复用缓存。+文件按需保留以支持重试/续传,插件不应生成随机 id 来反复下载同一内容。++通过 onHostMessage 订阅:+`{type:'event',name:'download-progress',data:{id,phase,loaded,total,speedBps}}`。+phase 为 queued/downloading/verifying/retrying/completed/failed/cancelled。+retrying 附带 attempt、delayMs,completed 附带 fromCache。+校验、重试等阶段不保证具有 loaded/total;界面应使用不确定进度,不能伪造百分比。+下载完成仅表示文件校验完成,插件自己的解包/内容验证应另行展示。++账号切换、插件批准身份改变或调用逻辑页销毁后中止下载,不向新账号发送进度。+旧宿主不存在 downloads 对象时,应提示升级;不能假装已接入进度。+现有 fetch、Node、Library 接口不变,存量插件无须迁移。