Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(media): 通过通用权限审批交付未知来源媒体

liugaoweief921c9e2ecb
diff --git a/.github/pr-assets/media-download-permission-light.png b/.github/pr-assets/media-download-permission-light.png
new file mode 100644
index 0000000000..dfe51a03ed
Binary files /dev/null and b/.github/pr-assets/media-download-permission-light.png differ
diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
index 0528bf1a7d..db23a3c97a 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';
interface MockPreparedGuide extends Record<string, unknown> {
modelId: string;
@@ -24,6 +25,9 @@ const mocks = vi.hoisted(() => ({
providerInvoke: vi.fn(),
guide: vi.fn(),
outboundFetch: vi.fn(),
+ guardedOutboundFetch: vi.fn(),
+ release: vi.fn(async () => undefined),
+ confirm: vi.fn(async (_input: { reasons: string[] }) => true),
ingestMedia: vi.fn(),
readBlob: vi.fn(),
resolveBlob: vi.fn(),
@@ -65,6 +69,7 @@ vi.mock('../../localDb/client/current.js', () => ({
}));
vi.mock('../../maker-host/outbound-fetch.js', () => ({
outboundFetch: mocks.outboundFetch,
+ guardedOutboundFetch: mocks.guardedOutboundFetch,
}));
vi.mock('../../model-access/mediaModels.js', () => ({
listAvailableMediaModels: mocks.models,
@@ -165,7 +170,15 @@ vi.mock('../mediaInvocationStore.js', () => ({
},
}));
-import { callCindyMedia } from '../invocationService.js';
+import { callCindyMedia as invokeMedia } from '../invocationService.js';
+
+// This harness supplies a real Host approval boundary. Individual cases replace
+// its decision; production never receives approval flags through tool arguments.
+const callCindyMedia: typeof invokeMedia = (request, context = {
+ assertActive: () => undefined,
+ confirm: mocks.confirm,
+ approvals: new Set<string>(),
+}) => invokeMedia(request, context);
const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1]);
const MP4 = Buffer.from([
@@ -220,6 +233,7 @@ async function prepare(): Promise<string> {
describe('Cindy Core media invocation state and security boundary', () => {
beforeEach(() => {
+ mocks.confirm.mockReset().mockResolvedValue(true);
mocks.currentUserId = `media-user-${crypto.randomUUID()}`;
mocks.ownerGeneration += 1;
mocks.dbOwnerId = mocks.currentUserId;
@@ -244,6 +258,18 @@ describe('Cindy Core media invocation state and security boundary', () => {
mocks.providerInvoke.mockReset();
mocks.guide.mockReset();
mocks.outboundFetch.mockReset();
+ mocks.release.mockClear();
+ // Preserve the existing upstream/download response sequences while checking
+ // that every result request enters the guarded adapter and dispatch gate.
+ mocks.guardedOutboundFetch
+ .mockReset()
+ .mockImplementation(
+ async (url: string, init: RequestInit, beforeDispatch: () => void | Promise<void>) => {
+ await beforeDispatch();
+ return { response: await mocks.outboundFetch(url, init), release: mocks.release };
+ },
+ );
+
mocks.ingestMedia.mockReset().mockResolvedValue({
url: `cindy-media://blobs/${'a'.repeat(64)}.png`,
});
@@ -537,6 +563,8 @@ describe('Cindy Core media invocation state and security boundary', () => {
}),
)
.mockRejectedValueOnce(new TypeError('temporary network failure'))
+ .mockRejectedValueOnce(new TypeError('temporary network failure'))
+ .mockRejectedValueOnce(new TypeError('temporary network failure'))
.mockResolvedValueOnce(
new Response(PNG, { status: 200, headers: { 'content-type': 'image/png' } }),
);
@@ -547,8 +575,7 @@ describe('Cindy Core media invocation state and security boundary', () => {
).resolves.toMatchObject({
ok: false,
errorCode: 'MEDIA_DOWNLOAD_FAILED',
- retryable: true,
- retry_action: 'request',
+ retryable: false,
});
expect(mocks.rows.get(invocationId)).toMatchObject({
state: 'pending',
@@ -558,7 +585,7 @@ describe('Cindy Core media invocation state and security boundary', () => {
await expect(
callCindyMedia({ action: 'request', invocationId, body: { prompt: 'ignored-on-retry' } }),
).resolves.toMatchObject({ ok: true, status: 'complete' });
- expect(mocks.outboundFetch).toHaveBeenCalledTimes(3);
+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(5);
expect(mocks.outboundFetch.mock.calls[0][0]).toBe(
'https://gateway.example.com/images/generations',
);
@@ -935,34 +962,39 @@ describe('Cindy Core media invocation state and security boundary', () => {
expect(result.message).not.toContain(opaque);
});
- it('拒绝非可信媒体域名,可信下载不携带网关凭据且禁止重定向', async () => {
+ it('受限网络未获批准时不下载,批准新 CDN 后不携带网关凭据', async () => {
const urlOperation = operation({
mode: 'sync',
- media: [{
- path: ['data'],
- encoding: 'url',
- kind: 'image',
- allowedUrlHosts: ['cdn.example.com'],
- }],
+ media: [
+ {
+ path: ['data'],
+ encoding: 'url',
+ kind: 'image',
+ allowedUrlHosts: ['cdn.example.com'],
+ },
+ ],
});
mocks.guide.mockResolvedValue(resolvedGuide(urlOperation));
mocks.outboundFetch.mockResolvedValueOnce(
new Response(JSON.stringify({ data: 'https://127.0.0.1/private.png' }), { status: 200 }),
);
+ mocks.confirm.mockImplementation(async ({ reasons }) => !reasons.includes('network'));
+ mocks.guardedOutboundFetch.mockRejectedValueOnce(new SsrFBlockedError('blocked private IP'));
await expect(
callCindyMedia({
action: 'request',
invocationId: await prepare(),
body: { prompt: 'cat' },
}),
- ).resolves.toMatchObject({ ok: false, errorCode: 'MEDIA_RESULT_INVALID' });
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MEDIA_DOWNLOAD_DENIED' });
expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);
- mocks.outboundFetch.mockReset()
+ mocks.outboundFetch
+ .mockReset()
.mockResolvedValueOnce(
new Response(
- JSON.stringify({ data: 'https://cdn.example.com/generated.png?signature=opaque' }),
+ JSON.stringify({ data: 'https://new-cdn.example.com/generated.png?signature=opaque' }),
{ status: 200 },
),
)
@@ -977,79 +1009,276 @@ describe('Cindy Core media invocation state and security boundary', () => {
}),
).resolves.toMatchObject({ ok: true, status: 'complete' });
const [, downloadInit] = mocks.outboundFetch.mock.calls[1];
- expect(downloadInit.redirect).toBe('error');
+ expect(downloadInit.redirect).toBe('manual');
+ expect(mocks.guardedOutboundFetch).toHaveBeenCalledTimes(2);
+ expect(mocks.release).toHaveBeenCalledTimes(1);
expect(downloadInit.headers).toBeUndefined();
});
- it('Core 命名空间模型保留供应商媒体域名的可信准入', async () => {
- const asyncOperation = {
- ...operation({
- mode: 'async',
- taskIdPath: ['task_id'],
- poll: {
- method: 'GET',
- path: '/video/tasks/{taskId}',
- statusPath: ['status'],
- successValues: ['succeeded'],
- failureValues: ['failed'],
- recommendedIntervalMs: 10,
- timeoutMs: 5_000,
- maxResponseBytes: 1_048_576,
- media: [{
- path: ['video', 'download_url'],
- encoding: 'url',
- kind: 'video',
- allowedUrlHosts: ['cdn.example.com'],
- }],
+ it.each(['video.generate', 'video.image_to_video'] as const)(
+ '%s 经人工批准后下载未登记的供应商 CDN 结果',
+ async (capability) => {
+ const asyncOperation = {
+ ...operation(
+ {
+ mode: 'async',
+ taskIdPath: ['task_id'],
+ poll: {
+ method: 'GET',
+ path: '/video/tasks/{taskId}',
+ statusPath: ['status'],
+ successValues: ['succeeded'],
+ failureValues: ['failed'],
+ recommendedIntervalMs: 10,
+ timeoutMs: 5_000,
+ maxResponseBytes: 1_048_576,
+ media: [
+ {
+ path: ['video', 'download_url'],
+ encoding: 'url',
+ kind: 'video',
+ allowedUrlHosts: ['cdn.example.com'],
+ },
+ ],
+ },
+ },
+ '/video/tasks',
+ ),
+ capability,
+ };
+ mocks.models.mockResolvedValue([
+ {
+ id: 'minimax/minimax-h3',
+ name: 'MiniMax H3',
+ providerId: 'xd',
+ mode: 'video_generation',
},
- }, '/video/tasks'),
- capability: 'video.generate',
- };
- mocks.models.mockResolvedValue([
- {
- id: 'minimax/minimax-h3',
- name: 'MiniMax H3',
- providerId: 'xd',
- mode: 'video_generation',
- },
- ]);
- mocks.guide.mockResolvedValue({
- ...resolvedGuide(asyncOperation),
- modelId: 'minimax-h3',
+ ]);
+ mocks.guide.mockResolvedValue({
+ ...resolvedGuide(asyncOperation),
+ modelId: 'minimax-h3',
+ });
+ mocks.outboundFetch
+ .mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'task-1' }), { status: 200 }))
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ status: 'succeeded',
+ video: {
+ download_url:
+ 'https://algeng-video-infer.oss-cn-shanghai.aliyuncs.com/generated.mp4',
+ },
+ }),
+ { status: 200 },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(MP4, { status: 200, headers: { 'content-type': 'video/mp4' } }),
+ );
+ mocks.ingestMedia.mockResolvedValue({
+ url: `cindy-media://blobs/${'e'.repeat(64)}.mp4`,
+ });
+
+ const prepared = await callCindyMedia({
+ action: 'prepare',
+ modelId: 'minimax/minimax-h3',
+ capability,
+ });
+ const invocationId = prepared.invocation_id as string;
+ await expect(
+ callCindyMedia({ action: 'request', invocationId, body: { content: [] } }),
+ ).resolves.toMatchObject({ ok: true, status: 'pending' });
+ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({
+ ok: true,
+ status: 'complete',
+ xdt_video_urls: [`cindy-media://blobs/${'e'.repeat(64)}.mp4`],
+ });
+ expect(mocks.outboundFetch.mock.calls[2][0]).toBe(
+ 'https://algeng-video-infer.oss-cn-shanghai.aliyuncs.com/generated.mp4',
+ );
+ },
+ );
+
+ it('逐跳校验重定向并释放响应,变更来源才再次审批', async () => {
+ mocks.guide.mockResolvedValue(
+ resolvedGuide(
+ operation({
+ mode: 'sync',
+ media: [
+ {
+ path: ['data'],
+ encoding: 'url',
+ kind: 'image',
+ allowedUrlHosts: ['old.example.com'],
+ },
+ ],
+ }),
+ ),
+ );
+ const cancelRedirect = vi.fn();
+ mocks.outboundFetch
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ data: 'https://new.example.com/start' })),
+ )
+ .mockResolvedValueOnce(
+ new Response(new ReadableStream({ cancel: cancelRedirect }), {
+ status: 302,
+ headers: { location: '/next' },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(null, { status: 307, headers: { location: 'https://cdn.example.com/end' } }),
+ )
+ .mockResolvedValueOnce(new Response(PNG));
+ const result = await callCindyMedia({
+ action: 'request',
+ invocationId: await prepare(),
+ body: {},
});
+ expect(result).toMatchObject({ ok: true, status: 'complete' });
+ expect(mocks.guardedOutboundFetch.mock.calls.map(([url]) => url)).toEqual([
+ 'https://new.example.com/start',
+ 'https://new.example.com/next',
+ 'https://cdn.example.com/end',
+ ]);
+ const signals = mocks.guardedOutboundFetch.mock.calls.map(([, init]) => init.signal);
+ expect(signals.every((signal) => signal instanceof AbortSignal)).toBe(true);
+ expect(mocks.confirm).toHaveBeenCalledTimes(2);
+ expect(
+ mocks.guardedOutboundFetch.mock.calls.every(([, init]) => init.headers === undefined),
+ ).toBe(true);
+ expect(cancelRedirect).toHaveBeenCalledOnce();
+ expect(mocks.release).toHaveBeenCalledTimes(3);
+ });
+
+ it.each([
+ 'http://cdn.example.com/x',
+ 'https://user:[email protected]/x',
+ 'https://cdn.example.com:8443/x',
+ ])('重定向权限变化且用户拒绝时停止 %s', async (location) => {
+ mocks.confirm.mockImplementation(async ({ reasons }) => reasons.every((reason) => reason === 'source'));
+ mocks.guide.mockResolvedValue(
+ resolvedGuide(
+ operation({
+ mode: 'sync',
+ media: [
+ {
+ path: ['data'],
+ encoding: 'url',
+ kind: 'image',
+ allowedUrlHosts: ['old.example.com'],
+ },
+ ],
+ }),
+ ),
+ );
mocks.outboundFetch
- .mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'task-1' }), { status: 200 }))
.mockResolvedValueOnce(
- new Response(
- JSON.stringify({
- status: 'succeeded',
- video: { download_url: 'https://file.minimaxi.com/generated.mp4' },
- }),
- { status: 200 },
- ),
+ new Response(JSON.stringify({ data: 'https://cdn.example.com/start' })),
)
+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location } }));
+ await expect(
+ callCindyMedia({ action: 'request', invocationId: await prepare(), body: {} }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MEDIA_DOWNLOAD_DENIED' });
+ expect(mocks.guardedOutboundFetch).toHaveBeenCalledOnce();
+ expect(mocks.release).toHaveBeenCalledOnce();
+ expect(mocks.ingestMedia).not.toHaveBeenCalled();
+ });
+
+ it('服务端循环跳转返回下载错误,不增加审批', async () => {
+ mocks.guide.mockResolvedValue(
+ resolvedGuide(
+ operation({
+ mode: 'sync',
+ media: [
+ {
+ path: ['data'],
+ encoding: 'url',
+ kind: 'image',
+ allowedUrlHosts: ['old.example.com'],
+ },
+ ],
+ }),
+ ),
+ );
+ mocks.outboundFetch
.mockResolvedValueOnce(
- new Response(MP4, { status: 200, headers: { 'content-type': 'video/mp4' } }),
+ new Response(JSON.stringify({ data: 'https://cdn.example.com/start' })),
+ )
+ .mockImplementation(
+ async () => new Response(null, { status: 302, headers: { location: '/loop' } }),
);
- mocks.ingestMedia.mockResolvedValue({
- url: `cindy-media://blobs/${'e'.repeat(64)}.mp4`,
- });
+ await expect(
+ callCindyMedia({ action: 'request', invocationId: await prepare(), body: {} }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MEDIA_DOWNLOAD_REDIRECT_LOOP' });
+ expect(mocks.guardedOutboundFetch).toHaveBeenCalledTimes(2);
+ expect(mocks.release).toHaveBeenCalledTimes(2);
+ });
- const prepared = await callCindyMedia({
- action: 'prepare',
- modelId: 'minimax/minimax-h3',
- capability: 'video.generate',
- });
- const invocationId = prepared.invocation_id as string;
+ 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'],
+ },
+ ],
+ }),
+ ),
+ );
+ 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, body: { content: [] } }),
- ).resolves.toMatchObject({ ok: true, status: 'pending' });
- await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({
- ok: true,
- status: 'complete',
- xdt_video_urls: [`cindy-media://blobs/${'e'.repeat(64)}.mp4`],
+ callCindyMedia({ action: 'request', invocationId: await prepare(), body: {} }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MEDIA_DOWNLOAD_DENIED' });
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(mocks.release).toHaveBeenCalledOnce();
+ expect(mocks.ingestMedia).not.toHaveBeenCalled();
+ });
+
+ it('DNS 等待期间切号会在 dispatch 前拒绝领取', async () => {
+ mocks.guide.mockResolvedValue(
+ resolvedGuide(
+ operation({
+ mode: 'sync',
+ media: [
+ {
+ path: ['data'],
+ encoding: 'url',
+ kind: 'image',
+ allowedUrlHosts: ['old.example.com'],
+ },
+ ],
+ }),
+ ),
+ );
+ mocks.outboundFetch.mockResolvedValueOnce(
+ new Response(JSON.stringify({ data: 'https://cdn.example.com/x' })),
+ );
+ mocks.guardedOutboundFetch.mockImplementationOnce(async (_url, _init, beforeDispatch) => {
+ mocks.ownerGeneration++;
+ await beforeDispatch();
+ throw new Error('must not dispatch');
});
- expect(mocks.outboundFetch.mock.calls[2][0]).toBe('https://file.minimaxi.com/generated.mp4');
+ await expect(
+ callCindyMedia({ action: 'request', invocationId: await prepare(), body: {} }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'ACCOUNT_CHANGED' });
+ expect(mocks.outboundFetch).toHaveBeenCalledOnce();
+ expect(mocks.ingestMedia).not.toHaveBeenCalled();
});
it('即使持久快照异常包含反斜杠路径,也在发网前拒绝跨 Gateway origin', async () => {
@@ -1164,6 +1393,8 @@ describe('Cindy Core media invocation state and security boundary', () => {
.mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'task-retry' }), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify(successPayload), { status: 200 }))
.mockRejectedValueOnce(new TypeError('temporary network failure'))
+ .mockRejectedValueOnce(new TypeError('temporary network failure'))
+ .mockRejectedValueOnce(new TypeError('temporary network failure'))
.mockResolvedValueOnce(
new Response(MP4, { status: 200, headers: { 'content-type': 'video/mp4' } }),
);
@@ -1182,8 +1413,7 @@ describe('Cindy Core media invocation state and security boundary', () => {
await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({
ok: false,
errorCode: 'MEDIA_DOWNLOAD_FAILED',
- retryable: true,
- retry_action: 'poll',
+ retryable: false,
});
expect(mocks.rows.get(invocationId)).toMatchObject({
state: 'pending',
@@ -1199,14 +1429,14 @@ describe('Cindy Core media invocation state and security boundary', () => {
await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject(completed);
expect(Number(mocks.rows.get(invocationId)!.updatedAt)).toBeGreaterThan(1);
await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject(completed);
- expect(mocks.outboundFetch).toHaveBeenCalledTimes(4);
+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(6);
expect(mocks.outboundFetch.mock.calls[1][0]).toBe(
'https://gateway.example.com/video/tasks/task-retry',
);
expect(mocks.ingestMedia).toHaveBeenCalledTimes(1);
});
- it('异步任务成功但媒体结果确定无效时终止 invocation,不诱导重复 poll', async () => {
+ it('异步结果异常保留成功响应,不诱导自动重复 poll', async () => {
const asyncOperation = {
...operation({
mode: 'async',
@@ -1248,14 +1478,14 @@ describe('Cindy Core media invocation state and security boundary', () => {
errorCode: 'MEDIA_RESULT_MISSING',
retryable: false,
});
- expect(mocks.rows.get(invocationId)?.state).toBe('failed');
+ expect(mocks.rows.get(invocationId)?.state).toBe('pending');
await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({
ok: false,
- errorCode: 'INVOCATION_NOT_PENDING',
+ errorCode: 'MEDIA_RESULT_MISSING',
});
});
- it('异步任务成功后的永久下载拒绝会终止 invocation', async () => {
+ it('下载地址失效后客户端自动刷新原任务地址,不重复生成', async () => {
const asyncOperation = {
...operation(
{
@@ -1296,7 +1526,9 @@ describe('Cindy Core media invocation state and security boundary', () => {
{ status: 200 },
),
)
- .mockResolvedValueOnce(new Response(null, { status: 403 }));
+ .mockResolvedValueOnce(new Response(null, { status: 403 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ status: 'succeeded', video: 'https://cdn.example.com/refreshed.mp4' })))
+ .mockResolvedValueOnce(new Response(MP4, { headers: { 'content-type': 'video/mp4' } }));
const prepared = await callCindyMedia({
action: 'prepare',
@@ -1307,11 +1539,12 @@ describe('Cindy Core media invocation state and security boundary', () => {
await callCindyMedia({ action: 'request', invocationId, body: { content: [] } });
await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({
- ok: false,
- errorCode: 'MEDIA_DOWNLOAD_REJECTED',
- retryable: false,
+ ok: true,
+ status: 'complete',
});
- expect(mocks.rows.get(invocationId)?.state).toBe('failed');
- expect(mocks.outboundFetch).toHaveBeenCalledTimes(3);
+ expect(mocks.rows.get(invocationId)?.state).toBe('complete');
+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(5);
+ expect(mocks.confirm).not.toHaveBeenCalled();
+ expect(mocks.outboundFetch.mock.calls.filter(([, init]) => init.method === 'POST')).toHaveLength(1);
});
});
diff --git a/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts b/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts
new file mode 100644
index 0000000000..32832bb3c0
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts
@@ -0,0 +1,159 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';
+import { downloadMediaResult, type MediaDownloadContext } from '../mediaDownload.js';
+
+const mocks = vi.hoisted(() => ({ fetch: vi.fn(), release: vi.fn(async () => {}) }));
+vi.mock('../../maker-host/outbound-fetch.js', () => ({ guardedOutboundFetch: mocks.fetch }));
+
+const bytes = Buffer.from('generated-media-fixture');
+function response(body: BodyInit | null = bytes, init?: ResponseInit) {
+ return { response: new Response(body, init), release: mocks.release };
+}
+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() });
+}
+
+describe('media download approval and network recovery', () => {
+ beforeEach(() => {
+ mocks.fetch.mockReset().mockImplementation(async (_url, _init, gate) => {
+ await gate();
+ return response();
+ });
+ mocks.release.mockClear();
+ });
+ afterEach(() => 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(ctx.confirm).not.toHaveBeenCalled();
+ });
+
+ it('does not dispatch before approval; does not disclose the signed URL', async () => {
+ const ctx = context();
+ let approve!: (allow: boolean) => void;
+ const shown = new Promise<void>((resolve) => {
+ ctx.confirm.mockImplementation(() => new Promise<boolean>((finish) => { approve = finish; resolve(); }));
+ });
+ const pending = download(ctx);
+ await shown;
+ 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(mocks.fetch.mock.calls[0][1].headers).toBeUndefined();
+ });
+
+ it('a refusal ends the download without retrying or asking again', async () => {
+ const ctx = context();
+ ctx.confirm.mockResolvedValue(false);
+ await expect(download(ctx)).rejects.toMatchObject({ code: 'MEDIA_DOWNLOAD_DENIED' });
+ expect(ctx.confirm).toHaveBeenCalledOnce();
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+
+ it('network errors are retried by the client using the same approval', async () => {
+ const ctx = context();
+ mocks.fetch.mockRejectedValueOnce(new TypeError('connection reset'))
+ .mockResolvedValueOnce(response(null, { status: 503 }));
+ const result = await download(ctx);
+ expect(result.buffer).toEqual(bytes);
+ expect(mocks.fetch).toHaveBeenCalledTimes(3);
+ expect(ctx.confirm).toHaveBeenCalledOnce();
+ expect(mocks.release).toHaveBeenCalledTimes(2);
+ });
+
+ it('exhausted network retries return an error, not another permission card', async () => {
+ const ctx = context();
+ mocks.fetch.mockRejectedValue(new TypeError('offline'));
+ await expect(download(ctx)).rejects.toMatchObject({ code: 'MEDIA_DOWNLOAD_FAILED' });
+ expect(mocks.fetch).toHaveBeenCalledTimes(3);
+ expect(ctx.confirm).toHaveBeenCalledOnce();
+ });
+
+ it('permission changes require an explicit exception, which survives network retry', async () => {
+ const ctx = context();
+ mocks.fetch.mockRejectedValueOnce(new SsrFBlockedError('private address'))
+ .mockRejectedValueOnce(new TypeError('connection reset'));
+ expect((await download(ctx)).buffer).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);
+ expect(mocks.fetch.mock.calls[1][3].targetUrl).toBe(mocks.fetch.mock.calls[1][0]);
+ });
+
+ it('redirecting to a different origin requires new approval; same origin does not', async () => {
+ const ctx = context();
+ mocks.fetch.mockResolvedValueOnce(response(null, { status: 302, headers: { location: '/next' } }))
+ .mockResolvedValueOnce(response(null, { status: 302, headers: { location: 'https://other.example.com/video' } }));
+ await download(ctx);
+ expect(ctx.confirm.mock.calls.map(([request]) => request.origin)).toEqual(['https://new.example.com', 'https://other.example.com']);
+ expect(mocks.release).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not transfer a private-network exception to the next origin', async () => {
+ const ctx = context();
+ mocks.fetch.mockRejectedValueOnce(new SsrFBlockedError('private'))
+ .mockResolvedValueOnce(response(null, { status: 302, headers: { location: 'https://other.example.com/video' } }))
+ .mockRejectedValueOnce(new SsrFBlockedError('another private target'));
+ await download(ctx);
+ expect(ctx.confirm.mock.calls.map(([request]) => [request.origin, request.reasons])).toEqual([
+ ['https://new.example.com', ['source']], ['https://new.example.com', ['network']],
+ ['https://other.example.com', ['source']], ['https://other.example.com', ['network']],
+ ]);
+ expect(mocks.fetch.mock.calls[2][3].allowPrivateNetwork).toBe(false);
+ });
+
+ it('HTTP and a custom port require approval before dispatch', async () => {
+ const ctx = context();
+ await download(ctx, 'http://known.example.com:8080/video');
+ expect(ctx.confirm).toHaveBeenCalledWith({ origin: 'http://known.example.com:8080', reasons: ['http', 'port'] });
+ expect(mocks.fetch.mock.calls[0][3]).toMatchObject({ allowHttp: true, targetUrl: 'http://known.example.com:8080/video' });
+ });
+
+ it('does not forward URL credentials on a redirect', async () => {
+ const ctx = context();
+ mocks.fetch.mockResolvedValueOnce(response(null, { status: 302, headers: { location: '/next' } }));
+ await download(ctx, 'https://user:[email protected]/video');
+ expect(JSON.stringify(ctx.confirm.mock.calls)).not.toContain('secret');
+ expect(mocks.fetch.mock.calls[0][0]).toBe('https://known.example.com/video');
+ expect(mocks.fetch.mock.calls[0][1].headers).toEqual({ Authorization: 'Basic dXNlcjpzZWNyZXQ=' });
+ expect(mocks.fetch.mock.calls[1][1].headers).toBeUndefined();
+ });
+
+ it('a refreshed signed URL on the same origin reuses the operation approval', async () => {
+ const ctx = context();
+ mocks.fetch.mockResolvedValueOnce(response(null, { status: 403 }));
+ await expect(download(ctx)).rejects.toMatchObject({ code: 'MEDIA_DOWNLOAD_URL_EXPIRED' });
+ await download(ctx, 'https://new.example.com/video?signature=fresh');
+ expect(ctx.confirm).toHaveBeenCalledOnce();
+ });
+
+ it('releases an oversized response before requesting a higher byte limit', async () => {
+ 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 });
+ });
+
+ it('cancelled approval cannot dispatch, even if a late response allows it', async () => {
+ const ctx = context();
+ const controller = new AbortController();
+ ctx.signal = controller.signal;
+ ctx.assertActive = () => controller.signal.throwIfAborted();
+ ctx.confirm.mockImplementation(async () => { controller.abort(); return true; });
+ await expect(download(ctx)).rejects.toBeDefined();
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-media/__tests__/mediaDownloadApproval.test.ts b/apps/desktop/src/main/cindy-media/__tests__/mediaDownloadApproval.test.ts
new file mode 100644
index 0000000000..eda24e3acb
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/__tests__/mediaDownloadApproval.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { Session } from '@cindy/maker-core';
+import { createMediaDownloadContext } from '../mediaDownloadApproval.js';
+
+const mocks = vi.hoisted(() => ({ request: vi.fn() }));
+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
+vi.mock('../../maker-ipc/interactionRouter.js', () => ({ requestHostInteraction: mocks.request }));
+
+function hostSession() {
+ let status = 'active';
+ let onStatus = () => {};
+ const unsubscribe = vi.fn();
+ const session = {
+ id: 'task-1', instanceId: 'instance-1',
+ runHostInteraction: (_request: unknown, resolve: () => Promise<unknown>) => resolve(),
+ getTurnGeneration: () => 1,
+ getStatus: () => status,
+ isTurnRunning: () => status === 'active',
+ onStatusChange: (listener: () => void) => { onStatus = listener; return unsubscribe; },
+ } as unknown as Session;
+ return { session, unsubscribe, stop: () => { status = 'aborting'; onStatus(); } };
+}
+
+describe('Host media permission', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('uses an ordinary single-use permission request with a reason and sanitized source', async () => {
+ const host = hostSession();
+ const ctx = createMediaDownloadContext(host.session, () => true);
+ mocks.request.mockResolvedValue({ kind: 'permission', behavior: 'allow', updatedInput: { approved: true } });
+ try {
+ await expect(ctx.confirm({ origin: 'https://cdn.example.com', reasons: ['source'] })).resolves.toBe(true);
+ const [session, request, signal] = mocks.request.mock.calls.at(-1)!;
+ expect(session).toBe(host.session);
+ expect(request).toMatchObject({ kind: 'permission', toolName: 'cindy.media.download', input: { source: 'https://cdn.example.com' } });
+ expect(request.description).toContain('newChat.mediaDownload.source');
+ expect(request.suggestions).toBeUndefined();
+ expect(signal).toBeInstanceOf(AbortSignal);
+ } finally { ctx.dispose?.(); }
+ expect(host.unsubscribe).toHaveBeenCalledOnce();
+ });
+
+ it('rejects a late approval after the task stops', async () => {
+ const host = hostSession();
+ const ctx = createMediaDownloadContext(host.session, () => true);
+ mocks.request.mockImplementation(async () => { host.stop(); return { kind: 'permission', behavior: 'allow' }; });
+ try {
+ await expect(ctx.confirm({ origin: 'https://cdn.example.com', reasons: ['network'] })).rejects.toMatchObject({ code: 'MEDIA_DOWNLOAD_DEFERRED' });
+ expect(ctx.signal?.aborted).toBe(true);
+ } finally { ctx.dispose?.(); }
+ });
+
+ it('rejects approval when the live task instance changes', async () => {
+ const host = hostSession();
+ let current = true;
+ const ctx = createMediaDownloadContext(host.session, () => current);
+ mocks.request.mockImplementation(async () => { current = false; return { kind: 'permission', behavior: 'allow' }; });
+ try {
+ await expect(ctx.confirm({ origin: 'https://cdn.example.com', reasons: ['source'] })).rejects.toMatchObject({ code: 'MEDIA_DOWNLOAD_DEFERRED' });
+ } finally { ctx.dispose?.(); }
+ });
+});
diff --git a/apps/desktop/src/main/cindy-media/__tests__/mediaInvocationStore.test.ts b/apps/desktop/src/main/cindy-media/__tests__/mediaInvocationStore.test.ts
new file mode 100644
index 0000000000..a8680c527b
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/__tests__/mediaInvocationStore.test.ts
@@ -0,0 +1,34 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import Database from 'better-sqlite3';
+import { describe, expect, it, vi } from 'vitest';
+import type { DbClient } from '../../localDb/client/DbClient.js';
+import { countMediaInvocations, pruneMediaInvocations } from '../mediaInvocationStore.js';
+
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: vi.fn() }));
+
+describe('saved generation responses', () => {
+ it('keeps undownloaded results across pruning without exhausting generation slots', async () => {
+ const raw = new Database(':memory:');
+ try {
+ raw.exec(readFileSync(path.resolve(__dirname, '../../../../drizzle/0092_fixed_zeigeist.sql'), 'utf8'));
+ const insert = raw.prepare(`INSERT INTO media_invocations
+ (id, owner, model_id, capability, guide_revision, guide_json, state, response_json, created_at, updated_at)
+ VALUES (?, ?, 'model', 'image.generate', 'v1', '{}', ?, ?, 1, 1)`);
+ insert.run('saved', 'owner', 'pending', '{"data":"saved-response"}');
+ insert.run('running', 'owner', 'pending', null);
+ insert.run('prepared', 'owner', 'prepared', null);
+ insert.run('complete', 'owner', 'complete', '{}');
+ insert.run('other-owner', 'other', 'pending', null);
+ const db = {
+ exec: async (sql: string, args: unknown[]) => raw.prepare(sql).run(...args),
+ queryOne: async (sql: string, args: unknown[]) => raw.prepare(sql).get(...args),
+ } as unknown as DbClient;
+ expect(await countMediaInvocations('owner', db)).toBe(2);
+ await pruneMediaInvocations({ owner: 'owner', preparedBefore: 2, terminalBefore: 2 }, db);
+ expect(raw.prepare('SELECT id FROM media_invocations ORDER BY id').all()).toEqual([
+ { id: 'other-owner' }, { id: 'saved' },
+ ]);
+ } finally { raw.close(); }
+ });
+});
diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.ts
index 7e19e28773..bf04547e7d 100644
--- a/apps/desktop/src/main/cindy-media/invocationService.ts
+++ b/apps/desktop/src/main/cindy-media/invocationService.ts
@@ -32,6 +32,7 @@ import {
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
import * as blobStore from './blobStore.js';
import { ingestMedia } from './ingest.js';
+import { downloadMediaResult, MediaDownloadError, type MediaDownloadContext } from './mediaDownload.js';
import { mediaRequestParamsForLog, mediaRequestUrlForLog } from './mediaRequestLog.js';
import {
invokeProviderMedia,
@@ -61,19 +62,7 @@ const MAX_MEDIA_RESULTS = 16;
const MAX_LOCAL_MEDIA_INPUTS = 32;
const MAX_LOCAL_MEDIA_INPUT_TOTAL_BYTES = 128 * 1024 * 1024;
const FORBIDDEN_PATH_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);
-const TERMINAL_MEDIA_RESULT_ERRORS = new Set([
- 'MEDIA_DOWNLOAD_REJECTED',
- 'MEDIA_RESULT_INVALID',
- 'MEDIA_RESULT_MISSING',
- 'MEDIA_RESULT_TOO_LARGE',
- 'RESPONSE_TOO_LARGE',
-]);
const CLIENT_PROVIDER_IMAGE_GUIDE_ID = 'cindy-provider-image-v1';
-// Gateway Guides can lag behind vendor CDN rotation. Keep this map keyed by the
-// vendor namespace already present in the executable Core model identity.
-const MODEL_NAMESPACE_MEDIA_HOST_SUFFIXES = new Map<string, readonly string[]>([
- ['minimax', ['minimax.io', 'minimaxi.com']],
-]);
interface MediaConnection {
baseUrl: string;
@@ -92,14 +81,17 @@ class MediaInvocationError extends Error {
}
const recoveredDatabases = new WeakSet<DbClient>();
+// Only coalesce active operations; the persisted invocation remains the result source.
+const activeInvocations = new Set<string>();
interface MediaAuthScope {
owner: string;
dbOwnerId: string;
generation: number;
+ downloadContext?: MediaDownloadContext;
}
-function currentAuthScope(): MediaAuthScope {
+function currentAuthScope(downloadContext?: MediaDownloadContext): MediaAuthScope {
const state = authManager.getAuthState();
const userId = state.user?.id ?? null;
const dbOwnerId = state.dataOwnerId;
@@ -110,10 +102,12 @@ function currentAuthScope(): MediaAuthScope {
owner: `${authManager.getActiveAuthRealm()}:${userId}`,
dbOwnerId,
generation: state.ownerGeneration,
+ downloadContext,
};
}
function assertAuthScope(scope: MediaAuthScope, expectedOwner = scope.owner): void {
+ scope.downloadContext?.assertActive();
const current = currentAuthScope();
if (
current.owner !== expectedOwner ||
@@ -758,66 +752,23 @@ function assertResultMime(kind: MediaResultKind, mimeType: string): void {
}
}
-function allowedDownloadUrl(raw: string, extractor: MediaResultExtractor): URL {
- let parsed: URL;
- try {
- parsed = new URL(raw);
- } catch {
- throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 不合法');
- }
- if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
- throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 必须是 HTTPS');
- }
- const hostname = parsed.hostname.toLowerCase();
- if (parsed.port) {
- throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 不允许自定义端口');
- }
- const allowed = (extractor.allowedUrlHosts ?? []).some((suffix) => {
- const normalized = suffix.toLowerCase();
- return hostname === normalized || hostname.endsWith(`.${normalized}`);
- });
- if (!allowed) {
- throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游媒体 URL 不在调用说明的可信域名内');
- }
- return parsed;
-}
-
async function mediaBytes(
raw: string,
extractor: MediaResultExtractor,
+ scope: MediaAuthScope,
): Promise<{ buffer: Buffer; mimeType: string }> {
let buffer: Buffer;
let headerMime: string | null = null;
if (extractor.encoding === 'url') {
- const url = allowedDownloadUrl(raw, extractor);
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 120_000);
- timeout.unref?.();
- try {
- const response = await outboundFetch(url.toString(), {
- method: 'GET',
- redirect: 'error',
- signal: controller.signal,
- });
- if (!response.ok) {
- const permanentClientError =
- response.status >= 400 &&
- response.status < 500 &&
- ![408, 425, 429].includes(response.status);
- throw new MediaInvocationError(
- permanentClientError ? 'MEDIA_DOWNLOAD_REJECTED' : 'MEDIA_DOWNLOAD_FAILED',
- `媒体下载失败 (HTTP ${response.status})`,
- );
- }
- headerMime =
- response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() ?? null;
- buffer = await readBoundedResponse(response, maxResultBytes(extractor.kind));
- } catch (error) {
- if (error instanceof MediaInvocationError) throw error;
- throw new MediaInvocationError('MEDIA_DOWNLOAD_FAILED', '媒体下载超时或网络失败');
- } finally {
- clearTimeout(timeout);
- }
+ const downloaded = await downloadMediaResult({
+ raw,
+ allowedHosts: extractor.allowedUrlHosts,
+ maxBytes: maxResultBytes(extractor.kind),
+ context: scope.downloadContext,
+ assertActive: () => assertAuthScope(scope),
+ });
+ buffer = downloaded.buffer;
+ headerMime = downloaded.headerMime;
} else {
const dataUrl = /^data:([^;,]+);base64,(.+)$/s.exec(raw);
const encoded = (dataUrl ? dataUrl[2] : raw).replace(/\s/g, '');
@@ -830,7 +781,7 @@ async function mediaBytes(
}
buffer = Buffer.from(encoded, 'base64');
}
- if (buffer.byteLength === 0 || buffer.byteLength > maxResultBytes(extractor.kind)) {
+ if (buffer.byteLength === 0 || (extractor.encoding !== 'url' && buffer.byteLength > maxResultBytes(extractor.kind))) {
throw new MediaInvocationError('MEDIA_RESULT_INVALID', '上游返回空媒体或媒体超过大小限制');
}
// Guide / Content-Type 只能帮助识别容器变体(例如无 ftyp 的 QuickTime),
@@ -870,7 +821,7 @@ async function materializeResults(
assertAuthScope(scope);
let media: Awaited<ReturnType<typeof mediaBytes>>;
try {
- media = await mediaBytes(item.raw, item.extractor);
+ media = await mediaBytes(item.raw, item.extractor, scope);
} catch (error) {
// 账号切换与下载失败同时发生时,账号边界优先,避免旧账号结果继续落状态。
assertAuthScope(scope);
@@ -929,31 +880,6 @@ function completedInvocationResult(invocation: StoredMediaInvocation): Record<st
};
}
-function withVendorMediaUrlHosts(
- guide: PreparedMediaInvocationGuide,
-): PreparedMediaInvocationGuide {
- const namespace = guide.modelId.slice(0, guide.modelId.indexOf('/')).toLowerCase();
- const vendorHosts = MODEL_NAMESPACE_MEDIA_HOST_SUFFIXES.get(namespace);
- if (!vendorHosts) return guide;
-
- const expand = (extractors: readonly MediaResultExtractor[]) =>
- extractors.map((extractor) => {
- if (extractor.encoding !== 'url') return extractor;
- return {
- ...extractor,
- allowedUrlHosts: [...new Set([...(extractor.allowedUrlHosts ?? []), ...vendorHosts])],
- };
- });
- const response = guide.response;
- if (response.mode === 'sync') {
- return { ...guide, response: { ...response, media: expand(response.media) } };
- }
- return {
- ...guide,
- response: { ...response, poll: { ...response.poll, media: expand(response.poll.media) } },
- };
-}
-
async function persistCompletedInvocation(
invocation: StoredMediaInvocation,
media: Record<string, unknown>,
@@ -1119,34 +1045,20 @@ async function materializeSyncInvocation(
return persistCompletedInvocation(invocation, media, scope, db);
} catch (error) {
assertAuthScope(scope, invocation.owner);
- if (error instanceof MediaInvocationError) {
- if (TERMINAL_MEDIA_RESULT_ERRORS.has(error.code)) {
- await transitionMediaInvocation(
- {
- id: invocation.id,
- owner: invocation.owner,
- from: 'pending',
- to: 'failed',
- },
- db,
- );
- assertAuthScope(scope, invocation.owner);
- return failure(error.code, error.message);
- }
- if (error.code === 'MEDIA_DOWNLOAD_FAILED') {
- return {
- ...failure(error.code, error.message, true),
- retry_action: 'request',
- };
- }
- throw error;
+ if (error instanceof MediaInvocationError || error instanceof MediaDownloadError) {
+ // Network recovery is owned by the client. Do not ask the agent to start
+ // another operation (and a fresh approval) after denial or exhausted retries.
+ return {
+ ...failure(error.code, error.message, false),
+ invocation_id: invocation.id,
+ };
}
log.warn('sync media materialization failed', {
error: error instanceof Error ? error.message : String(error),
});
return {
- ...failure('MEDIA_MATERIALIZATION_FAILED', '媒体结果暂时无法保存', true),
- retry_action: 'request',
+ ...failure('MEDIA_MATERIALIZATION_FAILED', '媒体结果暂时无法保存', false),
+ invocation_id: invocation.id,
};
}
}
@@ -1251,12 +1163,12 @@ async function prepareInvocation(
}
const { operations: _operations, ...guideProtocol } = resolvedGuide.guide;
void _operations;
- preparedGuide = withVendorMediaUrlHosts({
+ preparedGuide = {
// Guide 查询键不参与调用身份;配置、持久化和 Gateway 请求始终使用完整 modelId。
modelId: resolvedModelId,
...guideProtocol,
...operation,
- });
+ };
}
await pruneInvocations(owner, db);
assertAuthScope(scope);
@@ -1311,8 +1223,9 @@ async function requireInvocation(id: string): Promise<StoredMediaInvocation> {
async function submitInvocation(
invocation: StoredMediaInvocation,
body: Record<string, unknown>,
+ context?: MediaDownloadContext,
): Promise<Record<string, unknown>> {
- const scope = currentAuthScope();
+ const scope = currentAuthScope(context);
assertAuthScope(scope, invocation.owner);
const db = captureMediaDb(scope);
if (invocation.state === 'complete') {
@@ -1567,40 +1480,30 @@ async function materializeAsyncInvocation(
return persistCompletedInvocation(invocation, media, scope, db);
} catch (error) {
assertAuthScope(scope, invocation.owner);
- if (error instanceof MediaInvocationError) {
- if (TERMINAL_MEDIA_RESULT_ERRORS.has(error.code)) {
- await transitionMediaInvocation(
- {
- id: invocation.id,
- owner: invocation.owner,
- from: 'pending',
- to: 'failed',
- },
- db,
- );
- assertAuthScope(scope, invocation.owner);
- return failure(error.code, error.message);
- }
- if (error.code === 'MEDIA_DOWNLOAD_FAILED') {
- return {
- ...failure(error.code, error.message, true),
- retry_action: 'poll',
- };
- }
- throw error;
+ if (error instanceof MediaInvocationError || error instanceof MediaDownloadError) {
+ // Network recovery is owned by the client. Do not ask the agent to start
+ // another operation (and a fresh approval) after denial or exhausted retries.
+ return {
+ ...failure(error.code, error.message, false),
+ invocation_id: invocation.id,
+ };
}
log.warn('async media materialization failed', {
error: error instanceof Error ? error.message : String(error),
});
return {
- ...failure('MEDIA_MATERIALIZATION_FAILED', '媒体结果暂时无法保存', true),
- retry_action: 'poll',
+ ...failure('MEDIA_MATERIALIZATION_FAILED', '媒体结果暂时无法保存', false),
+ invocation_id: invocation.id,
};
}
}
-async function pollInvocation(invocation: StoredMediaInvocation): Promise<Record<string, unknown>> {
- const scope = currentAuthScope();
+async function pollInvocation(
+ invocation: StoredMediaInvocation,
+ context?: MediaDownloadContext,
+ refreshExpiredUrl = false,
+): Promise<Record<string, unknown>> {
+ const scope = currentAuthScope(context);
assertAuthScope(scope, invocation.owner);
const db = captureMediaDb(scope);
if (invocation.guide.response.mode !== 'async') {
@@ -1613,7 +1516,7 @@ async function pollInvocation(invocation: StoredMediaInvocation): Promise<Record
return failure('INVOCATION_NOT_PENDING', `该 invocation 当前状态为 ${invocation.state}`);
}
const guide = invocation.guide.response.poll;
- if (invocation.responseJson) {
+ if (invocation.responseJson && !refreshExpiredUrl) {
// 已有成功响应的 poll 是结果恢复重试;刷新活动时间,避免仍在主动恢复的
// 已付费结果被常规 TTL 清理。保持 pending,不引入新的本地状态。
await transitionMediaInvocation(
@@ -1626,7 +1529,11 @@ async function pollInvocation(invocation: StoredMediaInvocation): Promise<Record
db,
);
assertAuthScope(scope, invocation.owner);
- return materializeAsyncInvocation(invocation, persistedResponse(invocation), scope, db);
+ const restored = await materializeAsyncInvocation(invocation, persistedResponse(invocation), scope, db);
+ if (restored.errorCode !== 'MEDIA_DOWNLOAD_URL_EXPIRED') return restored;
+ // Refresh an expired signed URL through the existing read-only task poll.
+ // Never submit another paid generation to repair a download.
+ refreshExpiredUrl = true;
}
try {
const response = await dispatchRequest({
@@ -1675,12 +1582,21 @@ async function pollInvocation(invocation: StoredMediaInvocation): Promise<Record
}
return failure('POLL_UNAVAILABLE', '上游结果已生成,但本地未能保存结果', true);
}
- return materializeAsyncInvocation(
+ const downloaded = await materializeAsyncInvocation(
{ ...invocation, responseJson },
response,
scope,
db,
);
+ if (downloaded.errorCode === 'MEDIA_DOWNLOAD_URL_EXPIRED' && !refreshExpiredUrl) {
+ return pollInvocation({ ...invocation, responseJson }, context, true);
+ }
+ return downloaded;
+ }
+ if (invocation.responseJson) {
+ return failure('MEDIA_DOWNLOAD_FAILED', '暂时无法刷新下载地址,已保留原生成结果', false, {
+ invocation_id: invocation.id,
+ });
}
if (guide.failureValues.includes(status)) {
await transitionMediaInvocation(
@@ -1703,17 +1619,21 @@ async function pollInvocation(invocation: StoredMediaInvocation): Promise<Record
recommended_poll_after_ms: guide.recommendedIntervalMs,
};
} catch (error) {
+ assertAuthScope(scope, invocation.owner);
+ if (error instanceof MediaDownloadError) return failure(error.code, error.message, false);
if (error instanceof MediaInvocationError) {
- // Poll is read-only/idempotent: transient failure does not invalidate the submitted task.
- return failure(error.code, error.message, true);
+ // Polling an unfinished generation is safe to retry; completed-result
+ // recovery must not start a new operation after its client retries finish.
+ return failure(error.code, error.message, !invocation.responseJson);
}
- return failure('POLL_UNAVAILABLE', '媒体任务状态查询失败', true);
+ return failure('POLL_UNAVAILABLE', '媒体任务状态查询失败', !invocation.responseJson);
}
}
/** 当前 Agent 永久注册的 `mcp__cindy__media` 工具实现;不暴露给插件运行时。 */
export async function callCindyMedia(
request: CindyMediaToolRequest,
+ context?: MediaDownloadContext,
): Promise<Record<string, unknown>> {
try {
if (request.action === 'resolve_local_path') {
@@ -1808,11 +1728,20 @@ export async function callCindyMedia(
);
}
const invocation = await requireInvocation(request.invocationId);
- return await (request.action === 'request'
- ? submitInvocation(invocation, request.body)
- : pollInvocation(invocation));
+ const operationKey = `${invocation.owner}:${invocation.id}`;
+ if (activeInvocations.has(operationKey)) {
+ return failure('MEDIA_INVOCATION_BUSY', '此媒体操作正在进行,请等待当前下载或确认完成', false);
+ }
+ activeInvocations.add(operationKey);
+ try {
+ return await (request.action === 'request'
+ ? submitInvocation(invocation, request.body, context)
+ : pollInvocation(invocation, context));
+ } finally {
+ activeInvocations.delete(operationKey);
+ }
} catch (error) {
- if (error instanceof MediaInvocationError) return failure(error.code, error.message);
+ if (error instanceof MediaInvocationError || error instanceof MediaDownloadError) return failure(error.code, error.message);
if (error instanceof MediaModelCatalogError) {
log.warn('media model catalog rejected by current client', { detail: error.detail });
return failure('MODEL_CATALOG_UNAVAILABLE', error.message, true, {
diff --git a/apps/desktop/src/main/cindy-media/mediaDownload.ts b/apps/desktop/src/main/cindy-media/mediaDownload.ts
new file mode 100644
index 0000000000..bf03d494f8
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/mediaDownload.ts
@@ -0,0 +1,216 @@
+import { createHash } from 'node:crypto';
+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';
+
+/** 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>;
+}
+
+export class MediaDownloadError extends Error {
+ constructor(readonly code: string, message: string) {
+ super(message);
+ this.name = 'MediaDownloadError';
+ }
+}
+
+function parseUrl(raw: string, base?: URL): URL {
+ try {
+ const url = new URL(raw, base);
+ if (url.protocol === 'https:' || url.protocol === 'http:') return url;
+ } catch { /* Report without the signed URL. */ }
+ throw new MediaDownloadError('MEDIA_RESULT_INVALID', '生成结果的下载地址无效,已保留原结果');
+}
+
+/** A GET-only, credential-isolated download. Approval never grants another result or invocation. */
+export async function downloadMediaResult(input: {
+ raw: string;
+ allowedHosts?: string[];
+ maxBytes: number;
+ context?: MediaDownloadContext;
+ assertActive(): void;
+}): Promise<{ buffer: Buffer; headerMime: string | null }> {
+ 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) => {
+ const credentials = reason === 'credentials'
+ ? createHash('sha256').update(`${url.username}:${url.password}`).digest('hex') : '';
+ return `${url.origin}:${reason}:${credentials}`;
+ };
+ const assertActive = () => {
+ input.assertActive();
+ input.context?.assertActive();
+ };
+ const confirm = async (reasons: MediaDownloadReason[], bytes?: number) => {
+ assertActive();
+ if (!input.context) {
+ throw new MediaDownloadError('MEDIA_DOWNLOAD_CONFIRMATION_REQUIRED', '本次下载需要用户确认,当前任务的审批通道不可用');
+ }
+ const allowed = await input.context.confirm({ origin: url.origin, reasons, ...(bytes ? { bytes } : {}) });
+ assertActive();
+ if (!allowed) {
+ throw new MediaDownloadError('MEDIA_DOWNLOAD_DENIED', '用户未允许本次下载,已停止;不要自动重试或再次请求审批');
+ }
+ for (const reason of reasons) approved.add(approvalKey(reason));
+ };
+
+ 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();
+ return url.hostname === host || url.hostname.endsWith(`.${host}`);
+ });
+ if (!knownHost) reasons.push('source');
+ if (url.protocol === 'http:') reasons.push('http');
+ if (url.port) reasons.push('port');
+ if (url.username || url.password) reasons.push('credentials');
+ const missing = reasons.filter((reason) => !approved.has(approvalKey(reason)));
+ if (missing.length) await confirm(missing);
+
+ // The network budget excludes human decisions, but includes every DNS lookup,
+ // response and retry. No body or dispatcher is held while showing a card.
+ if (remainingMs <= 0) throw new MediaDownloadError('MEDIA_DOWNLOAD_FAILED', '下载超时,客户端重试未能完成,原生成结果已保留');
+ const target = new URL(url);
+ // URL credentials, when explicitly approved, belong only to this exact hop.
+ let authorization: string | undefined;
+ try {
+ if (target.username || target.password) {
+ authorization = `Basic ${Buffer.from(`${decodeURIComponent(target.username)}:${decodeURIComponent(target.password)}`).toString('base64')}`;
+ }
+ } catch {
+ throw new MediaDownloadError('MEDIA_RESULT_INVALID', '下载地址的登录信息格式无效');
+ }
+ target.username = '';
+ target.password = '';
+ const controller = new AbortController();
+ const signal = input.context?.signal
+ ? AbortSignal.any([controller.signal, input.context.signal]) : controller.signal;
+ const startedAt = Date.now();
+ const timeout = setTimeout(() => controller.abort(), remainingMs);
+ timeout.unref?.();
+ let idleTimeout: ReturnType<typeof setTimeout> | undefined;
+ const resetIdleTimeout = () => {
+ clearTimeout(idleTimeout);
+ idleTimeout = setTimeout(() => controller.abort(), 30_000);
+ idleTimeout.unref?.();
+ };
+ resetIdleTimeout();
+ let decisionNeeded: MediaDownloadReason | undefined;
+ let retryError: MediaDownloadError | undefined;
+ let requestedBytes: number | undefined;
+ let result: { buffer: Buffer; headerMime: string | null } | undefined;
+ try {
+ const allowPrivateNetwork = approved.has(approvalKey('network'));
+ const { response, release } = await guardedOutboundFetch(
+ target.href,
+ {
+ method: 'GET', redirect: 'manual', signal,
+ ...(authorization ? { headers: { Authorization: authorization } } : {}),
+ },
+ assertActive,
+ { targetUrl: target.href, allowHttp: url.protocol === 'http:', allowPrivateNetwork },
+ );
+ resetIdleTimeout();
+ try {
+ assertActive();
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
+ const location = response.headers.get('location');
+ if (!location) throw new MediaDownloadError('MEDIA_DOWNLOAD_FAILED', '下载服务未返回跳转地址,生成结果已保留');
+ // Do not inherit embedded credentials, even on a relative redirect.
+ const redirected = parseUrl(location, target);
+ if (visitedRedirects.has(redirected.href)) {
+ throw new MediaDownloadError('MEDIA_DOWNLOAD_REDIRECT_LOOP', '下载服务返回循环跳转,下载未能完成');
+ }
+ visitedRedirects.add(redirected.href);
+ url = redirected;
+ } 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,
+ };
+ }
+ }
+ }
+ } finally {
+ try { await response.body?.cancel().catch(() => undefined); }
+ finally { await release(); }
+ }
+ } catch (error) {
+ assertActive();
+ if (error instanceof SsrFBlockedError && !approved.has(approvalKey('network'))) {
+ decisionNeeded = 'network';
+ } else if (error instanceof MediaDownloadError && error.code !== 'MEDIA_DOWNLOAD_FAILED') {
+ throw error;
+ } else {
+ retryError = new MediaDownloadError('MEDIA_DOWNLOAD_FAILED', '客户端重试后仍未完成下载,原生成结果已保留');
+ }
+ } finally {
+ clearTimeout(timeout);
+ clearTimeout(idleTimeout);
+ remainingMs -= Date.now() - startedAt;
+ }
+ if (retryError) {
+ // Retry only transient network failures. Human denial never enters this branch.
+ // Keep approvals and the exact current target; do not resubmit generation.
+ if (++failures >= 3 || remainingMs <= 0) throw retryError;
+ const backoff = Math.min(250 * 2 ** (failures - 1), remainingMs);
+ await delay(backoff, undefined, { signal: input.context?.signal });
+ remainingMs -= backoff;
+ assertActive();
+ continue;
+ }
+ if (decisionNeeded) {
+ await confirm([decisionNeeded], requestedBytes);
+ if (requestedBytes) byteLimits.set(resourceKey, requestedBytes);
+ } else if (result) {
+ assertActive();
+ return result;
+ }
+ }
+}
diff --git a/apps/desktop/src/main/cindy-media/mediaDownloadApproval.ts b/apps/desktop/src/main/cindy-media/mediaDownloadApproval.ts
new file mode 100644
index 0000000000..1e65080c17
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/mediaDownloadApproval.ts
@@ -0,0 +1,54 @@
+import { randomUUID } from 'node:crypto';
+import type { InteractionRequest, Session } from '@cindy/maker-core';
+import { t } from '../i18n.js';
+import { requestHostInteraction } from '../maker-ipc/interactionRouter.js';
+import { MediaDownloadError, type MediaDownloadContext } from './mediaDownload.js';
+
+/** Bind approval to the live Host turn, never to a model-supplied approval flag. */
+export function createMediaDownloadContext(
+ session: Session,
+ isCurrent: () => boolean,
+): 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 = () => {
+ if (!isActive() || controller.signal.aborted) {
+ throw new MediaDownloadError('MEDIA_DOWNLOAD_DEFERRED', '本次下载已停止,原生成结果已保留');
+ }
+ };
+ const unsubscribe = session.onStatusChange(() => {
+ if (!isActive()) controller.abort();
+ });
+ return {
+ approvals: new Set<string>(),
+ byteLimits: new Map<string, number>(),
+ signal: controller.signal,
+ dispose: () => { clearTimeout(deadline); unsubscribe(); },
+ assertActive,
+ confirm: async ({ origin, reasons, bytes }) => {
+ assertActive();
+ // Leave time for the download inside the enclosing ten-minute MCP call.
+ 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 request: InteractionRequest = {
+ kind: 'permission',
+ requestId: randomUUID(),
+ toolName: 'cindy.media.download',
+ title: t('newChat.mediaDownload.title'),
+ description: `${t('newChat.mediaDownload.description')}\n${details}\n${t('newChat.mediaDownload.scope')}`,
+ input: { source: origin },
+ metadata: { hostOwnedConfirmation: 'media_download' },
+ };
+ const decision = await session.runHostInteraction(request, () =>
+ requestHostInteraction(session, request, approvalSignal));
+ assertActive();
+ // No permissionUpdates or updatedInput is consumed. Only this request can be approved.
+ return decision.kind === 'permission' && decision.behavior === 'allow';
+ },
+ };
+}
diff --git a/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts b/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts
index ddf4533b9b..bace721451 100644
--- a/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts
+++ b/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts
@@ -93,7 +93,8 @@ export async function pruneMediaInvocations(
`DELETE FROM media_invocations
WHERE owner = ? AND (
(state = 'prepared' AND created_at < ?)
- OR (state IN ('pending', 'complete', 'failed', 'unknown') AND updated_at < ?)
+ OR (state IN ('pending', 'complete', 'failed', 'unknown') AND updated_at < ?
+ AND NOT (state = 'pending' AND response_json IS NOT NULL))
)`,
[input.owner, input.preparedBefore, input.terminalBefore],
);
@@ -106,7 +107,8 @@ export async function countMediaInvocations(
const row = await db.queryOne<{ count: number }>(
`SELECT COUNT(*) AS count
FROM media_invocations
- WHERE owner = ? AND state IN ('prepared', 'submitting', 'pending')`,
+ WHERE owner = ? AND (state IN ('prepared', 'submitting')
+ OR (state = 'pending' AND response_json IS NULL))`,
[owner],
);
return Number(row?.count ?? 0);
diff --git a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts
index 305b9cb9ff..ca94ccc9f2 100644
--- a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts
@@ -1,4 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createServer } from 'node:http';
+import type { AddressInfo } from 'node:net';
import { Agent as UndiciAgent, Dispatcher, ProxyAgent } from 'undici';
import { Socks5HttpsAgent, TunnelingHttpsAgent } from '@cindy/anthropic-compat-proxy';
@@ -371,6 +373,73 @@ describe('outboundFetch', () => {
}
});
+ it.each([null, undefined])('handles a pre-connect error with controller %s', async (missing) => {
+ const controller = missing as unknown as Dispatcher.DispatchController;
+ const error = new Error('proxy handshake failed');
+ const responseError = vi.fn();
+ const beforeRetry = vi.fn();
+ const spy = vi
+ .spyOn(ProxyAgent.prototype, 'dispatch')
+ .mockImplementation((_options, handler) => {
+ handler.onResponseError?.(controller, error);
+ return true;
+ });
+ const dispatcher = createPinnedProxyDispatcher(
+ { kind: 'http', url: 'http://127.0.0.1:7890', hostname: '127.0.0.1', port: 7890 },
+ new URL('https://cdn.example.com/file'),
+ ['93.184.216.34', '93.184.216.35'],
+ beforeRetry,
+ );
+ try {
+ dispatcher.dispatch(
+ { origin: 'https://cdn.example.com', path: '/file', method: 'GET' },
+ {
+ onResponseError: responseError,
+ },
+ );
+ await vi.waitFor(() => expect(responseError).toHaveBeenCalledWith(controller, error));
+ expect(spy).toHaveBeenCalledTimes(2);
+ expect(beforeRetry).toHaveBeenCalledOnce();
+ } finally {
+ await dispatcher.close();
+ spy.mockRestore();
+ }
+ });
+
+ it('does not retry after cancellation while rechecking a pre-connect failure', async () => {
+ const signalController = new AbortController();
+ const error = new Error('proxy handshake failed');
+ const responseError = vi.fn();
+ const spy = vi
+ .spyOn(ProxyAgent.prototype, 'dispatch')
+ .mockImplementation((_options, handler) => {
+ handler.onResponseError?.(undefined as unknown as Dispatcher.DispatchController, error);
+ return true;
+ });
+ const dispatcher = createPinnedProxyDispatcher(
+ { kind: 'http', url: 'http://127.0.0.1:7890', hostname: '127.0.0.1', port: 7890 },
+ new URL('https://cdn.example.com/file'),
+ ['93.184.216.34', '93.184.216.35'],
+ () => {
+ signalController.abort();
+ },
+ signalController.signal,
+ );
+ try {
+ dispatcher.dispatch(
+ { origin: 'https://cdn.example.com', path: '/file', method: 'GET' },
+ {
+ onResponseError: responseError,
+ },
+ );
+ await vi.waitFor(() => expect(responseError).toHaveBeenCalledOnce());
+ expect(spy).toHaveBeenCalledOnce();
+ } finally {
+ await dispatcher.close();
+ spy.mockRestore();
+ }
+ });
+
it('does not try another proxy target when retry authorization has expired', async () => {
const dispatchSpy = vi.spyOn(ProxyAgent.prototype, 'dispatch');
const controller = {} as Dispatcher.DispatchController;
@@ -446,6 +515,37 @@ describe('outboundFetch', () => {
);
});
+ it('allows only the explicitly approved network target and keeps manual redirects', async () => {
+ const requests: Array<{ path?: string; method?: string; authorization?: string }> = [];
+ // The shared runtime resolves its own undici version; use a server owned by
+ // this test instead of relying on the Desktop-only fetch mock above.
+ const server = createServer((request, response) => {
+ requests.push({ path: request.url, method: request.method, authorization: request.headers.authorization });
+ response.writeHead(302, { location: '/unapproved' });
+ response.end();
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/video`;
+ try {
+ const result = await guardedOutboundFetch(url, { method: 'GET' }, vi.fn(), {
+ targetUrl: url, allowHttp: true, allowPrivateNetwork: true,
+ });
+ try {
+ expect(result.response.status).toBe(302);
+ expect(result.response.headers.get('location')).toBe('/unapproved');
+ } finally {
+ await result.response.body?.cancel();
+ await result.release();
+ }
+ await expect(guardedOutboundFetch(new URL('/unapproved', url).href, { method: 'GET' }, vi.fn(), {
+ targetUrl: url, allowHttp: true, allowPrivateNetwork: true,
+ })).rejects.toThrow('approval target mismatch');
+ expect(requests).toEqual([{ path: '/video', method: 'GET', authorization: undefined }]);
+ } finally {
+ await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
+ }
+ });
+
it('passes the proxy dispatcher through to undici fetch', async () => {
resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
await outboundFetch('https://platform.claude.com/v1/oauth/token', { method: 'POST' });
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 90c87343bb..fcbb2f671d 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -8,6 +8,7 @@
* 这样可以确保 localDb.ensureReady(userId) 已经完成才能用 SessionStorage。
*/
+import { createMediaDownloadContext } from '../cindy-media/mediaDownloadApproval.js';
import { readCodexContextWindowInfo } from './codex-context-window.js';
import { app, BrowserWindow } from 'electron';
import { createHash } from 'node:crypto';
@@ -832,6 +833,11 @@ export function getMaker(): Maker {
};
const makerMemoryProviderDeps = {
+ createMediaDownloadContext: (sessionId: string, sessionInstanceId: string) => {
+ const session = _maker?.getSession(sessionId);
+ if (!session || session.instanceId !== sessionInstanceId) return undefined;
+ return createMediaDownloadContext(session, () => _maker?.getSession(sessionId) === session);
+ },
getAppVersion: () => app.getVersion(),
getMakerMemoryManager: () => makerMemoryManager,
lspPool: getLspPool(),
diff --git a/apps/desktop/src/main/maker-host/outbound-fetch.ts b/apps/desktop/src/main/maker-host/outbound-fetch.ts
index ee0503d081..fcaf4bdce5 100644
--- a/apps/desktop/src/main/maker-host/outbound-fetch.ts
+++ b/apps/desktop/src/main/maker-host/outbound-fetch.ts
@@ -496,6 +496,7 @@ export function createPinnedProxyDispatcher(
upstream: URL,
addresses: readonly string[],
beforeRetry: () => void | Promise<void>,
+ signal?: AbortSignal,
): Dispatcher {
if (addresses.length === 0) throw new Error(`Unable to resolve hostname: ${upstream.hostname}`);
const base = createProxyDispatcher(
@@ -533,12 +534,12 @@ export function createPinnedProxyDispatcher(
// HTTPS CONNECT / SOCKS5 握手失败发生在 onRequestStart 之前;一旦请求开始,
// 就不能为了换 IP 而重放可能产生副作用的 POST。切换到下一个已审核 IP
// 也是一次新的真实派发,必须重新确认 callId 仍处于授权窗口。
- if (!requestStarted && !controller.aborted && index + 1 < addresses.length) {
+ if (!requestStarted && !controller?.aborted && !signal?.aborted && index + 1 < addresses.length) {
void Promise.resolve()
.then(beforeRetry)
.then(
() => {
- if (controller.aborted) {
+ if (controller?.aborted || signal?.aborted) {
handler.onResponseError?.(controller, error);
return;
}
@@ -602,19 +603,27 @@ export async function guardedOutboundFetch(
url: string,
init: RequestInit,
beforeDispatch: () => void | Promise<void>,
+ approval?: { targetUrl: string; allowHttp?: boolean; allowPrivateNetwork?: boolean },
): Promise<{ response: Response; release: () => Promise<void> }> {
const upstream = new URL(url);
+ // Host-owned, single-target exception. Never inherit it across a redirect.
+ if (approval && approval.targetUrl !== upstream.href) {
+ throw new Error('Download approval target mismatch');
+ }
const signal = init.signal ?? undefined;
const proxy = await resolveProxyTarget(upstream, signal);
return fetchSingleHopWithSsrFGuard({
url,
init,
signal,
- requireHttps: true,
+ requireHttps: !approval?.allowHttp,
+ ...(approval?.allowPrivateNetwork
+ ? { policy: { dangerouslyAllowPrivateNetwork: true, hostnameAllowlist: [upstream.hostname] } }
+ : {}),
...(proxy
? {
dispatcherFactory: ({ url: guardedUrl, pinned }) =>
- createPinnedProxyDispatcher(proxy, guardedUrl, pinned.addresses, beforeDispatch),
+ createPinnedProxyDispatcher(proxy, guardedUrl, pinned.addresses, beforeDispatch, signal),
}
: {}),
beforeDispatch,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
index 2f69512a87..980e7ad56e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionRouter.test.ts
@@ -3,6 +3,7 @@ import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core'
import {
beginInteractionRoute,
+ requestHostInteraction,
installDesktopInteractionHandler,
installInteractionLifecycleObserver,
type InteractionHandler,
@@ -41,6 +42,35 @@ function makeSession() {
}
describe('session interaction router', () => {
+ it('routes Host download permissions through the active channel without replacing the listener', async () => {
+ const host = makeSession();
+ const desktop = vi.fn(async (): Promise<InteractionDecision> => ({ kind: 'permission', behavior: 'deny' }));
+ const remote = vi.fn(async (): Promise<InteractionDecision> => ({ kind: 'permission', behavior: 'allow' }));
+ installDesktopInteractionHandler(host.session, desktop);
+ const lease = beginInteractionRoute(host.session, {
+ route: { sessionId: host.session.id, turnId: 'turn-1', origin: { kind: 'im', channel: 'feishu' }, interactionSurface: 'channel-card' },
+ handle: remote,
+ });
+ try {
+ await expect(requestHostInteraction(host.session, permission('download-1'), new AbortController().signal))
+ .resolves.toMatchObject({ behavior: 'allow' });
+ expect(remote).toHaveBeenCalledOnce();
+ expect(desktop).not.toHaveBeenCalled();
+ expect(host.setInteractionListener).toHaveBeenCalledOnce();
+ } finally { lease.release(); }
+ });
+
+ it('cancels the ordinary pending card when a Host permission is aborted', async () => {
+ const host = makeSession();
+ const controller = new AbortController();
+ const cancel = vi.fn();
+ installDesktopInteractionHandler(host.session, () => new Promise(() => {}), cancel);
+ const pending = requestHostInteraction(host.session, permission('download-2'), controller.signal);
+ controller.abort();
+ await expect(pending).resolves.toMatchObject({ behavior: 'deny' });
+ expect(cancel).toHaveBeenCalledWith('download-2', expect.objectContaining({ behavior: 'deny' }));
+ });
+
it('owns one listener and falls back to the Desktop handler', async () => {
const harness = makeSession();
const desktop = vi.fn(async (): Promise<InteractionDecision> => ({
diff --git a/apps/desktop/src/main/maker-ipc/interactionRouter.ts b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
index e2adca763d..55e9e4cd2b 100644
--- a/apps/desktop/src/main/maker-ipc/interactionRouter.ts
+++ b/apps/desktop/src/main/maker-ipc/interactionRouter.ts
@@ -96,6 +96,7 @@ function safeDecision(
class SessionInteractionRouter {
private desktopHandler: InteractionHandler | null = null;
+ private desktopCancel: ((requestId: string, decision: InteractionDecision) => void) | undefined;
private lifecycleObserver: InteractionLifecycleObserver | null = null;
private activeRoute: ActiveRoute | null = null;
private readonly pending = new Map<string, PendingRequest>();
@@ -104,8 +105,9 @@ class SessionInteractionRouter {
session.setInteractionListener((request) => this.dispatch(request));
}
- setDesktopHandler(handler: InteractionHandler): void {
+ setDesktopHandler(handler: InteractionHandler, cancel?: (requestId: string, decision: InteractionDecision) => void): void {
this.desktopHandler = handler;
+ this.desktopCancel = cancel;
}
setLifecycleObserver(observer: InteractionLifecycleObserver | null): void {
@@ -160,7 +162,8 @@ class SessionInteractionRouter {
};
}
- private async dispatch(request: InteractionRequest): Promise<InteractionDecision> {
+ async dispatch(request: InteractionRequest, signal?: AbortSignal): Promise<InteractionDecision> {
+ if (signal?.aborted) return safeDecision(request, 'session_aborted');
if (this.pending.has(request.requestId)) {
return safeDecision(request, 'duplicate_request_id');
}
@@ -185,6 +188,16 @@ class SessionInteractionRouter {
request,
cancel,
});
+ const abort = () => {
+ const decision = safeDecision(request, 'session_aborted');
+ if (active?.route.interactionSurface === 'channel-card' || active?.route.interactionSurface === 'headless') {
+ callSafely(() => active.onCancel?.(request.requestId, decision));
+ } else {
+ callSafely(() => this.desktopCancel?.(request.requestId, decision));
+ }
+ cancel(decision);
+ };
+ signal?.addEventListener('abort', abort, { once: true });
this.notifyLifecycle('onStart', request, active?.route);
this.notifyState(active?.route, 'waiting');
const timeoutMs = active?.route.timeoutMs;
@@ -200,7 +213,9 @@ class SessionInteractionRouter {
: null;
try {
- const decision = await Promise.race([handler(request), cancelled]);
+ const handled = handler(request);
+ if (signal?.aborted) abort();
+ const decision = await Promise.race([handled, cancelled]);
this.notifyState(
active?.route,
!cancelledByRouter && this.activeRoute?.token === active?.token
@@ -212,6 +227,7 @@ class SessionInteractionRouter {
this.notifyState(active?.route, 'cancelled');
return safeDecision(request, 'interaction_handler_failed');
} finally {
+ signal?.removeEventListener('abort', abort);
if (timeout) clearTimeout(timeout);
this.pending.delete(request.requestId);
this.notifyLifecycle('onEnd', request, active?.route);
@@ -235,8 +251,18 @@ function routerFor(session: InteractionSession): SessionInteractionRouter {
export function installDesktopInteractionHandler(
session: InteractionSession,
handler: InteractionHandler,
+ cancel?: (requestId: string, decision: InteractionDecision) => void,
): void {
- routerFor(session).setDesktopHandler(handler);
+ routerFor(session).setDesktopHandler(handler, cancel);
+}
+
+/** Host permissions use the same UI, remote responses and route lease as Agent permissions. */
+export function requestHostInteraction(
+ session: InteractionSession,
+ request: InteractionRequest,
+ signal: AbortSignal,
+): Promise<InteractionDecision> {
+ return routerFor(session).dispatch(request, signal);
}
export function installInteractionLifecycleObserver(
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c65fa4b24f..d25361cd96 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -3938,6 +3938,8 @@ export function installDesktopInteractionListener(session: {
agentIslandInteractionEpoch,
);
});
+ }, (requestId, decision) => {
+ resolvePendingInteraction(requestId, decision);
});
}
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index b8c66686cf..36fd172bf5 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -97,6 +97,7 @@ import { workdirWriteVerdict } from '../cindy-brain/fsSlot.js';
import * as blobStore from '../cindy-media/blobStore.js';
import { commitMessageMediaRefs } from '../cindy-media/chatAttachments.js';
import { callCindyMedia } from '../cindy-media/invocationService.js';
+import type { MediaDownloadContext } from '../cindy-media/mediaDownload.js';
import * as ledger from '../cindy-media/ledger.js';
import { chatAttachmentOrigin } from '../cindy-media/attachmentGrantGate.js';
import { resolveGhostAttachmentUrl } from './ghostAttachmentResolve.js';
@@ -190,6 +191,7 @@ export interface ToolResultImageDescription {
}
export interface CindyGhostsHostDeps {
+ createMediaDownloadContext?: (sessionId: string, sessionInstanceId: string) => MediaDownloadContext | undefined;
/** 当前 Desktop 版本;Forge scaffold 用它生成具体插件包的默认最低版本。 */
getAppVersion?: () => string;
/**
@@ -1355,8 +1357,17 @@ export function getCindyGhostsMcpDeps(
});
return {
callMedia: async (request) => {
- const result = await callCindyMedia(request);
- const sessionId = resolveSessionContext()?.sessionId;
+ const sessionContext = resolveSessionContext();
+ const sessionId = sessionContext?.sessionId;
+ const downloadContext = (request.action === 'request' || request.action === 'poll') && sessionId && sessionContext?.sessionInstanceId
+ ? hostDeps.createMediaDownloadContext?.(sessionId, sessionContext.sessionInstanceId)
+ : undefined;
+ let result: Record<string, unknown>;
+ try {
+ result = await callCindyMedia(request, downloadContext);
+ } finally {
+ downloadContext?.dispose?.();
+ }
if (request.action === 'resolve_local_path' && result.ok !== false) {
const localPath = typeof result.local_path === 'string' ? result.local_path : '';
const mimeType = typeof result.mime_type === 'string' ? result.mime_type : '';
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index ce27e3b178..0b931c4254 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -16,6 +16,7 @@ import type { MakerMemoryManager } from '@cindy/maker-core';
import {
getCindyGhostsMcpDeps,
type GhostGrantLiveSessionState,
+ type CindyGhostsHostDeps,
type ToolResultImageDescription,
} from './ghost.js';
import { createGroupHistoryMcpServer } from './groupHistoryMcpServer.js';
@@ -76,6 +77,7 @@ import {
import { botSessionLinks, sessions } from '../localDb/schema.js';
export interface DesktopMcpProvidersDeps {
+ createMediaDownloadContext?: CindyGhostsHostDeps['createMediaDownloadContext'];
/** 当前 Desktop 版本,供 Forge 为具体插件包生成默认 minCindyVersion。 */
getAppVersion?: () => string;
getMakerMemoryManager: () => MakerMemoryManager;
@@ -741,6 +743,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
getCindyGhostsMcpDeps(ctx, {
getAppVersion: deps.getAppVersion,
getLiveSessionGrantState: deps.getLiveSessionGrantState,
+ createMediaDownloadContext: deps.createMediaDownloadContext,
describeToolResultImage: deps.describeToolResultImage,
onToolResultImagesFailed: deps.onToolResultImagesFailed,
}),
diff --git a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
index 60dd78eaa9..fc726a9ef7 100644
--- a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
@@ -50,6 +50,7 @@ function firstString(input: Record<string, unknown>, keys: string[]): string | u
// 按语义分组(命令 / 文件 / 模式)归一化,任一命名命中就抽出清爽正文,否则回退 JSON。
export function formatToolInput(toolName: string, input: Record<string, unknown>): string {
const name = toolName.toLowerCase();
+ if (name === 'cindy.media.download' && typeof input.source === 'string') return input.source;
const fallback = () => {
const text = JSON.stringify(input, null, 2);
return text.length > 500 ? text.slice(0, 500) + '...' : text;
@@ -83,6 +84,7 @@ function filterSessionScopedSuggestions(suggestions?: unknown[]): unknown[] {
export function PermissionPrompt({ permission, onRespond, companion }: PermissionPromptProps) {
const { t } = useTranslation();
const { toolName, input, title, displayName, description, suggestions, autoReviewUnavailable } = permission;
+ const isMediaDownload = toolName === 'cindy.media.download';
const promptDescription = autoReviewUnavailable
? t('newChat.permissionPrompt.autoReviewUnavailable')
: description;
@@ -212,7 +214,7 @@ export function PermissionPrompt({ permission, onRespond, companion }: Permissio
'transition-colors hover:bg-[var(--perm-code-bg)]',
)}
>
- <span>{t('agentIsland.native.deny')}</span>
+ <span>{t(isMediaDownload ? 'newChat.mediaDownload.defer' : 'agentIsland.native.deny')}</span>
<kbd className="rounded-[4px] border border-[var(--chat-input-border)] bg-[var(--perm-code-bg)] px-1.5 py-[1px] text-11 font-normal text-[var(--status-bar-meta)]">
Esc
</kbd>
@@ -271,7 +273,7 @@ export function PermissionPrompt({ permission, onRespond, companion }: Permissio
'transition-colors hover:opacity-90',
)}
>
- <span>{t('agentIsland.native.allowOnce')}</span>
+ <span>{t(isMediaDownload ? 'newChat.mediaDownload.allow' : 'agentIsland.native.allowOnce')}</span>
<kbd className="rounded-[4px] border border-[var(--perm-allow-kbd-border)] bg-[var(--perm-allow-kbd-bg)] px-1.5 py-[1px] text-11 font-normal text-[var(--perm-allow-btn-text)] opacity-70">
Enter
</kbd>
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fb7844aefa..627bf11e5c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7993,6 +7993,19 @@
"cancelEdit": "Cancel Editing",
"saveEdit": "Save Text"
},
+ "mediaDownload": {
+ "title": "Download the generated media?",
+ "description": "The media has been generated and needs to be downloaded from the address below.",
+ "scope": "Allow this download only.",
+ "source": "This address is not among the download sources confirmed by Cindy, so your confirmation is needed.",
+ "http": "This address uses unencrypted HTTP. Others on the network may read or alter the download.",
+ "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"
+ },
"permissionPrompt": {
"alwaysAllowScoped": "Always Allow {{scope}} in This Session",
"alwaysAllowScopedHint": "Applies to the whole session, and only to what is listed here.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index aadb1fbfa5..eb020267ce 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7991,6 +7991,19 @@
"cancelEdit": "編集をキャンセル",
"saveEdit": "テキストを保存"
},
+ "mediaDownload": {
+ "title": "生成されたメディアをダウンロードしますか?",
+ "description": "メディアが生成されました。以下のアドレスからダウンロードする必要があります。",
+ "scope": "今回のダウンロードのみ許可します。",
+ "source": "このアドレスは Cindy が確認済みのダウンロード元に含まれていないため、確認が必要です。",
+ "http": "このアドレスは暗号化されていない HTTP を使用します。ネットワーク上の第三者が内容を読み取ったり変更したりする可能性があります。",
+ "port": "このアドレスは標準以外のネットワークポートを使用します。このポートへのアクセスを確認してください。",
+ "credentials": "このダウンロードアドレスにはログイン情報が含まれています。許可すると、その情報はこのアドレスにのみ送信されます。",
+ "network": "このアドレスは、このデバイス、ローカルネットワーク、または予約済みネットワークを指しています。アクセスすると、デバイスの内部サービスに接続する可能性があります。",
+ "size": "ファイルが標準のダウンロードサイズを超えています。今回は最大 {{bytes}} バイトのダウンロードを許可します。メモリやディスク容量を多く使用する可能性があります。",
+ "allow": "今回のダウンロードを許可",
+ "defer": "今はダウンロードしない"
+ },
"permissionPrompt": {
"alwaysAllowScoped": "このセッションでは {{scope}} を常に許可",
"alwaysAllowScopedHint": "このセッション全体に適用され、ここに挙げた範囲にのみ及びます。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 4d1072d790..3cbb7a7514 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7991,6 +7991,19 @@
"cancelEdit": "편집 취소",
"saveEdit": "텍스트 저장"
},
+ "mediaDownload": {
+ "title": "생성된 미디어를 다운로드할까요?",
+ "description": "미디어가 생성되었습니다. 아래 주소에서 다운로드해야 합니다.",
+ "scope": "이번 다운로드만 허용합니다.",
+ "source": "이 주소는 Cindy가 확인한 다운로드 출처에 포함되어 있지 않아 확인이 필요합니다.",
+ "http": "이 주소는 암호화되지 않은 HTTP를 사용합니다. 네트워크의 다른 사람이 다운로드 내용을 읽거나 변경할 수 있습니다.",
+ "port": "이 주소는 기본 네트워크 포트가 아닌 포트를 사용합니다. 해당 포트에 대한 접근을 확인해 주세요.",
+ "credentials": "이 다운로드 주소에는 로그인 정보가 포함되어 있습니다. 허용하면 해당 정보는 이 주소에만 전송됩니다.",
+ "network": "이 주소는 이 기기, 로컬 네트워크 또는 예약된 네트워크를 가리킵니다. 접근하면 기기의 내부 서비스에 연결될 수 있습니다.",
+ "size": "파일이 기본 다운로드 크기를 초과합니다. 이번에 최대 {{bytes}}바이트 다운로드를 허용하며, 메모리와 디스크 공간을 많이 사용할 수 있습니다.",
+ "allow": "이번 다운로드 허용",
+ "defer": "나중에 다운로드"
+ },
"permissionPrompt": {
"alwaysAllowScoped": "이 세션에서 {{scope}} 항상 허용",
"alwaysAllowScopedHint": "이 세션 전체에 적용되며, 여기에 표시된 범위에만 해당합니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 641b41f0ab..c91b78a079 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7991,6 +7991,19 @@
"cancelEdit": "取消编辑",
"saveEdit": "保存文本"
},
+ "mediaDownload": {
+ "title": "允许下载生成的媒体?",
+ "description": "媒体已生成,需要从下方地址下载。",
+ "scope": "仅允许本次下载。",
+ "source": "这个地址不在 Cindy 已确认的下载来源中,因此需要你确认。",
+ "http": "这个地址使用未加密的 HTTP 连接,下载内容可能被网络中的其他方读取或修改。",
+ "port": "这个地址使用非默认网络端口,需要确认访问该端口。",
+ "credentials": "这个下载地址包含登录信息。允许后,仅向该地址发送其中的登录信息。",
+ "network": "这个地址指向本机、局域网或保留网络,访问它可能触及设备上的内部服务。",
+ "size": "文件超过默认下载大小。允许后,本次最多下载 {{bytes}} 字节,可能占用较多内存和磁盘空间。",
+ "allow": "允许本次下载",
+ "defer": "暂不下载"
+ },
"permissionPrompt": {
"alwaysAllowScoped": "本任务都允许 {{scope}}",
"alwaysAllowScopedHint": "作用于整个任务,且只限这里列出的范围。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 52288d91c5..7565ffeb3b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7991,6 +7991,19 @@
"cancelEdit": "取消編輯",
"saveEdit": "儲存文字"
},
+ "mediaDownload": {
+ "title": "允許下載產生的媒體?",
+ "description": "媒體已產生,需要從下方位址下載。",
+ "scope": "僅允許本次下載。",
+ "source": "這個位址不在 Cindy 已確認的下載來源中,因此需要你確認。",
+ "http": "這個位址使用未加密的 HTTP 連線,下載內容可能被網路中的其他方讀取或修改。",
+ "port": "這個位址使用非預設網路連接埠,需要確認存取該連接埠。",
+ "credentials": "這個下載位址包含登入資訊。允許後,僅向該位址傳送其中的登入資訊。",
+ "network": "這個位址指向本機、區域網路或保留網路,存取它可能觸及裝置上的內部服務。",
+ "size": "檔案超過預設下載大小。允許後,本次最多下載 {{bytes}} 位元組,可能佔用較多記憶體和磁碟空間。",
+ "allow": "允許本次下載",
+ "defer": "暫不下載"
+ },
"permissionPrompt": {
"alwaysAllowScoped": "本任務都允許 {{scope}}",
"alwaysAllowScopedHint": "作用於整個任務,且只限這裡列出的範圍。",
diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.md
index 8302179659..26ca276b8c 100644
--- a/docs/dev-rules/media-storage-and-protocols.md
+++ b/docs/dev-rules/media-storage-and-protocols.md
@@ -65,6 +65,29 @@
- 删除或清理历史目录必须走已有的显式名单、复验和用户确认流程;不得新增任意
`cc-agent` 子目录删除能力。
+## 已授权生成任务的结果下载
+
+- 下载是生成流程内部的一步,不新增“领取”状态、列表或用户操作。上游返回后,客户端
+ 下载并通过 `ingestMedia` 返回受管媒体;需要确认时暂停同一次操作,批准后自动继续。
+- Guide 的 `allowedUrlHosts` 保留为已确认来源名单。名单内正常目标自动下载;名单外
+ 来源、HTTP、特殊端口、地址内登录信息、受限网络或扩大文件大小等权限要求通过
+ Cindy 普通 `permission` 交互确认。卡片只说明实际地址、原因和本次范围,不出现
+ Guide、“模型说明”等内部概念,不使用仅限本机的 `ghost_grant_confirm`。
+- 用户拒绝后结束本次下载,不自动重试或再次审批。网络失败由客户端最多自动尝试
+ 三次,同一次操作及其只读地址刷新复用已经批准的来源和权限;只有目标或所需权限
+ 变化才再次确认。不以浏览器或外部应用作为强制下载出口。
+- 默认经 `guardedOutboundFetch` 做 HTTPS、DNS/IP 校验及固定 IP 连接。人工例外只对
+ 当前精确 URL 的单跳生效,不自动传递到重定向目标,不改变其他网络调用的默认策略。
+ 不附带生成接口凭证;地址内登录信息须单独确认,且不得沿重定向传递。
+- 网络时间累计最多 120 秒,连续 30 秒没有响应或数据则重试,人工审批等待另计并受 Host 操作时限
+ 约束。正常跳转逐跳重验目标与权限,循环跳转作为下载故障处理,不为次数追加审批。
+ 等待更大文件审批前取消响应体并释放连接;所有结束路径均释放 body 和 dispatcher。
+- 下载失败保留原调用的成功响应。异步签名地址失效时只查询原上游任务刷新地址,不重新
+ 付费生成。`pending` 且存在成功响应的记录不随六小时清理删除,也不占正在生成的名额;
+ 不新增并行的领取状态或授权表。用户拒绝或客户端重试耗尽均返回非自动重试结果,避免模型另起一次调用而重复发起审批。
+- 真实 MIME 识别、账号/任务归属、受管入库规则持续有效。下载授权不包含执行文件、
+ 安装程序或覆盖用户文件的授权。旧 Guide 快照与 base64 结果保持兼容。
+
## 多端与远程
- 媒体记录必须保留设备、会话、插件或远程主机等真实归属信息,不能相信调用方自报的
diff --git a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts
index 7f4e4ac445..a013b43013 100644
--- a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts
+++ b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts
@@ -128,6 +128,89 @@ describe('fetchWithSsrFGuard thin shell', () => {
expect(close).toHaveBeenCalledTimes(1);
});
+ it("cancels a pending DNS lookup without dispatching after its late result", async () => {
+ let finishDns!: (value: Array<{ address: string; family: number }>) => void;
+ const dns = new Promise<Array<{ address: string; family: number }>>(
+ (resolve) => {
+ finishDns = resolve;
+ },
+ );
+ const lookup = vi.fn(() => dns);
+ const dispatcherFactory = vi.fn();
+ const beforeDispatch = vi.fn();
+ const controller = new AbortController();
+ const pending = fetchSingleHopWithSsrFGuard({
+ url: "https://cdn.example.com/file",
+ signal: controller.signal,
+ lookupFn: lookup as unknown as LookupFn,
+ dispatcherFactory,
+ beforeDispatch,
+ });
+ const rejected = expect(pending).rejects.toThrow("cancelled during DNS");
+ expect(lookup).toHaveBeenCalledOnce();
+ controller.abort(new Error("cancelled during DNS"));
+ await rejected;
+ finishDns([{ address: "93.184.216.34", family: 4 }]);
+ await dns;
+ await Promise.resolve();
+ expect(dispatcherFactory).not.toHaveBeenCalled();
+ expect(beforeDispatch).not.toHaveBeenCalled();
+ });
+
+ it("cleans up a dispatcher factory that completes after cancellation", async () => {
+ let finishFactory!: (value: never) => void;
+ const factoryResult = new Promise<never>((resolve) => {
+ finishFactory = resolve;
+ });
+ const dispatcherFactory = vi.fn(() => factoryResult);
+ const close = vi.fn(async () => undefined);
+ const beforeDispatch = vi.fn();
+ const controller = new AbortController();
+ const pending = fetchSingleHopWithSsrFGuard({
+ url: "https://cdn.example.com/file",
+ signal: controller.signal,
+ lookupFn: lookupAddresses([{ address: "93.184.216.34", family: 4 }]),
+ dispatcherFactory,
+ beforeDispatch,
+ });
+ const rejected = expect(pending).rejects.toThrow("cancelled during setup");
+ await vi.waitFor(() => expect(dispatcherFactory).toHaveBeenCalledOnce());
+ controller.abort(new Error("cancelled during setup"));
+ await rejected;
+ finishFactory({ close } as never);
+ await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
+ expect(beforeDispatch).not.toHaveBeenCalled();
+ });
+
+ it("does not start DNS when the request is already cancelled", async () => {
+ const lookup = vi.fn();
+ const controller = new AbortController();
+ controller.abort(new Error("already cancelled"));
+ await expect(
+ fetchSingleHopWithSsrFGuard({
+ url: "https://cdn.example.com/file",
+ signal: controller.signal,
+ lookupFn: lookup as LookupFn,
+ }),
+ ).rejects.toThrow("already cancelled");
+ expect(lookup).not.toHaveBeenCalled();
+ });
+
+ it("rejects a mixed public/private DNS answer before creating a dispatcher", async () => {
+ const dispatcherFactory = vi.fn();
+ await expect(
+ fetchSingleHopWithSsrFGuard({
+ url: "https://cdn.example.com/file",
+ lookupFn: lookupAddresses([
+ { address: "93.184.216.34", family: 4 },
+ { address: "10.0.0.1", family: 4 },
+ ]),
+ dispatcherFactory,
+ }),
+ ).rejects.toThrow(/blocked/i);
+ expect(dispatcherFactory).not.toHaveBeenCalled();
+ });
+
it('does NOT block an allowlisted loopback host (regression: CDP control plane)', async () => {
// With the host in allowedHostnames, the policy gate must pass it. We use a
// port nothing listens on, so the only acceptable failure is a CONNECTION
diff --git a/packages/browser-control-runtime/src/shim/ssrf-runtime.ts b/packages/browser-control-runtime/src/shim/ssrf-runtime.ts
index 52902dda7e..6f4b7ef988 100644
--- a/packages/browser-control-runtime/src/shim/ssrf-runtime.ts
+++ b/packages/browser-control-runtime/src/shim/ssrf-runtime.ts
@@ -30,6 +30,7 @@ import {
type SsrFPolicy,
} from '../_generated/leaf/src/infra/net/ssrf.js';
+export { SsrFBlockedError } from '../_generated/leaf/src/infra/net/ssrf.js';
export type { LookupFn, SsrFPolicy } from '../_generated/leaf/src/infra/net/ssrf.js';
export interface GuardedFetchOptions {
@@ -89,6 +90,44 @@ function assertScheme(url: URL, requireHttps: boolean | undefined): void {
}
}
+// DNS lookup cannot itself be cancelled. Stop waiting promptly, and never use a
+// late result to open a connection. Async dispatcher factories also need cleanup.
+function awaitWithSignal<T>(
+ pending: Promise<T>,
+ signal: AbortSignal | undefined,
+ disposeLate?: (value: T) => void,
+): Promise<T> {
+ if (!signal) return pending;
+ return new Promise<T>((resolve, reject) => {
+ let cancelled = false;
+ const abort = (): void => {
+ cancelled = true;
+ signal.removeEventListener('abort', abort);
+ reject(signal.reason);
+ };
+ if (signal.aborted) abort();
+ else signal.addEventListener('abort', abort, { once: true });
+ pending.then(
+ (value) => {
+ signal.removeEventListener('abort', abort);
+ if (cancelled) disposeLate?.(value);
+ else resolve(value);
+ },
+ (error: unknown) => {
+ signal.removeEventListener('abort', abort);
+ reject(error);
+ },
+ );
+ });
+}
+
+function guardSignal(params: GuardedFetchOptions): AbortSignal | undefined {
+ const signal = params.signal ?? params.init?.signal ?? undefined;
+ if (params.timeoutMs === undefined) return signal;
+ const deadline = AbortSignal.timeout(params.timeoutMs);
+ return signal ? AbortSignal.any([signal, deadline]) : deadline;
+}
+
/**
* Guard a single hop: scheme check, then the vendored policy gate.
*
@@ -106,13 +145,24 @@ async function guardHop(
lookupFn: LookupFn | undefined,
requireHttps: boolean | undefined,
dispatcherFactory: GuardedFetchOptions['dispatcherFactory'],
+ signal?: AbortSignal,
): Promise<{ url: URL; dispatcher: Dispatcher }> {
+ signal?.throwIfAborted();
const url = new URL(rawUrl);
assertScheme(url, requireHttps);
- const pinned = await resolvePinnedHostnameWithPolicy(url.hostname, { policy, lookupFn });
- const dispatcher =
- (await dispatcherFactory?.({ url, pinned, policy }))
- ?? createPinnedDispatcher(pinned, undefined, policy);
+ const pinned = await awaitWithSignal(
+ resolvePinnedHostnameWithPolicy(url.hostname, { policy, lookupFn }), signal,
+ );
+ signal?.throwIfAborted();
+ const customDispatcher = await awaitWithSignal(
+ Promise.resolve(dispatcherFactory?.({ url, pinned, policy })), signal,
+ (late) => { void closeDispatcher(late); },
+ );
+ if (signal?.aborted) {
+ await closeDispatcher(customDispatcher);
+ signal.throwIfAborted();
+ }
+ const dispatcher = customDispatcher ?? createPinnedDispatcher(pinned, undefined, policy);
return { url, dispatcher };
}
@@ -126,18 +176,23 @@ async function guardHop(
export async function fetchSingleHopWithSsrFGuard(
params: GuardedFetchOptions,
): Promise<{ response: Response; release: () => Promise<void> }> {
+ const signal = guardSignal(params);
const { url, dispatcher } = await guardHop(
params.url,
params.policy,
params.lookupFn,
params.requireHttps,
params.dispatcherFactory,
+ signal,
);
try {
- await params.beforeDispatch?.();
+ await awaitWithSignal(Promise.resolve().then(() => {
+ signal?.throwIfAborted();
+ return params.beforeDispatch?.();
+ }), signal);
const fetchOptions = {
...params.init,
- signal: params.signal ?? params.init?.signal,
+ signal,
redirect: 'manual' as const,
dispatcher,
};
@@ -167,6 +222,7 @@ function stripSensitiveHeaders(init: RequestInit | undefined): RequestInit | und
* response plus a `release()` that closes the pinned dispatcher.
*/
export async function fetchWithSsrFGuard(params: GuardedFetchOptions): Promise<GuardedFetchResult> {
+ const signal = guardSignal(params);
const maxRedirects = params.maxRedirects ?? 10;
let currentUrl = params.url;
let currentInit: RequestInit | undefined = params.init;
@@ -186,16 +242,20 @@ export async function fetchWithSsrFGuard(params: GuardedFetchOptions): Promise<G
params.lookupFn,
params.requireHttps,
params.dispatcherFactory,
+ signal,
);
dispatchers.push(dispatcher);
- await params.beforeDispatch?.();
+ await awaitWithSignal(Promise.resolve().then(() => {
+ signal?.throwIfAborted();
+ return params.beforeDispatch?.();
+ }), signal);
// undici's fetch accepts a `dispatcher`; its RequestInit differs slightly
// from the DOM lib types, so we go through `unknown` for the options bag.
const fetchOptions = {
...currentInit,
- signal: params.signal ?? currentInit?.signal,
+ signal,
redirect: 'manual' as const,
dispatcher,
};
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 71574bf240..6686f929c0 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -534,30 +534,19 @@ export class Session {
// 注入 InteractionResolver 到底层 handle, 转发到 host 维护的 listener。
// 没接 listener 时按 kind 给出安全默认: 都视作 deny(host 必须接 listener 才能交互)。
- this.handle.setInteractionResolver(async (req) => {
- // 等用户回应期间挂起 stall 看门狗:用户可能离开电脑很久,没有事件是正常的,
- // 中断这种 turn 等于把"等你决定"误判成"卡死"(见 DEFAULT_TURN_STALL_MS)。
- this.pendingInteractions += 1;
- const interactionRuntime = this.observeInteractionStarted(req);
- this.clearTurnStallWatchdog();
- try {
- if (!this.interactionListener) {
- this.logger.warn('interaction request received but no listener attached, denying', { kind: req.kind, requestId: req.requestId });
- if (req.kind === 'ask_user_question') {
- return { kind: 'ask_user_question', answers: {} };
- }
- if (req.kind === 'plan_review') {
- return { kind: 'plan_review', behavior: 'deny', reason: 'no_listener_attached', dismissed: true };
- }
- return { kind: req.kind, behavior: 'deny', reason: 'no_listener_attached' } as InteractionDecision;
+ this.handle.setInteractionResolver((req) => this.runHostInteraction(req, async () => {
+ if (!this.interactionListener) {
+ this.logger.warn('interaction request received but no listener attached, denying', { kind: req.kind, requestId: req.requestId });
+ if (req.kind === 'ask_user_question') {
+ return { kind: 'ask_user_question', answers: {} };
}
- return await this.interactionListener(req);
- } finally {
- this.pendingInteractions = Math.max(0, this.pendingInteractions - 1);
- this.observeInteractionSettled(interactionRuntime);
- this.armTurnStallWatchdog();
+ if (req.kind === 'plan_review') {
+ return { kind: 'plan_review', behavior: 'deny', reason: 'no_listener_attached', dismissed: true };
+ }
+ return { kind: req.kind, behavior: 'deny', reason: 'no_listener_attached' } as InteractionDecision;
}
- });
+ return await this.interactionListener(req);
+ }));
}
// ── 公开 API ─────────────────────────────────────────────────────────────
@@ -1907,6 +1896,23 @@ export class Session {
return () => this.statusListeners.delete(listener);
}
+ /** Host-owned permissions share the same waiting lifecycle as provider interactions. */
+ async runHostInteraction(
+ request: InteractionRequest,
+ resolve: () => Promise<InteractionDecision>,
+ ): Promise<InteractionDecision> {
+ this.pendingInteractions += 1;
+ const runtime = this.observeInteractionStarted(request);
+ this.clearTurnStallWatchdog();
+ try {
+ return await resolve();
+ } finally {
+ this.pendingInteractions = Math.max(0, this.pendingInteractions - 1);
+ this.observeInteractionSettled(runtime);
+ this.armTurnStallWatchdog();
+ }
+ }
+
setInteractionListener(listener: InteractionRequestListener | null): void {
this.interactionListener = listener;
}
diff --git a/packages/maker-core/src/session.turn-stall.test.ts b/packages/maker-core/src/session.turn-stall.test.ts
index 9f789e1cd2..1cfe16efb5 100644
--- a/packages/maker-core/src/session.turn-stall.test.ts
+++ b/packages/maker-core/src/session.turn-stall.test.ts
@@ -12,7 +12,7 @@ import {
STALL_ABORT_RECOVERY_GRACE_MS,
Session,
} from './session.js';
-import type { AgentEvent, SendOrigin } from './types/events.js';
+import type { AgentEvent, InteractionDecision, SendOrigin } from './types/events.js';
import type { AgentSessionHandle, BackgroundTaskSnapshot } from './agents/base-agent.js';
type LoggedError = { msg: string; meta?: Record<string, unknown> };
@@ -219,6 +219,25 @@ describe('Session turn stall watchdog', () => {
}
});
+ it('Host 下载审批等待时挂起看门狗,结束后恢复', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createStubHandle();
+ const session = createSession(stub);
+ await session.send('generate');
+ let answer!: (decision: InteractionDecision) => void;
+ const pending = session.runHostInteraction({
+ kind: 'permission', requestId: 'download-1', toolName: 'cindy.media.download', input: {},
+ }, () => new Promise((resolve) => { answer = resolve; }));
+ await vi.advanceTimersByTimeAsync(STALL_MS * 3);
+ expect(stub.abort).not.toHaveBeenCalled();
+ answer({ kind: 'permission', behavior: 'allow' });
+ await pending;
+ await vi.advanceTimersByTimeAsync(STALL_MS + 1);
+ expect(stub.abort).toHaveBeenCalledOnce();
+ } finally { vi.useRealTimers(); }
+ });
+
it('有后台任务在跑时不计时(后台 Bash / subagent 期间安静是正常的)', async () => {
vi.useFakeTimers();
try {