Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): persist recoverable media results
liugaowei057751c5cd00
diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.tsindex 1d9e22357d..ce2c83babc 100644--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts@@ -102,7 +102,10 @@ vi.mock('../../serverApiClient.js', () => ({vi.mock('../mediaInvocationStore.js', () => ({recoverInterruptedMediaInvocations: mocks.recover,pruneMediaInvocations: mocks.prune,- countMediaInvocations: async () => mocks.rows.size,+ countMediaInvocations: async () =>+ [...mocks.rows.values()].filter((row) =>+ ['prepared', 'submitting', 'pending'].includes(String(row.state)),+ ).length,createMediaInvocation: async ({id,owner,@@ -259,8 +262,35 @@ describe('Cindy Core media invocation state and security boundary', () => {expect(init.headers.Authorization).toBe('Bearer test-api-key');await expect(callCindyMedia({ action: 'request', invocationId, body: { prompt: 'again' } }),- ).resolves.toMatchObject({ ok: false, errorCode: 'INVOCATION_ALREADY_USED' });+ ).resolves.toMatchObject({+ ok: true,+ status: 'complete',+ xdt_image_urls: [`cindy-media://blobs/${'a'.repeat(64)}.png`],+ });expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);+ expect(mocks.ingestMedia).toHaveBeenCalledTimes(1);+ });++ it('终态历史不占用在途 invocation 上限', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ for (let index = 0; index < 128; index += 1) {+ mocks.rows.set(`complete-${index}`, { state: 'complete' });+ }++ await expect(+ callCindyMedia({+ action: 'prepare',+ modelId: 'image-model',+ capability: 'image.generate',+ }),+ ).resolves.toMatchObject({ ok: true, status: 'prepared' });});it('按 Guide 把受管图片机械组装为 multipart 文件请求', async () => {@@ -767,6 +797,84 @@ describe('Cindy Core media invocation state and security boundary', () => {);});+ it('异步成功响应先持久化,临时下载失败后不再查询上游任务并可重放完成结果', 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'],+ encoding: 'url',+ kind: 'video',+ allowedUrlHosts: ['cdn.example.com'],+ },+ ],+ },+ }, '/video/tasks'),+ capability: 'video.generate',+ };+ mocks.models.mockResolvedValue([+ { id: 'image-model', name: 'Video Model', mode: 'video_generation' },+ ]);+ mocks.guide.mockResolvedValue(resolvedGuide(asyncOperation));+ const successPayload = {+ status: 'succeeded',+ video: 'https://cdn.example.com/generated.mp4',+ };+ mocks.outboundFetch+ .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'))+ .mockResolvedValueOnce(+ new Response(MP4, { status: 200, headers: { 'content-type': 'video/mp4' } }),+ );+ mocks.ingestMedia.mockResolvedValue({+ url: `cindy-media://blobs/${'d'.repeat(64)}.mp4`,+ });++ const prepared = await callCindyMedia({+ action: 'prepare',+ modelId: 'image-model',+ capability: 'video.generate',+ });+ const invocationId = prepared.invocation_id as string;+ await callCindyMedia({ action: 'request', invocationId, body: { content: [] } });++ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject({+ ok: false,+ errorCode: 'MEDIA_DOWNLOAD_FAILED',+ retryable: true,+ retry_action: 'poll',+ });+ expect(mocks.rows.get(invocationId)).toMatchObject({+ state: 'pending',+ responseJson: JSON.stringify(successPayload),+ });++ const completed = {+ ok: true,+ status: 'complete',+ xdt_video_urls: [`cindy-media://blobs/${'d'.repeat(64)}.mp4`],+ };+ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject(completed);+ await expect(callCindyMedia({ action: 'poll', invocationId })).resolves.toMatchObject(completed);+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(4);+ 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 () => {const asyncOperation = {...operation({diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.tsindex 5b1a5c7758..67c90df84a 100644--- a/apps/desktop/src/main/cindy-media/invocationService.ts+++ b/apps/desktop/src/main/cindy-media/invocationService.ts@@ -723,6 +723,52 @@ function persistedResponse(invocation: StoredMediaInvocation): unknown {}}+function completedInvocationResult(invocation: StoredMediaInvocation): Record<string, unknown> {+ const media = persistedResponse(invocation);+ if (!media || typeof media !== 'object' || Array.isArray(media)) {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '已完成调用保存的媒体结果不合法');+ }+ return {+ ...(media as Record<string, unknown>),+ ok: true,+ status: 'complete',+ invocation_id: invocation.id,+ };+}++async function persistCompletedInvocation(+ invocation: StoredMediaInvocation,+ media: Record<string, unknown>,+ scope: MediaAuthScope,+ db: DbClient,+): Promise<Record<string, unknown>> {+ const responseJson = JSON.stringify(media);+ const persisted = await transitionMediaInvocation(+ {+ id: invocation.id,+ owner: invocation.owner,+ from: 'pending',+ to: 'complete',+ responseJson,+ },+ db,+ );+ assertAuthScope(scope, invocation.owner);+ if (persisted) {+ return completedInvocationResult({+ ...invocation,+ state: 'complete',+ responseJson,+ });+ }+ const current = await getMediaInvocation(invocation.id, invocation.owner, db);+ assertAuthScope(scope, invocation.owner);+ if (current?.state === 'complete' && current.responseJson) {+ return completedInvocationResult(current);+ }+ return failure('INTERNAL', '媒体结果已生成,但本地未能保存最终结果');+}+async function materializeSyncInvocation(invocation: StoredMediaInvocation,response: unknown,@@ -736,17 +782,7 @@ async function materializeSyncInvocation(try {const media = await materializeResults(response, responseGuide.media, scope, db);assertAuthScope(scope, invocation.owner);- await transitionMediaInvocation(- {- id: invocation.id,- owner: invocation.owner,- from: 'pending',- to: 'complete',- },- db,- );- assertAuthScope(scope, invocation.owner);- return { ok: true, status: 'complete', invocation_id: invocation.id, ...media };+ return persistCompletedInvocation(invocation, media, scope, db);} catch (error) {assertAuthScope(scope, invocation.owner);if (error instanceof MediaInvocationError) {@@ -903,6 +939,9 @@ async function submitInvocation(const scope = currentAuthScope();assertAuthScope(scope, invocation.owner);const db = captureMediaDb(scope);+ if (invocation.state === 'complete') {+ return completedInvocationResult(invocation);+ }if (invocation.state === 'pending' &&invocation.guide.response.mode === 'sync' &&@@ -1070,6 +1109,54 @@ function pollBody(guide: MediaAsyncPollGuide, taskId: string): Record<string, unreturn body;}+async function materializeAsyncInvocation(+ invocation: StoredMediaInvocation,+ response: unknown,+ scope: MediaAuthScope,+ db: DbClient,+): Promise<Record<string, unknown>> {+ const responseGuide = invocation.guide.response;+ if (responseGuide.mode !== 'async') {+ throw new MediaInvocationError('MEDIA_RESULT_INVALID', '异步媒体调用缺少轮询响应说明');+ }+ try {+ const media = await materializeResults(response, responseGuide.poll.media, scope, db);+ assertAuthScope(scope, invocation.owner);+ 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;+ }+ log.warn('async media materialization failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ return {+ ...failure('MEDIA_MATERIALIZATION_FAILED', '媒体结果暂时无法保存', true),+ retry_action: 'poll',+ };+ }+}+async function pollInvocation(invocation: StoredMediaInvocation): Promise<Record<string, unknown>> {const scope = currentAuthScope();assertAuthScope(scope, invocation.owner);@@ -1077,10 +1164,16 @@ async function pollInvocation(invocation: StoredMediaInvocation): Promise<Recordif (invocation.guide.response.mode !== 'async') {return failure('POLL_NOT_SUPPORTED', '同步媒体调用不需要 poll');}+ if (invocation.state === 'complete') {+ return completedInvocationResult(invocation);+ }if (invocation.state !== 'pending' || !invocation.taskId) {return failure('INVOCATION_NOT_PENDING', `该 invocation 当前状态为 ${invocation.state}`);}const guide = invocation.guide.response.poll;+ if (invocation.responseJson) {+ return materializeAsyncInvocation(invocation, persistedResponse(invocation), scope, db);+ }try {const response = await dispatchRequest({connection: resolveConnection(invocation.guide.connection.providerId),@@ -1096,37 +1189,40 @@ async function pollInvocation(invocation: StoredMediaInvocation): Promise<Recordconst rawStatus = valuesAtPath(response, guide.statusPath)[0];const status = typeof rawStatus === 'string' ? rawStatus : '';if (guide.successValues.includes(status)) {- let media: Record<string, unknown>;- try {- media = await materializeResults(response, guide.media, scope, db);- } catch (error) {- assertAuthScope(scope, invocation.owner);- if (error instanceof MediaInvocationError && 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);- }- throw error;- }- await transitionMediaInvocation(+ const responseJson = JSON.stringify(response);+ const persisted = await transitionMediaInvocation({id: invocation.id,owner: invocation.owner,from: 'pending',- to: 'complete',+ to: 'pending',+ responseJson,},db,);assertAuthScope(scope, invocation.owner);- return { ok: true, status: 'complete', invocation_id: invocation.id, ...media };+ if (!persisted) {+ const current = await getMediaInvocation(invocation.id, invocation.owner, db);+ assertAuthScope(scope, invocation.owner);+ if (current?.state === 'complete' && current.responseJson) {+ return completedInvocationResult(current);+ }+ if (current?.state === 'pending' && current.responseJson) {+ return materializeAsyncInvocation(+ current,+ persistedResponse(current),+ scope,+ db,+ );+ }+ return failure('POLL_UNAVAILABLE', '上游结果已生成,但本地未能保存结果', true);+ }+ return materializeAsyncInvocation(+ { ...invocation, responseJson },+ response,+ scope,+ db,+ );}if (guide.failureValues.includes(status)) {await transitionMediaInvocation(diff --git a/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts b/apps/desktop/src/main/cindy-media/mediaInvocationStore.tsindex a8d76dd1cc..ddf4533b9b 100644--- a/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts+++ b/apps/desktop/src/main/cindy-media/mediaInvocationStore.ts@@ -104,7 +104,9 @@ export async function countMediaInvocations(db: DbClient = getDbClient(),): Promise<number> {const row = await db.queryOne<{ count: number }>(- 'SELECT COUNT(*) AS count FROM media_invocations WHERE owner = ?',+ `SELECT COUNT(*) AS count+ FROM media_invocations+ WHERE owner = ? AND state IN ('prepared', 'submitting', 'pending')`,[owner],);return Number(row?.count ?? 0);diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 4706a4414d..aa4c38bc2c 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -1451,6 +1451,20 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {expect(valid.ok).toBe(true);if (valid.ok) {expect(valid.manifest.tools?.[0]?.attachmentArgs).toEqual(['mediaUrl', 'references']);+ const previous = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'tool'],+ tools: [tool],+ });+ expect(previous.ok).toBe(true);+ if (previous.ok) {+ expect(diffGhostPermissionItems(previous.manifest, valid.manifest).added).toEqual([+ expect.objectContaining({+ key: 'tool:import_media',+ detail: expect.stringContaining('attachmentArgs: mediaUrl, references'),+ }),+ ]);+ }}expect(validate(['missing']).ok).toBe(false);expect(validate(['count']).ok).toBe(false);diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex afd7606b0b..736ed294cc 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -2047,12 +2047,15 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt});}for (const tool of manifest.tools ?? []) {+ const attachmentDetail = tool.attachmentArgs?.length+ ? `attachmentArgs: ${[...tool.attachmentArgs].sort().join(', ')}`+ : null;items.push({key: `tool:${tool.name}`,kind: 'tool',labelKey: 'tool',labelArgs: { name: tool.name },- detail: tool.description,+ detail: attachmentDetail ? `${tool.description}\n${attachmentDetail}` : tool.description,});}if (manifest.command) {