164 lines
8.7 KiB
TypeScript
164 lines
8.7 KiB
TypeScript
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}`] : [])
|
||
}
|
||
|
||
export async function submitDesktopFeedback(ownerId: string, raw: string) {
|
||
const data = parseDesktopFeedback(raw)
|
||
const { feedbackId } = data
|
||
const { count } = await prisma.desktopClientFeedback.createMany({
|
||
data: { ...data, ownerId },
|
||
skipDuplicates: true,
|
||
})
|
||
const record = await prisma.desktopClientFeedback.findFirst({
|
||
where: { feedbackId, ownerId },
|
||
select: { feedbackId: true, status: true, createdAt: true, owner: { select: { realName: true, username: 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' })
|
||
}
|
||
}
|
||
return { feedback: { feedbackId, status: record.status, createdAt: record.createdAt, detailPath } }
|
||
}
|
||
|
||
export async function loadDesktopFeedback(id: string, viewerId: string) {
|
||
const parsedId = feedbackIdSchema.safeParse(id)
|
||
if (!parsedId.success) return { status: 404 } as const
|
||
|
||
const viewer = await prisma.user.findUnique({
|
||
where: { id: viewerId },
|
||
select: { role: true, isSuperAdmin: true, isActive: true, status: true, archivedAt: true, dingtalkUserId: true },
|
||
})
|
||
if (!viewer?.isActive || viewer.status !== 'active' || viewer.archivedAt) return { status: 403 } as const
|
||
|
||
const feedbackId = parsedId.data
|
||
const dingtalkId = viewer.dingtalkUserId?.trim()
|
||
const canReadAll = viewer.isSuperAdmin
|
||
|| isSystemAdmin(viewer.role)
|
||
|| (Boolean(dingtalkId) && configuredFeedbackRecipients().includes(dingtalkId!))
|
||
const feedback = await prisma.desktopClientFeedback.findFirst({
|
||
where: { feedbackId, ...(canReadAll ? {} : { ownerId: viewerId }) },
|
||
include: { owner: { select: { realName: true, username: true } } },
|
||
})
|
||
if (feedback) return { status: 200, feedback } as const
|
||
// For an ordinary viewer, only check existence so a 403 never loads another user's snapshot.
|
||
const exists = !canReadAll && await prisma.desktopClientFeedback.findUnique({
|
||
where: { feedbackId }, select: { feedbackId: true },
|
||
})
|
||
return exists ? { status: 403 } as const : { status: 404 } as const
|
||
}
|