586 lines
29 KiB
TypeScript
586 lines
29 KiB
TypeScript
/** @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: '<b>导出失败</b>',
|
||
projectId: 'project-01', taskId: 'task-01', requestId: 'req-01', snapshot: { message: '<script>unsafe</script>' },
|
||
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<void>(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(/<script>([\s\S]*?)<\/script>/g))
|
||
expect(scripts).toHaveLength(1)
|
||
expect(scripts[0][1]).toContain("getElementById('copy-json')")
|
||
const digest = createHash('sha256').update(scripts[0][1]).digest('base64')
|
||
expect(response.headers.get('content-security-policy')).toContain(`script-src 'sha256-${digest}'`)
|
||
}
|
||
|
||
beforeEach(() => {
|
||
jest.resetAllMocks()
|
||
jest.replaceProperty(process, 'env', {
|
||
...process.env, NEXT_PUBLIC_APP_PUBLIC_URL: appOrigin,
|
||
YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID: 'recipient-test', YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS: '',
|
||
YYD_NOTIFICATION_CENTER_URL: new URL('/notify', appOrigin).href,
|
||
YYD_NOTIFICATION_CENTER_PROJECT_CODE: 'test-project', YYD_NOTIFICATION_CENTER_PROJECT_SECRET: randomUUID(),
|
||
})
|
||
for (const key of ['FEEDBACK_GITHUB_TOKEN', 'FEEDBACK_GITHUB_REPO', 'FEEDBACK_DINGTALK_OWNER_USER_ID',
|
||
'FEEDBACK_AGENT_WEBHOOK_URL', 'FEEDBACK_AGENT_WEBHOOK_SECRET']) delete process.env[key]
|
||
jest.spyOn(console, 'info').mockImplementation(() => {})
|
||
jest.mocked(requireDesktop).mockResolvedValue({ id: 'session-01', account: { id: ownerId, name: '提交人甲' }, isSuperAdmin: false, expiresAt: createdAt })
|
||
jest.mocked(submitYouyidianNotification).mockResolvedValue({ id: 'notice-01', projectCode: 'test', status: 'pending', recipientUserId: 'recipient-test', title: '小壹问题反馈' })
|
||
})
|
||
|
||
afterEach(() => jest.restoreAllMocks())
|
||
|
||
describe('POST /api/desktop/feedback', () => {
|
||
it('passes through desktop session authentication and rejects extra path segments', async () => {
|
||
jest.mocked(requireDesktop).mockRejectedValueOnce(new DesktopClientError('请先登录', 401, 'unauthenticated'))
|
||
expect((await post()).status).toBe(401)
|
||
expect((await post({}, ['feedback', 'extra'])).status).toBe(404)
|
||
expect(feedbackStore.createMany).not.toHaveBeenCalled()
|
||
})
|
||
|
||
it('handles concurrent repeats with one insert and one notification', async () => {
|
||
feedbackStore.createMany.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
const responses = await Promise.all([post(), post({ feedbackId: id.toUpperCase(), summary: '新的说明' })])
|
||
const receipt = { feedback: { feedbackId: id, status: 'submitted', createdAt: createdAt.toISOString(), detailPath: `/feedback/${id}` } }
|
||
for (const response of responses) {
|
||
expect(response.status).toBe(200)
|
||
expect(await response.json()).toEqual(receipt)
|
||
}
|
||
expect(feedbackStore.createMany).toHaveBeenCalledWith({ data: expect.objectContaining({ ownerId, feedbackId: id, summary: '导出失败' }), skipDuplicates: true })
|
||
await dispatchTurn()
|
||
expect(jest.mocked(submitYouyidianNotification)).toHaveBeenCalledTimes(1)
|
||
expect(jest.mocked(submitYouyidianNotification)).toHaveBeenCalledWith(expect.objectContaining({
|
||
recipientUserId: 'recipient-test', idempotencyKey: `desktop-feedback:${id}`, actionUrl: expect.stringMatching(`/feedback/${id}$`),
|
||
}))
|
||
expect(userStore.findMany).not.toHaveBeenCalled()
|
||
})
|
||
|
||
it('deduplicates configured DingTalk IDs and delivers to each recipient independently', async () => {
|
||
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS = ' ding-second, , recipient-test, ding-second, ding-third '
|
||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
jest.mocked(submitYouyidianNotification)
|
||
.mockRejectedValueOnce(new Error('opaque details'))
|
||
.mockResolvedValueOnce({ id: 'notice-02', projectCode: 'test', status: 'failed', recipientUserId: 'ding-second', title: '小壹问题反馈' })
|
||
|
||
expect((await post()).status).toBe(200)
|
||
await dispatchTurn()
|
||
expect(jest.mocked(submitYouyidianNotification).mock.calls.map(([input]) => [input.recipientUserId, input.idempotencyKey])).toEqual(
|
||
['recipient-test', 'ding-second', 'ding-third'].map(recipient => [recipient, `desktop-feedback:${id}:${recipient}`]),
|
||
)
|
||
expect(userStore.findMany).not.toHaveBeenCalled()
|
||
expect(warning.mock.calls).toEqual([
|
||
['[desktop-feedback] dispatch', { feedbackId: id, channel: 'dingtalk', outcome: 'failed', errorCode: 'request_failed' }],
|
||
['[desktop-feedback] dispatch', { feedbackId: id, channel: 'dingtalk', outcome: 'failed', errorCode: 'delivery_failed' }],
|
||
])
|
||
})
|
||
|
||
it('sends a bounded, sanitized summary and the private link to the configured owner', async () => {
|
||
process.env.FEEDBACK_DINGTALK_OWNER_USER_ID = 'ding-owner'
|
||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
const summary = '🛋'.repeat(125)
|
||
const response = await post({ feedbackId: id, summary, context: {
|
||
project: { name: '森屿布艺沙发', cookie: 'private' }, clientVersion: '1.2612.107', errors: ['Bearer fake-secret'],
|
||
} })
|
||
|
||
expect(response.status).toBe(200)
|
||
await dispatchTurn()
|
||
expect(userStore.findMany).not.toHaveBeenCalled()
|
||
expect(submitYouyidianNotification).toHaveBeenCalledWith({
|
||
recipientUserId: 'ding-owner', idempotencyKey: `desktop-feedback:${id}`, title: '小壹问题反馈',
|
||
content: `反馈人:提交人甲\n项目:森屿布艺沙发\n客户端版本:1.2612.107\n摘要:${'🛋'.repeat(120)}\n反馈编号:${id}`,
|
||
actionTitle: '查看反馈', actionUrl: expect.stringMatching(`^https?://[^/]+/feedback/${id}$`),
|
||
})
|
||
})
|
||
|
||
it('skips all unconfigured channels after returning the receipt', async () => {
|
||
const fetchMock = jest.spyOn(globalThis, 'fetch')
|
||
delete process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID
|
||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
|
||
expect((await post()).status).toBe(200)
|
||
await dispatchTurn()
|
||
expect(submitYouyidianNotification).not.toHaveBeenCalled()
|
||
expect(fetchMock).not.toHaveBeenCalled()
|
||
expect(userStore.findMany).not.toHaveBeenCalled()
|
||
expect(jest.mocked(console.info).mock.calls.map(([, fields]) => fields)).toEqual([
|
||
{ feedbackId: id, channel: 'github', outcome: 'skipped', missing: ['FEEDBACK_GITHUB_TOKEN'] },
|
||
{ feedbackId: id, channel: 'dingtalk', outcome: 'skipped', missing: ['FEEDBACK_DINGTALK_OWNER_USER_ID'] },
|
||
{ feedbackId: id, channel: 'agent_webhook', outcome: 'skipped', missing: ['FEEDBACK_AGENT_WEBHOOK_URL'] },
|
||
])
|
||
})
|
||
|
||
it.each([500, 'timeout'] as const)('returns the stored receipt before GitHub and the webhook finish with %s', async failure => {
|
||
process.env.FEEDBACK_GITHUB_TOKEN = randomUUID()
|
||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl
|
||
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||
const github = Promise.withResolvers<Response>()
|
||
const webhook = Promise.withResolvers<Response>()
|
||
const fetchMock = jest.spyOn(globalThis, 'fetch').mockReturnValueOnce(github.promise).mockReturnValueOnce(webhook.promise)
|
||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
|
||
const response = await post()
|
||
expect(response.status).toBe(200)
|
||
expect(await response.json()).toMatchObject({ feedback: { feedbackId: id, status: 'submitted' } })
|
||
expect(feedbackStore.createMany).toHaveBeenCalledTimes(1)
|
||
await dispatchTurn()
|
||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||
expect(submitYouyidianNotification).not.toHaveBeenCalled()
|
||
|
||
for (const pending of [github, webhook]) {
|
||
if (failure === 'timeout') pending.reject(new DOMException('opaque details', 'TimeoutError'))
|
||
else pending.resolve(new Response(null, { status: 500 }))
|
||
await dispatchTurn()
|
||
}
|
||
|
||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||
expect(submitYouyidianNotification).toHaveBeenCalledTimes(1)
|
||
const webhookPayload = JSON.parse(String(fetchMock.mock.calls[1][1]?.body))
|
||
expect(webhookPayload).toMatchObject({
|
||
event: 'xiaoyi.feedback.created', feedbackId: id, reporter: { name: '提交人甲', department: '运营部' },
|
||
githubIssueUrl: null, githubIssueNumber: null,
|
||
})
|
||
expect(warning.mock.calls.map(([, fields]) => fields)).toEqual(['github', 'agent_webhook'].map(channel => ({
|
||
feedbackId: id, channel, outcome: 'failed', errorCode: failure === 'timeout' ? 'timeout' : 'http_error',
|
||
...(failure === 500 ? { status: 500 } : {}),
|
||
})))
|
||
})
|
||
|
||
it('validates before writing and enforces the body size limit', async () => {
|
||
expect((await post({ feedbackId: id, summary: '字'.repeat(2001) })).status).toBe(400)
|
||
expect((await post('{')).status).toBe(400)
|
||
expect((await post('a'.repeat(262145))).status).toBe(413)
|
||
expect(feedbackStore.createMany).not.toHaveBeenCalled()
|
||
})
|
||
|
||
it('returns a successful receipt when notification fails and persists only the sanitized snapshot', async () => {
|
||
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
jest.mocked(submitYouyidianNotification).mockRejectedValue(new Error('opaque details'))
|
||
const response = await post({ feedbackId: id, summary: '问题描述', context: { cookie: 'raw-cookie', errors: ['Bearer fake-secret', 'data:image/png;base64,raw-data'] } })
|
||
expect(response.status).toBe(200)
|
||
expect(feedbackStore.createMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({
|
||
snapshot: { errors: ['[敏感信息已移除]', '[图片已移除]'] },
|
||
}) }))
|
||
await dispatchTurn()
|
||
expect(warning).toHaveBeenCalledWith('[desktop-feedback] dispatch', {
|
||
feedbackId: id, channel: 'dingtalk', outcome: 'failed', errorCode: 'request_failed',
|
||
})
|
||
})
|
||
|
||
it('does not expose another account’s receipt for a reused UUID', async () => {
|
||
feedbackStore.createMany.mockResolvedValue({ count: 0 })
|
||
feedbackStore.findFirst.mockResolvedValue(null)
|
||
const response = await post()
|
||
expect(response.status).toBe(409)
|
||
expect(await response.json()).toMatchObject({ code: 'feedback_id_conflict' })
|
||
expect(feedbackStore.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { feedbackId: id, ownerId } }))
|
||
expect(submitYouyidianNotification).not.toHaveBeenCalled()
|
||
})
|
||
|
||
it('includes short commit hash and trimmed currentError or daemon stderrSummary in DingTalk notifications', async () => {
|
||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
|
||
const longError = '渲染队列超时 '.repeat(25)
|
||
expect((await post({
|
||
feedbackId: id,
|
||
summary: '画布导出卡死',
|
||
context: {
|
||
clientVersion: '1.2612.112',
|
||
commit: 'abc123456789',
|
||
currentError: longError,
|
||
agentDaemon: { stderrSummary: 'should not override currentError' },
|
||
},
|
||
})).status).toBe(200)
|
||
|
||
await dispatchTurn()
|
||
const firstCall = jest.mocked(submitYouyidianNotification).mock.calls[0][0]
|
||
expect(firstCall.content).toContain('客户端版本:1.2612.112 (abc1234)')
|
||
expect(firstCall.content).toContain(`当前报错:${Array.from(longError.replace(/\s+/g, ' ').trim()).slice(0, 120).join('')}`)
|
||
|
||
jest.mocked(submitYouyidianNotification).mockClear()
|
||
expect((await post({
|
||
feedbackId: id,
|
||
summary: '本机服务异常',
|
||
context: {
|
||
clientVersion: '1.2612.112',
|
||
commit: ' ',
|
||
agentDaemon: { available: false, stderrSummary: 'Bearer leaked-token' },
|
||
},
|
||
})).status).toBe(200)
|
||
|
||
await dispatchTurn()
|
||
const secondCall = jest.mocked(submitYouyidianNotification).mock.calls[0][0]
|
||
expect(secondCall.content).toContain('客户端版本:1.2612.112\n')
|
||
expect(secondCall.content).toContain('当前报错:\\[敏感信息已移除\\]')
|
||
})
|
||
|
||
it('posts v3 diagnostics and sends a concise, escaped DingTalk triage summary', async () => {
|
||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
const response = await post({ feedbackId: id, summary: '画布导出失败', context: {
|
||
schemaVersion: 3, clientVersion: '1.2612.120', channel: 'stable', os: 'windows', arch: 'x86_64',
|
||
workspaceState: { activeScreen: 'canvas', activeTab: 'editor', mode: 'workspace', activeTaskStatus: 'failed' },
|
||
errors: { lastFailedOperation: { toolName: 'create_image', category: 'Network', code: 503 } },
|
||
display: { physicalWidth: 1600, physicalHeight: 1200, gpu: { backend: 'Vulkan' } },
|
||
modelConfig: { chat: { modelId: 'chat-*v1*', providerId: 'provider-a', apiKey: 'unsafe-key' },
|
||
copy: { modelId: 'copy-v1' }, hasPersonalKey: false },
|
||
recentErrors: ['WARN 重试中', 'ERROR 连接失败'],
|
||
recentToolFailures: [{ toolName: 'create_image', status: 'failed', code: 503 }],
|
||
recentLogs: ['PhotoCraft Pi verbose', 'Bearer unsafe-token'],
|
||
} })
|
||
expect(response.status).toBe(200)
|
||
expect(feedbackStore.createMany).toHaveBeenCalledWith(expect.objectContaining({
|
||
data: expect.objectContaining({ snapshot: expect.objectContaining({
|
||
schemaVersion: 3, recentLogs: ['PhotoCraft Pi verbose', '[敏感信息已移除]'],
|
||
}) }),
|
||
}))
|
||
await dispatchTurn()
|
||
const notification = jest.mocked(submitYouyidianNotification).mock.calls[0][0]
|
||
expect(notification.actionUrl).toMatch(new RegExp(`/feedback/${id}$`))
|
||
for (const line of [
|
||
'客户端版本:1.2612.120', '发布渠道:stable', '系统与显示:windows / x86\\_64 / 1600 × 1200 px / Vulkan',
|
||
'工作区:canvas / editor / workspace / failed', '模型:provider-a / chat-\\*v1\\* / copy-v1 / 个人密钥未配置',
|
||
'当前报错:create\\_image / Network / 503', '最近错误:ERROR 连接失败', '近况:错误 2 条 · 工具失败 1 条',
|
||
]) expect(notification.content).toContain(line)
|
||
expect(notification.content).not.toMatch(/unsafe|\bPi\b|PhotoCraft/i)
|
||
expect(notification.content.length).toBeLessThan(500)
|
||
})
|
||
})
|
||
|
||
describe('GET /feedback/[id]', () => {
|
||
it('redirects to login and preserves the feedback path', async () => {
|
||
const response = await get()
|
||
expect(response.status).toBe(307)
|
||
expect(response.headers.get('location')).toBe(`/login?redirect=%2Ffeedback%2F${id}`)
|
||
expect(feedbackStore.findFirst).not.toHaveBeenCalled()
|
||
})
|
||
|
||
it.each([
|
||
[ownerId, active],
|
||
['admin', { ...active, role: 'ADMIN' as const }],
|
||
['system-admin', { ...active, role: 'SYSTEM_ADMIN' as const }],
|
||
['super-admin', { ...active, isSuperAdmin: true }],
|
||
['legacy-configured-recipient', { ...active, dingtalkUserId: 'recipient-test' }],
|
||
['configured-owner', { ...active, dingtalkUserId: 'ding-owner' }],
|
||
])('serves escaped, private HTML to %s', async (viewerId, identity) => {
|
||
if (viewerId === 'configured-owner') process.env.FEEDBACK_DINGTALK_OWNER_USER_ID = 'ding-owner'
|
||
jest.mocked(getServerSession).mockResolvedValue({ user: { id: viewerId } })
|
||
userStore.findUnique.mockResolvedValue(identity as never)
|
||
feedbackStore.findFirst.mockResolvedValue(record)
|
||
const response = await get()
|
||
expect(response.status).toBe(200)
|
||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||
const html = await response.text()
|
||
for (const expected of ['<b>导出失败</b>', '提交人甲', 'project-01', 'task-01', 'req-01', '<script>unsafe</script>']) {
|
||
expect(html).toContain(expected)
|
||
}
|
||
expectOnlyCopyScript(response, html)
|
||
expect(feedbackStore.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: viewerId === ownerId ? { feedbackId: id, ownerId } : { feedbackId: id } }))
|
||
})
|
||
|
||
it.each([
|
||
['USER', undefined],
|
||
['DEPT_ADMIN', undefined],
|
||
['USER', 'other-ding-user'],
|
||
] as const)('returns a real 403 to another %s (%s) and checks only metadata', async (role, dingtalkUserId) => {
|
||
jest.mocked(getServerSession).mockResolvedValue({ user: { id: 'another', role: 'ADMIN' } })
|
||
userStore.findUnique.mockResolvedValue({ ...active, role, dingtalkUserId } as never)
|
||
feedbackStore.findFirst.mockResolvedValue(null)
|
||
feedbackStore.findUnique.mockResolvedValue({ feedbackId: id } as never)
|
||
const response = await get()
|
||
expect(response.status).toBe(403)
|
||
expect(await response.text()).not.toContain('导出失败')
|
||
expect(feedbackStore.findUnique).toHaveBeenCalledWith({ where: { feedbackId: id }, select: { feedbackId: true } })
|
||
const download = await get(id, '?format=json')
|
||
expect(download.status).toBe(403)
|
||
expect(download.headers.has('content-disposition')).toBe(false)
|
||
})
|
||
|
||
it('returns 404 for missing or invalid IDs and 403 for an inactive account', async () => {
|
||
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
|
||
expect((await get('not-a-uuid')).status).toBe(404)
|
||
userStore.findUnique.mockResolvedValueOnce(active as never).mockResolvedValueOnce({ ...active, isActive: false } as never)
|
||
feedbackStore.findFirst.mockResolvedValue(null)
|
||
feedbackStore.findUnique.mockResolvedValue(null)
|
||
expect((await get()).status).toBe(404)
|
||
expect((await get()).status).toBe(403)
|
||
})
|
||
|
||
it('renders rich v2 triage cards, highlights WARN/ERROR logs, preserves strict CSP and collapses raw JSON by default', async () => {
|
||
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
|
||
userStore.findUnique.mockResolvedValue(active as never)
|
||
feedbackStore.findFirst.mockResolvedValue({
|
||
...record,
|
||
summary: 'GPU 渲染降级导致导出模糊',
|
||
snapshot: {
|
||
clientVersion: '1.2612.112',
|
||
commit: 'abc1234',
|
||
channel: 'stable',
|
||
builtAt: '2026-12-03T01:00:00Z',
|
||
os: 'Windows 11',
|
||
arch: 'x86_64',
|
||
page: 'workspace',
|
||
view: 'detail-editor',
|
||
online: false,
|
||
capturedAt: '2026-12-03T01:25:00Z',
|
||
currentError: 'WebGPU adapter lost',
|
||
project: { name: '森屿布艺沙发' },
|
||
agentDaemon: {
|
||
available: false,
|
||
ready: false,
|
||
spawnCount: 3,
|
||
activeRuns: ['run-a', 'run-b'],
|
||
heartbeatAgeMs: 4200,
|
||
exitCode: 137,
|
||
lastError: 'process killed',
|
||
stderrSummary: 'fatal: daemon exited',
|
||
},
|
||
models: {
|
||
chatModel: 'chat-pro',
|
||
copyModel: 'copy-v2',
|
||
imageModel: 'img-hd',
|
||
hasPersonalKey: true,
|
||
knowledgeMode: 'cloud',
|
||
},
|
||
canvas: {
|
||
renderPath: 'cpu',
|
||
gpuFallback: true,
|
||
gpuFallbackKind: 'deviceLost',
|
||
documentWidth: 750,
|
||
documentHeight: 1200,
|
||
layerCount: 18,
|
||
activeOutput: { id: 'out-1', name: '主图 01' },
|
||
outputId: 'out-1',
|
||
variantId: 'var-2',
|
||
templateHash: 'tpl-abc123',
|
||
revision: 9,
|
||
dirty: true,
|
||
professionalMode: true,
|
||
},
|
||
multiProject: { runningCount: 1, queuedCount: 2, pausedCount: 1 },
|
||
storage: { usingCustomRoot: true, migrationPhase: 'completed', freeBytes: 2147483648 },
|
||
notices: [{ kind: 'warning', message: '存储空间低于阈值' }],
|
||
recentErrors: [{ errorCode: 'E_RENDER', message: '切换软件渲染' }],
|
||
recentLogs: [
|
||
'10:00:01 INFO canvas ready',
|
||
'10:00:02 WARN memory pressure high',
|
||
'10:00:03 ERROR device lost during export',
|
||
],
|
||
},
|
||
})
|
||
|
||
const response = await get()
|
||
expect(response.status).toBe(200)
|
||
expect(response.headers.get('content-security-policy')).toMatch(/^default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; script-src 'sha256-/)
|
||
const html = await response.text()
|
||
|
||
for (const expected of [
|
||
'问题说明',
|
||
'核心故障摘要',
|
||
'提交与关联信息',
|
||
'运行环境与状态速览',
|
||
'近期通知与告警',
|
||
'近期客户端日志摘要',
|
||
'完整诊断 JSON',
|
||
'本机服务状态',
|
||
'模型配置',
|
||
'画布与渲染状态',
|
||
'多项目与存储状态',
|
||
'1.2612.112',
|
||
'abc1234',
|
||
'Windows 11 / x86_64',
|
||
'workspace / detail-editor',
|
||
'离线',
|
||
'WebGPU adapter lost',
|
||
'fatal: daemon exited',
|
||
'750 × 1200 px',
|
||
'2 GB',
|
||
'class="log-line"',
|
||
'class="log-line log-warn"',
|
||
'class="log-line log-error"',
|
||
'<details class="json-details">',
|
||
]) {
|
||
expect(html).toContain(expected)
|
||
}
|
||
expect(html).not.toContain('<details class="json-details" open>')
|
||
expectOnlyCopyScript(response, html)
|
||
expect(html).not.toMatch(/\bPi\b|PhotoCraft/i)
|
||
})
|
||
|
||
it('escapes HTML and XSS payloads in every v2 triage field', async () => {
|
||
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
|
||
userStore.findUnique.mockResolvedValue(active as never)
|
||
const xss = '<img src=x onerror=alert(1)>'
|
||
const scriptXss = '<script>alert("xss")</script>'
|
||
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(/<script>/g)).toHaveLength(1)
|
||
expect(html).not.toContain('<img ')
|
||
expect(html).toContain('<img src=x onerror=alert(1)>')
|
||
expect(html).toContain('<script>alert("xss")</script>')
|
||
})
|
||
|
||
it('renders only matching overview cards for partial v2 snapshots and ignores gpuFallback=false', async () => {
|
||
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
|
||
userStore.findUnique.mockResolvedValue(active as never)
|
||
feedbackStore.findFirst.mockResolvedValue({
|
||
...record,
|
||
snapshot: {
|
||
models: { chatModel: 'model-a' },
|
||
canvas: { renderPath: 'gpu', gpuFallback: false },
|
||
},
|
||
})
|
||
|
||
const html = await (await get()).text()
|
||
expect(html).toContain('模型配置')
|
||
expect(html).toContain('画布与渲染状态')
|
||
expect(html).toContain('未降级')
|
||
expect(html).not.toContain('核心故障摘要')
|
||
expect(html).not.toContain('本机服务状态')
|
||
expect(html).not.toContain('多项目与存储状态')
|
||
expect(html).not.toContain('近期通知与告警')
|
||
expect(html).not.toContain('近期客户端日志摘要')
|
||
})
|
||
|
||
it('renders v3 triage disclosure, escapes diagnostic strings and serves private download', async () => {
|
||
jest.mocked(getServerSession).mockResolvedValue({ user: { id: ownerId } })
|
||
userStore.findUnique.mockResolvedValue(active as never)
|
||
const marker = '<img src=x onerror=alert(1)>'
|
||
const script = '</script><script>alert("unsafe")</script>'
|
||
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('<details class="json-details">')[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('<details class="json-details" open>')
|
||
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('<details')
|
||
})
|
||
})
|