/** @jest-environment node */ import { parseDesktopFeedback } from './feedback-contract' const feedbackId = '5acdddaa-6c85-4d20-9783-17de944b2e8a' const parse = (data: Record) => parseDesktopFeedback(JSON.stringify({ feedbackId, summary: '导出失败', ...data })) describe('desktop feedback contract', () => { it('normalizes the UUID, trims summary, and accepts 2000 Unicode characters', () => { const summary = '🖼'.repeat(2000) expect(parse({ feedbackId: feedbackId.toUpperCase(), summary: ` ${summary}\n` })).toMatchObject({ feedbackId, summary }) }) it.each(['', ' \n ', '\u0000', '字'.repeat(2001), '🖼'.repeat(2001), null])('rejects invalid summary %#', summary => { expect(() => parse({ summary })).toThrow('2000 字以内') }) it('rejects malformed body, invalid UUID and non-object context', () => { expect(() => parseDesktopFeedback('{')).toThrow('反馈资料格式不正确') expect(() => parse({ feedbackId: 'invalid' })).toThrow('反馈资料格式不正确') expect(() => parse({ context: [] })).toThrow('反馈资料格式不正确') }) it('drops unknown fields and removes credentials, URLs and images at every accepted depth', () => { const result = parse({ requestId: 'dcs_test_payload', context: { Authorization: 'unused-secret', client: { appVersion: '1.0.5', headers: { Cookie: 'sid=unused-secret' }, apiKey: 'unused-secret' }, project: { title: '详情制作', screenshot: { bytes: [1, 2, 3] } }, errors: [ 'Cookie: sid=unused-secret; another=unused-secret', 'b\u0000earer unused-secret', 'x-api-key="unused-secret"', '%41uthorization%3A Basic unused-secret', 'postgres://user:unused-secret@internal.invalid/db', '请求失败 https://service.invalid/?signature=unused-secret', 'signed request /assets/preview?X-Amz-Signature=unused-secret', 'sid=unused-secret; other=unused-secret', 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwC', '附件 data:image/png;base64,unused-image', ], events: [{ requestId: 'req-01', diagnostics: { message: '记录保留', screenshot: [1, 2, 3] } }], }, }) expect(result.requestId).toBe('[敏感信息已移除]') expect(result.snapshot).toEqual({ client: { appVersion: '1.0.5' }, project: { title: '详情制作', screenshot: '[图片已移除]' }, errors: [...Array(9).fill('[敏感信息已移除]'), '[图片已移除]'], events: [{ requestId: 'req-01', diagnostics: { message: '记录保留', screenshot: '[图片已移除]' } }], }) }) it('limits lengths, rows and depth after scanning for secrets', () => { const long = '长'.repeat(1500) const result = parse({ projectId: '项'.repeat(200), context: { errors: Array(16).fill(long), message: `${long} Bearer fake`, diagnostics: { client: { project: { task: { title: '过深' } } } } }, }) expect(result.projectId).toHaveLength(180) expect(result.snapshot).toEqual({ errors: Array(12).fill('长'.repeat(1000)), message: '[敏感信息已移除]', diagnostics: { client: { project: {} } }, }) }) it('preserves v2 diagnostic keys across runtime, model, canvas, multi-project and storage scopes while dropping unknown keys and images', () => { const result = parse({ context: { commit: 'abc123456789', channel: 'stable', builtAt: '2026-12-03T01:00:00Z', page: 'workspace', view: 'canvas', currentError: '导出渲染失败', notices: [{ kind: 'warning', message: '显存占用偏高', screenshot: [1, 2] }], recentErrors: [{ errorCode: 'E_GPU', message: '回退软件渲染' }], agentDaemon: { available: true, ready: true, spawnCount: 2, activeRuns: ['run-1', 'run-2'], heartbeatAgeMs: 1200, exitCode: 0, lastError: '无', stderrSummary: 'warn: slow init', unknownSecret: 'drop-me', }, models: { chatModel: 'chat-v1', copyModel: 'copy-v1', imageModel: 'img-v1', hasPersonalKey: true, knowledgeMode: 'cloud', extraField: 'drop-me', }, canvas: { renderPath: 'cpu', gpuFallback: true, gpuFallbackKind: 'overBudget', documentWidth: 750, documentHeight: 1200, layerCount: 24, outputId: 'out-01', activeOutput: { id: 'out-01', name: '主图' }, variantId: 'var-01', templateHash: 'tpl-hash-01', revision: 7, dirty: true, professionalMode: true, thumbnail: 'raw-thumb', }, render: { renderPath: 'cpu', gpuFallback: 'overBudget' }, multiProject: { runningCount: 1, queuedCount: 2, pausedCount: 3, unexpected: 'drop' }, storage: { usingCustomRoot: true, migrationPhase: 'idle', freeBytes: 1024000, preview: [9] }, recentLogs: ['2026-12-03 INFO 启动完成'], unknownTopLevel: 'should-be-dropped', }, }) expect(result.snapshot).toEqual({ commit: 'abc123456789', channel: 'stable', builtAt: '2026-12-03T01:00:00Z', page: 'workspace', view: 'canvas', currentError: '导出渲染失败', notices: [{ kind: 'warning', message: '显存占用偏高', screenshot: '[图片已移除]' }], recentErrors: [{ errorCode: 'E_GPU', message: '回退软件渲染' }], agentDaemon: { available: true, ready: true, spawnCount: 2, activeRuns: ['run-1', 'run-2'], heartbeatAgeMs: 1200, exitCode: 0, lastError: '无', stderrSummary: 'warn: slow init', }, models: { chatModel: 'chat-v1', copyModel: 'copy-v1', imageModel: 'img-v1', hasPersonalKey: true, knowledgeMode: 'cloud', }, canvas: { renderPath: 'cpu', gpuFallback: true, gpuFallbackKind: 'overBudget', documentWidth: 750, documentHeight: 1200, layerCount: 24, outputId: 'out-01', activeOutput: { id: 'out-01', name: '主图' }, variantId: 'var-01', templateHash: 'tpl-hash-01', revision: 7, dirty: true, professionalMode: true, thumbnail: '[图片已移除]', }, render: { renderPath: 'cpu', gpuFallback: 'overBudget' }, multiProject: { runningCount: 1, queuedCount: 2, pausedCount: 3 }, storage: { usingCustomRoot: true, migrationPhase: 'idle', freeBytes: 1024000, preview: '[图片已移除]' }, recentLogs: ['2026-12-03 INFO 启动完成'], }) }) it('raises the object key limit from 16 to 24', () => { const allowedKeys = [ 'client', 'clientVersion', 'appVersion', 'version', 'platform', 'os', 'arch', 'capturedAt', 'online', 'projectId', 'projectName', 'taskId', 'requestId', 'id', 'name', 'title', 'kind', 'type', 'status', 'stage', 'model', 'commit', 'channel', 'builtAt', 'page', 'view', ] const context = Object.fromEntries(allowedKeys.map((key, idx) => [key, `v-${idx}`])) const result = parse({ context }) expect(Object.keys(result.snapshot)).toHaveLength(24) expect(result.snapshot).not.toHaveProperty('page') expect(result.snapshot).not.toHaveProperty('view') }) it('caps recentLogs at 25 string entries, truncates to 240 chars, and redacts secrets while keeping errors at 12', () => { const longLog = 'INFO log entry '.repeat(25) const recentLogs: unknown[] = [ 123, { ignored: true }, longLog, 'Authorization: Bearer secret-token-value', 'request https://internal.invalid/secret?token=1', 'payload data:image/png;base64,abc', ...Array.from({ length: 24 }, (_, idx) => `WARN line ${idx}`), ] const result = parse({ context: { errors: Array(15).fill('普通错误'), recentLogs, diagnostics: { client: { project: { task: { recentLogs: ['too deep'] } } } }, }, }) expect(result.snapshot.errors).toEqual(Array(12).fill('普通错误')) const logs = result.snapshot.recentLogs as string[] expect(logs).toHaveLength(25) expect(logs[0]).toHaveLength(240) expect(logs[1]).toBe('[敏感信息已移除]') expect(logs[2]).toBe('[敏感信息已移除]') expect(logs[3]).toBe('[图片已移除]') expect(logs[4]).toBe('WARN line 0') expect(logs[24]).toBe('WARN line 20') expect(result.snapshot.diagnostics).toEqual({ client: { project: {} } }) }) })