/** @jest-environment node */ import { createHash, randomUUID } from 'node:crypto' import { getServerSession } from 'next-auth' import { POST } from '@/app/api/desktop/[...path]/route' import { DesktopClientError } from '@/lib/desktop-client/contract.mjs' import { requireDesktop } from '@/lib/desktop-client/service' import { prisma } from '@/lib/prisma' import { submitYouyidianNotification } from '@/lib/youyidian-notification-center' import { GET } from './route' jest.mock('next-auth', () => ({ getServerSession: jest.fn() })) jest.mock('@/lib/auth', () => ({ authOptions: {} })) jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() })) jest.mock('@/lib/youyidian-notification-center', () => ({ ...jest.requireActual('@/lib/youyidian-notification-center'), submitYouyidianNotification: jest.fn(), })) jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn(), findMany: jest.fn() }, desktopClientFeedback: { createMany: jest.fn(), findFirst: jest.fn(), findUnique: jest.fn() }, } })) const id = '5acdddaa-6c85-4d20-9783-17de944b2e8a' const ownerId = 'submitter' const createdAt = new Date('2026-12-01T10:00:00.000Z') const active = { role: 'USER', isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null } as const const record = { feedbackId: id, ownerId, createdAt, status: 'submitted', summary: '导出失败', projectId: 'project-01', taskId: 'task-01', requestId: 'req-01', snapshot: { message: '' }, owner: { username: 'submitter', realName: '提交人甲', department: '旧部门名', departmentRef: { name: '运营部' } }, } const feedbackStore = jest.mocked(prisma.desktopClientFeedback) const userStore = jest.mocked(prisma.user) const appOrigin = ['https:', '', 'example.invalid'].join('/') const webhookUrl = new URL('/incoming', appOrigin).href function dispatchTurn() { return new Promise(resolve => setImmediate(resolve)) } function post(input: object | string = { feedbackId: id, summary: ' 导出失败 ' }, path = ['feedback']) { const request = new Request(new URL('/api/desktop/feedback', appOrigin), { method: 'POST', body: typeof input === 'string' ? input : JSON.stringify(input), }) return POST(request, { params: { path } }) } function get(idParam = id, query = '') { return GET(new Request(new URL(`/feedback/${idParam}${query}`, appOrigin)), { params: { id: idParam } }) } function expectOnlyCopyScript(response: Response, html: string) { const scripts = Array.from(html.matchAll(/' feedbackStore.findFirst.mockResolvedValue({ ...record, snapshot: { clientVersion: xss, commit: scriptXss, channel: xss, os: xss, arch: scriptXss, page: xss, currentError: scriptXss, agentDaemon: { available: false, lastError: xss, stderrSummary: scriptXss, activeRuns: [xss] }, models: { chatModel: xss, knowledgeMode: scriptXss }, canvas: { renderPath: xss, gpuFallback: scriptXss, templateHash: xss }, notices: [xss], recentErrors: [{ message: scriptXss }], recentLogs: [`ERROR ${scriptXss}`], }, }) const html = await (await get()).text() expect(html.match(/' const snapshot = { schemaVersion: 3, clientVersion: '1.2612.120', channel: 'stable', workspaceState: { activeScreen: marker, activeTab: 'editor', documentReady: false }, errors: { activeBanners: [{ operation: 'workspace', message: script }], lastFailedOperation: { operation: 'export', code: 503 } }, modelConfig: { chat: { modelId: marker, providerId: script }, hasPersonalKey: false }, updateState: { status: marker, latestVersion: script, checkFailed: true, error: { message: marker } }, display: { logicalWidth: 390, logicalHeight: 844, gpu: { adapter: marker, backend: 'Vulkan' } }, breadcrumbs: [{ action: marker, source: script, timestampMs: 123 }], recentToolFailures: [{ toolName: script, code: 503, durationMs: 450, ageMs: 100 }], recentErrors: [marker], recentLogs: [`ERROR ${script}`], } feedbackStore.findFirst.mockResolvedValue({ ...record, snapshot }) const response = await get() const html = await response.text() expect(response.status).toBe(200) expect(response.headers.get('cache-control')).toBe('private, no-store') expectOnlyCopyScript(response, html) expect(html).not.toContain(marker) expect(html).not.toContain(script) const visibleView = html.split('
')[0] for (const text of [ '记录到异常', '版本 1.2612.120', '更新检查失败', '工作区状态', '模型配置', 'Vulkan', '近期工具失败', '近期错误', '操作轨迹', '近期客户端日志摘要', '耗时 ms:450', '<img src=x onerror=alert(1)>', '</script><script>alert("unsafe")</script>', ]) expect(visibleView).toContain(text) expect(html).toContain('href="?format=json" download') expect(html).toContain('id="copy-json"') const download = await get(id, '?format=json') expect(download.headers.get('content-type')).toBe('application/json; charset=utf-8') expect(download.headers.get('content-disposition')).toMatch(/^attachment;/) expect(download.headers.get('cache-control')).toBe('private, no-store') expect(await download.json()).toEqual(snapshot) jest.mocked(getServerSession).mockResolvedValue(null) const redirect = await get(id, '?format=json') expect(redirect.status).toBe(307) expect(redirect.headers.get('location')).toBe(`/login?redirect=%2Ffeedback%2F${id}%3Fformat%3Djson`) }) it('degrades gracefully for v1 and empty snapshots with expanded JSON fallback', async () => { jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } }) userStore.findUnique.mockResolvedValue(active as never) feedbackStore.findFirst.mockResolvedValueOnce({ ...record, snapshot: { clientVersion: '1.0.5', os: 'Windows', project: { name: '老项目' }, message: 'v1报错' }, }).mockResolvedValueOnce({ ...record, snapshot: {}, }) const v1Html = await (await get()).text() expect(v1Html).toContain('老项目') expect(v1Html).toContain('1.0.5') expect(v1Html).toContain('
') expect(v1Html).not.toContain('核心故障摘要') expect(v1Html).not.toContain('运行环境与状态速览') expect(v1Html).not.toContain('近期通知与告警') expect(v1Html).not.toContain('近期客户端日志摘要') const emptyHtml = await (await get()).text() expect(emptyHtml).toContain('没有记录诊断信息。') expect(emptyHtml).not.toContain('