Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(cindy-media): 本地组装失败不再误报为「结果未知」,并消除大图 base64 正则回溯(#5081) (#5085)
FicoWang60bee530e899
diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.tsindex d0e60d2873..8f0da35df0 100644--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts@@ -1,6 +1,7 @@import fs from 'node:fs/promises';import { beforeEach, describe, expect, it, vi } from 'vitest';import { SsrFBlockedError } from '@cindy/browser-control-runtime/ssrf-runtime';+import type { MediaCapability } from '@cindy/model-providers';interface MockPreparedGuide extends Record<string, unknown> {modelId: string;@@ -45,6 +46,7 @@ const mocks = vi.hoisted(() => ({recover: vi.fn<(owner: string, db: unknown) => Promise<number>>(async () => 0),prune: vi.fn(async () => undefined),rows: new Map<string, Record<string, unknown>>(),+ failRequestLog: false,}));vi.mock('../../authManager.js', () => ({@@ -70,6 +72,19 @@ vi.mock('../../localDb/client/current.js', () => ({getDbClient: () => mocks.db,getCurrentDbClientUserId: () => mocks.dbOwnerId,}));+vi.mock('../mediaRequestLog.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../mediaRequestLog.js')>();+ return {+ ...actual,+ mediaRequestParamsForLog: (value: unknown) => {+ // 只在记录请求 body 时抛错,模拟组装/日志阶段(出站之前)的异常。+ if (mocks.failRequestLog && typeof value === 'object') {+ throw new RangeError('Maximum call stack size exceeded');+ }+ return actual.mediaRequestParamsForLog(value);+ },+ };+});vi.mock('../../maker-host/outbound-fetch.js', () => ({outboundFetch: mocks.outboundFetch,guardedOutboundFetch: mocks.guardedOutboundFetch,@@ -224,11 +239,11 @@ function resolvedGuide(op: Record<string, unknown>) {};}-async function prepare(): Promise<string> {+async function prepare(capability: MediaCapability = 'image.generate'): Promise<string> {const result = await callCindyMedia({action: 'prepare',modelId: 'image-model',- capability: 'image.generate',+ capability,});expect(result).toMatchObject({ ok: true, status: 'prepared', model_id: 'image-model' });return result.invocation_id as string;@@ -236,6 +251,7 @@ async function prepare(): Promise<string> {describe('Cindy Core media invocation state and security boundary', () => {beforeEach(() => {+ mocks.failRequestLog = false;mocks.confirm.mockReset().mockResolvedValue(true);mocks.currentUserId = `media-user-${crypto.randomUUID()}`;mocks.localMode = false;@@ -655,6 +671,84 @@ describe('Cindy Core media invocation state and security boundary', () => {expect(form.get('image[]')).toBeInstanceOf(Blob);});+ it.each([+ ['image.generate', 'image'],+ ['video.image_to_video', 'image'],+ ] as const)('%s:受管大图(base64 ≥ 2^22 字符)的 multipart 组装与发出回归(#5081)', async (capability, kind) => {+ const op = operation(+ {+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ },+ '/v1/images/edits',+ );+ mocks.guide.mockResolvedValue(+ resolvedGuide({+ ...op,+ capability,+ request: {+ ...op.request,+ bodyEncoding: 'multipart',+ maxRequestBytes: 8 * 1024 * 1024,+ multipartFiles: [{ bodyField: 'image', formField: 'image', kind, maxItems: 1 }],+ },+ }),+ );+ // 8 字节 PNG 签名 + 3.2MiB 填充 → base64 约 4.47M 字符,覆盖 #5081 报告的阈值之上。+ const largePng = Buffer.concat([PNG.subarray(0, 8), Buffer.alloc(3.2 * 1024 * 1024, 7)]);+ mocks.readBlob.mockResolvedValue({ buffer: largePng, mimeType: 'image/png' });+ mocks.outboundFetch.mockResolvedValue(+ new Response(JSON.stringify({ data: PNG.toString('base64') }), { status: 200 }),+ );++ await expect(+ callCindyMedia({+ action: 'request',+ invocationId: await prepare(capability),+ body: { prompt: 'animate', image: `cindy-media://blobs/${'b'.repeat(64)}.png` },+ }),+ ).resolves.toMatchObject({ ok: true, status: 'complete' });++ expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);+ const [, init] = mocks.outboundFetch.mock.calls[0];+ const file = (init.body as FormData).get('image');+ expect(file).toBeInstanceOf(Blob);+ expect((file as Blob).size).toBe(largePng.byteLength);+ });++ it('请求在本地组装阶段抛错时归类为 REQUEST_BUILD_FAILED,可重试且不标记结果未知(#5081)', async () => {+ mocks.guide.mockResolvedValue(+ resolvedGuide(+ operation({+ mode: 'sync',+ media: [{ path: ['data'], encoding: 'base64', kind: 'image' }],+ }),+ ),+ );+ mocks.failRequestLog = true;++ const invocationId = await prepare();+ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'REQUEST_BUILD_FAILED',+ retryable: true,+ outcomeKnown: true,+ });+ expect(mocks.outboundFetch).not.toHaveBeenCalled();+ // 请求从未出站:invocation 回到 prepared,同一 invocation_id 再次 request 可正常发出。+ expect(mocks.rows.get(invocationId)?.state).toBe('prepared');+ mocks.failRequestLog = false;+ mocks.outboundFetch.mockResolvedValue(+ new Response(JSON.stringify({ data: PNG.toString('base64') }), { status: 200 }),+ );+ await expect(+ callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } }),+ ).resolves.toMatchObject({ ok: true, status: 'complete' });+ expect(mocks.outboundFetch).toHaveBeenCalledTimes(1);+ });+it('同步生成成功后下载暂时失败时复用已保存响应,不会再次付费 POST', async () => {mocks.guide.mockResolvedValue(resolvedGuide(diff --git a/apps/desktop/src/main/cindy-media/__tests__/mediaRequestLog.test.ts b/apps/desktop/src/main/cindy-media/__tests__/mediaRequestLog.test.tsindex 9b97de05ac..1da1fe5c92 100644--- a/apps/desktop/src/main/cindy-media/__tests__/mediaRequestLog.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/mediaRequestLog.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest';-import { mediaErrorForLog, mediaRequestParamsForLog, mediaRequestUrlForLog } from '../mediaRequestLog.js';+import {+ mediaErrorForLog,+ mediaErrorStackForLog,+ mediaRequestParamsForLog,+ mediaRequestUrlForLog,+} from '../mediaRequestLog.js';+import { base64DecodedByteLength, normalizeBase64Payload, parseDataUrl } from '../dataUrl.js';describe('media request log redaction', () => {it('保留实际 URL 并脱敏 query 凭证', () => {@@ -59,3 +65,59 @@ describe('media error log redaction', () => {expect(mediaErrorForLog('token=private')).toBe('token=[REDACTED]');});});++describe('data URL 结构性解析(#5081)', () => {+ it('base64 超过 2^22 字符的 data URL 仍能正确摘要', () => {+ const bytes = Buffer.alloc(3.2 * 1024 * 1024, 7);+ const encoded = bytes.toString('base64');+ expect(encoded.length).toBeGreaterThan(2 ** 22);+ expect(+ mediaRequestParamsForLog({ image: `data:image/png;base64,${encoded}` }),+ ).toEqual({ image: `[data URL mime=image/png bytes=${bytes.byteLength}]` });+ });++ it('parseDataUrl 只按前缀与首个逗号切分,MIME 小写且识别 ;base64', () => {+ expect(parseDataUrl('data:Image/PNG;charset=x;Base64,aGk=')).toEqual({+ mimeType: 'image/png',+ base64: true,+ payload: 'aGk=',+ });+ expect(parseDataUrl('data:text/plain,hi,there')).toEqual({+ mimeType: 'text/plain',+ base64: false,+ payload: 'hi,there',+ });+ expect(parseDataUrl('data:,x')).toBeNull();+ expect(parseDataUrl('http://example.test')).toBeNull();+ });++ it('normalizeBase64Payload 去掉 CR/LF 并拒绝非法字符', () => {+ expect(normalizeBase64Payload('aG\r\nk=')).toBe('aGk=');+ expect(normalizeBase64Payload('aGk=')).toBe('aGk=');+ expect(normalizeBase64Payload('aG k=')).toBeNull();+ expect(normalizeBase64Payload('aGk=<script>')).toBeNull();+ });++ it('base64DecodedByteLength 与真实解码长度一致', () => {+ for (const length of [0, 1, 2, 3, 4, 5, 6, 7, 100, 1023]) {+ const encoded = Buffer.alloc(length, 1).toString('base64');+ expect(base64DecodedByteLength(encoded)).toBe(length);+ expect(base64DecodedByteLength(`${encoded.slice(0, 4)}\r\n${encoded.slice(4)}`)).toBe(length);+ }+ });++ it('mediaErrorStackForLog 输出有界、脱敏的栈摘要,无栈时返回 null', () => {+ const error = new RangeError('Maximum call stack size exceeded');+ error.stack = [+ 'RangeError: Maximum call stack size exceeded',+ ' at multipartRequestBody (https://user:[email protected]/app.js:1:1)',+ ...Array.from({ length: 20 }, (_, index) => ` at frame${index} (file.js:${index}:1)`),+ ].join('\n');+ const summary = mediaErrorStackForLog(error);+ expect(summary).toMatch(/^RangeError: at multipartRequestBody /);+ expect(summary).not.toContain('secret');+ expect(summary).not.toContain('Maximum call stack');+ expect(summary!.split(' | ')).toHaveLength(6);+ expect(mediaErrorStackForLog('plain')).toBeNull();+ });+});diff --git a/apps/desktop/src/main/cindy-media/dataUrl.ts b/apps/desktop/src/main/cindy-media/dataUrl.tsnew file mode 100644index 0000000000..a13e765035--- /dev/null+++ b/apps/desktop/src/main/cindy-media/dataUrl.ts@@ -0,0 +1,73 @@+/**+ * 结构性解析 data URL(#5081)。+ *+ * 参考图展开成 base64 后单段可达数百万字符。#5081 报告单张约 3MiB(base64 ≈ 2^22 字符)+ * 在组装阶段抛 `RangeError: Maximum call stack size exceeded`;为避免把整段载荷交给+ * 带捕获组/贪婪量词的正则回溯,这里只做前缀判断与 `indexOf(',')` 切分,对载荷本身+ * 不跑任何正则,成本与长度线性。+ */+export interface ParsedDataUrl {+ /** 已小写的 MIME 类型(`data:` 与首个 `;`/`,` 之间)。 */+ mimeType: string;+ /** header 段是否声明 `;base64`。 */+ base64: boolean;+ /** 逗号之后的原始载荷(未去空白)。 */+ payload: string;+}++export function parseDataUrl(value: string): ParsedDataUrl | null {+ if (value.length < 6 || value.slice(0, 5).toLowerCase() !== 'data:') return null;+ const comma = value.indexOf(',');+ if (comma < 5) return null;+ const header = value.slice(5, comma);+ const segments = header.split(';');+ const mimeType = segments[0].trim().toLowerCase();+ if (!mimeType) return null;+ const base64 = segments.slice(1).some((segment) => segment.trim().toLowerCase() === 'base64');+ return { mimeType, base64, payload: value.slice(comma + 1) };+}++/**+ * 校验 base64 载荷只含 `A-Za-z0-9+/=` 与 CR/LF,返回去掉换行后的字符串;+ * 非法字符返回 null。逐字符扫描,不用正则。+ */+export function normalizeBase64Payload(payload: string): string | null {+ let hasLineBreak = false;+ for (let index = 0; index < payload.length; index += 1) {+ const code = payload.charCodeAt(index);+ if (+ (code >= 0x41 && code <= 0x5a) || // A-Z+ (code >= 0x61 && code <= 0x7a) || // a-z+ (code >= 0x30 && code <= 0x39) || // 0-9+ code === 0x2b || code === 0x2f || code === 0x3d // + / =+ ) continue;+ if (code === 0x0d || code === 0x0a) { hasLineBreak = true; continue; }+ return null;+ }+ if (!hasLineBreak) return payload;+ let cleaned = '';+ let start = 0;+ for (let index = 0; index < payload.length; index += 1) {+ const code = payload.charCodeAt(index);+ if (code === 0x0d || code === 0x0a) {+ if (index > start) cleaned += payload.slice(start, index);+ start = index + 1;+ }+ }+ if (start < payload.length) cleaned += payload.slice(start);+ return cleaned;+}++/** 统计去掉空白后的 base64 字符数对应的解码字节数(不解码、不分配)。 */+export function base64DecodedByteLength(payload: string): number {+ let chars = 0;+ let padding = 0;+ for (let index = 0; index < payload.length; index += 1) {+ const code = payload.charCodeAt(index);+ if (code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d || code === 0x0c || code === 0x0b) continue;+ chars += 1;+ if (code === 0x3d) padding += 1;+ else padding = 0;+ }+ return Math.max(0, Math.floor((chars * 3) / 4) - Math.min(padding, 2));+}diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.tsindex 90f8f8278c..cdae4debdc 100644--- a/apps/desktop/src/main/cindy-media/invocationService.ts+++ b/apps/desktop/src/main/cindy-media/invocationService.ts@@ -34,7 +34,8 @@ 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 { mediaErrorForLog, mediaErrorStackForLog, mediaRequestParamsForLog, mediaRequestUrlForLog } from './mediaRequestLog.js';+import { normalizeBase64Payload, parseDataUrl } from './dataUrl.js';import {invokeProviderMedia,resolveProviderMediaModel,@@ -375,15 +376,18 @@ function multipartRequestBody(if (typeof item !== 'string') {throw new MediaInvocationError('MEDIA_INPUT_INVALID', `媒体字段 ${field} 必须是媒体地址`);}- const match = /^data:([^;,]+);base64,([A-Za-z0-9+/=\r\n]+)$/i.exec(item);- if (!match) {+ // 结构性解析(#5081):单张 ≥ ~3MiB 的参考图在组装阶段抛 RangeError,+ // 这里不再对数百万字符的 base64 载荷跑带捕获组的正则,只切分前缀并逐字符校验。+ const parsed = parseDataUrl(item);+ const encoded = parsed?.base64 ? normalizeBase64Payload(parsed.payload) : null;+ if (!parsed || !encoded) {throw new MediaInvocationError('MEDIA_INPUT_INVALID',`multipart 媒体字段 ${field} 必须使用 Cindy 受管媒体`,);}- const mimeType = match[1].toLowerCase();- const buffer = Buffer.from(match[2].replace(/[\r\n]/g, ''), 'base64');+ const mimeType = parsed.mimeType;+ const buffer = Buffer.from(encoded, 'base64');if (buffer.byteLength === 0 ||!mimeType.startsWith(`${fileGuide.kind}/`) ||@@ -443,6 +447,9 @@ async function dispatchRequest(input: {url: mediaRequestUrlForLog(url),};let responseStatus: number | undefined;+ // 组装/日志阶段任何异常都发生在出站之前:请求从未发起、不产生费用,必须与+ // 「结果未知」的上游失败区分开(#5081:RangeError 曾被包成 SUBMISSION_OUTCOME_UNKNOWN)。+ let dispatched = false;try {const requestBody = input.body? input.bodyEncoding === 'multipart'@@ -453,6 +460,7 @@ async function dispatchRequest(input: {...requestLog,params: mediaRequestParamsForLog(input.body ?? {}),});+ dispatched = true;const response = await outboundFetch(url, {method: input.method,headers: {@@ -507,13 +515,23 @@ async function dispatchRequest(input: {throw new MediaInvocationError('UPSTREAM_RESPONSE_INVALID', '上游成功响应不是合法 JSON');}} catch (error) {+ const stack = mediaErrorStackForLog(error);log.warn('media request failed', {...requestLog,...(responseStatus !== undefined ? { status: responseStatus } : {}),durationMs: Date.now() - startedAt,+ dispatched,error: mediaRequestParamsForLog(error instanceof Error ? error.message : String(error)),+ ...(error instanceof Error ? { errorName: error.name } : {}),+ ...(stack ? { stack } : {}),});if (error instanceof MediaInvocationError) throw error;+ if (!dispatched) {+ throw new MediaInvocationError(+ 'REQUEST_BUILD_FAILED',+ `请求在本地组装失败,未向上游发起、不产生费用,可安全重试:${mediaErrorForLog(error)}`,+ );+ }const aborted = error instanceof Error && error.name === 'AbortError';if (input.operation === 'poll') {throw new MediaInvocationError(@@ -1495,19 +1513,26 @@ async function submitInvocation(};} catch (error) {const expected = error instanceof MediaInvocationError ? error : null;- await transitionMediaInvocation(+ // 本地组装失败(#5081):请求从未出站、无费用,把 invocation 放回 prepared,+ // 让同一 invocation_id 可以直接再次 request;其余失败仍进入 failed / unknown。+ const buildFailed = expected?.code === 'REQUEST_BUILD_FAILED';+ const restored = await transitionMediaInvocation({id: invocation.id,owner: invocation.owner,from: 'submitting',- to: expected?.outcomeUnknown ? 'unknown' : 'failed',+ to: buildFailed ? 'prepared' : expected?.outcomeUnknown ? 'unknown' : 'failed',},db,).catch(() => false);if (expected) {- return expected.outcomeUnknown- ? submissionOutcomeUnknown(expected.message)- : failure(expected.code, expected.message, false, { outcomeKnown: true });+ if (expected.outcomeUnknown) return submissionOutcomeUnknown(expected.message);+ if (buildFailed && restored) {+ return failure(expected.code, `${expected.message};同一 invocation_id 可直接再次 request`, true, {+ outcomeKnown: true,+ });+ }+ return failure(expected.code, expected.message, false, { outcomeKnown: true });}log.warn('media submission failed', {error: error instanceof Error ? error.message : String(error),diff --git a/apps/desktop/src/main/cindy-media/mediaRequestLog.ts b/apps/desktop/src/main/cindy-media/mediaRequestLog.tsindex b7681e6a02..d87ae6dba4 100644--- a/apps/desktop/src/main/cindy-media/mediaRequestLog.ts+++ b/apps/desktop/src/main/cindy-media/mediaRequestLog.ts@@ -1,5 +1,7 @@import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';+import { base64DecodedByteLength, parseDataUrl } from './dataUrl.js';+const MAX_LOG_STRING_CHARS = 20_000;const MAX_LOG_DEPTH = 24;const SENSITIVE_PARAM_NAME =@@ -12,18 +14,13 @@ function boundedText(value: string): string {}function dataUrlSummary(value: string): string | null {- const match = /^data:([^;,]+)(;base64)?,([\s\S]*)$/i.exec(value);- if (!match) return null;- const mimeType = match[1].toLowerCase();- const encoded = match[3].replace(/\s/g, '');- const bytes = match[2]- ? Math.max(- 0,- Math.floor((encoded.length * 3) / 4) -- (encoded.endsWith('==') ? 2 : encoded.endsWith('=') ? 1 : 0),- )- : Buffer.byteLength(encoded, 'utf8');- return `[data URL mime=${mimeType} bytes=${bytes}]`;+ // 结构性解析,不对数百万字符的载荷跑正则(#5081)。+ const parsed = parseDataUrl(value);+ if (!parsed) return null;+ const bytes = parsed.base64+ ? base64DecodedByteLength(parsed.payload)+ : Buffer.byteLength(parsed.payload, 'utf8');+ return `[data URL mime=${parsed.mimeType} bytes=${bytes}]`;}function urlForLog(rawUrl: string, stripFragment: boolean): string {@@ -104,3 +101,22 @@ export function mediaErrorForLog(error: unknown): string {: typeof error === 'string' ? error : `Non-Error thrown (${typeof error})`;return redactSensitiveText(message.replace(/\bhttps?:\/\/[^\s"'<>]+/gi, '[REDACTED_URL]')).slice(0, 1_000);}++const MAX_STACK_FRAMES = 6;+const MAX_STACK_CHARS = 1_500;++/**+ * 有界的调用栈摘要:只保留错误类型与前几帧位置,脱敏 URL/凭证,不带消息载荷。+ * 供本地组装阶段这类「message 一句话定位不了」的失败(#5081 的 RangeError)留下线索。+ */+export function mediaErrorStackForLog(error: unknown): string | null {+ if (!(error instanceof Error) || typeof error.stack !== 'string') return null;+ const frames = error.stack+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.startsWith('at '))+ .slice(0, MAX_STACK_FRAMES)+ .map((line) => redactSensitiveText(line.replace(/\bhttps?:\/\/[^\s"'<>]+/gi, '[REDACTED_URL]')));+ if (frames.length === 0) return null;+ return `${error.name}: ${frames.join(' | ')}`.slice(0, MAX_STACK_CHARS);+}