feat: 修复定时日报错误通知微信机器人功能

增加定时日报debug
修复定时日报历史头像显示并区分定时日报标题
This commit is contained in:
Wxw-Gu committed 2026-09-02 15:01:03 +08:00
1 parent 1c8bbae1f0
commit 7c8b45a24a
32 files changed
+2975 -213

No files matched your search

+1
View File
@@ -2,6 +2,7 @@
interface ImportMetaEnv {
readonly VITE_DEEPSEEK_API_KEY: string
readonly VITE_SCHEDULED_REPORT_DEBUG: string
}
interface ImportMeta {
+22 -1
View File
@@ -460,6 +460,27 @@ function createScheduledReportRoute(
}
}
const retryPrefix = `${SCHEDULED_REPORTS_ROUTE}/executions/`
if (pathname.startsWith(retryPrefix)) {
const segments = pathname.slice(retryPrefix.length).split('/').filter(Boolean)
if (segments.length !== 2 || segments[1] !== 'retry-send') return undefined
let executionId: string
try {
executionId = decodeURIComponent(segments[0])
} catch {
return undefined
}
return async ({ req, res }) => {
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
try {
const execution = await api.retrySend(executionId)
sendJson(res, 200, { success: execution.status !== 'failed', execution })
} catch (error) {
sendScheduledError(res, error)
}
}
}
const prefix = `${SCHEDULED_REPORTS_ROUTE}/`
if (!pathname.startsWith(prefix)) return undefined
const segments = pathname.slice(prefix.length).split('/').filter(Boolean)
@@ -500,7 +521,7 @@ function createScheduledReportRoute(
}
if (action === 'run' && req.method === 'POST') {
const execution = await api.run(taskId)
sendJson(res, 200, { success: execution.status === 'success', execution })
sendJson(res, 200, { success: execution.status !== 'failed', execution })
return
}
if (action === 'executions' && req.method === 'GET') {
+19
View File
@@ -122,6 +122,7 @@ import type {
ScheduledReportCreateInput,
ScheduledReportUpdateInput
} from '../shared/scheduled-report'
import { isTruthyDebugFlag } from '../shared/debug-flags'
import { TextToSpeechSettingsService } from './services/text-to-speech-settings-service'
import type {
ListTextToSpeechVoicesRequest,
@@ -1315,6 +1316,12 @@ app.whenReady().then(async () => {
ipcMain.handle('scheduled-report:listExecutions', (_, taskId?: string) =>
scheduledReportService.listExecutions(taskId)
)
ipcMain.handle('scheduled-report:getNotificationSettings', () =>
scheduledReportService.getNotificationSettings()
)
ipcMain.handle('scheduled-report:setNotificationEnabled', (_, enabled: boolean) =>
scheduledReportService.setNotificationEnabled(Boolean(enabled))
)
ipcMain.handle('scheduled-report:create', (_, request: ScheduledReportCreateInput) =>
scheduledReportService.createTask(request)
)
@@ -1332,6 +1339,18 @@ app.whenReady().then(async () => {
ipcMain.handle('scheduled-report:runNow', (_, taskId: string) =>
scheduledReportService.runScheduledReportNow(taskId)
)
ipcMain.handle('scheduled-report:retrySend', (_, executionId: string) =>
scheduledReportService.retryScheduledReportSend(executionId)
)
ipcMain.handle('scheduled-report:testErrorNotification', (_, taskId: string) => {
if (!isTruthyDebugFlag(import.meta.env.VITE_SCHEDULED_REPORT_DEBUG)) {
return Promise.resolve({
success: false,
error: '调试测试按钮未开启,请在 .env 中设置 VITE_SCHEDULED_REPORT_DEBUG=true。'
})
}
return scheduledReportService.testScheduledReportErrorNotification(taskId)
})
ipcMain.handle('report:reveal', async (_, filePath: string) => {
try {
+1
View File
@@ -171,6 +171,7 @@ export async function saveGeneratedReport(
contactId: request.contactId,
contactName: request.contactName,
contactAvatar: request.contactAvatar,
source: request.source,
dateRange: request.dateRange,
messageCount: request.messageCount,
generatedAt: timestamp.toISOString(),
+43 -13
View File
@@ -7,6 +7,7 @@ import type {
ScheduledReportMemberNameMode,
ScheduledReportMessageType
} from '../../shared/scheduled-report'
import type { ScheduledReportExecutionStage } from '../../shared/scheduled-report'
import type { SelectableReportTemplateId } from '../../shared/report-templates'
import { resolveMemberName } from '../../shared/member-names'
import {
@@ -47,6 +48,10 @@ export interface AgentGroupReportResult {
}
duration?: number
error?: string
errorCode?: string
errorStage?: ScheduledReportExecutionStage
errorStatus?: number
errorType?: string
}
export async function generateAgentGroupReport(
@@ -57,11 +62,11 @@ export async function generateAgentGroupReport(
.trim()
.replace(/群聊?$/, '')
.trim()
if (!query) return { success: false, error: '缺少群聊名称' }
if (!query) return reportFailure('缺少群聊名称', 'data', 'CHAT_NOT_FOUND')
const contact = resolveMd5(query)
if (!contact) return { success: false, error: `没有找到群聊“${query}”` }
if (!contact) return reportFailure(`没有找到群聊“${query}”`, 'data', 'CHAT_NOT_FOUND')
if (contact.type !== 'group' && !contact.m_nsUsrName.endsWith('@chatroom')) {
return { success: false, error: `“${query}”不是群聊` }
return reportFailure(`“${query}”不是群聊`, 'data', 'CHAT_NOT_FOUND')
}
const range = request.range === 'yesterday' || request.range === '7days' ? request.range : 'today'
@@ -73,7 +78,7 @@ export async function generateAgentGroupReport(
})()
: getSummaryDateRange(range)
let messages = listMessages(contact.md5, startTime, endTime) as Message[]
if (!messages.length) return { success: false, error: '所选时间范围没有可总结的消息' }
if (!messages.length) return reportFailure('所选时间范围没有可总结的消息', 'data', 'NO_MESSAGES')
const messageTypeMap: Record<ScheduledReportMessageType, string[]> = {
text: ['普通文本'],
@@ -91,7 +96,7 @@ export async function generateAgentGroupReport(
).flatMap((type) => messageTypeMap[type] || [])
)
messages = messages.filter((message) => selectedTypes.has(message.type))
if (!messages.length) return { success: false, error: '所选时间范围没有可总结的消息' }
if (!messages.length) return reportFailure('所选时间范围没有可总结的消息', 'data', 'NO_MESSAGES')
const snapshot = getGroupSnapshot(contact.md5)
if (snapshot) {
@@ -122,7 +127,13 @@ export async function generateAgentGroupReport(
],
{ timeoutMs: Math.max(30, Math.min(1800, request.timeoutSeconds || 300)) * 1000 }
)
if (!ai.success || !ai.data) return { success: false, error: ai.error || 'AI 总结失败' }
if (!ai.success || !ai.data) {
return {
...reportFailure(ai.error || 'AI 总结失败', 'ai', ai.errorCode),
...(ai.errorStatus !== undefined ? { errorStatus: ai.errorStatus } : {}),
...(ai.errorType ? { errorType: ai.errorType } : {})
}
}
let tokenUsage = ai.usage
const parseReport = (raw: string): ReturnType<typeof parseGroupDailyReport> =>
parseGroupDailyReport(
@@ -147,18 +158,24 @@ export async function generateAgentGroupReport(
if (!repaired.success || !repaired.data) {
const cause = parseError instanceof Error ? parseError.message : String(parseError)
return {
success: false,
error: `${repaired.error || 'AI 修复日报 JSON 失败'}(原始错误:${cause})`
...reportFailure(
`${repaired.error || 'AI 修复日报 JSON 失败'}(原始错误:${cause})`,
'ai',
repaired.errorCode
),
...(repaired.errorStatus !== undefined ? { errorStatus: repaired.errorStatus } : {}),
...(repaired.errorType ? { errorType: repaired.errorType } : {})
}
}
tokenUsage = mergeTokenUsage(tokenUsage, repaired.usage)
try {
report = parseReport(repaired.data)
} catch (repairError) {
return {
success: false,
error: repairError instanceof Error ? repairError.message : String(repairError)
}
return reportFailure(
repairError instanceof Error ? repairError.message : String(repairError),
'report',
'REPORT_GENERATION_FAILED'
)
}
}
const exported = await exportGroupReport({
@@ -167,7 +184,7 @@ export async function generateAgentGroupReport(
templateId: request.templateId
})
if (!exported.success || !exported.pngPath) {
return { success: false, error: exported.error || '总结图片生成失败' }
return reportFailure(exported.error || '总结图片生成失败', 'report', 'REPORT_GENERATION_FAILED')
}
return {
success: true,
@@ -196,3 +213,16 @@ function mergeTokenUsage(
estimated: Boolean(first.estimated || second.estimated)
}
}
function reportFailure(
error: string,
errorStage: ScheduledReportExecutionStage,
errorCode?: string
): AgentGroupReportResult {
return {
success: false,
error,
errorStage,
...(errorCode ? { errorCode } : {})
}
}
+142 -21
View File
@@ -1,7 +1,7 @@
import { app, BrowserWindow } from 'electron'
import { ChildProcess, execFile, spawn } from 'child_process'
import { randomBytes, timingSafeEqual } from 'crypto'
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from 'fs'
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
import { dirname, join } from 'path'
import { promisify } from 'util'
@@ -40,6 +40,19 @@ interface InboundMessage {
items?: Array<{ type?: number; text?: string }>
}
interface AgentHubNotificationRecipient {
accountId?: string
userId: string
updatedAt: number
}
export interface AgentHubNotificationResult {
success: boolean
status: 'sent' | 'recipient_unavailable' | 'connector_offline' | 'token_expired' | 'send_failed'
recipient?: string
error?: string
}
interface GroupReportIntent {
group: string
range: 'today' | 'yesterday' | '7days'
@@ -94,7 +107,7 @@ export function resolveWechatConnectorBinaryPath(
)
}
class AgentHubService {
export class AgentHubService {
private hubServer: Server | null = null
private connectorChild: ChildProcess | null = null
private loginChild: ChildProcess | null = null
@@ -103,6 +116,8 @@ class AgentHubService {
private logs: AgentHubLogEntry[] = []
private nextLogId = 1
private readonly processedMessages = new Map<string, number>()
private notificationRecipient: AgentHubNotificationRecipient | null = null
private notificationRecipientLoaded = false
private readonly inboundToken =
process.env['AGENT_HUB_INBOUND_TOKEN'] || randomBytes(32).toString('hex')
private status: AgentHubStatus = {
@@ -115,6 +130,7 @@ class AgentHubService {
async start(settings: AppSettings): Promise<boolean> {
void settings
this.stopping = false
this.loadNotificationRecipient()
const hubStarted = await this.startHub()
await this.initializeConnector()
return hubStarted
@@ -124,6 +140,53 @@ class AgentHubService {
return { ...this.status }
}
/** The last user who sent an inbound message to this Agent Hub bot. */
getNotificationRecipient(): string | undefined {
this.loadNotificationRecipient()
return this.notificationRecipient?.userId
}
async sendNotification(input: {
to?: string
text: string
}): Promise<AgentHubNotificationResult> {
const to = String(input.to || this.getNotificationRecipient() || '').trim()
const text = String(input.text || '').trim()
if (!to || !text) {
return {
success: false,
status: 'recipient_unavailable',
error: 'Agent Hub 尚未记录可靠的通知接收者'
}
}
const accountId = this.notificationRecipient?.accountId || this.status.accountId
try {
const response = await this.postConnectorMessage({
accountId,
to,
text,
timeoutMs: 30_000
})
if (response.ok) return { success: true, status: 'sent', recipient: to }
const expired = /token|session|expired|unauthorized/i.test(response.body)
return {
success: false,
status: expired ? 'token_expired' : 'send_failed',
recipient: to,
error: expired
? 'Agent Hub 微信连接器登录凭证已失效'
: `Agent Hub 通知发送失败:${response.body || response.status}`
}
} catch (error) {
return {
success: false,
status: 'connector_offline',
recipient: to,
error: `Agent Hub 微信连接器不可用:${this.errorMessage(error)}`
}
}
}
getLogs(): AgentHubLogEntry[] {
return [...this.logs]
}
@@ -154,29 +217,24 @@ class AgentHubService {
}
}
try {
const response = await fetch(`http://${CONNECTOR_ADDR}/api/send`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_id: this.status.accountId,
to,
text: text || undefined,
media_url: mediaUrl || undefined
}),
signal: AbortSignal.timeout(30_000)
const response = await this.postConnectorMessage({
accountId: this.status.accountId,
to,
text: text || undefined,
mediaUrl: mediaUrl || undefined,
timeoutMs: 30_000
})
const body = await response.text()
if (response.ok) {
this.addLog('system', 'info', 'API 页面发送测试成功')
return { success: true, status: 'sent', message: '发送成功' }
}
const expired = /token|session|expired|unauthorized/i.test(body)
const expired = /token|session|expired|unauthorized/i.test(response.body)
return {
success: false,
status: expired ? 'token_expired' : 'send_failed',
message: expired
? '微信登录凭证已失效,请重新扫码登录'
: `发送失败:${body || response.status}`
: `发送失败:${response.body || response.status}`
}
} catch (error) {
return {
@@ -326,6 +384,7 @@ class AgentHubService {
}
const from = String(inbound.from_user_id || '').trim()
if (!from) return this.sendHubJson(response, 400, { error: 'from_user_id is required' })
this.rememberNotificationRecipient(inbound.account_id, from)
const messageId = String(inbound.message_id || '')
this.cleanProcessedMessages()
@@ -791,18 +850,35 @@ class AgentHubService {
text?: string,
mediaUrl?: string
): Promise<void> {
const response = await this.postConnectorMessage({
accountId: inbound.account_id || this.status.accountId,
to: String(inbound.from_user_id || '').trim(),
text,
mediaUrl,
timeoutMs: mediaUrl ? 60_000 : 30_000
})
if (!response.ok) throw new Error(response.body || `HTTP ${response.status}`)
}
private async postConnectorMessage(input: {
accountId?: string
to: string
text?: string
mediaUrl?: string
timeoutMs: number
}): Promise<{ ok: boolean; status: number; body: string }> {
const response = await fetch(`http://${CONNECTOR_ADDR}/api/send`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_id: inbound.account_id,
to: inbound.from_user_id,
text,
media_url: mediaUrl
account_id: input.accountId,
to: input.to,
text: input.text,
media_url: input.mediaUrl
}),
signal: AbortSignal.timeout(mediaUrl ? 60_000 : 30_000)
signal: AbortSignal.timeout(input.timeoutMs)
})
if (!response.ok) throw new Error((await response.text()) || `HTTP ${response.status}`)
return { ok: response.ok, status: response.status, body: await response.text() }
}
private matchRecentChatIntent(text: string): number | null {
@@ -965,6 +1041,51 @@ class AgentHubService {
}
}
private loadNotificationRecipient(): void {
if (this.notificationRecipientLoaded) return
this.notificationRecipientLoaded = true
try {
const stored = JSON.parse(readFileSync(this.notificationRecipientPath(), 'utf8')) as {
accountId?: unknown
userId?: unknown
updatedAt?: unknown
}
const userId = String(stored.userId || '').trim()
if (userId) {
this.notificationRecipient = {
userId,
accountId: String(stored.accountId || '').trim() || undefined,
updatedAt: Number(stored.updatedAt) || Date.now()
}
}
} catch {
this.notificationRecipient = null
}
}
private rememberNotificationRecipient(accountId: string | undefined, userId: string): void {
const normalizedUserId = String(userId || '').trim()
if (!normalizedUserId) return
const recipient: AgentHubNotificationRecipient = {
userId: normalizedUserId,
accountId: String(accountId || this.status.accountId || '').trim() || undefined,
updatedAt: Date.now()
}
this.notificationRecipient = recipient
this.notificationRecipientLoaded = true
try {
const filePath = this.notificationRecipientPath()
mkdirSync(dirname(filePath), { recursive: true })
writeFileSync(filePath, JSON.stringify(recipient, null, 2), 'utf8')
} catch (error) {
this.addLog('agent-hub', 'warn', `通知接收者保存失败:${this.errorMessage(error)}`)
}
}
private notificationRecipientPath(): string {
return join(app.getPath('userData'), 'agent-hub', 'notification-recipient.json')
}
private async loadAccounts(): Promise<{ accountId: string; wechatUserId: string }[]> {
const executable = resolveWechatConnectorBinaryPath()
if (!existsSync(executable)) throw new Error(`微信连接器不存在:${executable}`)
+75 -9
View File
@@ -31,7 +31,7 @@ type AIRequestResult = {
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
}
interface OpenAIResponsePayload {
error?: { message?: string }
error?: { message?: string; code?: string | number; type?: string }
choices?: Array<{
message?: {
content?: string | Array<{ type?: string; text?: string }> | null
@@ -42,12 +42,12 @@ interface OpenAIResponsePayload {
usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }
}
interface OpenAIStreamPayload {
error?: { message?: string }
error?: { message?: string; code?: string | number; type?: string }
choices?: Array<{ delta?: { content?: string }; finish_reason?: string }>
usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }
}
interface OpenAIResponsesPayload {
error?: { message?: string }
error?: { message?: string; code?: string | number; type?: string }
incomplete_details?: { reason?: string }
status?: string
output_text?: string
@@ -61,16 +61,35 @@ interface OpenAIResponsesStreamPayload {
type?: string
delta?: string
message?: string
error?: { message?: string }
error?: { message?: string; code?: string | number; type?: string }
response?: OpenAIResponsesPayload
}
interface AnthropicResponsePayload {
error?: { message?: string }
error?: { message?: string; type?: string }
content?: Array<{ type?: string; text?: string }>
stop_reason?: string
usage?: { input_tokens?: number; output_tokens?: number }
}
export class AIProviderRequestError extends Error {
readonly status?: number
readonly code?: string
readonly type?: string
readonly responseBody?: unknown
constructor(
message: string,
details: { status?: number; code?: unknown; type?: unknown; responseBody?: unknown } = {}
) {
super(message)
this.name = 'AIProviderRequestError'
this.status = details.status
this.code = typeof details.code === 'string' ? details.code : undefined
this.type = typeof details.type === 'string' ? details.type : undefined
this.responseBody = details.responseBody
}
}
export class AIProviderService {
constructor(private readonly keyStore = new AIProviderKeyStore()) {}
@@ -272,12 +291,15 @@ export class AIProviderService {
finishReason?: string
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
error?: string
errorCode?: string
errorStatus?: number
errorType?: string
}> {
try {
return { success: true, ...(await this.request(messages, options, false, signal, onDelta)) }
} catch (error) {
if (signal?.aborted) throw error
return { success: false, error: safeAIError(error) }
return { success: false, error: safeAIError(error), ...aiProviderErrorDetails(error) }
}
}
@@ -752,7 +774,15 @@ async function requestOpenAICompatible(
async (response) => {
if (!response.ok) {
const payload = await parseJsonResponse<OpenAIResponsePayload>(response)
throw new Error(payload.error?.message || `AI 请求失败 (${response.status})`)
throw new AIProviderRequestError(
payload.error?.message || `AI 请求失败 (${response.status})`,
{
status: response.status,
code: payload.error?.code,
type: payload.error?.type,
responseBody: payload.error
}
)
}
if (
provider.advanced.stream &&
@@ -810,7 +840,15 @@ async function requestOpenAIResponses(
async (response) => {
if (!response.ok) {
const payload = await parseJsonResponse<OpenAIResponsesPayload>(response)
throw new Error(payload.error?.message || `AI 请求失败 (${response.status})`)
throw new AIProviderRequestError(
payload.error?.message || `AI 请求失败 (${response.status})`,
{
status: response.status,
code: payload.error?.code,
type: payload.error?.type,
responseBody: payload.error
}
)
}
if (provider.advanced.stream) return parseOpenAIResponsesStream(response, onDelta)
const payload = await parseJsonResponse<OpenAIResponsesPayload>(response)
@@ -867,7 +905,14 @@ async function requestAnthropic(
async (response) => {
const payload = await parseJsonResponse<AnthropicResponsePayload>(response)
if (!response.ok)
throw new Error(payload.error?.message || `Anthropic 请求失败 (${response.status})`)
throw new AIProviderRequestError(
payload.error?.message || `Anthropic 请求失败 (${response.status})`,
{
status: response.status,
type: payload.error?.type,
responseBody: payload.error
}
)
return {
data: Array.isArray(payload.content)
? payload.content
@@ -1156,6 +1201,27 @@ function safeAIError(error: unknown): string {
return message.replace(/sk-[a-z0-9_-]+/gi, '***').slice(0, 300)
}
function aiProviderErrorDetails(error: unknown): {
errorCode?: string
errorStatus?: number
errorType?: string
} {
if (error instanceof AIProviderRequestError) {
return {
...(error.code ? { errorCode: error.code } : {}),
...(error.status !== undefined ? { errorStatus: error.status } : {}),
...(error.type ? { errorType: error.type } : {})
}
}
const record = error && typeof error === 'object' ? (error as Record<string, unknown>) : undefined
const status = Number(record?.status)
return {
...(typeof record?.code === 'string' ? { errorCode: record.code } : {}),
...(Number.isFinite(status) && status > 0 ? { errorStatus: status } : {}),
...(typeof record?.type === 'string' ? { errorType: record.type } : {})
}
}
function parseVisionImage(dataUrl: string): { mimeType: string; base64: string; bytes: number } {
const match = /^data:(image\/(?:png|jpeg|webp));base64,([a-z0-9+/=]+)$/i.exec(dataUrl)
if (!match) throw new Error('图片格式不受支持,请选择 PNG、JPG、JPEG 或 WebP')
@@ -27,7 +27,8 @@ export interface ScheduledReportApiDependencies {
| 'deleteTask'
| 'setTaskEnabled'
| 'runScheduledReportNow'
>
> &
Partial<Pick<ScheduledReportService, 'retryScheduledReportSend'>>
getCapability: () => Promise<PersonalWechatSendCapability>
listContacts: () => FormattedContact[]
isDatabaseReady: () => boolean
@@ -102,7 +103,6 @@ export class ScheduledReportApiService {
request: ScheduledReportApiCreateRequest
): Promise<ScheduledReportApiTask> {
this.assertDatabaseReady()
await this.assertCapabilityReady()
if (!isRecord(request))
throw new ScheduledReportApiError(400, 'invalid_request', '请求体格式无效')
@@ -250,6 +250,18 @@ export class ScheduledReportApiService {
return result.data
}
async retrySend(executionId: string): Promise<ScheduledReportExecution> {
const retry = this.deps.service.retryScheduledReportSend
if (!retry) {
throw new ScheduledReportApiError(501, 'not_supported', '当前运行时不支持重新发送日报')
}
const result = await retry.call(this.deps.service, executionId)
if (!result.data) {
throw new ScheduledReportApiError(404, 'not_found', result.error || '未找到定时日报执行记录')
}
return result.data
}
async executions(taskId: string): Promise<ScheduledReportApiExecution[]> {
this.assertDatabaseReady()
const task = await this.findTask(taskId)
@@ -277,27 +289,6 @@ export class ScheduledReportApiService {
}
}
private async assertCapabilityReady(): Promise<void> {
let capability: PersonalWechatSendCapability
try {
capability = this.applyPlatformCapability(await this.deps.getCapability())
} catch (error) {
throw new ScheduledReportApiError(
503,
'wechat_capability_unavailable',
'微信发送能力检测失败,请在 TraceMemo 设置中检查个人微信。',
error instanceof Error ? error.message : String(error)
)
}
if (capability.ready && capability.capabilities.image) return
throw new ScheduledReportApiError(
409,
'wechat_not_ready',
capability.message || 'TraceMemo 当前还没有完成微信消息发送能力配置',
{ capability: publicCapability(capability) }
)
}
private applyPlatformCapability(
capability: PersonalWechatSendCapability
): PersonalWechatSendCapability {
File diff suppressed because it is too large. Load diff
+12
View File
@@ -65,6 +65,8 @@ import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
import type {
ScheduledReportCreateInput,
ScheduledReportExecution,
ScheduledReportNotificationSettings,
ScheduledReportNotificationSettingsResult,
ScheduledReportResult,
ScheduledReportTask,
ScheduledReportUpdateInput
@@ -636,6 +638,10 @@ declare global {
) => Promise<PersonalWechatSendResult>
listScheduledReports: () => Promise<ScheduledReportTask[]>
listScheduledReportExecutions: (taskId?: string) => Promise<ScheduledReportExecution[]>
getScheduledReportNotificationSettings: () => Promise<ScheduledReportNotificationSettings>
setScheduledReportNotificationEnabled: (
enabled: boolean
) => Promise<ScheduledReportNotificationSettingsResult>
createScheduledReport: (
request: ScheduledReportCreateInput
) => Promise<ScheduledReportResult<ScheduledReportTask>>
@@ -653,6 +659,12 @@ declare global {
runScheduledReportNow: (
taskId: string
) => Promise<ScheduledReportResult<ScheduledReportExecution>>
retryScheduledReportSend: (
executionId: string
) => Promise<ScheduledReportResult<ScheduledReportExecution>>
testScheduledReportErrorNotification: (
taskId: string
) => Promise<ScheduledReportResult<ScheduledReportExecution>>
getPersonalWechatVoiceDiagnostic: () => Promise<PersonalWechatVoiceDiagnostic | null>
getAgentHubStatus: () => Promise<AgentHubStatus>
getAgentHubLogs: () => Promise<AgentHubLogEntry[]>
+16
View File
@@ -37,6 +37,8 @@ import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
import type {
ScheduledReportCreateInput,
ScheduledReportExecution,
ScheduledReportNotificationSettings,
ScheduledReportNotificationSettingsResult,
ScheduledReportResult,
ScheduledReportTask,
ScheduledReportUpdateInput
@@ -441,6 +443,12 @@ const api = {
ipcRenderer.invoke('scheduled-report:list'),
listScheduledReportExecutions: (taskId?: string): Promise<ScheduledReportExecution[]> =>
ipcRenderer.invoke('scheduled-report:listExecutions', taskId),
getScheduledReportNotificationSettings: (): Promise<ScheduledReportNotificationSettings> =>
ipcRenderer.invoke('scheduled-report:getNotificationSettings'),
setScheduledReportNotificationEnabled: (
enabled: boolean
): Promise<ScheduledReportNotificationSettingsResult> =>
ipcRenderer.invoke('scheduled-report:setNotificationEnabled', enabled),
createScheduledReport: (
request: ScheduledReportCreateInput
): Promise<ScheduledReportResult<ScheduledReportTask>> =>
@@ -461,6 +469,14 @@ const api = {
taskId: string
): Promise<ScheduledReportResult<ScheduledReportExecution>> =>
ipcRenderer.invoke('scheduled-report:runNow', taskId),
retryScheduledReportSend: (
executionId: string
): Promise<ScheduledReportResult<ScheduledReportExecution>> =>
ipcRenderer.invoke('scheduled-report:retrySend', executionId),
testScheduledReportErrorNotification: (
taskId: string
): Promise<ScheduledReportResult<ScheduledReportExecution>> =>
ipcRenderer.invoke('scheduled-report:testErrorNotification', taskId),
getPersonalWechatVoiceDiagnostic: (): Promise<PersonalWechatVoiceDiagnostic | null> =>
ipcRenderer.invoke('wechat-personal:getVoiceDiagnostic'),
getAgentHubStatus: () => ipcRenderer.invoke('agent-hub:getStatus'),
+7
View File
@@ -1512,6 +1512,10 @@ function App(): React.ReactElement {
setActivePage('settings')
}
const openAgentHub = (): void => {
setActivePage('agent-hub')
}
const dismissFirstUseWelcome = (): void => {
try {
localStorage.setItem(FIRST_USE_WELCOME_SEEN_KEY, '1')
@@ -1604,6 +1608,7 @@ function App(): React.ReactElement {
contactId: reportSourceContact.md5,
contactName: contactDisplayName(reportSourceContact),
contactAvatar: reportSourceContact.avatar || undefined,
source: 'manual',
dateRange:
summaryDateRange === 'yesterday'
? '昨日'
@@ -1816,6 +1821,7 @@ function App(): React.ReactElement {
contacts={contacts}
platformSupported={supportsPersonalWechatSend}
onOpenWechatSettings={openWechatSendSettings}
onOpenAgentHub={openAgentHub}
onOpenModelSettings={openModelSettings}
onNotice={(message, variant) =>
toast({ description: message, variant, duration: 3200 })
@@ -1825,6 +1831,7 @@ function App(): React.ReactElement {
<div className="report-center-page">
<ReportHistorySidebar
reports={generatedReports}
contacts={contacts}
selectedReportId={selectedReportId}
selfInfo={selfInfo}
dbReady={isDatabaseConnected}
@@ -12,6 +12,7 @@ import {
Input
} from '../ui'
import type { GeneratedReportRecord } from './types'
import type { Contact } from '../../../../shared/types'
interface SelfInfo {
wxid: string
@@ -22,6 +23,7 @@ interface SelfInfo {
interface ReportHistorySidebarProps {
reports: GeneratedReportRecord[]
contacts?: Contact[]
selectedReportId: string | null
selfInfo: SelfInfo | null
dbReady: boolean
@@ -88,8 +90,12 @@ const buildGroups = (reports: GeneratedReportRecord[]): ReportGroup[] => {
return groups
}
const reportTitle = (report: GeneratedReportRecord): string =>
report.source === 'scheduled' ? `${report.contactName}的定时日报` : report.contactName
export function ReportHistorySidebar({
reports,
contacts = [],
selectedReportId,
selfInfo,
dbReady,
@@ -105,6 +111,15 @@ export function ReportHistorySidebar({
const [deletePending, setDeletePending] = useState(false)
const deleteTriggerRef = useRef<HTMLButtonElement | null>(null)
const restoreDeleteFocusRef = useRef(false)
const contactAvatars = useMemo(() => {
const result = new Map<string, string>()
contacts.forEach((contact) => {
if (!contact.avatar) return
result.set(contact.md5, contact.avatar)
result.set(contact.m_nsUsrName, contact.avatar)
})
return result
}, [contacts])
useEffect(() => {
if (pendingDelete || !restoreDeleteFocusRef.current) return
@@ -116,9 +131,10 @@ export function ReportHistorySidebar({
const lower = keyword.trim().toLowerCase()
const filteredReports = reports
.filter((report) => {
const haystack = `${report.contactName} ${report.dateRange} ${formatGeneratedAt(
report.generatedAt
)}`.toLowerCase()
const haystack =
`${reportTitle(report)} ${report.contactName} ${report.dateRange} ${formatGeneratedAt(
report.generatedAt
)}`.toLowerCase()
return lower ? haystack.includes(lower) : true
})
.sort((left, right) => dateKey(right.generatedAt) - dateKey(left.generatedAt))
@@ -187,10 +203,10 @@ export function ReportHistorySidebar({
}}
>
<span className="report-history-avatar">
{report.contactAvatar ? (
{report.contactAvatar || contactAvatars.get(report.contactId) ? (
<img
src={report.contactAvatar}
alt={report.contactName}
src={report.contactAvatar || contactAvatars.get(report.contactId)}
alt={reportTitle(report)}
referrerPolicy="no-referrer"
/>
) : (
@@ -198,7 +214,7 @@ export function ReportHistorySidebar({
)}
</span>
<span className="report-history-text">
<b>{report.contactName}</b>
<b>{reportTitle(report)}</b>
<small>{formatGeneratedAt(report.generatedAt)}</small>
<small>{report.messageCount} 条消息</small>
<em>PNG{report.pngStatus === 'ready' ? '已保存' : '缺失'}</em>
@@ -6,6 +6,7 @@ import type {
ScheduledReportExecution,
ScheduledReportMessageType,
ScheduledReportMemberNameMode,
ScheduledReportNotificationCapabilityReason,
ScheduledReportRange,
ScheduledReportTask
} from '../../../../shared/scheduled-report'
@@ -46,6 +47,7 @@ import {
type SummaryDateRange
} from '../../utils/group-report'
import { REPORT_TEMPLATES, DEFAULT_REPORT_TEMPLATE } from '../../../../shared/report-templates'
import { isTruthyDebugFlag } from '../../../../shared/debug-flags'
type ReportDialogMode = 'create' | 'edit'
@@ -53,6 +55,7 @@ interface ScheduledReportsWorkspaceProps {
contacts: Contact[]
platformSupported?: boolean
onOpenWechatSettings: () => void
onOpenAgentHub: () => void
onOpenModelSettings?: () => void
onNotice: (message: string, variant?: 'default' | 'success' | 'warning' | 'destructive') => void
}
@@ -125,24 +128,37 @@ const capabilityTone = (capability: PersonalWechatSendCapability | null): string
const readableError = (error?: string): string => {
const value = String(error || '')
if (value.includes('wechat_not_ready') || value.includes('仅支持 macOS')) {
if (value.includes('unsupported') || value.includes('仅支持'))
return '微信消息发送目前仅支持 macOS 和 Windows'
if (value.includes('needs_binding') || value.includes('unconfigured')) return '请先绑定个人微信'
if (value.includes('needs_verification')) return '请先完成微信消息能力检测'
return '微信发送能力不可用,请检查微信连接。'
}
if (value.includes('wechat_send_failed')) return '微信发送失败,请检查微信连接。'
if (value.includes('report_generation_failed')) return '日报生成失败,请稍后重试。'
return value || '操作失败,请稍后重试。'
}
const notificationFailureCopy = (
reason?: ScheduledReportNotificationCapabilityReason,
error?: string
): string => {
if (reason === 'agent_hub_offline') return '需要先连接 Agent Hub 微信机器人,才能接收异常通知。'
if (reason === 'connector_offline') return 'Agent Hub 微信连接器当前未在线,请先恢复连接。'
if (reason === 'recipient_not_bound') {
return 'Agent Hub 已连接,但还不知道异常通知应该发送给谁。请先在微信中给 TraceMemo 机器人发送一条消息,完成通知接收者绑定。'
}
if (reason === 'settings_persist_failed') return '异常通知开关保存失败,请稍后重试。'
return error ? `异常通知测试发送失败:${error}` : '异常通知测试发送失败,请检查 Agent Hub 连接。'
}
const executionLabel = (execution: ScheduledReportExecution): string => {
if (execution.status === 'running') return '生成中 · 待发送'
if (execution.status === 'success') return '已生成并发送'
if (execution.error?.includes('report_generation_failed')) return '日报生成失败'
if (execution.error?.includes('wechat_not_ready')) return '微信发送能力不可用'
return '微信发送失败'
if (execution.status === 'waiting_to_send') return '日报已生成,但未发送'
if (execution.status === 'partial_success') return '日报已生成,微信发送失败'
if (execution.status === 'waiting_for_recovery') return '等待恢复'
if (execution.status === 'skipped') return execution.userTitle || '暂无可生成的日报'
return execution.userTitle || '日报生成失败'
}
const executionDescription = (execution: ScheduledReportExecution): string => {
if (execution.status === 'success') {
return execution.sendTarget ? `已发送到:${execution.sendTarget}` : '日报已生成并发送'
}
return execution.userMessage || execution.message || '本次定时日报执行失败。'
}
function GroupAvatar({ contact }: { contact: Contact }): React.ReactElement {
@@ -550,11 +566,19 @@ export function ScheduledReportsWorkspace({
contacts,
platformSupported = true,
onOpenWechatSettings,
onOpenAgentHub,
onOpenModelSettings,
onNotice
}: ScheduledReportsWorkspaceProps): React.ReactElement {
const [capability, setCapability] = React.useState<PersonalWechatSendCapability | null>(null)
const [capabilityError, setCapabilityError] = React.useState(false)
const [notificationEnabled, setNotificationEnabled] = React.useState(false)
const [notificationBusy, setNotificationBusy] = React.useState(false)
const [notificationSettingsError, setNotificationSettingsError] = React.useState(false)
const [notificationFailure, setNotificationFailure] = React.useState<{
reason?: ScheduledReportNotificationCapabilityReason
error?: string
} | null>(null)
const [tasks, setTasks] = React.useState<ScheduledReportTask[]>([])
const [executions, setExecutions] = React.useState<ScheduledReportExecution[]>([])
const [loading, setLoading] = React.useState(true)
@@ -580,14 +604,23 @@ export function ScheduledReportsWorkspace({
})
setTasks([])
setExecutions([])
try {
const settings = await window.api.getScheduledReportNotificationSettings()
setNotificationEnabled(settings.enabled)
setNotificationSettingsError(false)
} catch {
setNotificationSettingsError(true)
}
setLoading(false)
return
}
const [taskResult, executionResult, capabilityResult] = await Promise.allSettled([
window.api.listScheduledReports(),
window.api.listScheduledReportExecutions(),
window.api.getPersonalWechatSendCapability()
])
const [taskResult, executionResult, capabilityResult, notificationSettingsResult] =
await Promise.allSettled([
window.api.listScheduledReports(),
window.api.listScheduledReportExecutions(),
window.api.getPersonalWechatSendCapability(),
window.api.getScheduledReportNotificationSettings()
])
if (taskResult.status === 'fulfilled') setTasks(taskResult.value)
else setListError(true)
if (executionResult.status === 'fulfilled') setExecutions(executionResult.value)
@@ -597,6 +630,12 @@ export function ScheduledReportsWorkspace({
} else {
setCapabilityError(true)
}
if (notificationSettingsResult.status === 'fulfilled') {
setNotificationEnabled(notificationSettingsResult.value.enabled)
setNotificationSettingsError(false)
} else {
setNotificationSettingsError(true)
}
setLoading(false)
}, [platformSupported])
@@ -624,10 +663,39 @@ export function ScheduledReportsWorkspace({
setCapabilityError(false)
})
.catch(() => setCapabilityError(true))
void window.api
.getScheduledReportNotificationSettings()
.then((settings) => {
setNotificationEnabled(settings.enabled)
setNotificationSettingsError(false)
})
.catch(() => setNotificationSettingsError(true))
}, 15_000)
return () => window.clearInterval(timer)
}, [dialogOpen, refreshTasks])
const setNotification = async (enabled: boolean): Promise<void> => {
setNotificationBusy(true)
try {
const result = await window.api.setScheduledReportNotificationEnabled(enabled)
setNotificationEnabled(result.data.enabled)
if (result.success) {
setNotificationFailure(null)
onNotice(enabled ? '微信异常通知已开启' : '微信异常通知已关闭', 'success')
} else {
setNotificationFailure({ reason: result.reason, error: result.error })
onNotice(notificationFailureCopy(result.reason, result.error), 'warning')
}
} catch (error) {
setNotificationEnabled(false)
const message = readableError(error instanceof Error ? error.message : String(error))
setNotificationFailure({ reason: 'send_failed', error: message })
onNotice(message, 'warning')
} finally {
setNotificationBusy(false)
}
}
const submit = async (input: ScheduledReportCreateInput, taskId?: string): Promise<void> => {
setSaving(true)
try {
@@ -666,9 +734,21 @@ export function ScheduledReportsWorkspace({
try {
const result = await window.api.runScheduledReportNow(task.id)
await refreshTasks()
if (!result.success)
onNotice(readableError(result.error || result.data?.error), 'destructive')
else onNotice('日报已生成并发送', 'success')
const execution = result.data
if (execution?.status === 'waiting_to_send') {
onNotice('日报已生成,但未发送', 'warning')
} else if (execution?.status === 'partial_success') {
onNotice('日报已生成,微信发送失败', 'warning')
} else if (execution?.status === 'success') {
onNotice('日报已生成并发送', 'success')
} else if (execution?.status === 'skipped') {
onNotice('本次没有可生成的日报', 'default')
} else if (!result.success) {
onNotice(
execution?.userMessage || readableError(result.error || execution?.error),
'destructive'
)
}
} catch (error) {
onNotice(readableError(error instanceof Error ? error.message : String(error)), 'destructive')
} finally {
@@ -676,6 +756,50 @@ export function ScheduledReportsWorkspace({
}
}
const retrySend = async (execution: ScheduledReportExecution): Promise<void> => {
const task = tasks.find((item) => item.id === execution.taskId)
const busyId = task?.id || execution.id
setBusyTaskId(busyId)
try {
const result = await window.api.retryScheduledReportSend(execution.id)
await refreshTasks()
if (result.data?.status === 'success') onNotice('日报已重新发送', 'success')
else if (result.data?.status === 'waiting_to_send')
onNotice('微信发送能力仍未恢复', 'warning')
else onNotice(result.data?.userMessage || readableError(result.error), 'warning')
} catch (error) {
onNotice(readableError(error instanceof Error ? error.message : String(error)), 'destructive')
} finally {
setBusyTaskId(null)
}
}
const testErrorNotification = async (task: ScheduledReportTask): Promise<void> => {
setBusyTaskId(task.id)
try {
const result = await window.api.testScheduledReportErrorNotification(task.id)
await refreshTasks()
if (result.data?.notificationStatus === 'sent') {
onNotice('测试错误信息已发送到 Agent Hub 微信通知接收者', 'success')
} else {
onNotice(readableError(result.error), 'warning')
}
} catch (error) {
onNotice(readableError(error instanceof Error ? error.message : String(error)), 'destructive')
} finally {
setBusyTaskId(null)
}
}
const openReport = async (execution: ScheduledReportExecution): Promise<void> => {
if (!execution.pngPath) {
onNotice('该执行记录没有可查看的日报文件', 'destructive')
return
}
const result = await window.api.revealGroupReport(execution.pngPath)
if (!result.success) onNotice(result.error || '日报文件打开失败', 'destructive')
}
const confirmDelete = async (): Promise<void> => {
if (!deletingTask) return
setBusyTaskId(deletingTask.id)
@@ -711,8 +835,7 @@ export function ScheduledReportsWorkspace({
.slice(0, 8),
[executions]
)
const canCreate = capability?.status === 'ready'
const showDebugNotificationButton = isTruthyDebugFlag(import.meta.env.VITE_SCHEDULED_REPORT_DEBUG)
return (
<div className="report-scheduled-page">
<div className="report-scheduled-header">
@@ -720,10 +843,50 @@ export function ScheduledReportsWorkspace({
<h1>定时日报</h1>
<p>每天自动生成群聊日报,并发送到指定微信群。</p>
</div>
<Button onClick={openCreate} disabled={!canCreate}>
<span aria-hidden>+</span> 新建定时日报
</Button>
<div className="flex flex-wrap items-center justify-end gap-3">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">微信异常通知</span>
<Switch
aria-label="微信异常通知"
checked={notificationEnabled}
disabled={!platformSupported || notificationBusy || notificationSettingsError}
onCheckedChange={(value) => void setNotification(value)}
/>
{notificationEnabled && <span className="text-sm text-success">✓</span>}
</div>
<Button onClick={openCreate}>
<span aria-hidden>+</span> 新建定时日报
</Button>
</div>
</div>
{notificationEnabled && (
<p className="-mt-3 text-xs text-muted-foreground">
定时日报出现异常时,通过 Agent Hub 微信机器人通知你。
</p>
)}
{notificationFailure && (
<div
role="alert"
className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-warning/30 bg-warning/10 px-4 py-3 text-sm"
>
<span>
{notificationFailureCopy(notificationFailure.reason, notificationFailure.error)}
</span>
<div className="flex shrink-0 items-center gap-2">
<Button variant="link" size="sm" onClick={onOpenAgentHub}>
前往 Agent Hub
</Button>
<Button
variant="outline"
size="sm"
disabled={notificationBusy}
onClick={() => void setNotification(true)}
>
重试
</Button>
</div>
</div>
)}
<div className={`report-wechat-capability ${capabilityTone(capability)}`}>
<span className="font-medium">微信发送能力</span>
<span
@@ -760,7 +923,7 @@ export function ScheduledReportsWorkspace({
) : tasks.length ? (
<div className="overflow-x-auto rounded-xl border border-border-subtle bg-surface">
<div className="min-w-[760px]">
<div className="grid grid-cols-[1.5fr_.8fr_1fr_1fr_.8fr_1fr_190px] gap-3 border-b border-border-subtle px-5 py-3 text-xs font-medium text-muted-foreground">
<div className="grid grid-cols-[1.5fr_.8fr_1fr_1fr_.8fr_1fr_300px] gap-3 border-b border-border-subtle px-5 py-3 text-xs font-medium text-muted-foreground">
<span>任务名称</span>
<span>执行时间</span>
<span>日报范围</span>
@@ -776,7 +939,7 @@ export function ScheduledReportsWorkspace({
return (
<div
key={task.id}
className="grid grid-cols-[1.5fr_.8fr_1fr_1fr_.8fr_1fr_190px] items-center gap-3 border-b border-border-subtle px-5 py-4 last:border-b-0"
className="grid grid-cols-[1.5fr_.8fr_1fr_1fr_.8fr_1fr_300px] items-center gap-3 border-b border-border-subtle px-5 py-4 last:border-b-0"
>
<div className="flex min-w-0 items-center gap-3">
{group && <GroupAvatar contact={group} />}
@@ -813,6 +976,16 @@ export function ScheduledReportsWorkspace({
>
{running ? '生成中…' : '立即执行'}
</Button>
{showDebugNotificationButton && (
<Button
variant="outline"
size="sm"
onClick={() => void testErrorNotification(task)}
disabled={running}
>
{running ? '测试中…' : '测试错误信息发送'}
</Button>
)}
<Button
variant="ghost"
size="sm"
@@ -850,7 +1023,7 @@ export function ScheduledReportsWorkspace({
</div>
<h2>还没有定时日报</h2>
<p>创建一个任务,让 TraceMemo 每天自动生成群聊日报并发送到微信。</p>
<Button onClick={openCreate} disabled={!canCreate}>
<Button onClick={openCreate}>
<span aria-hidden>+</span> 新建定时日报
</Button>
</div>
@@ -867,20 +1040,85 @@ export function ScheduledReportsWorkspace({
{sortedExecutions.map((execution) => {
const task = tasks.find((item) => item.id === execution.taskId)
const success = execution.status === 'success'
const skipped = execution.status === 'skipped'
const sendPending =
execution.status === 'waiting_to_send' || execution.status === 'partial_success'
const busy = busyTaskId === (task?.id || execution.id)
return (
<div
key={execution.id}
className="flex items-center gap-3 rounded-lg border border-border-subtle bg-surface px-4 py-3"
className="flex items-start gap-3 rounded-lg border border-border-subtle bg-surface px-4 py-3"
>
<span
className={`text-lg ${success ? 'text-success' : execution.status === 'running' ? 'text-warning' : 'text-destructive'}`}
className={`pt-0.5 text-lg ${success ? 'text-success' : skipped ? 'text-muted-foreground' : execution.status === 'running' || sendPending ? 'text-warning' : 'text-destructive'}`}
aria-hidden
>
{success ? '✓' : execution.status === 'running' ? '…' : '×'}
{success
? '✓'
: skipped
? '–'
: execution.status === 'running'
? '…'
: sendPending
? '!'
: '×'}
</span>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{task?.name || '定时日报'}</p>
<p className="text-xs text-muted-foreground">{executionLabel(execution)}</p>
<p className="mt-1 text-sm text-foreground">
{executionDescription(execution)}
</p>
{execution.suggestedAction && execution.status !== 'success' && (
<p className="mt-1 text-xs text-muted-foreground">
建议:{execution.suggestedAction}
</p>
)}
<div className="mt-2 flex flex-wrap items-center gap-2">
{sendPending && (
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => void retrySend(execution)}
>
{busy ? '发送中…' : '重新发送'}
</Button>
)}
{execution.status === 'failed' && (
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => task && void runNow(task)}
>
{busy ? '执行中…' : '重新执行'}
</Button>
)}
{execution.pngPath && (
<Button
size="sm"
variant="ghost"
onClick={() => void openReport(execution)}
>
查看日报
</Button>
)}
{execution.status !== 'success' &&
execution.errorCode?.startsWith('WECHAT_') && (
<Button size="sm" variant="ghost" onClick={onOpenWechatSettings}>
去检测
</Button>
)}
{execution.technicalMessage && (
<details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">查看详情</summary>
<p className="mt-1 max-w-xl whitespace-pre-wrap break-words">
{execution.technicalMessage}
</p>
</details>
)}
</div>
</div>
<time className="text-xs text-muted-foreground">
{formatDateTime(execution.finishedAt || execution.startedAt)}
+8
View File
@@ -0,0 +1,8 @@
const truthyValues = new Set(['1', 'true', 'yes', 'on'])
export const isTruthyDebugFlag = (value: unknown): boolean =>
truthyValues.has(
String(value ?? '')
.trim()
.toLowerCase()
)
+3
View File
@@ -6,12 +6,14 @@ import type {
import type { SelectableReportTemplateId } from './report-templates'
export type ReportAssetStatus = 'ready' | 'missing'
export type GeneratedReportSource = 'manual' | 'scheduled'
export interface GeneratedReportRecord {
id: string
contactId: string
contactName: string
contactAvatar?: string
source?: GeneratedReportSource
dateRange: string
messageCount: number
generatedAt: string
@@ -59,6 +61,7 @@ export interface SaveGeneratedReportRequest {
contactId: string
contactName: string
contactAvatar?: string
source?: GeneratedReportSource
dateRange: string
messageCount: number
generatedAt: string
+2 -11
View File
@@ -1,4 +1,4 @@
import type { ScheduledReportRange, ScheduledReportExecutionStatus } from './scheduled-report'
import type { ScheduledReportRange, ScheduledReportExecution } from './scheduled-report'
export type ScheduledReportApiSchedule = {
type: 'daily'
@@ -55,13 +55,4 @@ export interface ScheduledReportApiUpdateRequest {
enabled?: boolean
}
export interface ScheduledReportApiExecution {
id: string
taskId: string
startedAt: string
finishedAt?: string
status: ScheduledReportExecutionStatus
error?: string
message?: string
scheduledSlot?: string
}
export type ScheduledReportApiExecution = ScheduledReportExecution
+312
View File
@@ -0,0 +1,312 @@
import type { ScheduledReportExecutionStage } from './scheduled-report'
export const SCHEDULED_REPORT_ERROR_CODES = [
'AI_CONTEXT_LIMIT',
'AI_QUOTA_EXCEEDED',
'AI_AUTH_INVALID',
'AI_PROVIDER_UNAVAILABLE',
'AI_TIMEOUT',
'DATABASE_UNAVAILABLE',
'CHAT_NOT_FOUND',
'NO_MESSAGES',
'REPORT_GENERATION_FAILED',
'REPORT_HISTORY_SAVE_FAILED',
'WECHAT_SEND_UNAVAILABLE',
'WECHAT_SEND_FAILED',
'WECHAT_AUTH_EXPIRED',
'UNKNOWN'
] as const
export type ScheduledReportErrorCode = (typeof SCHEDULED_REPORT_ERROR_CODES)[number]
export type ScheduledReportErrorSeverity = 'info' | 'warning' | 'error'
export interface ScheduledReportErrorDetails {
code: ScheduledReportErrorCode
stage: ScheduledReportExecutionStage
severity: ScheduledReportErrorSeverity
technicalMessage: string
userTitle: string
userMessage: string
suggestedAction: string
retryable: boolean
}
export interface ScheduledReportErrorInput {
error?: unknown
code?: unknown
status?: unknown
type?: unknown
stage?: ScheduledReportExecutionStage
}
const knownCodes = new Set<string>(SCHEDULED_REPORT_ERROR_CODES)
const asRecord = (value: unknown): Record<string, unknown> | undefined =>
value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined
const safeString = (value: unknown): string => {
if (value instanceof Error) return value.message
if (typeof value === 'string') return value
if (value === undefined || value === null) return ''
try {
return JSON.stringify(value)
} catch {
return String(value)
}
}
const redact = (value: string): string =>
value
.replace(/sk-[a-z0-9_-]+/gi, '***')
.replace(/Bearer\s+[A-Za-z0-9._~-]+/gi, 'Bearer [已隐藏]')
.slice(0, 1_000)
const legacyCode = (value: string): ScheduledReportErrorCode | undefined => {
const match = value.match(/^([a-z_]+):/i)?.[1]
switch (match) {
case 'wechat_not_ready':
return 'WECHAT_SEND_UNAVAILABLE'
case 'wechat_send_failed':
return 'WECHAT_SEND_FAILED'
case 'report_generation_failed':
return 'REPORT_GENERATION_FAILED'
case 'report_history_save_failed':
return 'REPORT_HISTORY_SAVE_FAILED'
default:
return undefined
}
}
const stageForCode = (code: ScheduledReportErrorCode): ScheduledReportExecutionStage => {
if (code.startsWith('AI_')) return 'ai'
if (code === 'DATABASE_UNAVAILABLE' || code === 'CHAT_NOT_FOUND' || code === 'NO_MESSAGES') {
return 'data'
}
if (code === 'REPORT_HISTORY_SAVE_FAILED') return 'persist'
if (code.startsWith('WECHAT_')) return 'send'
return 'report'
}
const messagesFor = (
code: ScheduledReportErrorCode
): Omit<ScheduledReportErrorDetails, 'code' | 'stage' | 'technicalMessage'> => {
switch (code) {
case 'AI_CONTEXT_LIMIT':
return {
severity: 'error',
userTitle: '日报生成失败',
userMessage: '今天的聊天内容较多,超过当前 AI 模型一次可以处理的内容长度。',
suggestedAction: '可以缩短日报范围,或更换支持更长上下文的模型。',
retryable: true
}
case 'AI_QUOTA_EXCEEDED':
return {
severity: 'error',
userTitle: '日报生成失败',
userMessage: '当前 AI 服务额度不足,因此暂时无法生成日报。',
suggestedAction: '请检查 AI Provider 的账户额度,或切换其他可用模型。',
retryable: true
}
case 'AI_AUTH_INVALID':
return {
severity: 'error',
userTitle: 'AI 服务不可用',
userMessage: '当前 AI 服务的认证信息无效。',
suggestedAction: '请检查 API Key 或重新配置模型。',
retryable: true
}
case 'AI_PROVIDER_UNAVAILABLE':
return {
severity: 'error',
userTitle: 'AI 服务暂时不可用',
userMessage: 'AI 服务暂时无法响应,本次日报没有生成。',
suggestedAction: '稍后重新执行。',
retryable: true
}
case 'AI_TIMEOUT':
return {
severity: 'error',
userTitle: '日报生成超时',
userMessage: 'AI 服务在限定时间内没有完成响应,本次日报没有生成。',
suggestedAction: '稍后重新执行,或适当增加日报生成超时时间。',
retryable: true
}
case 'DATABASE_UNAVAILABLE':
return {
severity: 'error',
userTitle: '日报生成失败',
userMessage: 'TraceMemo 当前无法读取微信数据库,本次日报没有生成。',
suggestedAction: '请连接微信数据后重新执行。',
retryable: true
}
case 'CHAT_NOT_FOUND':
return {
severity: 'error',
userTitle: '日报生成失败',
userMessage: '没有找到任务配置的目标群聊。',
suggestedAction: '请检查群聊配置后重新执行。',
retryable: false
}
case 'NO_MESSAGES':
return {
severity: 'warning',
userTitle: '没有可生成的日报',
userMessage: '所选时间范围内没有可总结的聊天消息。',
suggestedAction: '可以扩大日报范围,或稍后重新执行。',
retryable: true
}
case 'REPORT_HISTORY_SAVE_FAILED':
return {
severity: 'error',
userTitle: '日报保存失败',
userMessage: '日报已经生成,但保存到日报历史时失败。',
suggestedAction: '请检查磁盘空间和文件权限后重新执行。',
retryable: true
}
case 'WECHAT_SEND_UNAVAILABLE':
return {
severity: 'warning',
userTitle: '日报已生成,但未发送',
userMessage: '日报已经生成并保存,但当前个人微信发送能力不可用。',
suggestedAction: '恢复微信消息能力后,可以直接重新发送这份日报。',
retryable: true
}
case 'WECHAT_AUTH_EXPIRED':
return {
severity: 'warning',
userTitle: '日报已生成,微信登录已失效',
userMessage: '日报已经生成并保存,但个人微信登录凭证已失效。',
suggestedAction: '重新登录微信后,可以直接重新发送这份日报。',
retryable: true
}
case 'WECHAT_SEND_FAILED':
return {
severity: 'warning',
userTitle: '日报已生成,发送失败',
userMessage: '日报已经生成并保存,但发送到微信时失败。',
suggestedAction: '检查微信连接后重新发送。',
retryable: true
}
case 'REPORT_GENERATION_FAILED':
return {
severity: 'error',
userTitle: '日报生成失败',
userMessage: '日报生成过程中发生异常,本次日报没有生成。',
suggestedAction: '稍后重新执行;如果持续失败,请检查模型配置。',
retryable: true
}
case 'UNKNOWN':
return {
severity: 'error',
userTitle: '定时日报执行失败',
userMessage: '本次定时日报执行失败。',
suggestedAction: '查看详情并稍后重新执行。',
retryable: true
}
}
}
const inferCode = (
message: string,
stage: ScheduledReportExecutionStage,
input: ScheduledReportErrorInput
): ScheduledReportErrorCode => {
const explicit = safeString(input.code).trim().toUpperCase()
if (knownCodes.has(explicit)) return explicit as ScheduledReportErrorCode
const legacy = legacyCode(message)
if (legacy) return legacy
const status = Number(input.status)
const type = safeString(input.type).toLowerCase()
const lower = message.toLowerCase()
if (
/context.{0,30}(length|limit|window)|maximum.{0,20}(context|token)|too many tokens|prompt.{0,20}long|input.{0,20}token|上下文|超出.*长度|token.*超限/.test(
lower
)
)
return 'AI_CONTEXT_LIMIT'
if (
/quota|insufficient[_ -]?quota|billing|credit|额度|余额|付费|rate.?limit|too many requests/.test(
lower
) ||
status === 402
)
return 'AI_QUOTA_EXCEEDED'
if (
status === 401 ||
status === 403 ||
/invalid api key|incorrect api key|authentication|unauthorized|api key.*invalid|认证信息|密钥无效/.test(
lower
)
)
return stage === 'send' ? 'WECHAT_AUTH_EXPIRED' : 'AI_AUTH_INVALID'
if (/timeout|timed out|etimedout|超时/.test(lower)) {
return stage === 'send' ? 'WECHAT_SEND_FAILED' : 'AI_TIMEOUT'
}
if (/database|db unavailable|数据库|数据库未|wcdb/.test(lower)) return 'DATABASE_UNAVAILABLE'
if (/no messages|没有.*消息|没有可总结|消息为空/.test(lower)) return 'NO_MESSAGES'
if (/chat.*not found|group.*not found|没有找到群|未找到群|不是群聊/.test(lower))
return 'CHAT_NOT_FOUND'
if (stage === 'persist' || /history|日报历史|保存.*日报/.test(lower))
return 'REPORT_HISTORY_SAVE_FAILED'
if (stage === 'send' || /wechat|微信|connector|发送/.test(lower)) return 'WECHAT_SEND_FAILED'
if (
stage === 'ai' &&
(status >= 500 || /fetch failed|econnrefused|enotfound|network|unavailable|service/.test(lower))
)
return 'AI_PROVIDER_UNAVAILABLE'
if (stage === 'ai') return 'REPORT_GENERATION_FAILED'
if (type.includes('provider') || status >= 500) return 'AI_PROVIDER_UNAVAILABLE'
return 'UNKNOWN'
}
export function normalizeScheduledReportError(
input: unknown,
fallbackStage: ScheduledReportExecutionStage = 'report'
): ScheduledReportErrorDetails {
const record = asRecord(input)
const source = (record && 'error' in record ? record.error : input) as unknown
const sourceRecord = asRecord(source)
const message = safeString(
sourceRecord?.message || sourceRecord?.error || sourceRecord?.detail || source
)
const details: ScheduledReportErrorInput = {
error: source,
code: record?.code || sourceRecord?.code,
status: record?.status || sourceRecord?.status,
type: record?.type || sourceRecord?.type,
stage: (record?.stage || fallbackStage) as ScheduledReportExecutionStage
}
const stage = details.stage || fallbackStage
const code = inferCode(message, stage, details)
const copy = messagesFor(code)
return {
code,
stage: code === 'UNKNOWN' ? stage : stageForCode(code),
technicalMessage: redact(message || '未知错误'),
...copy
}
}
export function legacyScheduledReportError(
code: ScheduledReportErrorCode,
message: string
): string {
const prefix: Record<ScheduledReportErrorCode, string> = {
AI_CONTEXT_LIMIT: 'report_generation_failed',
AI_QUOTA_EXCEEDED: 'report_generation_failed',
AI_AUTH_INVALID: 'report_generation_failed',
AI_PROVIDER_UNAVAILABLE: 'report_generation_failed',
AI_TIMEOUT: 'report_generation_failed',
DATABASE_UNAVAILABLE: 'report_generation_failed',
CHAT_NOT_FOUND: 'report_generation_failed',
NO_MESSAGES: 'report_generation_failed',
REPORT_GENERATION_FAILED: 'report_generation_failed',
REPORT_HISTORY_SAVE_FAILED: 'report_history_save_failed',
WECHAT_SEND_UNAVAILABLE: 'wechat_not_ready',
WECHAT_SEND_FAILED: 'wechat_send_failed',
WECHAT_AUTH_EXPIRED: 'wechat_send_failed',
UNKNOWN: 'scheduled_report_failed'
}
return `${prefix[code]}:${message}`
}
+91 -1
View File
@@ -10,7 +10,79 @@ export type ScheduledReportMessageType =
| 'share'
| 'system'
export type ScheduledReportMemberNameMode = 'groupNickname' | 'wechatNickname' | 'remark'
export type ScheduledReportExecutionStatus = 'running' | 'success' | 'failed'
export type ScheduledReportExecutionStatus =
| 'running'
| 'success'
| 'waiting_to_send'
| 'partial_success'
| 'failed'
| 'waiting_for_recovery'
| 'skipped'
export type ScheduledReportExecutionStage =
| 'precheck'
| 'data'
| 'ai'
| 'report'
| 'persist'
| 'send'
| 'notify'
export type ScheduledReportSendStatus = 'pending' | 'success' | 'failed' | 'unavailable'
export type ScheduledReportNotificationStatus =
| 'pending'
| 'sent'
| 'failed'
| 'not_needed'
| 'suppressed'
export type ScheduledReportNotificationType = 'failure' | 'partial_success' | 'recovery'
export type ScheduledReportNotificationSeverity = 'info' | 'warning' | 'error'
export type ScheduledReportNotificationDeliveryStatus = 'pending' | 'sent' | 'failed' | 'suppressed'
export type ScheduledReportNotificationCapabilityReason =
| 'agent_hub_offline'
| 'connector_offline'
| 'recipient_not_bound'
| 'send_failed'
| 'settings_persist_failed'
export interface ScheduledReportNotificationSettings {
enabled: boolean
}
export interface ScheduledReportNotificationSettingsResult {
success: boolean
data: ScheduledReportNotificationSettings
reason?: ScheduledReportNotificationCapabilityReason
error?: string
}
export interface ScheduledReportNotificationCapability {
ready: boolean
recipient?: string
reason?: ScheduledReportNotificationCapabilityReason
error?: string
}
export interface ScheduledReportNotification {
id: string
executionId: string
taskId: string
type: ScheduledReportNotificationType
severity: ScheduledReportNotificationSeverity
title: string
message: string
dedupeKey: string
channel: 'agent_hub'
recipient?: string
status: ScheduledReportNotificationDeliveryStatus
createdAt: string
sentAt?: string
attempts: number
lastError?: string
suppressedAt?: string
}
export interface ScheduledReportTask {
id: string
@@ -37,12 +109,30 @@ export interface ScheduledReportTask {
export interface ScheduledReportExecution {
id: string
taskId: string
/** Missing on old executions; normalized reads treat them as scheduled runs. */
triggerType?: 'scheduled' | 'manual'
startedAt: string
finishedAt?: string
status: ScheduledReportExecutionStatus
error?: string
message?: string
scheduledSlot?: string
currentStage?: ScheduledReportExecutionStage
failedStage?: ScheduledReportExecutionStage
errorCode?: string
technicalMessage?: string
userTitle?: string
userMessage?: string
suggestedAction?: string
retryable?: boolean
retryCount?: number
reportId?: string
htmlPath?: string
pngPath?: string
sendTarget?: string
sendStatus?: ScheduledReportSendStatus
sendError?: string
notificationStatus?: ScheduledReportNotificationStatus
}
export interface ScheduledReportCreateInput {