gongxiangp2/lib/desktop-client/feedback-contract.test.ts

331 lines
15 KiB
TypeScript

/** @jest-environment node */
import { parseDesktopFeedback } from './feedback-contract'
const feedbackId = '5acdddaa-6c85-4d20-9783-17de944b2e8a'
const parse = (data: Record<string, unknown>) => parseDesktopFeedback(JSON.stringify({ feedbackId, summary: '导出失败', ...data }))
describe('desktop feedback contract', () => {
it.each([undefined, 1, 2])('keeps version %s on the legacy diagnostic contract', schemaVersion => {
const context = {
schemaVersion, currentError: '导出失败', recentErrors: Array(20).fill('旧版错误'),
recentLogs: Array(80).fill('旧版日志'), modelConfig: { hasPersonalKey: true },
}
expect(parse({ context }).snapshot).toEqual({
currentError: '导出失败', recentErrors: Array(12).fill('旧版错误'), recentLogs: Array(25).fill('旧版日志'),
})
})
it('rejects unsupported versions and conflicting version declarations', () => {
for (const context of [{ schemaVersion: 4 }, { schemaVersion: '3' }]) {
expect(() => parse({ context })).toThrow('反馈资料格式不正确')
}
expect(() => parse({ schemaVersion: 2, context: { schemaVersion: 3 } })).toThrow('反馈资料格式不正确')
})
it('accepts the desktop v3 snapshot shape with bounded, sanitized nested diagnostics', () => {
const result = parse({
context: {
schemaVersion: 3, clientVersion: '1.2612.120', channel: 'stable',
workspaceState: {
activeScreen: 'canvas', activeTab: 'editor', mode: 'workspace', projectCount: 3, openProjectCount: 1,
openDocumentCount: 1, recentNoticeCount: 2, hasActiveProject: true, canvasReady: true, documentReady: true, activeTaskStatus: null,
projectTitle: 'private project title',
},
errors: {
activeBanners: [{ operation: 'workspace', message: '处理失败', category: 'Network', code: 503 }],
lastFailedOperation: { toolName: 'create_image', status: 'failed', durationMs: 450, ageMs: 100 },
},
modelConfig: {
chat: { modelId: 'chat-model', providerId: 'provider', routeId: 'route-1', protocol: 'responses', ready: false },
image: { modelId: 'image-model', apiKey: 'private-key' }, copy: { modelId: 'copy-model' },
routingMode: 'unconfigured', hasPersonalKey: false,
},
updateState: { channel: 'stable', currentVersion: '1.2612.120', latestVersion: '1.2612.121', status: 'idle',
checkedAt: 123456, checkFailed: true, error: { operation: 'client-update', category: 'Network', message: '无法连接' } },
display: { logicalWidth: 800, logicalHeight: 600, physicalWidth: 1600, physicalHeight: 1200, scaleFactor: 2,
nativeScaleFactor: 2, gpu: { adapter: 'GPU', backend: 'Vulkan', deviceType: 'DiscreteGpu',
driver: '驱动', videoMemoryMb: 8192 } },
breadcrumbs: [true, ...Array(30).fill({ action: 'tool-activity', source: 'create_image', timestampMs: 123, text: 'private prose' })],
recentToolFailures: Array(15).fill({ toolName: 'create_image', status: 'failed', code: 500, category: 'Network', durationMs: 450, timestampMs: 123, ageMs: 100 }),
recentErrors: Array(30).fill('WARN 连接超时'),
recentLogs: [{ message: 'discarded' }, ...Array(95).fill('日'.repeat(245))],
},
})
expect(result.snapshot).toMatchObject({
schemaVersion: 3, clientVersion: '1.2612.120', channel: 'stable',
workspaceState: { activeScreen: 'canvas', activeTab: 'editor', openDocumentCount: 1, recentNoticeCount: 2, documentReady: true },
errors: { activeBanners: [{ message: '处理失败', code: 503 }], lastFailedOperation: { toolName: 'create_image', ageMs: 100 } },
modelConfig: { chat: { modelId: 'chat-model', routeId: 'route-1', protocol: 'responses', ready: false },
image: { modelId: 'image-model' }, copy: { modelId: 'copy-model' }, hasPersonalKey: false },
updateState: { latestVersion: '1.2612.121', checkedAt: 123456, checkFailed: true, error: { operation: 'client-update' } },
display: { physicalWidth: 1600, scaleFactor: 2, gpu: { backend: 'Vulkan', videoMemoryMb: 8192 } },
breadcrumbs: Array(25).fill({ action: 'tool-activity', source: 'create_image', timestampMs: 123 }),
recentToolFailures: Array(10).fill({ toolName: 'create_image', code: 500, durationMs: 450, timestampMs: 123, ageMs: 100 }),
recentErrors: Array(20).fill('WARN 连接超时'),
recentLogs: Array(80).fill('日'.repeat(240)),
})
expect(JSON.stringify(result.snapshot)).not.toMatch(/private project title|private-key|private prose|discarded/)
})
it('normalizes legacy chatModel/copyModel/imageModel aliases inside v3 modelConfig', () => {
const result = parse({
context: {
schemaVersion: 3,
modelConfig: {
chatModel: { modelId: 'chat-alias', providerId: 'provider', ready: true },
copyModel: { modelId: 'copy-alias' },
imageModel: { modelId: 'image-alias' },
routingMode: 'personal-key',
hasPersonalKey: true,
},
},
})
expect(result.snapshot.modelConfig).toEqual({
chat: { modelId: 'chat-alias', providerId: 'provider', ready: true },
copy: { modelId: 'copy-alias' },
image: { modelId: 'image-alias' },
routingMode: 'personal-key',
hasPersonalKey: true,
})
})
it('redacts v3 secrets, paths and images before truncation and enforces the personal key boolean', () => {
const result = parse({
schemaVersion: 3,
context: {
project: { id: 'project-01', name: 'private project title' },
modelConfig: { hasPersonalKey: 'raw-key', chat: { modelId: 'safe-model', token: 'unsafe-token' } },
errors: { activeBanners: [{ message: `${'字'.repeat(241)} Bearer unsafe-secret` }],
lastFailedOperation: { message: 'file C:\\Users\\Example\\document.json' } },
updateState: { error: { message: 'signed request /assets?X-Amz-Signature=unsafe-signature' } },
display: { gpu: { driver: '/home/example/driver', screenshot: 'raw pixels' } },
breadcrumbs: [{ action: 'open-feedback', source: '%41uthorization%3A Basic unsafe-token' }],
recentToolFailures: [{ toolName: 'data:image/png;base64,raw-image' }],
recentErrors: ['Cookie: sid=unsafe-token'],
recentLogs: ['sk-example-key', 'safe log'],
},
})
expect(result.snapshot).toEqual({
schemaVersion: 3,
project: { id: 'project-01' },
modelConfig: { chat: { modelId: 'safe-model' } },
errors: { activeBanners: [{ message: '[敏感信息已移除]' }], lastFailedOperation: { message: '[本地路径已移除]' } },
updateState: { error: { message: '[敏感信息已移除]' } },
display: { gpu: { driver: '[本地路径已移除]', screenshot: '[图片已移除]' } },
breadcrumbs: [{ action: 'open-feedback', source: '[敏感信息已移除]' }],
recentToolFailures: [{ toolName: '[图片已移除]' }],
recentErrors: ['[敏感信息已移除]'],
recentLogs: ['[敏感信息已移除]', 'safe log'],
})
})
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: {} } })
})
})