Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): guard streaming dispatch and drain cancelled downloads
Dash72c9a09f909a
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.tsindex 92d8469b59..7058218fcc 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts@@ -158,7 +158,7 @@ it('restricts redirects, rejects arbitrary paths and isolates owner delivery', aawait fs.rm(root, { recursive: true, force: true });}});-it('cancel reaches only the matching active request', async () => {+it('cancel drains the matching request before acknowledging an immediate same-id retry', async () => {const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));const ghost = {enabled: true,@@ -167,29 +167,57 @@ it('cancel reaches only the matching active request', async () => {} as unknown as InstalledGhost;let started!: () => void;const ready = new Promise<void>((r) => (started = r));+ let finish!: () => void;+ const cleanup = new Promise<void>((r) => (finish = r));+ let calls = 0;const slot = new PluginDownloadSlot({root: (id) => path.join(root, id),scope: () => 'a',getGhost: () => ghost,send: () => {},- download: async (o) =>- new Promise((_, reject) => {- started();- o.signal!.addEventListener('abort', () => reject(Error('aborted')));- }),+ download: async (o) => {+ if (++calls === 1) {+ await new Promise<void>((resolve) => {+ started();+ o.signal!.addEventListener('abort', () => resolve());+ });+ await cleanup;+ throw Error('aborted');+ }+ await fs.writeFile(o.targetPath, 'ok');+ return {+ path: o.targetPath,+ size: 2,+ sha256: o.sha256,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ },});try {- const work = slot.handle('p', {+ const request = {kind: 'start',id: 'x',url: 'https://github.com/file',sha256: 'a'.repeat(64),bytes: 2,- });+ };+ const work = slot.handle('p', request);await ready;- await slot.handle('p', { kind: 'cancel', id: 'x' });+ let acknowledged = false;+ const cancel = slot.handle('p', { kind: 'cancel', id: 'x' }).then(() => {+ acknowledged = true;+ });+ await Promise.resolve();+ expect(acknowledged).toBe(false);+ finish();+ await cancel;expect(await work).toMatchObject({ ok: false, message: '下载已取消' });+ expect(await slot.handle('p', request)).toMatchObject({ ok: true });+ expect(calls).toBe(2);} finally {+ finish();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.tsindex 9a896af804..22fd8bcc6d 100644--- a/apps/desktop/src/main/cindy-brain/downloadSlot.ts+++ b/apps/desktop/src/main/cindy-brain/downloadSlot.ts@@ -124,7 +124,9 @@ export class PluginDownloadSlot {const scope = this.deps.scope(),key = JSON.stringify([scope, id, p.id]);if (p.kind === 'cancel') {- this.active.get(key)?.controller.abort();+ const item = this.active.get(key);+ item?.controller.abort();+ await item?.promise;return { ok: true };}if (diff --git a/apps/desktop/src/main/downloader/__tests__/streaming.test.ts b/apps/desktop/src/main/downloader/__tests__/streaming.test.tsindex e881cdc9fa..192ed0986d 100644--- a/apps/desktop/src/main/downloader/__tests__/streaming.test.ts+++ b/apps/desktop/src/main/downloader/__tests__/streaming.test.ts@@ -3,8 +3,13 @@ import os from 'node:os';import path from 'node:path';import { createHash } from 'node:crypto';import { afterEach, expect, it, vi } from 'vitest';-const mocks = vi.hoisted(() => ({ fetch: vi.fn() }));-vi.mock('electron', () => ({ net: { fetch: mocks.fetch } }));+const mocks = vi.hoisted(() => ({ fetch: vi.fn(), release: vi.fn(async () => {}) }));+vi.mock('../../maker-host/outbound-fetch', () => ({+ guardedOutboundFetch: async (url: string, init: RequestInit, beforeDispatch: () => void) => {+ beforeDispatch();+ return { response: await mocks.fetch(url, init), release: mocks.release };+ },+}));import { executeStreaming } from '../streaming';import { readMeta, writeMeta } from '../resume';import { withRetry } from '../retry';@@ -33,6 +38,74 @@ it('cancellation while waiting for data cannot publish a completed artifact', asawait rejected;await expect(fs.stat(opts.targetPath)).rejects.toMatchObject({ code: 'ENOENT' });}));++it('rechecks caller policy after address resolution and does not dispatch or retry a revoked caller', async () =>+ fixture(async (_, opts) => {+ mocks.fetch.mockReset();+ let validations = 0;+ const onRetry = vi.fn();+ await expect(+ withRetry(+ () =>+ execute({+ ...opts,+ validateUrl: () => {+ if (++validations === 2) throw Error('caller revoked');+ },+ }),+ { logger: {}, onRetry },+ ),+ ).rejects.toMatchObject({ code: 'INVALID_ARG' });+ expect(validations).toBe(2);+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(onRetry).not.toHaveBeenCalled();+ }));++it('cancels a resumed prefix hash and releases the response before settling', async () =>+ fixture(async (_, opts) => {+ const nodeFs = await import('node:fs');+ const { PassThrough, addAbortSignal } = await import('node:stream');+ await fs.writeFile(opts.targetPath + '.part', 'abc');+ writeMeta(opts.targetPath, {+ url: opts.url,+ expectedSize: 6,+ expectedSha256: opts.sha256,+ downloadedBytes: 3,+ etag: null,+ lastModified: null,+ createdAt: '',+ updatedAt: '',+ });+ const abort = new AbortController();+ let entered!: () => void;+ const ready = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const stream = new PassThrough();+ vi.spyOn(nodeFs.default, 'createReadStream').mockImplementation(((+ _path: unknown,+ options: { signal: AbortSignal },+ ) => {+ addAbortSignal(options.signal, stream);+ entered();+ return stream;+ }) as any);+ mocks.release.mockClear();+ mocks.fetch.mockReset().mockResolvedValue(+ new Response('def', {+ status: 206,+ headers: { 'content-range': 'bytes 3-5/6' },+ }),+ );+ const result = execute({ ...opts, signal: abort.signal });+ const rejected = expect(result).rejects.toMatchObject({ code: 'ABORTED' });+ await ready;+ abort.abort();+ await rejected;+ expect(stream.destroyed).toBe(true);+ expect(mocks.release).toHaveBeenCalledOnce();+ await expect(fs.stat(opts.targetPath)).rejects.toMatchObject({ code: 'ENOENT' });+ }));async function fixture(run: (root: string, opts: any) => Promise<void>) {const root = await fs.mkdtemp(path.join(os.tmpdir(), 'download-stream-test-'));const body = Buffer.from('abcdef');@@ -110,7 +183,12 @@ it('validates each redirect and never sends credentials', async () =>await expect(execute({ ...opts, validateUrl: (u: string) => urls.push(u) }),).resolves.toMatchObject({ size: 6 });- expect(urls).toEqual([opts.url, 'https://cdn.invalid/file']);+ expect(urls).toEqual([+ opts.url,+ opts.url,+ 'https://cdn.invalid/file',+ 'https://cdn.invalid/file',+ ]);for (const [, request] of mocks.fetch.mock.calls)expect(request).toMatchObject({ credentials: 'omit', redirect: 'manual' });}));diff --git a/apps/desktop/src/main/downloader/integrity.ts b/apps/desktop/src/main/downloader/integrity.tsindex cee40f51f5..7a4eb836fb 100644--- a/apps/desktop/src/main/downloader/integrity.ts+++ b/apps/desktop/src/main/downloader/integrity.ts@@ -51,7 +51,10 @@ export interface StreamingHasher {* prime, once via update()), producing a guaranteed CHECKSUM mismatch on every* resume — and CHECKSUM is non-retryable, so the whole download dies.*/-export function createStreamingHasher(existingPartPath: string | null): StreamingHasher {+export function createStreamingHasher(+ existingPartPath: string | null,+ signal?: AbortSignal,+): StreamingHasher {const hash = crypto.createHash('sha256');let primed: Promise<void>;@@ -73,6 +76,7 @@ export function createStreamingHasher(existingPartPath: string | null): Streaminreturn;}const stream = fs.createReadStream(existingPartPath, {+ signal,start: 0,end: priorSize - 1, // inclusive — pins the read to original EOF});@@ -84,6 +88,9 @@ export function createStreamingHasher(existingPartPath: string | null): Streamin});}+ // Observe early prime rejection even if opening the destination fails first.+ void primed.catch(() => {});+return {/*** Feed a chunk into the streaming hash.@@ -104,10 +111,12 @@ export function createStreamingHasher(existingPartPath: string | null): Streamin*/async update(chunk: Buffer): Promise<void> {await primed;+ signal?.throwIfAborted();hash.update(chunk);},async digest(): Promise<string> {await primed;+ signal?.throwIfAborted();return hash.digest('hex');},};diff --git a/apps/desktop/src/main/downloader/streaming.ts b/apps/desktop/src/main/downloader/streaming.tsindex 6a7ba77927..02ba2ff34e 100644--- a/apps/desktop/src/main/downloader/streaming.ts+++ b/apps/desktop/src/main/downloader/streaming.ts@@ -1,4 +1,4 @@-import { net } from 'electron';+import { guardedOutboundFetch } from '../maker-host/outbound-fetch';import fs from 'node:fs/promises';import path from 'node:path';import type { TransportContext, TransportResult } from './transport';@@ -32,6 +32,7 @@ export async function executeStreaming(ctx: TransportContext): Promise<Transport};let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;let file: fs.FileHandle | undefined;+ let release: (() => Promise<void>) | undefined;try {if (controller.signal.aborted) throw new DownloadError('ABORTED', 'Download cancelled');try {@@ -58,31 +59,42 @@ export async function executeStreaming(ctx: TransportContext): Promise<Transportlet url = opts.url;let response: Response;for (let hop = 0; ; hop++) {- if (controller.signal.aborted) throw new DownloadError('ABORTED', 'Download cancelled');- try {- opts.validateUrl?.(url);- } catch {- // A caller policy refusal cannot be repaired by retrying the same URL.- throw new DownloadError('INVALID_ARG', 'Download URL is not allowed');- }+ const validate = () => {+ controller.signal.throwIfAborted();+ try {+ opts.validateUrl?.(url);+ } catch {+ // A caller policy refusal cannot be repaired by retrying the same URL.+ throw new DownloadError('INVALID_ARG', 'Download URL is not allowed');+ }+ };+ validate();arm(opts.timeout?.connectMs ?? 10_000);- response = await net.fetch(url, {- redirect: 'manual',- credentials: 'omit',- cache: 'no-store',- signal: controller.signal,- headers:- offset === null- ? {}- : {- Range: `bytes=${offset}-`,- ...(previous?.etag || previous?.lastModified- ? { 'If-Range': previous.etag || previous.lastModified! }- : {}),- },- });+ const guarded = await guardedOutboundFetch(+ url,+ {+ credentials: 'omit',+ cache: 'no-store',+ redirect: 'manual',+ signal: controller.signal,+ headers:+ offset === null+ ? {}+ : {+ Range: `bytes=${offset}-`,+ ...(previous?.etag || previous?.lastModified+ ? { 'If-Range': previous.etag || previous.lastModified! }+ : {}),+ },+ },+ validate,+ );+ response = guarded.response;+ release = guarded.release;if (![301, 302, 303, 307, 308].includes(response.status)) break;await response.body?.cancel();+ await release();+ release = undefined;const location = response.headers.get('location');if (!location || hop >= 9) throw new DownloadError('INVALID_ARG', 'Invalid redirect');try {@@ -123,7 +135,10 @@ export async function executeStreaming(ctx: TransportContext): Promise<TransportdeleteMeta(opts.targetPath);throw new DownloadError('CHECKSUM', 'Content length mismatch');}- const hasher = createStreamingHasher(resumed ? partPath(opts.targetPath) : null);+ const hasher = createStreamingHasher(+ resumed ? partPath(opts.targetPath) : null,+ controller.signal,+ );file = await fs.open(partPath(opts.targetPath), resumed ? 'a' : 'w', 0o600);const tracker = new ProgressTracker({initialLoaded: initial,@@ -203,10 +218,12 @@ export async function executeStreaming(ctx: TransportContext): Promise<Transport);throw new DownloadError(diskFailure ? 'DISK' : 'NETWORK', 'Download failed', cause);} finally {+ controller.abort();clearTimeout(timer);opts.signal?.removeEventListener('abort', abort);await reader?.cancel().catch(() => {});reader?.releaseLock();+ await release?.();await file?.close().catch(() => {});}}