Dispatch Xiaoyi feedback to GitHub, DingTalk and Agent webhook
This commit is contained in:
parent
581ee41cef
commit
47d6c4ce6e
@ -1,6 +1,6 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
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'
|
||||
@ -12,7 +12,10 @@ 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', () => ({ submitYouyidianNotification: 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() },
|
||||
@ -25,20 +28,26 @@ const active = { role: 'USER', isSuperAdmin: false, isActive: true, status: 'act
|
||||
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: '提交人甲' },
|
||||
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('https://example.invalid/api/desktop/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(`https://example.invalid/feedback/${idParam}${query}`), { params: { id: idParam } })
|
||||
return GET(new Request(new URL(`/feedback/${idParam}${query}`, appOrigin)), { params: { id: idParam } })
|
||||
}
|
||||
|
||||
function expectOnlyCopyScript(response: Response, html: string) {
|
||||
@ -52,8 +61,14 @@ function expectOnlyCopyScript(response: Response, html: string) {
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks()
|
||||
jest.replaceProperty(process, 'env', {
|
||||
...process.env, YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID: 'recipient-test', YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS: '',
|
||||
...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: '小壹问题反馈' })
|
||||
})
|
||||
@ -78,6 +93,7 @@ describe('POST /api/desktop/feedback', () => {
|
||||
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}$`),
|
||||
@ -95,54 +111,89 @@ describe('POST /api/desktop/feedback', () => {
|
||||
.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] 通知投递失败', { feedbackId: id, recipientUserId: 'recipient-test', errorCode: 'notification_request_failed' }],
|
||||
['[desktop-feedback] 通知投递失败', { feedbackId: id, recipientUserId: 'ding-second', errorCode: 'delivery_failed' }],
|
||||
['[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('uses active super-admin DingTalk IDs and sends a bounded, sanitized summary with the feedback link', async () => {
|
||||
delete process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID
|
||||
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS = ' , '
|
||||
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)
|
||||
userStore.findMany.mockResolvedValue([
|
||||
{ id: 'app-admin-id', dingtalkUserId: 'ding-admin', username: 'admin', realName: '管理员' },
|
||||
] as Awaited<ReturnType<typeof prisma.user.findMany>>)
|
||||
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)
|
||||
expect(userStore.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true,
|
||||
dingtalkUserId: { not: null }, NOT: { dingtalkUserId: '' },
|
||||
},
|
||||
select: { id: true, dingtalkUserId: true, realName: true, username: true },
|
||||
})
|
||||
await dispatchTurn()
|
||||
expect(userStore.findMany).not.toHaveBeenCalled()
|
||||
expect(submitYouyidianNotification).toHaveBeenCalledWith({
|
||||
recipientUserId: 'ding-admin', idempotencyKey: `desktop-feedback:${id}`, title: '小壹问题反馈',
|
||||
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('warns without attempting delivery when no eligible recipient exists', async () => {
|
||||
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
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
|
||||
userStore.findMany.mockResolvedValue([])
|
||||
feedbackStore.createMany.mockResolvedValue({ count: 1 })
|
||||
feedbackStore.findFirst.mockResolvedValue(record)
|
||||
|
||||
expect((await post()).status).toBe(200)
|
||||
await dispatchTurn()
|
||||
expect(submitYouyidianNotification).not.toHaveBeenCalled()
|
||||
expect(warning).toHaveBeenCalledWith('[desktop-feedback] 没有可用的钉钉收件人', { feedbackId: id })
|
||||
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 () => {
|
||||
@ -162,8 +213,9 @@ describe('POST /api/desktop/feedback', () => {
|
||||
expect(feedbackStore.createMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({
|
||||
snapshot: { errors: ['[敏感信息已移除]', '[图片已移除]'] },
|
||||
}) }))
|
||||
expect(warning).toHaveBeenCalledWith('[desktop-feedback] 通知投递失败', {
|
||||
feedbackId: id, recipientUserId: 'recipient-test', errorCode: 'notification_request_failed',
|
||||
await dispatchTurn()
|
||||
expect(warning).toHaveBeenCalledWith('[desktop-feedback] dispatch', {
|
||||
feedbackId: id, channel: 'dingtalk', outcome: 'failed', errorCode: 'request_failed',
|
||||
})
|
||||
})
|
||||
|
||||
@ -193,6 +245,7 @@ describe('POST /api/desktop/feedback', () => {
|
||||
},
|
||||
})).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('')}`)
|
||||
@ -208,6 +261,7 @@ describe('POST /api/desktop/feedback', () => {
|
||||
},
|
||||
})).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('当前报错:\\[敏感信息已移除\\]')
|
||||
@ -233,6 +287,7 @@ describe('POST /api/desktop/feedback', () => {
|
||||
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 [
|
||||
@ -258,8 +313,10 @@ describe('GET /feedback/[id]', () => {
|
||||
['admin', { ...active, role: 'ADMIN' as const }],
|
||||
['system-admin', { ...active, role: 'SYSTEM_ADMIN' as const }],
|
||||
['super-admin', { ...active, isSuperAdmin: true }],
|
||||
['configured-recipient', { ...active, dingtalkUserId: 'recipient-test' }],
|
||||
['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)
|
||||
|
||||
@ -70,6 +70,12 @@ services:
|
||||
- YYD_NOTIFICATION_CENTER_PROJECT_SECRET=${YYD_NOTIFICATION_CENTER_PROJECT_SECRET:-}
|
||||
- YYD_NOTIFICATION_CENTER_TEST_USER_IDS=${YYD_NOTIFICATION_CENTER_TEST_USER_IDS:-}
|
||||
- YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID=${YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID:-}
|
||||
- YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS=${YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS:-}
|
||||
- FEEDBACK_DINGTALK_OWNER_USER_ID=${FEEDBACK_DINGTALK_OWNER_USER_ID:-}
|
||||
- FEEDBACK_GITHUB_TOKEN=${FEEDBACK_GITHUB_TOKEN:-}
|
||||
- FEEDBACK_GITHUB_REPO=${FEEDBACK_GITHUB_REPO:-}
|
||||
- FEEDBACK_AGENT_WEBHOOK_URL=${FEEDBACK_AGENT_WEBHOOK_URL:-}
|
||||
- FEEDBACK_AGENT_WEBHOOK_SECRET=${FEEDBACK_AGENT_WEBHOOK_SECRET:-}
|
||||
# 视频转码配置:默认 720P H.265、10 秒片段;单实例单任务、单线程
|
||||
- VIDEO_PREVIEW_RESOLUTION=720
|
||||
- VIDEO_CLIP_DURATION=10
|
||||
|
||||
@ -1,44 +1,69 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { submitYouyidianNotification } from '@/lib/youyidian-notification-center'
|
||||
|
||||
describe('由壹点通知中心客户端', () => {
|
||||
const originalFetch = global.fetch
|
||||
const notifyOrigin = ['https:', '', 'notify.invalid'].join('/')
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.YYD_NOTIFICATION_CENTER_URL = 'https://notify.example.com'
|
||||
process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE = 'material_library'
|
||||
process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET = '123456789012345678901234'
|
||||
jest.replaceProperty(process, 'env', {
|
||||
...process.env,
|
||||
YYD_NOTIFICATION_CENTER_URL: notifyOrigin,
|
||||
YYD_NOTIFICATION_CENTER_PROJECT_CODE: 'test-project',
|
||||
YYD_NOTIFICATION_CENTER_PROJECT_SECRET: randomUUID(),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch
|
||||
jest.restoreAllMocks()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const notification = {
|
||||
idempotencyKey: 'survey.assignment.created:assignment-1',
|
||||
recipientUserId: 'ding-user-1',
|
||||
title: '待填写',
|
||||
content: '请完成考核调研',
|
||||
actionTitle: '立即填写',
|
||||
actionUrl: new URL('/performance-survey/survey/1', notifyOrigin).href,
|
||||
}
|
||||
|
||||
test('使用项目签名提交通知任务', async () => {
|
||||
global.fetch = jest.fn(async (_url, init) => ({
|
||||
const fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 202,
|
||||
json: async () => ({
|
||||
id: 'notification-1',
|
||||
projectCode: 'material_library',
|
||||
projectCode: 'test-project',
|
||||
status: 'pending',
|
||||
recipientUserId: 'ding-user-1',
|
||||
title: '【由壹点·素材库】待填写',
|
||||
}),
|
||||
})) as unknown as typeof fetch
|
||||
} as Response)
|
||||
|
||||
const result = await submitYouyidianNotification({
|
||||
idempotencyKey: 'survey.assignment.created:assignment-1',
|
||||
recipientUserId: 'ding-user-1',
|
||||
title: '待填写',
|
||||
content: '请完成考核调研',
|
||||
actionTitle: '立即填写',
|
||||
actionUrl: 'https://sc.jiansun.vip/performance-survey/survey/1',
|
||||
})
|
||||
const result = await submitYouyidianNotification(notification)
|
||||
|
||||
expect(result.id).toBe('notification-1')
|
||||
const [, init] = (global.fetch as jest.Mock).mock.calls[0]
|
||||
expect(init.headers['x-yyd-project-code']).toBe('material_library')
|
||||
expect(init.headers['x-yyd-signature']).toMatch(/^[a-f0-9]{64}$/)
|
||||
expect(init.headers['x-yyd-nonce']).toBeTruthy()
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init?.headers).toMatchObject({
|
||||
'x-yyd-project-code': 'test-project',
|
||||
'x-yyd-signature': expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
'x-yyd-nonce': expect.any(String),
|
||||
})
|
||||
})
|
||||
|
||||
test('读取通知回执正文超时时中止请求', async () => {
|
||||
jest.useFakeTimers()
|
||||
jest.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => ({
|
||||
ok: true,
|
||||
json: () => new Promise((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true })
|
||||
}),
|
||||
}) as Response)
|
||||
const rejected = expect(submitYouyidianNotification(notification)).rejects.toHaveProperty('name', 'AbortError')
|
||||
|
||||
await jest.advanceTimersByTimeAsync(8_000)
|
||||
await rejected
|
||||
})
|
||||
})
|
||||
|
||||
@ -32,7 +32,7 @@ const privateV3Fields = new Set(['name', 'title', 'projectName', 'notices', 'eve
|
||||
const removedImage = '[图片已移除]'
|
||||
const removedCredential = '[敏感信息已移除]'
|
||||
|
||||
function redactText(value: string, max: number, rich = false): string {
|
||||
export function redactText(value: string, max: number, rich = false): string {
|
||||
const text = Array.from(value).filter(character => !/^[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff]$/.test(character)).join('').trim()
|
||||
// Scan the complete input before truncating so a secret or data URL cannot be split at the limit.
|
||||
const scan = text.normalize('NFKC').replace(/%([\da-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
|
||||
|
||||
195
lib/desktop-client/feedback-dispatch.test.ts
Normal file
195
lib/desktop-client/feedback-dispatch.test.ts
Normal file
@ -0,0 +1,195 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { submitYouyidianNotification } from '@/lib/youyidian-notification-center'
|
||||
import { parseDesktopFeedback } from './feedback-contract'
|
||||
import { dispatchDesktopFeedback } from './feedback-dispatch'
|
||||
|
||||
jest.mock('@/lib/youyidian-notification-center', () => ({
|
||||
...jest.requireActual('@/lib/youyidian-notification-center'),
|
||||
submitYouyidianNotification: jest.fn(),
|
||||
}))
|
||||
|
||||
const feedbackId = randomUUID()
|
||||
const createdAt = new Date('2026-12-04T10:00:00.000Z')
|
||||
const owner = 'ding-owner'
|
||||
const labels = ['feedback', 'status:triage']
|
||||
const appOrigin = ['https:', '', 'app.invalid'].join('/')
|
||||
const webhookUrl = new URL('/incoming', ['https:', '', 'harness.invalid'].join('/'))
|
||||
const detailPath = `/feedback/${feedbackId}`
|
||||
const adminUrl = new URL(detailPath, appOrigin).href
|
||||
const envKeys = [
|
||||
'FEEDBACK_GITHUB_TOKEN', 'FEEDBACK_GITHUB_REPO', 'FEEDBACK_DINGTALK_OWNER_USER_ID',
|
||||
'FEEDBACK_AGENT_WEBHOOK_URL', 'FEEDBACK_AGENT_WEBHOOK_SECRET', 'YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID',
|
||||
'YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS', 'YYD_NOTIFICATION_CENTER_URL', 'YYD_NOTIFICATION_CENTER_PROJECT_CODE',
|
||||
'YYD_NOTIFICATION_CENTER_PROJECT_SECRET',
|
||||
]
|
||||
const reporter = { name: '同事甲', department: '运营部' }
|
||||
const data = {
|
||||
feedbackId, createdAt, detailPath, reporter, summary: '导出时闪退',
|
||||
snapshot: {
|
||||
type: 'crash', clientVersion: '1.2612.120', commit: 'abc123456789',
|
||||
os: 'windows', arch: 'x86_64', updateState: { channel: 'stable' }, recentErrors: ['一条原始诊断'],
|
||||
},
|
||||
}
|
||||
const sendDingTalk = jest.mocked(submitYouyidianNotification)
|
||||
let fetchMock: jest.SpiedFunction<typeof fetch>
|
||||
let info: jest.SpiedFunction<typeof console.info>
|
||||
let warn: jest.SpiedFunction<typeof console.warn>
|
||||
|
||||
function issueResponse() {
|
||||
return Response.json({ number: 43, labels: labels.map(name => ({ name })) }, { status: 201 })
|
||||
}
|
||||
|
||||
function configureDingTalk() {
|
||||
process.env.FEEDBACK_DINGTALK_OWNER_USER_ID = owner
|
||||
process.env.YYD_NOTIFICATION_CENTER_URL = new URL('/notify', appOrigin).href
|
||||
process.env.YYD_NOTIFICATION_CENTER_PROJECT_CODE = 'test-project'
|
||||
process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET = randomUUID()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.replaceProperty(process, 'env', { ...process.env, NEXT_PUBLIC_APP_PUBLIC_URL: appOrigin })
|
||||
for (const name of envKeys) delete process.env[name]
|
||||
fetchMock = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }))
|
||||
info = jest.spyOn(console, 'info').mockImplementation(() => {})
|
||||
warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
sendDingTalk.mockReset().mockResolvedValue({
|
||||
id: 'notice', projectCode: 'test-project', recipientUserId: owner, status: 'pending', title: '小壹问题反馈',
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => jest.restoreAllMocks())
|
||||
|
||||
it('creates a labeled Issue, then shares the link with the personal DingTalk recipient and the Agent', async () => {
|
||||
const token = randomUUID()
|
||||
const webhookSecret = randomUUID()
|
||||
process.env.FEEDBACK_GITHUB_TOKEN = token
|
||||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||||
process.env.FEEDBACK_AGENT_WEBHOOK_SECRET = webhookSecret
|
||||
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID = 'legacy-recipient'
|
||||
configureDingTalk()
|
||||
fetchMock.mockResolvedValueOnce(issueResponse())
|
||||
|
||||
await dispatchDesktopFeedback({ ...data, summary: 'detail-agent-pi 导出时闪退' })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
const [[gitUrl, gitRequest], [webhookTarget, webhookRequest]] = fetchMock.mock.calls
|
||||
expect(gitUrl).toEqual(expect.objectContaining({
|
||||
protocol: 'https:', hostname: 'api.github.com', pathname: '/repos/wuyongjie1990-coder/gongxiangp2/issues',
|
||||
}))
|
||||
expect(gitRequest).toMatchObject({
|
||||
method: 'POST', signal: expect.any(AbortSignal), redirect: 'error', headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
const issue = JSON.parse(String(gitRequest?.body))
|
||||
expect(issue).toEqual({
|
||||
title: '[小壹崩溃反馈 · 1.2612.120] 小壹 导出时闪退',
|
||||
labels,
|
||||
body: expect.stringMatching(/反馈人:同事甲[\s\S]*部门:运营部[\s\S]*提交号:abc123456789[\s\S]*问题描述[\s\S]*导出时闪退/),
|
||||
})
|
||||
expect(issue.body).toContain(feedbackId)
|
||||
expect(issue.body).toContain(adminUrl)
|
||||
expect(issue.body).toContain('最近错误 1 条,工具失败 0 条')
|
||||
expect(issue.body).not.toContain('一条原始诊断')
|
||||
const issueUrl = new URL('/wuyongjie1990-coder/gongxiangp2/issues/43', ['https:', '', 'github.com'].join('/')).href
|
||||
expect(sendDingTalk).toHaveBeenCalledTimes(1)
|
||||
expect(sendDingTalk).toHaveBeenCalledWith({
|
||||
idempotencyKey: `desktop-feedback:${feedbackId}`, recipientUserId: owner, title: '小壹问题反馈',
|
||||
actionTitle: '查看反馈', actionUrl: adminUrl,
|
||||
content: expect.stringContaining(`[查看 GitHub Issue](${issueUrl})`),
|
||||
})
|
||||
expect(webhookTarget).toEqual(webhookUrl)
|
||||
expect(webhookRequest).toMatchObject({
|
||||
method: 'POST', signal: expect.any(AbortSignal), redirect: 'error',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Feedback-Webhook-Token': webhookSecret },
|
||||
})
|
||||
expect(JSON.parse(String(webhookRequest?.body))).toEqual({
|
||||
event: 'xiaoyi.feedback.created', feedbackId, reporter, clientVersion: '1.2612.120', commit: 'abc123456789',
|
||||
summary: '小壹 导出时闪退', githubIssueUrl: issueUrl, githubIssueNumber: 43, adminUrl, createdAt: createdAt.toISOString(),
|
||||
})
|
||||
expect(info).toHaveBeenCalledWith(expect.any(String), {
|
||||
feedbackId, channel: 'github', outcome: 'created', githubIssueUrl: issueUrl, githubIssueNumber: 43,
|
||||
})
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('only dispatches configured channels and sends a webhook without an optional secret', async () => {
|
||||
process.env.FEEDBACK_DINGTALK_OWNER_USER_ID = owner
|
||||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||||
|
||||
await dispatchDesktopFeedback(data)
|
||||
|
||||
expect(sendDingTalk).not.toHaveBeenCalled()
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(fetchMock.mock.calls[0][1]?.headers).toEqual({ 'Content-Type': 'application/json' })
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toMatchObject({ githubIssueUrl: null, githubIssueNumber: null })
|
||||
expect(info.mock.calls.map(([, fields]) => fields)).toEqual([
|
||||
{ feedbackId, channel: 'github', outcome: 'skipped', missing: ['FEEDBACK_GITHUB_TOKEN'] },
|
||||
{ feedbackId, channel: 'dingtalk', outcome: 'skipped', missing: [
|
||||
'YYD_NOTIFICATION_CENTER_URL', 'YYD_NOTIFICATION_CENTER_PROJECT_CODE', 'YYD_NOTIFICATION_CENTER_PROJECT_SECRET',
|
||||
] },
|
||||
])
|
||||
})
|
||||
|
||||
it.each(['github', 'agent_webhook'] as const)('uses an 8 second abort signal and isolates a %s timeout', async channel => {
|
||||
process.env.FEEDBACK_GITHUB_TOKEN = randomUUID()
|
||||
process.env.FEEDBACK_GITHUB_REPO = 'example-owner/private-test'
|
||||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||||
configureDingTalk()
|
||||
const controller = new AbortController()
|
||||
const timeout = jest.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(controller.signal)
|
||||
const started = Promise.withResolvers<void>()
|
||||
const slow = (_url: Parameters<typeof fetch>[0], init?: RequestInit) => {
|
||||
const response = Promise.withResolvers<Response>()
|
||||
init?.signal?.addEventListener('abort', () => response.reject(init.signal?.reason), { once: true })
|
||||
started.resolve()
|
||||
return response.promise
|
||||
}
|
||||
if (channel === 'github') {
|
||||
fetchMock.mockImplementationOnce(slow)
|
||||
} else {
|
||||
fetchMock.mockResolvedValueOnce(issueResponse()).mockImplementationOnce(slow)
|
||||
timeout.mockReset().mockReturnValueOnce(new AbortController().signal).mockReturnValueOnce(controller.signal)
|
||||
}
|
||||
|
||||
const dispatch = dispatchDesktopFeedback(data)
|
||||
await started.promise
|
||||
controller.abort(new DOMException('request expired', 'TimeoutError'))
|
||||
await dispatch
|
||||
|
||||
expect(timeout.mock.calls).toEqual([[8000], [8000]])
|
||||
expect(fetchMock.mock.calls[0][0]).toMatchObject({ pathname: '/repos/example-owner/private-test/issues' })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
expect(sendDingTalk).toHaveBeenCalledTimes(1)
|
||||
expect(warn).toHaveBeenCalledWith(expect.any(String), { feedbackId, channel, outcome: 'failed', errorCode: 'timeout' })
|
||||
})
|
||||
|
||||
it('sends no private fields or internal names and logs no raw upstream error data', async () => {
|
||||
const raw = randomUUID()
|
||||
const token = randomUUID()
|
||||
process.env.FEEDBACK_GITHUB_TOKEN = token
|
||||
process.env.FEEDBACK_AGENT_WEBHOOK_URL = webhookUrl.href
|
||||
configureDingTalk()
|
||||
fetchMock.mockResolvedValueOnce(new Response(raw, { status: 500 })).mockResolvedValueOnce(new Response(raw, { status: 500 }))
|
||||
const parsed = parseDesktopFeedback(JSON.stringify({
|
||||
feedbackId, summary: `PhotoCraft Pi 无法启动 ${token}`,
|
||||
context: { schemaVersion: 3, cookie: raw, commit: `Bearer ${raw}`, clientVersion: `key is ${raw}`,
|
||||
currentError: `Cookie: sid=${raw}`, recentErrors: [`Cookie: sid=${raw}`],
|
||||
screenshot: `data:image/png;base64,${raw}`, os: raw },
|
||||
}))
|
||||
|
||||
await dispatchDesktopFeedback({ ...data, ...parsed, reporter: { name: `https://${raw}.invalid`, department: `secret=${raw}` } })
|
||||
|
||||
const bodiesAndLogs = JSON.stringify([
|
||||
fetchMock.mock.calls.map(([, init]) => init?.body), sendDingTalk.mock.calls, info.mock.calls, warn.mock.calls,
|
||||
])
|
||||
for (const forbidden of [raw, token, 'PhotoCraft', 'screenshot', 'sid=']) expect(bodiesAndLogs).not.toContain(forbidden)
|
||||
const webhook = JSON.parse(String(fetchMock.mock.calls[1][1]?.body))
|
||||
expect(webhook).toMatchObject({
|
||||
summary: '[敏感信息已移除]', clientVersion: null, commit: null, githubIssueNumber: null, githubIssueUrl: null,
|
||||
})
|
||||
expect(warn.mock.calls.map(([, fields]) => fields)).toEqual([
|
||||
{ feedbackId, channel: 'github', outcome: 'failed', errorCode: 'http_error', status: 500 },
|
||||
{ feedbackId, channel: 'agent_webhook', outcome: 'failed', errorCode: 'http_error', status: 500 },
|
||||
])
|
||||
})
|
||||
305
lib/desktop-client/feedback-dispatch.ts
Normal file
305
lib/desktop-client/feedback-dispatch.ts
Normal file
@ -0,0 +1,305 @@
|
||||
import { getPublicAppOrigin } from '@/lib/public-app-url'
|
||||
import { getNotificationCenterConfigStatus, submitYouyidianNotification } from '@/lib/youyidian-notification-center'
|
||||
import { redactText, type Diagnostic } from './feedback-contract'
|
||||
|
||||
const timeoutMs = 8_000
|
||||
const defaultRepo = 'wuyongjie1990-coder/gongxiangp2'
|
||||
const githubHost = 'github.com'
|
||||
const issueLabels = ['feedback', 'status:triage']
|
||||
const logPrefix = '[desktop-feedback] dispatch'
|
||||
|
||||
type DispatchInput = {
|
||||
feedbackId: string
|
||||
reporter: { name: string; department: string }
|
||||
summary: string
|
||||
snapshot: Record<string, Diagnostic>
|
||||
createdAt: Date
|
||||
detailPath: string
|
||||
}
|
||||
|
||||
type FeedbackEvent = {
|
||||
event: 'xiaoyi.feedback.created'
|
||||
feedbackId: string
|
||||
reporter: DispatchInput['reporter']
|
||||
clientVersion: string | null
|
||||
commit: string | null
|
||||
summary: string
|
||||
adminUrl: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
type GitHubIssue = { githubIssueUrl: string; githubIssueNumber: number }
|
||||
type Channel = 'github' | 'dingtalk' | 'agent_webhook'
|
||||
|
||||
export function configuredFeedbackRecipients(): string[] {
|
||||
const owner = process.env.FEEDBACK_DINGTALK_OWNER_USER_ID?.trim()
|
||||
if (owner) return [owner]
|
||||
|
||||
const configured = [
|
||||
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID ?? '',
|
||||
...(process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS ?? '').split(','),
|
||||
].map(id => id.trim()).filter(Boolean)
|
||||
return Array.from(new Set(configured))
|
||||
}
|
||||
|
||||
function cleanText(value: unknown, limit: number) {
|
||||
if (typeof value !== 'string') return ''
|
||||
const knownSecrets = [process.env.FEEDBACK_GITHUB_TOKEN, process.env.FEEDBACK_AGENT_WEBHOOK_SECRET,
|
||||
process.env.YYD_NOTIFICATION_CENTER_PROJECT_SECRET]
|
||||
const text = value.replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/g, '')
|
||||
const scan = text.normalize('NFKC')
|
||||
if (knownSecrets.some(secret => secret?.trim() && scan.includes(secret.trim()))
|
||||
|| /(?<!\d)(?:\+?86[ -]?)?1[3-9]\d{9}(?!\d)|\b[\w.+-]+@[\w.-]+\.[a-z]{2,}\b/i.test(scan)
|
||||
|| /\b[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}\b/i.test(scan)
|
||||
|| /\b(?:[a-z0-9]+_)*(?:key|token|cookie|password|secret)(?:\s+is|\s*[=::,,]\s*|\s*=>)\s*\S/i.test(scan)) {
|
||||
return '[敏感信息已移除]'
|
||||
}
|
||||
return redactText(text, limit, true).replace(/\b(?:detail[-_](?:agent[-_]pi|photocraft|desktop)|PhotoCraft|Pi)\b/gi, '小壹')
|
||||
}
|
||||
|
||||
function compactText(value: unknown, limit: number) {
|
||||
const text = cleanText(value, 2000).replace(/\s+/g, ' ').trim().replace(/@/g, '@')
|
||||
return Array.from(text).slice(0, limit).join('')
|
||||
}
|
||||
|
||||
function escapeMarkdown(text: string) {
|
||||
return text.replace(/[\\`*_\[\]~#<>]/g, '\\$&')
|
||||
}
|
||||
|
||||
function notificationText(value: unknown, limit: number) {
|
||||
return escapeMarkdown(compactText(value, limit))
|
||||
}
|
||||
|
||||
function asRecord(value: Diagnostic | undefined): Record<string, Diagnostic> | undefined {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined
|
||||
}
|
||||
|
||||
function diagnosticRows(snapshot: Record<string, Diagnostic>, field: string) {
|
||||
const value = snapshot[field]
|
||||
return Array.isArray(value) ? value : []
|
||||
}
|
||||
|
||||
function githubDiagnostics(snapshot: Record<string, Diagnostic>) {
|
||||
const channel = snapshot.channel ?? asRecord(snapshot.updateState)?.channel
|
||||
const os = snapshot.os ?? snapshot.platform
|
||||
const arch = snapshot.arch
|
||||
const lines = []
|
||||
if (typeof channel === 'string' && /^(stable|beta|alpha|nightly|dev)$/i.test(channel)) {
|
||||
lines.push(`- 发布渠道:${channel}`)
|
||||
}
|
||||
if (typeof os === 'string' && /^(windows(?: \d{1,2})?|macos|linux)$/i.test(os)) {
|
||||
const architecture = typeof arch === 'string' && /^(x86|x86_64|aarch64|arm64|arm)$/i.test(arch) ? ` / ${escapeMarkdown(arch)}` : ''
|
||||
lines.push(`- 系统:${os}${architecture}`)
|
||||
}
|
||||
const errors = diagnosticRows(snapshot, 'recentErrors').length
|
||||
const failures = diagnosticRows(snapshot, 'recentToolFailures').length
|
||||
if (errors || failures) lines.push(`- 最近错误 ${errors} 条,工具失败 ${failures} 条`)
|
||||
if (snapshot.currentError || asRecord(snapshot.errors)?.lastFailedOperation) lines.push('- 记录到当前异常')
|
||||
return lines.join('\n') || '无可用的诊断摘要'
|
||||
}
|
||||
|
||||
function logSkip(feedbackId: string, channel: Channel, missing: string[]) {
|
||||
console.info(logPrefix, { feedbackId, channel, outcome: 'skipped', missing })
|
||||
}
|
||||
|
||||
function logFailure(feedbackId: string, channel: Channel, errorCode: string, status?: number) {
|
||||
console.warn(logPrefix, { feedbackId, channel, outcome: 'failed', errorCode, ...(status === undefined ? {} : { status }) })
|
||||
}
|
||||
|
||||
function logRequestFailure(feedbackId: string, channel: Channel, error: unknown) {
|
||||
const timedOut = (error instanceof Error || error instanceof DOMException)
|
||||
&& (error.name === 'TimeoutError' || error.name === 'AbortError')
|
||||
logFailure(feedbackId, channel, timedOut ? 'timeout' : 'request_failed')
|
||||
}
|
||||
|
||||
function postJson(url: URL, headers: Record<string, string>, body: object) {
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
redirect: 'error',
|
||||
cache: 'no-store',
|
||||
})
|
||||
}
|
||||
|
||||
async function createGitHubIssue(feedback: FeedbackEvent, snapshot: Record<string, Diagnostic>): Promise<GitHubIssue | null> {
|
||||
const { feedbackId, reporter, clientVersion, commit, summary, adminUrl } = feedback
|
||||
const token = process.env.FEEDBACK_GITHUB_TOKEN?.trim()
|
||||
if (!token) {
|
||||
logSkip(feedbackId, 'github', ['FEEDBACK_GITHUB_TOKEN'])
|
||||
return null
|
||||
}
|
||||
const repo = process.env.FEEDBACK_GITHUB_REPO?.trim() || defaultRepo
|
||||
if (!/^[a-z\d][a-z\d-]*\/[a-z\d_.-]+$/i.test(repo) || /\/\.\.?$/.test(repo)) {
|
||||
logFailure(feedbackId, 'github', 'invalid_repo')
|
||||
return null
|
||||
}
|
||||
|
||||
const type = [snapshot.type, snapshot.kind].some(value => typeof value === 'string' && /^(crash|崩溃)$/i.test(value.trim()))
|
||||
? '崩溃反馈' : '问题反馈'
|
||||
const title = `[小壹${type} · ${clientVersion ?? '版本未提供'}] ${compactText(summary, 140)}`
|
||||
const description = escapeMarkdown(summary.replace(/@/g, '@')).replace(/^(\s*)([-+=]|\d+\.)(?=\s|$)/gm, '$1\\$2')
|
||||
const body = [
|
||||
`- 反馈人:${escapeMarkdown(reporter.name)}`,
|
||||
`- 部门:${escapeMarkdown(reporter.department || '未提供')}`,
|
||||
`- 反馈编号:${feedbackId}`,
|
||||
`- 客户端版本:${clientVersion ?? '未提供'}`,
|
||||
`- 提交号:${commit ?? '未提供'}`,
|
||||
'', '### 问题描述', description,
|
||||
'', '### 诊断摘要', githubDiagnostics(snapshot),
|
||||
'', `[查看受控反馈详情](<${adminUrl}>)`,
|
||||
].join('\n')
|
||||
|
||||
try {
|
||||
const url = new URL(`https://api.${githubHost}/repos/${repo}/issues`)
|
||||
const response = await postJson(url, {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
Authorization: `Bearer ${token}`,
|
||||
}, { title, body, labels: issueLabels })
|
||||
if (!response.ok) {
|
||||
logFailure(feedbackId, 'github', 'http_error', response.status)
|
||||
await response.body?.cancel()
|
||||
return null
|
||||
}
|
||||
const { number, labels } = await response.json() as { number?: number; labels?: Array<{ name: string }> }
|
||||
if (typeof number !== 'number' || !Number.isSafeInteger(number) || number < 1) {
|
||||
logFailure(feedbackId, 'github', 'invalid_response')
|
||||
return null
|
||||
}
|
||||
const issue = { githubIssueNumber: number, githubIssueUrl: `https://${githubHost}/${repo}/issues/${number}` }
|
||||
console.info(logPrefix, { feedbackId, channel: 'github', outcome: 'created', ...issue })
|
||||
if (!Array.isArray(labels) || !issueLabels.every(name => labels.some(label => label?.name === name))) {
|
||||
logFailure(feedbackId, 'github', 'labels_missing')
|
||||
}
|
||||
return issue
|
||||
} catch (error) {
|
||||
logRequestFailure(feedbackId, 'github', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function richNotificationLines(snapshot: Record<string, Diagnostic>) {
|
||||
const display = asRecord(snapshot.display)
|
||||
const gpu = asRecord(display?.gpu)
|
||||
const workspace = asRecord(snapshot.workspaceState)
|
||||
const model = asRecord(snapshot.modelConfig)
|
||||
const chat = asRecord(model?.chat)
|
||||
const copy = asRecord(model?.copy)
|
||||
const image = asRecord(model?.image)
|
||||
const errors = diagnosticRows(snapshot, 'recentErrors')
|
||||
const failures = diagnosticRows(snapshot, 'recentToolFailures')
|
||||
const parts = (values: Array<Diagnostic | undefined>) => values
|
||||
.map(value => notificationText(typeof value === 'number' ? String(value) : value, 40)).filter(Boolean).join(' / ')
|
||||
const dimensions = [display?.physicalWidth, display?.physicalHeight]
|
||||
const resolution = dimensions.every(value => typeof value === 'number') ? `${dimensions.join(' × ')} px` : undefined
|
||||
const modelIds = [chat?.modelId, copy?.modelId, image?.modelId].filter((value): value is string => typeof value === 'string')
|
||||
const signals = [
|
||||
['发布渠道', parts([snapshot.channel ?? asRecord(snapshot.updateState)?.channel])],
|
||||
['系统与显示', parts([snapshot.os ?? snapshot.platform, snapshot.arch, resolution, gpu?.backend])],
|
||||
['工作区', parts([workspace?.activeScreen, workspace?.activeTab, workspace?.mode, workspace?.activeTaskStatus])],
|
||||
['模型', parts([chat?.providerId, ...Array.from(new Set(modelIds)), model?.routingMode,
|
||||
typeof model?.hasPersonalKey === 'boolean' ? `个人密钥${model.hasPersonalKey ? '已配置' : '未配置'}` : undefined])],
|
||||
['近况', errors.length || failures.length ? `错误 ${errors.length} 条 · 工具失败 ${failures.length} 条` : ''],
|
||||
]
|
||||
return signals.flatMap(([label, value]) => value ? [`${label}:${value}`] : [])
|
||||
}
|
||||
|
||||
async function notifyDingTalk(feedback: FeedbackEvent, snapshot: Record<string, Diagnostic>, issue: GitHubIssue | null) {
|
||||
const { feedbackId, reporter, clientVersion, commit, summary, adminUrl } = feedback
|
||||
const recipients = configuredFeedbackRecipients()
|
||||
if (!recipients.length) {
|
||||
logSkip(feedbackId, 'dingtalk', ['FEEDBACK_DINGTALK_OWNER_USER_ID'])
|
||||
return
|
||||
}
|
||||
const config = getNotificationCenterConfigStatus()
|
||||
if (!config.ready) {
|
||||
logSkip(feedbackId, 'dingtalk', config.missing)
|
||||
return
|
||||
}
|
||||
|
||||
const rich = snapshot.schemaVersion === 3
|
||||
const recentError = rich ? diagnosticRows(snapshot, 'recentErrors').at(-1) : undefined
|
||||
const errors = rich ? asRecord(snapshot.errors) : undefined
|
||||
const failed = asRecord(errors?.lastFailedOperation) ?? asRecord(diagnosticRows(errors ?? {}, 'activeBanners')[0])
|
||||
const failedText = [failed?.operation ?? failed?.toolName, failed?.message ?? failed?.category, failed?.code]
|
||||
.filter(value => typeof value === 'string' || typeof value === 'number').join(' / ')
|
||||
const latestErrorText = notificationText(recentError, 120)
|
||||
const currentErrorText = notificationText(snapshot.currentError, 120) || notificationText(failedText, 120)
|
||||
|| notificationText(asRecord(snapshot.agentDaemon)?.stderrSummary, 120)
|
||||
const versionLine = `${clientVersion ?? '未提供'}${commit ? ` (${commit.slice(0, 7)})` : ''}`
|
||||
const lines = [
|
||||
`反馈人:${escapeMarkdown(reporter.name)}`,
|
||||
`项目:${notificationText(asRecord(snapshot.project)?.name, 120) || '未提供'}`,
|
||||
`客户端版本:${escapeMarkdown(versionLine)}`,
|
||||
`摘要:${notificationText(summary, 120)}`,
|
||||
`反馈编号:${feedbackId}`,
|
||||
]
|
||||
if (currentErrorText) lines.push(`当前报错:${currentErrorText}`)
|
||||
if (latestErrorText && latestErrorText !== currentErrorText) lines.push(`最近错误:${latestErrorText}`)
|
||||
if (rich) lines.push(...richNotificationLines(snapshot))
|
||||
if (issue) lines.push(`[查看 GitHub Issue](${issue.githubIssueUrl})`)
|
||||
const content = lines.join('\n')
|
||||
|
||||
await Promise.all(recipients.map(async recipientUserId => {
|
||||
const idempotencyKey = recipients.length === 1
|
||||
? `desktop-feedback:${feedbackId}`
|
||||
: `desktop-feedback:${feedbackId}:${recipientUserId}`
|
||||
try {
|
||||
const delivery = await submitYouyidianNotification({
|
||||
idempotencyKey, recipientUserId, title: '小壹问题反馈', content, actionTitle: '查看反馈', actionUrl: adminUrl,
|
||||
})
|
||||
if (delivery.status === 'failed') logFailure(feedbackId, 'dingtalk', 'delivery_failed')
|
||||
} catch (error) {
|
||||
logRequestFailure(feedbackId, 'dingtalk', error)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
async function notifyAgent(feedback: FeedbackEvent, issue: GitHubIssue | null) {
|
||||
const { feedbackId } = feedback
|
||||
const endpoint = process.env.FEEDBACK_AGENT_WEBHOOK_URL?.trim()
|
||||
if (!endpoint) {
|
||||
logSkip(feedbackId, 'agent_webhook', ['FEEDBACK_AGENT_WEBHOOK_URL'])
|
||||
return
|
||||
}
|
||||
|
||||
const url = URL.parse(endpoint)
|
||||
if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
|
||||
logFailure(feedbackId, 'agent_webhook', 'invalid_url')
|
||||
return
|
||||
}
|
||||
const secret = process.env.FEEDBACK_AGENT_WEBHOOK_SECRET?.trim()
|
||||
try {
|
||||
const response = await postJson(url, secret ? { 'X-Feedback-Webhook-Token': secret } : {}, {
|
||||
...feedback,
|
||||
githubIssueUrl: issue?.githubIssueUrl ?? null,
|
||||
githubIssueNumber: issue?.githubIssueNumber ?? null,
|
||||
})
|
||||
if (!response.ok) logFailure(feedbackId, 'agent_webhook', 'http_error', response.status)
|
||||
await response.body?.cancel()
|
||||
} catch (error) {
|
||||
logRequestFailure(feedbackId, 'agent_webhook', error)
|
||||
}
|
||||
}
|
||||
|
||||
export async function dispatchDesktopFeedback(input: DispatchInput) {
|
||||
const { snapshot, reporter } = input
|
||||
const client = asRecord(snapshot.client)
|
||||
const version = compactText(snapshot.clientVersion ?? asRecord(snapshot.updateState)?.currentVersion
|
||||
?? snapshot.appVersion ?? snapshot.version ?? client?.appVersion ?? client?.version, 48)
|
||||
const commit = compactText(snapshot.commit ?? client?.commit, 40)
|
||||
const feedback: FeedbackEvent = {
|
||||
event: 'xiaoyi.feedback.created',
|
||||
feedbackId: input.feedbackId,
|
||||
reporter: { name: compactText(reporter.name, 80) || '未提供', department: compactText(reporter.department, 80) },
|
||||
clientVersion: /^v?\d+(?:\.\d+){1,3}(?:[-+][\w.-]+)?$/i.test(version) ? version : null,
|
||||
commit: /^[a-f\d]{7,40}$/i.test(commit) ? commit : null,
|
||||
summary: cleanText(input.summary, 2000),
|
||||
adminUrl: new URL(input.detailPath, getPublicAppOrigin()).href,
|
||||
createdAt: input.createdAt.toISOString(),
|
||||
}
|
||||
const issue = await createGitHubIssue(feedback, snapshot)
|
||||
await Promise.all([notifyDingTalk(feedback, snapshot, issue), notifyAgent(feedback, issue)])
|
||||
}
|
||||
@ -1,67 +1,8 @@
|
||||
import { isSystemAdmin } from '@/lib/department-permission'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { getPublicAppOrigin } from '@/lib/public-app-url'
|
||||
import { submitYouyidianNotification } from '@/lib/youyidian-notification-center'
|
||||
import { DesktopClientError } from './contract.mjs'
|
||||
import { feedbackIdSchema, parseDesktopFeedback, type Diagnostic } from './feedback-contract'
|
||||
|
||||
function configuredFeedbackRecipients(): string[] {
|
||||
const configured = [
|
||||
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID ?? '',
|
||||
...(process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS ?? '').split(','),
|
||||
].map(id => id.trim()).filter(Boolean)
|
||||
return Array.from(new Set(configured))
|
||||
}
|
||||
|
||||
async function feedbackNotificationRecipients() {
|
||||
const configured = configuredFeedbackRecipients()
|
||||
if (configured.length) return configured
|
||||
|
||||
const admins = await prisma.user.findMany({
|
||||
where: {
|
||||
isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true,
|
||||
dingtalkUserId: { not: null }, NOT: { dingtalkUserId: '' },
|
||||
},
|
||||
select: { id: true, dingtalkUserId: true, realName: true, username: true },
|
||||
})
|
||||
return Array.from(new Set(admins.map(admin => admin.dingtalkUserId?.trim()).filter((id): id is string => Boolean(id))))
|
||||
}
|
||||
|
||||
function notificationText(value: unknown, limit: number) {
|
||||
if (typeof value !== 'string') return ''
|
||||
return Array.from(value.replace(/\b(?:Pi|PhotoCraft)\b/gi, '小壹').replace(/\s+/g, ' ').trim()).slice(0, limit).join('')
|
||||
.replace(/[\\`*_\[\]~#<>]/g, '\\$&')
|
||||
}
|
||||
|
||||
function asRecord(value: Diagnostic | undefined): Record<string, Diagnostic> | undefined {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined
|
||||
}
|
||||
|
||||
function richNotificationLines(snapshot: Record<string, Diagnostic>) {
|
||||
const display = asRecord(snapshot.display)
|
||||
const gpu = asRecord(display?.gpu)
|
||||
const workspace = asRecord(snapshot.workspaceState)
|
||||
const model = asRecord(snapshot.modelConfig)
|
||||
const chat = asRecord(model?.chat)
|
||||
const copy = asRecord(model?.copy)
|
||||
const image = asRecord(model?.image)
|
||||
const errors = Array.isArray(snapshot.recentErrors) ? snapshot.recentErrors : []
|
||||
const failures = Array.isArray(snapshot.recentToolFailures) ? snapshot.recentToolFailures : []
|
||||
const parts = (values: Array<Diagnostic | undefined>) => values
|
||||
.map(value => notificationText(typeof value === 'number' ? String(value) : value, 40)).filter(Boolean).join(' / ')
|
||||
const dimensions = [display?.physicalWidth, display?.physicalHeight]
|
||||
const resolution = dimensions.every(value => typeof value === 'number') ? `${dimensions.join(' × ')} px` : undefined
|
||||
const modelIds = [chat?.modelId, copy?.modelId, image?.modelId].filter((value): value is string => typeof value === 'string')
|
||||
const signals = [
|
||||
['发布渠道', parts([snapshot.channel ?? asRecord(snapshot.updateState)?.channel])],
|
||||
['系统与显示', parts([snapshot.os ?? snapshot.platform, snapshot.arch, resolution, gpu?.backend])],
|
||||
['工作区', parts([workspace?.activeScreen, workspace?.activeTab, workspace?.mode, workspace?.activeTaskStatus])],
|
||||
['模型', parts([chat?.providerId, ...Array.from(new Set(modelIds)), model?.routingMode,
|
||||
typeof model?.hasPersonalKey === 'boolean' ? `个人密钥${model.hasPersonalKey ? '已配置' : '未配置'}` : undefined])],
|
||||
['近况', errors.length || failures.length ? `错误 ${errors.length} 条 · 工具失败 ${failures.length} 条` : ''],
|
||||
]
|
||||
return signals.flatMap(([label, value]) => value ? [`${label}:${value}`] : [])
|
||||
}
|
||||
import { feedbackIdSchema, parseDesktopFeedback } from './feedback-contract'
|
||||
import { configuredFeedbackRecipients, dispatchDesktopFeedback } from './feedback-dispatch'
|
||||
|
||||
export async function submitDesktopFeedback(ownerId: string, raw: string) {
|
||||
const data = parseDesktopFeedback(raw)
|
||||
@ -72,65 +13,30 @@ export async function submitDesktopFeedback(ownerId: string, raw: string) {
|
||||
})
|
||||
const record = await prisma.desktopClientFeedback.findFirst({
|
||||
where: { feedbackId, ownerId },
|
||||
select: { feedbackId: true, status: true, createdAt: true, owner: { select: { realName: true, username: true } } },
|
||||
select: {
|
||||
status: true, createdAt: true,
|
||||
owner: { select: { realName: true, username: true, department: true, departmentRef: { select: { name: true } } } },
|
||||
},
|
||||
})
|
||||
if (!record) throw new DesktopClientError('反馈编号不可用', 409, 'feedback_id_conflict')
|
||||
|
||||
const detailPath = `/feedback/${feedbackId}`
|
||||
if (count === 1) {
|
||||
try {
|
||||
const recipients = await feedbackNotificationRecipients()
|
||||
if (!recipients.length) {
|
||||
console.warn('[desktop-feedback] 没有可用的钉钉收件人', { feedbackId })
|
||||
} else {
|
||||
const projectName = asRecord(data.snapshot.project)?.name
|
||||
const rich = data.snapshot.schemaVersion === 3
|
||||
const update = rich ? asRecord(data.snapshot.updateState) : undefined
|
||||
const versionBase = notificationText(data.snapshot.clientVersion ?? update?.currentVersion, 48) || '未提供'
|
||||
const commitShort = notificationText(data.snapshot.commit, 7)
|
||||
const versionLine = commitShort ? `${versionBase} (${commitShort})` : versionBase
|
||||
const daemonStderr = asRecord(data.snapshot.agentDaemon)?.stderrSummary
|
||||
const errors = rich ? asRecord(data.snapshot.errors) : undefined
|
||||
const latestError = rich && Array.isArray(data.snapshot.recentErrors) ? data.snapshot.recentErrors.at(-1) : undefined
|
||||
const failed = asRecord(errors?.lastFailedOperation)
|
||||
?? (Array.isArray(errors?.activeBanners) ? asRecord(errors.activeBanners[0]) : undefined)
|
||||
const failedText = [failed?.operation ?? failed?.toolName, failed?.message ?? failed?.category, failed?.code]
|
||||
.filter(value => typeof value === 'string' || typeof value === 'number').join(' / ')
|
||||
const latestErrorText = notificationText(latestError, 120)
|
||||
const currentErrorText = notificationText(data.snapshot.currentError, 120)
|
||||
|| notificationText(failedText, 120)
|
||||
|| notificationText(daemonStderr, 120)
|
||||
const lines = [
|
||||
`反馈人:${notificationText(record.owner.realName || record.owner.username, 80)}`,
|
||||
`项目:${notificationText(projectName, 120) || '未提供'}`,
|
||||
`客户端版本:${versionLine}`,
|
||||
`摘要:${notificationText(data.summary, 120)}`,
|
||||
`反馈编号:${feedbackId}`,
|
||||
]
|
||||
if (currentErrorText) lines.push(`当前报错:${currentErrorText}`)
|
||||
if (latestErrorText && latestErrorText !== currentErrorText) lines.push(`最近错误:${latestErrorText}`)
|
||||
if (rich) lines.push(...richNotificationLines(data.snapshot))
|
||||
const content = lines.join('\n')
|
||||
const actionUrl = `${getPublicAppOrigin()}${detailPath}`
|
||||
await Promise.all(recipients.map(async recipientUserId => {
|
||||
const idempotencyKey = recipients.length === 1
|
||||
? `desktop-feedback:${feedbackId}`
|
||||
: `desktop-feedback:${feedbackId}:${recipientUserId}`
|
||||
let errorCode = 'delivery_failed'
|
||||
try {
|
||||
const result = await submitYouyidianNotification({
|
||||
idempotencyKey, recipientUserId, title: '小壹问题反馈', content, actionTitle: '查看反馈', actionUrl,
|
||||
})
|
||||
if (result.status !== 'failed') return
|
||||
} catch {
|
||||
errorCode = 'notification_request_failed'
|
||||
}
|
||||
console.warn('[desktop-feedback] 通知投递失败', { feedbackId, recipientUserId, errorCode })
|
||||
}))
|
||||
}
|
||||
} catch {
|
||||
console.warn('[desktop-feedback] 通知准备失败', { feedbackId, errorCode: 'notification_preparation_failed' })
|
||||
}
|
||||
setImmediate(() => {
|
||||
void dispatchDesktopFeedback({
|
||||
feedbackId,
|
||||
reporter: {
|
||||
name: record.owner.realName || record.owner.username,
|
||||
department: record.owner.departmentRef?.name || record.owner.department,
|
||||
},
|
||||
summary: data.summary,
|
||||
snapshot: data.snapshot,
|
||||
createdAt: record.createdAt,
|
||||
detailPath,
|
||||
}).catch(() => {
|
||||
console.warn('[desktop-feedback] dispatch', { feedbackId, outcome: 'failed', errorCode: 'unexpected_error' })
|
||||
})
|
||||
})
|
||||
}
|
||||
return { feedback: { feedbackId, status: record.status, createdAt: record.createdAt, detailPath } }
|
||||
}
|
||||
|
||||
@ -55,22 +55,22 @@ const request = async (path: string, init: { method: 'GET' | 'POST'; body?: Reco
|
||||
const body = init.body ? JSON.stringify(init.body) : ''
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), init.timeoutMs ?? 8_000)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(`${config.baseUrl}${path}`, {
|
||||
const response = await fetch(`${config.baseUrl}${path}`, {
|
||||
method: init.method,
|
||||
headers: signedHeaders({ method: init.method, path, body }),
|
||||
body: body || undefined,
|
||||
signal: controller.signal,
|
||||
})
|
||||
const data = await response.json().catch(() => ({})) as Record<string, any>
|
||||
controller.signal.throwIfAborted()
|
||||
if (!response.ok) {
|
||||
throw new Error(`由壹点通知中心请求失败: ${data.error || response.status}`)
|
||||
}
|
||||
return data
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
const data = await response.json().catch(() => ({})) as Record<string, any>
|
||||
if (!response.ok) {
|
||||
throw new Error(`由壹点通知中心请求失败: ${data.error || response.status}`)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
export const submitYouyidianNotification = async (input: {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user