gongxiangp2/lib/desktop-client/feedback-dispatch.ts

306 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)])
}