Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(media): 以分块落盘替代下载大小审批
liugaoweicffcfe984f0f
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.tsindex bc2d8eae4d..f469499732 100644--- a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts@@ -171,6 +171,34 @@ describe('ingestMedia(主路径)', () => {});describe('ingestMedia(全局去重)', () => {+ it('Host 文件分块入库,沿用相同指纹、去重和引用账本,不整体读入内存', async () => {+ const sourcePath = path.join(tmpUserData, 'download-fixture.png');+ fs.writeFileSync(sourcePath, PNG_BYTES);+ const fsp = await import('node:fs/promises');+ const readFile = vi.spyOn(fsp.default, 'readFile');+ const concat = vi.spyOn(Buffer, 'concat');+ try {+ const first = await ingest.ingestMedia({+ filePath: sourcePath, mimeType: 'image/png',+ refs: [{ refKind: 'message', refId: 'download-message', originSessionId: 'download-session' }],+ }, db);+ const second = await ingest.ingestMedia({ buffer: PNG_BYTES, mimeType: 'image/png', refs: [] }, db);+ expect(first.hash).toBe(PNG_HASH);+ expect(first.bytes).toBe(PNG_BYTES.length);+ expect(first.url).toBe(second.url);+ expect(second.deduplicated).toBe(true);+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(1);+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(1);+ expect(readFile).not.toHaveBeenCalled();+ expect(concat).not.toHaveBeenCalled();+ expect(fs.readFileSync(sourcePath)).toEqual(PNG_BYTES);+ } finally {+ readFile.mockRestore();+ concat.mockRestore();+ fs.rmSync(sourcePath, { force: true });+ }+ });+it('cache 先入、非 cache 后到:去重命中时 isCache 降为 false(只降不升)', async () => {await ingest.ingestMedia({ buffer: PNG_BYTES, mimeType: 'image/png', isCache: true, refs: [] },diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.tsindex 39de868bda..a15d14466c 100644--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts@@ -1,3 +1,4 @@+import fs from 'node:fs/promises';import { beforeEach, describe, expect, it, vi } from 'vitest';import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';@@ -718,9 +719,10 @@ describe('Cindy Core media invocation state and security boundary', () => {expect(mocks.rows.get(invocationId)).toMatchObject({ state: 'pending', responseJson: JSON.stringify(payload) });}expect(mocks.ingestMedia).toHaveBeenCalledTimes(3);- const firstBytes = mocks.ingestMedia.mock.calls[0][0].buffer;- expect(firstBytes).toEqual(PNG);- expect(mocks.ingestMedia.mock.calls.every(([input]) => input.buffer === firstBytes)).toBe(true);+ const firstFile = mocks.ingestMedia.mock.calls[0][0].filePath;+ expect(firstFile).toEqual(expect.any(String));+ expect(mocks.ingestMedia.mock.calls.every(([input]) => input.filePath === firstFile && !input.buffer)).toBe(true);+ await expect(fs.stat(firstFile)).rejects.toMatchObject({ code: 'ENOENT' });expect(mocks.guardedOutboundFetch).toHaveBeenCalledOnce();expect(mocks.confirm).toHaveBeenCalledOnce();expect(mocks.outboundFetch.mock.calls.filter(([, init]) => init.method === 'POST')).toHaveLength(1);@@ -1282,39 +1284,34 @@ describe('Cindy Core media invocation state and security boundary', () => {expect(mocks.release).toHaveBeenCalledTimes(2);});- it('用户未允许更大文件时先释放连接再停止,不自动重试', async () => {- mocks.confirm.mockImplementation(async ({ reasons }) => !reasons.includes('size'));- const cancel = vi.fn();- mocks.guide.mockResolvedValue(- resolvedGuide(- operation({- mode: 'sync',- media: [- {- path: ['data'],- encoding: 'url',- kind: 'image',- allowedUrlHosts: ['old.example.com'],- },- ],- }),- ),- );+ it('超过原图片大小限制的 URL 结果直接分块落盘入库,只审批来源一次', async () => {+ mocks.guide.mockResolvedValue(resolvedGuide(operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'url', kind: 'image', allowedUrlHosts: ['old.example.com'] }],+ })));+ const chunk = Buffer.alloc(64 * 1024);+ PNG.copy(chunk);+ let remaining = 33 * 16;mocks.outboundFetch- .mockResolvedValueOnce(- new Response(JSON.stringify({ data: 'https://cdn.example.com/large' })),- )- .mockResolvedValueOnce(- new Response(new ReadableStream({ cancel }), {- headers: { 'content-length': String(33 * 1024 * 1024) },- }),- );- await expect(- callCindyMedia({ action: 'request', invocationId: await prepare(), body: {} }),- ).resolves.toMatchObject({ ok: false, errorCode: 'MEDIA_DOWNLOAD_DENIED' });- expect(cancel).toHaveBeenCalledOnce();+ .mockResolvedValueOnce(new Response(JSON.stringify({ data: 'https://cdn.example.com/large' })))+ .mockResolvedValueOnce(new Response(new ReadableStream({+ pull(controller) {+ if (remaining-- > 0) controller.enqueue(chunk);+ else controller.close();+ },+ })));+ mocks.ingestMedia.mockImplementationOnce(async ({ filePath, buffer, mimeType }) => {+ expect(buffer).toBeUndefined();+ expect(mimeType).toBe('image/png');+ expect((await fs.stat(filePath)).size).toBe(33 * 1024 * 1024);+ return { url: 'cindy-media://blobs/' + 'a'.repeat(64) + '.png' };+ });+ await expect(callCindyMedia({ action: 'request', invocationId: await prepare(), body: {} }))+ .resolves.toMatchObject({ ok: true, status: 'complete' });+ expect(mocks.confirm).toHaveBeenCalledOnce();+ expect(mocks.confirm.mock.calls[0][0].reasons).toEqual(['source']);expect(mocks.release).toHaveBeenCalledOnce();- expect(mocks.ingestMedia).not.toHaveBeenCalled();+ await expect(fs.stat(mocks.ingestMedia.mock.calls[0][0].filePath)).rejects.toMatchObject({ code: 'ENOENT' });});it('DNS 等待期间切号会在 dispatch 前拒绝领取', async () => {diff --git a/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts b/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.tsindex 1402b87daa..aa84931e0f 100644--- a/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts@@ -1,4 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import path from 'node:path';import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';import { downloadMediaResult, type MediaDownloadContext } from '../mediaDownload.js';@@ -12,8 +14,14 @@ function response(body: BodyInit | null = bytes, init?: ResponseInit) {function context(): MediaDownloadContext & { confirm: ReturnType<typeof vi.fn> } {return { assertActive: vi.fn(), approvals: new Set(), confirm: vi.fn(async () => true) };}-function download(ctx?: MediaDownloadContext, raw = 'https://new.example.com/video?signature=secret') {- return downloadMediaResult({ raw, allowedHosts: ['known.example.com'], maxBytes: 1024, context: ctx, assertActive: vi.fn() });+const downloads: Awaited<ReturnType<typeof downloadMediaResult>>[] = [];+async function download(ctx?: MediaDownloadContext, raw = 'https://new.example.com/video?signature=secret') {+ const result = await downloadMediaResult({ raw, allowedHosts: ['known.example.com'], context: ctx, assertActive: vi.fn() });+ downloads.push(result);+ return result;+}+async function downloadedBytes(result: Awaited<ReturnType<typeof download>>) {+ return fs.readFile(result.filePath);}describe('media download approval and network recovery', () => {@@ -24,11 +32,15 @@ describe('media download approval and network recovery', () => {});mocks.release.mockClear();});- afterEach(() => vi.useRealTimers());+ afterEach(async () => {+ await Promise.all(downloads.splice(0).map((result) => result.dispose()));+ vi.restoreAllMocks();+ vi.useRealTimers();+ });it('automatically downloads known sources without asking', async () => {const ctx = context();- expect((await download(ctx, 'https://known.example.com/video')).buffer).toEqual(bytes);+ expect(await downloadedBytes(await download(ctx, 'https://known.example.com/video'))).toEqual(bytes);expect(ctx.confirm).not.toHaveBeenCalled();});@@ -43,7 +55,7 @@ describe('media download approval and network recovery', () => {expect(mocks.fetch).not.toHaveBeenCalled();expect(ctx.confirm).toHaveBeenCalledWith({ origin: 'https://new.example.com', reasons: ['source'] });approve(true);- expect((await pending).buffer).toEqual(bytes);+ expect(await downloadedBytes(await pending)).toEqual(bytes);expect(mocks.fetch.mock.calls[0][1].headers).toBeUndefined();});@@ -60,7 +72,7 @@ describe('media download approval and network recovery', () => {mocks.fetch.mockRejectedValueOnce(new TypeError('connection reset')).mockResolvedValueOnce(response(null, { status: 503 }));const result = await download(ctx);- expect(result.buffer).toEqual(bytes);+ expect(await downloadedBytes(result)).toEqual(bytes);expect(mocks.fetch).toHaveBeenCalledTimes(3);expect(ctx.confirm).toHaveBeenCalledOnce();expect(mocks.release).toHaveBeenCalledTimes(2);@@ -78,7 +90,7 @@ describe('media download approval and network recovery', () => {const ctx = context();mocks.fetch.mockRejectedValueOnce(new SsrFBlockedError('private address')).mockRejectedValueOnce(new TypeError('connection reset'));- expect((await download(ctx)).buffer).toEqual(bytes);+ expect(await downloadedBytes(await download(ctx))).toEqual(bytes);expect(ctx.confirm.mock.calls.map(([request]) => request.reasons)).toEqual([['source'], ['network']]);expect(mocks.fetch.mock.calls[0][3].allowPrivateNetwork).toBe(false);expect(mocks.fetch.mock.calls.slice(1).every((call) => call[3].allowPrivateNetwork === true)).toBe(true);@@ -149,19 +161,57 @@ describe('media download approval and network recovery', () => {expect(ctx.confirm).toHaveBeenCalledOnce();});- it('releases an oversized response before requesting a higher byte limit', async () => {+ it.each([true, false])('streams to disk without buffering or size approval (length header: %s)', async (declared) => {const ctx = context();- const cancel = vi.fn();- mocks.fetch.mockResolvedValueOnce(response(new ReadableStream({ cancel }), { headers: { 'content-length': '2048' } }));- ctx.confirm.mockImplementation(async ({ reasons }) => {- if (reasons.includes('size')) {- expect(cancel).toHaveBeenCalledOnce();- expect(mocks.release).toHaveBeenCalledOnce();- }- return true;- });- expect((await download(ctx)).buffer).toEqual(bytes);- expect(ctx.confirm.mock.calls[1][0]).toMatchObject({ reasons: ['size'], bytes: 2048 });+ const chunk = new Uint8Array(64 * 1024).fill(7);+ const chunks = 40;+ let emitted = 0;+ mocks.fetch.mockResolvedValueOnce(response(new ReadableStream({+ pull(controller) {+ if (emitted++ < chunks) controller.enqueue(chunk);+ else controller.close();+ },+ }), declared ? { headers: { 'content-length': String(chunks * chunk.length) } } : undefined));+ const concat = vi.spyOn(Buffer, 'concat');+ const readFile = vi.spyOn(fs, 'readFile');+ const result = await download(ctx);+ expect((await fs.stat(result.filePath)).size).toBe(chunks * chunk.length);+ expect(concat).not.toHaveBeenCalled();+ expect(readFile).not.toHaveBeenCalled();+ expect(ctx.confirm).toHaveBeenCalledOnce();+ await result.dispose();+ await expect(fs.stat(path.dirname(result.filePath))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('removes partial files on failed reads before retrying the same approved source', async () => {+ const ctx = context();+ const mkdtemp = vi.spyOn(fs, 'mkdtemp');+ mocks.fetch.mockResolvedValueOnce(response(new ReadableStream({+ start(controller) { controller.enqueue(bytes); },+ pull(controller) { controller.error(new Error('connection lost')); },+ })));+ const result = await download(ctx);+ expect(await downloadedBytes(result)).toEqual(bytes);+ const failedDir = await mkdtemp.mock.results[0].value;+ await expect(fs.stat(failedDir)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(ctx.confirm).toHaveBeenCalledOnce();+ expect(mocks.release).toHaveBeenCalledTimes(2);+ });++ it('cleans up a partial file when the task is cancelled', async () => {+ const ctx = context();+ const controller = new AbortController();+ ctx.signal = controller.signal;+ ctx.assertActive = () => controller.signal.throwIfAborted();+ const mkdtemp = vi.spyOn(fs, 'mkdtemp');+ mocks.fetch.mockResolvedValueOnce(response(new ReadableStream({+ pull(stream) { controller.abort(); stream.enqueue(bytes); },+ }, { highWaterMark: 0 })));+ await expect(download(ctx)).rejects.toBeDefined();+ const dir = await mkdtemp.mock.results[0].value;+ await expect(fs.stat(dir)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(mocks.fetch).toHaveBeenCalledOnce();+ expect(mocks.release).toHaveBeenCalledOnce();});it('cancelled approval cannot dispatch, even if a late response allows it', async () => {diff --git a/apps/desktop/src/main/cindy-media/__tests__/mediaDownloadApproval.test.ts b/apps/desktop/src/main/cindy-media/__tests__/mediaDownloadApproval.test.tsindex eda24e3acb..07a995fcb7 100644--- a/apps/desktop/src/main/cindy-media/__tests__/mediaDownloadApproval.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/mediaDownloadApproval.test.ts@@ -24,6 +24,19 @@ function hostSession() {describe('Host media permission', () => {afterEach(() => vi.useRealTimers());+ it('does not expire the download context while the upstream generation is running', async () => {+ vi.useFakeTimers();+ const host = hostSession();+ const ctx = createMediaDownloadContext(host.session, () => true);+ try {+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(ctx.signal?.aborted).toBe(false);+ expect(() => ctx.assertActive()).not.toThrow();+ host.stop();+ expect(ctx.signal?.aborted).toBe(true);+ } finally { ctx.dispose?.(); }+ });+it('uses an ordinary single-use permission request with a reason and sanitized source', async () => {const host = hostSession();const ctx = createMediaDownloadContext(host.session, () => true);diff --git a/apps/desktop/src/main/cindy-media/blobStore.ts b/apps/desktop/src/main/cindy-media/blobStore.tsindex 77648ea7e5..ae3a1bd41a 100644--- a/apps/desktop/src/main/cindy-media/blobStore.ts+++ b/apps/desktop/src/main/cindy-media/blobStore.ts@@ -92,80 +92,106 @@ export function mimeForExt(ext: string): string | null {return MIME_BY_EXT[ext] ?? null;}-/**- * 写入一段字节:算指纹 → 分桶落盘(幂等)→ 返回指纹与地址。- * 只写字节仓;账本记账(recordBlob/addRef)由调用方接着做。- */-export async function writeBlob(params: {- buffer: Uint8Array;+/** File sources are private Host-owned downloads, never plugin-supplied paths. */+export type BlobSource =+ | { buffer: Uint8Array; filePath?: never }+ | { filePath: string; buffer?: never };++/** 写入内存或 Host 文件字节,复用相同的指纹、原子发布和去重校验。 */+export async function writeBlob(params: BlobSource & {mimeType: string;+ assertStillValid?: () => void;}): Promise<WrittenBlob> {- const { buffer, mimeType } = params;- if (!buffer || buffer.byteLength === 0) {- throw new Error('cindy-media: empty buffer');- }+ const { mimeType } = params;const ext = EXT_BY_MIME[mimeType];- if (!ext) {- throw new Error(`cindy-media: unsupported mime type: ${mimeType}`);- }-- const hash = createHash('sha256').update(buffer).digest('hex');- const bytes = buffer.byteLength;- const { dir, dest } = await prepareBlobDestination(hash, ext);-- return withDestLock(dest, async () => {- // 同目录 tmp + link/rename 发布:终点不以半截内容出现;已存在分支- // (EEXIST 与不支持 hard-link 且 dest 已在)共用 inspectExistingBlob。- let deduplicated = false;- const tmpPath = path.join(dir, `.tmp-${hash}-${process.pid}-${randomUUID()}`);- try {- await fs.writeFile(tmpPath, buffer, { flag: 'wx' });+ if (!ext) throw new Error(`cindy-media: unsupported mime type: ${mimeType}`);+ const source = params.filePath !== undefined ? await fs.open(params.filePath, noFollowReadFlags()) : undefined;+ try {+ const hasher = createHash('sha256');+ let bytes = 0;+ if (source) {+ if (!(await source.stat()).isFile()) throw new Error('cindy-media: source is not a regular file');+ for await (const chunk of source.createReadStream({ autoClose: false, emitClose: false })) {+ params.assertStillValid?.();+ hasher.update(chunk);+ bytes += chunk.byteLength;+ }+ } else if (params.buffer) {+ hasher.update(params.buffer);+ bytes = params.buffer.byteLength;+ }+ if (bytes === 0) throw new Error('cindy-media: empty buffer');+ const hash = hasher.digest('hex');+ const { dir, dest } = await prepareBlobDestination(hash, ext);++ return await withDestLock(dest, async () => {+ // 同目录 tmp + link/rename 发布:终点不以半截内容出现;已存在分支+ // (EEXIST 与不支持 hard-link 且 dest 已在)共用 inspectExistingBlob。+ let deduplicated = false;+ const tmpPath = path.join(dir, `.tmp-${hash}-${process.pid}-${randomUUID()}`);try {- await fs.link(tmpPath, dest);- } catch (err) {- const code = (err as NodeJS.ErrnoException)?.code;- if (code === 'EEXIST') {- deduplicated = await reconcileExistingBlob(tmpPath, dest, hash, bytes);+ if (source) {+ const output = await fs.open(tmpPath, 'wx', 0o600);+ try {+ for await (const chunk of source.createReadStream({ start: 0, autoClose: false, emitClose: false })) {+ params.assertStillValid?.();+ await output.writeFile(chunk);+ }+ } finally {+ await output.close();+ }} else {- // 个别文件系统不支持硬链接(exFAT 等):已存在走同一校验出口,- // 缺失才 rename 发布。destExists 不得在未核验时当去重成功。- const destExists = await fs.lstat(dest).then(- () => true,- (accessErr: NodeJS.ErrnoException) => {- if (accessErr.code === 'ENOENT') return false;- throw accessErr;- },- );- if (destExists) {+ await fs.writeFile(tmpPath, params.buffer!, { flag: 'wx' });+ }+ try {+ await fs.link(tmpPath, dest);+ } catch (err) {+ const code = (err as NodeJS.ErrnoException)?.code;+ if (code === 'EEXIST') {deduplicated = await reconcileExistingBlob(tmpPath, dest, hash, bytes);} else {- await publishByRename(tmpPath, dest, hash, bytes);+ // 个别文件系统不支持硬链接(exFAT 等):已存在走同一校验出口,+ // 缺失才 rename 发布。destExists 不得在未核验时当去重成功。+ const destExists = await fs.lstat(dest).then(+ () => true,+ (accessErr: NodeJS.ErrnoException) => {+ if (accessErr.code === 'ENOENT') return false;+ throw accessErr;+ },+ );+ if (destExists) {+ deduplicated = await reconcileExistingBlob(tmpPath, dest, hash, bytes);+ } else {+ await publishByRename(tmpPath, dest, hash, bytes);+ }}}- }- let finalState = await inspectExistingBlob(dest, hash, bytes);- if (finalState.kind !== 'ok') {- finalState = await rereadOnce(dest, hash, bytes);- }- if (finalState.kind !== 'ok') {- throw finalState.kind === 'invalid'- ? existingBlobError(finalState)- : new Error('cindy-media: blob destination did not match input hash');+ let finalState = await inspectExistingBlob(dest, hash, bytes);+ if (finalState.kind !== 'ok') {+ finalState = await rereadOnce(dest, hash, bytes);+ }+ if (finalState.kind !== 'ok') {+ throw finalState.kind === 'invalid'+ ? existingBlobError(finalState)+ : new Error('cindy-media: blob destination did not match input hash');+ }+ await assertBlobPathContained(dest);+ return {+ hash,+ ext,+ mimeType,+ bytes,+ url: blobUrl(hash, ext),+ deduplicated,+ };+ } finally {+ await fs.rm(tmpPath, { force: true }).catch(() => {});}- await assertBlobPathContained(dest);- return {- hash,- ext,- mimeType,- bytes,- url: blobUrl(hash, ext),- deduplicated,- };- } finally {- await fs.rm(tmpPath, { force: true }).catch(() => {});- }- });+ });+ } finally {+ await source?.close();+ }}async function withDestLock<T>(dest: string, fn: () => Promise<T>): Promise<T> {diff --git a/apps/desktop/src/main/cindy-media/ingest.ts b/apps/desktop/src/main/cindy-media/ingest.tsindex 392c8f136f..14f67481f8 100644--- a/apps/desktop/src/main/cindy-media/ingest.ts+++ b/apps/desktop/src/main/cindy-media/ingest.ts@@ -39,8 +39,7 @@ export interface IngestRef {label?: string;}-export interface IngestMediaParams {- buffer: Uint8Array;+export type IngestMediaParams = blobStore.BlobSource & {/** 真实 mime(由主机侧判定,不信调用方之外的自报);白名单外直接拒。 */mimeType: string;/** 性质=可再生缓存(吃 cache 上限可清);附件/作品传 false(默认)。 */@@ -96,10 +95,7 @@ export async function ingestMedia(}params.assertStillValid?.();// writeBlob 只在最终实际内容 hash 正确时返回;损坏/symlink/目录不会被当成去重。- const written = await blobStore.writeBlob({- buffer: params.buffer,- mimeType: params.mimeType,- });+ const written = await blobStore.writeBlob(params);params.assertStillValid?.();await ledger.recordBlob({diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.tsindex 6a6985f63b..326cbbaf7f 100644--- a/apps/desktop/src/main/cindy-media/invocationService.ts+++ b/apps/desktop/src/main/cindy-media/invocationService.ts@@ -40,7 +40,7 @@ import {resolveProviderMediaModel,type ProviderMediaRuntimeModel,} from './providerMediaRuntime.js';-import { sniffMediaMime } from './sniffMediaMime.js';+import { sniffMediaMime, additionalMp3BytesNeeded } from './sniffMediaMime.js';import {countMediaInvocations,createMediaInvocation,@@ -757,19 +757,40 @@ async function mediaBytes(raw: string,extractor: MediaResultExtractor,scope: MediaAuthScope,-): Promise<{ buffer: Buffer; mimeType: string }> {+): Promise<blobStore.BlobSource & { mimeType: string; dispose?(): Promise<void> }> {let buffer: Buffer;let headerMime: string | null = null;if (extractor.encoding === 'url') {const downloaded = await downloadMediaResult({raw,allowedHosts: extractor.allowedUrlHosts,- maxBytes: maxResultBytes(extractor.kind),context: scope.downloadContext,assertActive: () => assertAuthScope(scope),});- buffer = downloaded.buffer;- headerMime = downloaded.headerMime;+ try {+ const file = await fs.open(downloaded.filePath, 'r');+ try {+ // Reuse the existing bounded MIME probe; file size never controls allocation.+ let probe = Buffer.alloc(4096);+ const first = await file.read(probe, 0, probe.length, 0);+ probe = probe.subarray(0, first.bytesRead);+ const needed = additionalMp3BytesNeeded(probe);+ if (needed && needed > probe.length) {+ probe = Buffer.alloc(needed);+ const read = await file.read(probe, 0, probe.length, 0);+ probe = probe.subarray(0, read.bytesRead);+ }+ const mimeType = sniffMediaMime(probe, extractor.mediaType ?? downloaded.headerMime ?? '');+ if (!mimeType) throw new MediaInvocationError('MEDIA_RESULT_INVALID', '无法从上游字节识别媒体类型');+ assertResultMime(extractor.kind, mimeType);+ return { filePath: downloaded.filePath, mimeType, dispose: downloaded.dispose };+ } finally {+ await file.close();+ }+ } catch (error) {+ await downloaded.dispose();+ throw error;+ }} else {const dataUrl = /^data:([^;,]+);base64,(.+)$/s.exec(raw);const encoded = (dataUrl ? dataUrl[2] : raw).replace(/\s/g, '');@@ -782,7 +803,7 @@ async function mediaBytes(}buffer = Buffer.from(encoded, 'base64');}- if (buffer.byteLength === 0 || (extractor.encoding !== 'url' && buffer.byteLength > maxResultBytes(extractor.kind))) {+ if (buffer.byteLength === 0 || buffer.byteLength > maxResultBytes(extractor.kind)) {throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游返回空媒体或媒体超过大小限制');}// Guide / Content-Type 只能帮助识别容器变体(例如无 ftyp 的 QuickTime),@@ -828,33 +849,37 @@ async function materializeResults(assertAuthScope(scope);throw error;}- assertAuthScope(scope);- let stored: Awaited<ReturnType<typeof ingestMedia>>;- for (let attempt = 0; ; attempt += 1) {+ try {assertAuthScope(scope);- try {- // Content-addressed writes and zero-reference ledger updates are- // idempotent. Retry these same bytes without downloading or approving again.- stored = await ingestMedia(- {- buffer: media.buffer,- mimeType: media.mimeType,- refs: [],- assertStillValid: () => assertAuthScope(scope),- },- db.drizzle,- );- break;- } catch (error) {+ let stored: Awaited<ReturnType<typeof ingestMedia>>;+ for (let attempt = 0; ; attempt += 1) {assertAuthScope(scope);- if (attempt >= 2) throw error;- await delay(250 * 2 ** attempt, undefined, { signal: scope.downloadContext?.signal });+ try {+ // Content-addressed writes and zero-reference ledger updates are+ // idempotent. Retry these same bytes without downloading or approving again.+ stored = await ingestMedia(+ {+ ...(media.filePath !== undefined ? { filePath: media.filePath } : { buffer: media.buffer }),+ mimeType: media.mimeType,+ refs: [],+ assertStillValid: () => assertAuthScope(scope),+ },+ db.drizzle,+ );+ break;+ } catch (error) {+ assertAuthScope(scope);+ if (attempt >= 2) throw error;+ await delay(250 * 2 ** attempt, undefined, { signal: scope.downloadContext?.signal });+ }}+ assertAuthScope(scope);+ if (item.extractor.kind === 'image') images.push(stored.url);+ else if (item.extractor.kind === 'video') videos.push(stored.url);+ else audio.push(stored.url);+ } finally {+ await media.dispose?.();}- assertAuthScope(scope);- if (item.extractor.kind === 'image') images.push(stored.url);- else if (item.extractor.kind === 'video') videos.push(stored.url);- else audio.push(stored.url);}return {...(images.length > 0 ? { xdt_image_urls: images } : {}),diff --git a/apps/desktop/src/main/cindy-media/mediaDownload.ts b/apps/desktop/src/main/cindy-media/mediaDownload.tsindex 16a26b3936..c6a7ceb736 100644--- a/apps/desktop/src/main/cindy-media/mediaDownload.ts+++ b/apps/desktop/src/main/cindy-media/mediaDownload.ts@@ -1,19 +1,21 @@import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';import { setTimeout as delay } from 'node:timers/promises';import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';import { guardedOutboundFetch } from '../maker-host/outbound-fetch.js';-export type MediaDownloadReason = 'source' | 'http' | 'port' | 'credentials' | 'network' | 'size';+export type MediaDownloadReason = 'source' | 'http' | 'port' | 'credentials' | 'network';/** Only Host code constructs this context; it is never part of the media tool schema. */export interface MediaDownloadContext {signal?: AbortSignal;/** Scoped to one Host invocation operation, including read-only URL refresh. */approvals?: Set<string>;- byteLimits?: Map<string, number>;dispose?(): void;assertActive(): void;- confirm(input: { origin: string; reasons: MediaDownloadReason[]; bytes?: number }): Promise<boolean>;+ confirm(input: { origin: string; reasons: MediaDownloadReason[] }): Promise<boolean>;}export class MediaDownloadError extends Error {@@ -35,17 +37,14 @@ function parseUrl(raw: string, base?: URL): URL {export async function downloadMediaResult(input: {raw: string;allowedHosts?: string[];- maxBytes: number;context?: MediaDownloadContext;assertActive(): void;-}): Promise<{ buffer: Buffer; headerMime: string | null }> {+}): Promise<{ filePath: string; headerMime: string | null; dispose(): Promise<void> }> {let url = parseUrl(input.raw);- let maxBytes = input.maxBytes;const visitedRedirects = new Set([url.href]);let failures = 0;let remainingMs = 120_000;const approved = input.context?.approvals ?? new Set<string>();- const byteLimits = input.context?.byteLimits ?? new Map<string, number>();const approvalKey = (reason: MediaDownloadReason) => {if (reason === 'network') {// A private-network exception belongs to this exact HTTP target. Source@@ -62,12 +61,12 @@ export async function downloadMediaResult(input: {input.assertActive();input.context?.assertActive();};- const confirm = async (reasons: MediaDownloadReason[], bytes?: number) => {+ const confirm = async (reasons: MediaDownloadReason[]) => {assertActive();if (!input.context) {throw new MediaDownloadError('MEDIA_DOWNLOAD_CONFIRMATION_REQUIRED', '本次下载需要用户确认,当前任务的审批通道不可用');}- const allowed = await input.context.confirm({ origin: url.origin, reasons, ...(bytes ? { bytes } : {}) });+ const allowed = await input.context.confirm({ origin: url.origin, reasons });assertActive();if (!allowed) {throw new MediaDownloadError('MEDIA_DOWNLOAD_DENIED', '用户未允许本次下载,已停止;不要自动重试或再次请求审批');@@ -77,8 +76,6 @@ export async function downloadMediaResult(input: {for (;;) {assertActive();- const resourceKey = `${url.origin}${url.pathname}`;- maxBytes = Math.max(input.maxBytes, byteLimits.get(resourceKey) ?? 0);const reasons: MediaDownloadReason[] = [];const knownHost = input.allowedHosts?.some((suffix) => {const host = suffix.toLowerCase();@@ -121,8 +118,8 @@ export async function downloadMediaResult(input: {resetIdleTimeout();let decisionNeeded: MediaDownloadReason | undefined;let retryError: MediaDownloadError | undefined;- let requestedBytes: number | undefined;- let result: { buffer: Buffer; headerMime: string | null } | undefined;+ let tempDir: string | undefined;+ let result: { filePath: string; headerMime: string | null; dispose(): Promise<void> } | undefined;try {const allowPrivateNetwork = approved.has(approvalKey('network'));const { response, release } = await guardedOutboundFetch(@@ -150,45 +147,36 @@ export async function downloadMediaResult(input: {} else if (!response.ok) {throw new MediaDownloadError([401, 403, 404, 410].includes(response.status) ? 'MEDIA_DOWNLOAD_URL_EXPIRED' : ([408, 425, 429].includes(response.status) || response.status >= 500) ? 'MEDIA_DOWNLOAD_FAILED' : 'MEDIA_DOWNLOAD_UNAVAILABLE', `下载服务暂不可用(HTTP ${response.status}),生成结果已保留`);} else {- const declaredBytes = Number(response.headers.get('content-length'));- if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {- decisionNeeded = 'size';- requestedBytes = declaredBytes;- } else {- const reader = response.body?.getReader();- const chunks: Uint8Array[] = [];- let size = 0;- try {- while (reader) {- const { done, value } = await reader.read();- if (done) break;- assertActive();- resetIdleTimeout();- size += value.byteLength;- if (size > maxBytes) {- decisionNeeded = 'size';- requestedBytes = Math.max(size, maxBytes * 2);- await reader.cancel();- break;- }- chunks.push(value);- }- } finally {- reader?.releaseLock();- }- if (!decisionNeeded) {- result = {- buffer: Buffer.concat(chunks, size),- headerMime: response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() ?? null,- };+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-media-download-'));+ const filePath = path.join(tempDir, 'result');+ const file = await fs.open(filePath, 'wx', 0o600);+ const reader = response.body?.getReader();+ try {+ while (reader) {+ const { done, value } = await reader.read();+ if (done) break;+ assertActive();+ resetIdleTimeout();+ // Await each write: network backpressure keeps memory bounded.+ await file.writeFile(value);}+ } finally {+ reader?.releaseLock();+ await file.close();}+ const completedDir = tempDir;+ result = {+ filePath,+ headerMime: response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() ?? null,+ dispose: () => fs.rm(completedDir, { recursive: true, force: true }).catch(() => undefined),+ };}} finally {try { await response.body?.cancel().catch(() => undefined); }finally { await release(); }}} catch (error) {+ result = undefined;assertActive();if (error instanceof SsrFBlockedError && !approved.has(approvalKey('network'))) {decisionNeeded = 'network';@@ -201,6 +189,7 @@ export async function downloadMediaResult(input: {clearTimeout(timeout);clearTimeout(idleTimeout);remainingMs -= Date.now() - startedAt;+ if (tempDir && !result) await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);}if (retryError) {// Retry only transient network failures. Human denial never enters this branch.@@ -213,10 +202,10 @@ export async function downloadMediaResult(input: {continue;}if (decisionNeeded) {- await confirm([decisionNeeded], requestedBytes);- if (requestedBytes) byteLimits.set(resourceKey, requestedBytes);+ await confirm([decisionNeeded]);} else if (result) {- assertActive();+ try { assertActive(); }+ catch (error) { await result.dispose(); throw error; }return result;}}diff --git a/apps/desktop/src/main/cindy-media/mediaDownloadApproval.ts b/apps/desktop/src/main/cindy-media/mediaDownloadApproval.tsindex 1e65080c17..e05ce26e3f 100644--- a/apps/desktop/src/main/cindy-media/mediaDownloadApproval.ts+++ b/apps/desktop/src/main/cindy-media/mediaDownloadApproval.ts@@ -11,8 +11,6 @@ export function createMediaDownloadContext(): MediaDownloadContext {const generation = session.getTurnGeneration();const controller = new AbortController();- const deadline = setTimeout(() => controller.abort(), 9 * 60_000);- deadline.unref?.();const isActive = () => isCurrent() && session.getTurnGeneration() === generation &&session.getStatus() === 'active' && session.isTurnRunning();const assertActive = () => {@@ -25,16 +23,14 @@ export function createMediaDownloadContext(});return {approvals: new Set<string>(),- byteLimits: new Map<string, number>(),signal: controller.signal,- dispose: () => { clearTimeout(deadline); unsubscribe(); },+ dispose: unsubscribe,assertActive,- confirm: async ({ origin, reasons, bytes }) => {+ confirm: async ({ origin, reasons }) => {assertActive();- // Leave time for the download inside the enclosing ten-minute MCP call.+ // Bound only the human decision; generation has its own request timeout.const approvalSignal = AbortSignal.any([controller.signal, AbortSignal.timeout(8 * 60_000)]);- const details = reasons.map((reason) => t(`newChat.mediaDownload.${reason}`)- .replaceAll('{{bytes}}', String(bytes ?? 0))).join('\n');+ const details = reasons.map((reason) => t(`newChat.mediaDownload.${reason}`)).join('\n');const request: InteractionRequest = {kind: 'permission',requestId: randomUUID(),diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 627bf11e5c..c080ac1607 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8002,7 +8002,6 @@"port": "This address uses a non-default network port. Confirm access to that port.","credentials": "This download address includes login details. If allowed, those details will be sent only to this address.","network": "This address points to this device, a local network, or a reserved network. Access may reach internal services on the device.",- "size": "The file exceeds the default download size. Allow downloading up to {{bytes}} bytes this time, which may use significant memory and disk space.","allow": "Allow this download","defer": "Not now"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex eb020267ce..8c8d466911 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8000,7 +8000,6 @@"port": "このアドレスは標準以外のネットワークポートを使用します。このポートへのアクセスを確認してください。","credentials": "このダウンロードアドレスにはログイン情報が含まれています。許可すると、その情報はこのアドレスにのみ送信されます。","network": "このアドレスは、このデバイス、ローカルネットワーク、または予約済みネットワークを指しています。アクセスすると、デバイスの内部サービスに接続する可能性があります。",- "size": "ファイルが標準のダウンロードサイズを超えています。今回は最大 {{bytes}} バイトのダウンロードを許可します。メモリやディスク容量を多く使用する可能性があります。","allow": "今回のダウンロードを許可","defer": "今はダウンロードしない"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 3cbb7a7514..11d02c4ab1 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8000,7 +8000,6 @@"port": "이 주소는 기본 네트워크 포트가 아닌 포트를 사용합니다. 해당 포트에 대한 접근을 확인해 주세요.","credentials": "이 다운로드 주소에는 로그인 정보가 포함되어 있습니다. 허용하면 해당 정보는 이 주소에만 전송됩니다.","network": "이 주소는 이 기기, 로컬 네트워크 또는 예약된 네트워크를 가리킵니다. 접근하면 기기의 내부 서비스에 연결될 수 있습니다.",- "size": "파일이 기본 다운로드 크기를 초과합니다. 이번에 최대 {{bytes}}바이트 다운로드를 허용하며, 메모리와 디스크 공간을 많이 사용할 수 있습니다.","allow": "이번 다운로드 허용","defer": "나중에 다운로드"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex c91b78a079..a4619b829b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8000,7 +8000,6 @@"port": "这个地址使用非默认网络端口,需要确认访问该端口。","credentials": "这个下载地址包含登录信息。允许后,仅向该地址发送其中的登录信息。","network": "这个地址指向本机、局域网或保留网络,访问它可能触及设备上的内部服务。",- "size": "文件超过默认下载大小。允许后,本次最多下载 {{bytes}} 字节,可能占用较多内存和磁盘空间。","allow": "允许本次下载","defer": "暂不下载"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 7565ffeb3b..c8e7c4fcdf 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8000,7 +8000,6 @@"port": "這個位址使用非預設網路連接埠,需要確認存取該連接埠。","credentials": "這個下載位址包含登入資訊。允許後,僅向該位址傳送其中的登入資訊。","network": "這個位址指向本機、區域網路或保留網路,存取它可能觸及裝置上的內部服務。",- "size": "檔案超過預設下載大小。允許後,本次最多下載 {{bytes}} 位元組,可能佔用較多記憶體和磁碟空間。","allow": "允許本次下載","defer": "暫不下載"},diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex 10469ec8bc..e804ada805 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -70,7 +70,7 @@- 下载是生成流程内部的一步,不新增“领取”状态、列表或用户操作。上游返回后,客户端下载并通过 `ingestMedia` 返回受管媒体;需要确认时暂停同一次操作,批准后自动继续。- Guide 的 `allowedUrlHosts` 保留为已确认来源名单。名单内正常目标自动下载;名单外- 来源、HTTP、特殊端口、地址内登录信息、受限网络或扩大文件大小等权限要求通过+ 来源、HTTP、特殊端口、地址内登录信息、受限网络等权限要求通过Cindy 普通 `permission` 交互确认。卡片只说明实际地址、原因和本次范围,不出现Guide、“模型说明”等内部概念,不使用仅限本机的 `ghost_grant_confirm`。- 用户拒绝后结束本次下载,不自动重试或再次审批。网络失败由客户端最多自动尝试@@ -81,9 +81,14 @@来源批准按 origin 复用;受限网络例外按不含 fragment 的完整 URL 绑定,路径或 query变化后须重新确认该受限目标,不能借同源跳转访问另一内部接口。不附带生成接口凭证;地址内登录信息须单独确认,且不得沿重定向传递。-- 网络时间累计最多 120 秒,连续 30 秒没有响应或数据则重试,人工审批等待另计并受 Host 操作时限- 约束。正常跳转逐跳重验目标与权限,循环跳转作为下载故障处理,不为次数追加审批。- 等待更大文件审批前取消响应体并释放连接;所有结束路径均释放 body 和 dispatcher。+- 网络时间累计最多 120 秒,连续 30 秒没有响应或数据则重试,单次人工审批最多等待八分钟。+ 上游生成沿用自身请求超时,不另加覆盖生成阶段的下载计时器。+ 正常跳转逐跳重验目标与权限,循环跳转作为下载故障处理,不为次数追加审批。+ 所有结束路径均释放 body 和 dispatcher。+- URL 媒体逐块写入 Host 私有临时文件,类型识别使用有界探测,哈希与入仓同样分块处理。+ 不因原内存大小上限拒绝下载或追加大小审批;完成、失败、取消后尽力清理临时文件。+ 文件源仍走 `ingestMedia` 和现有字节仓的原子发布、去重与记账,不另建媒体存储。+ base64 响应沿用原大小限制。- 下载失败保留原调用的成功响应。异步签名地址失效时只查询原上游任务刷新地址,不重新付费生成;刷新结果成功入库前不覆盖原成功响应。本地入库失败由客户端对同一份已下载字节最多尝试三次,期间复核账号和任务,不再次下载、生成或审批。