diff --git a/src/main/services/automation-action-runner.ts b/src/main/services/automation-action-runner.ts index ad5229d..ad1ff2e 100644 --- a/src/main/services/automation-action-runner.ts +++ b/src/main/services/automation-action-runner.ts @@ -337,6 +337,19 @@ export class AutomationActionRunner { return { steps, status: 'failed', errorSummary: reportStep.error } } pngPath = result.pngPath + const persisted = await this.persistRunReport(input, result) + if (persisted.ok) { + // 发出去的图就是日报历史里的那一份(同一文件),避免「历史一张、发出去另一张」。 + pngPath = persisted.pngPath || pngPath + } else { + /* + * 落库失败**不阻断发送**:日报确实生成了、图片已经在手上,把它扣下不发对用户没有任何好处。 + * 但也**绝不假装没事** —— 失败会写进步骤细节,用户在执行详情里一眼能看见。 + * 细节文案刻意不带原始错误串(fs 报错常含本地绝对路径),原始错误只进主进程日志。 + */ + reportStep.detail = '日报已生成,但未写入日报历史。' + console.warn('[Automation] 日报历史写入失败:', persisted.error) + } markSuccess(reportStep, this.now()) } @@ -369,6 +382,61 @@ export class AutomationActionRunner { return { steps, status: 'success', pngPath } } + /** + * 把「@我生成日报」产出的日报写进**日报历史**。 + * + * 与定时日报共用同一个 `saveGeneratedReport`(同一条历史、同一个日报页), + * 唯一差别是 `source: 'automation'` —— 让用户能区分这条日报是谁触发的。 + * + * 为什么必须在这里补:`run()` 只把 PNG 交给发送,图发出去之后**没有任何地方** + * 再碰这份日报。此前只有 `runScheduledReport` 落库,于是消息型规则产出的日报 + * 在日报历史里**从来没存在过**(发出去的那张图成了孤儿)。 + * + * 失败语义与 `runScheduledReport` **刻意不同**:那边发的是历史里的文件、落库是发送的前置, + * 所以落库失败即整次失败;这里图片已经在手上,落库失败只降级成一句提示,不阻断发送。 + */ + private async persistRunReport( + input: AutomationRunInput, + generated: AgentGroupReportResult + ): Promise<{ ok: boolean; error?: string; pngPath?: string }> { + try { + const reportContact = this.resolveReportContact(input.conversationId) + let contactAvatar = reportContact?.avatar + if (!contactAvatar && reportContact?.m_nsUsrName) { + try { + const avatars = await this.getContactAvatars([reportContact.m_nsUsrName]) + contactAvatar = avatars[reportContact.m_nsUsrName] + } catch (error) { + console.warn('[Automation] 日报群头像补全失败:', error) + } + } + const saved = await this.saveGeneratedReport({ + contactId: reportContact?.md5 || input.conversationId, + contactName: + generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊', + contactAvatar, + source: 'automation', + dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel('today'), + reportDate: generated.reportMetadata?.reportDate, + messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0, + generatedAt: new Date(this.now()).toISOString(), + htmlPath: generated.htmlPath, + pngPath: generated.pngPath, + duration: generated.duration, + modelName: generated.modelName, + tokenUsage: generated.tokenUsage, + reportSnapshot: generated.reportSnapshot, + reportMetadata: generated.reportMetadata + }) + if (!saved.success) { + return { ok: false, error: saved.error || '日报历史保存失败' } + } + return { ok: true, ...(saved.record?.pngPath ? { pngPath: saved.record.pngPath } : {}) } + } catch (error) { + return { ok: false, error: error instanceof Error ? error.message : String(error) } + } + } + /** * 定时日报:把一次「到点触发 / 手动立即执行」跑成一次生成 + 一次发送。 * diff --git a/src/renderer/src/features/logs/LogsWorkspace.tsx b/src/renderer/src/features/logs/LogsWorkspace.tsx index 36602d3..dfde556 100644 --- a/src/renderer/src/features/logs/LogsWorkspace.tsx +++ b/src/renderer/src/features/logs/LogsWorkspace.tsx @@ -13,7 +13,12 @@ import { } from '../../components/ui' type StatusFilter = 'all' | WechatActionStatus -type PurposeFilter = 'all' | 'leave_notification' | 'scheduled_report' | 'other' +type PurposeFilter = + | 'all' + | 'leave_notification' + | 'scheduled_report' + | 'automation_report' + | 'other' /** * 「退群通知」的发送用途。 @@ -32,7 +37,10 @@ const LEAVE_NOTIFICATION_PURPOSES: readonly string[] = [ const sourceLabel = (source: ActionLogEntry['source']): string => { if (source === 'member_monitor') return '退群监控' if (source === 'scheduled_report') return '定时日报' + // 消息型自动化「@我生成日报」发出的动作。少了这一条会直接显示英文原文 `automation`。 + if (source === 'automation') return '自动化' if (source === 'user_tts') return '文字转语音' + if (source === 'user_manual') return '手动发送' if (source === 'unknown') return '未知来源' return source || '未知来源' } @@ -40,9 +48,21 @@ const sourceLabel = (source: ActionLogEntry['source']): string => { const triggerLabel = (triggerType: ActionLogEntry['triggerType']): string => triggerType === 'user' ? '用户触发' : '自动化' +/** + * purpose → 中文。 + * + * **每一个有生产者的 purpose 都必须在这里有分支**:`WechatActionPurpose` 是字符串联合, + * 漏掉谁,那类记录就会顶着英文原文出现在列表里(筛选项里也找不到对应项)—— + * 「@我生成日报」的发送记录此前就是这样被用户当成"压根没有"的。 + * 未知值仍回落到原文,好让将来新增 purpose 时一眼能看出漏了映射。 + */ const purposeLabel = (purpose: WechatActionPurpose): string => { if (LEAVE_NOTIFICATION_PURPOSES.includes(purpose)) return '退群通知' if (purpose === 'scheduled_report') return '定时日报' + if (purpose === 'automation_report') return '生成日报(@我)' + if (purpose === 'automation_reply') return '回复确认(@我)' + if (purpose === 'manual_report_image') return '日报图片(手动发送)' + if (purpose === 'manual_report_postfix') return '日报后置词(手动发送)' if (purpose === 'tts_voice') return '文字转语音' return purpose || '其它动作' } @@ -65,8 +85,11 @@ const statusDetails = (entry: ActionLogEntry): { label: string; className: strin const matchesPurpose = (entry: ActionLogEntry, filter: PurposeFilter): boolean => { if (filter === 'all') return true if (filter === 'other') { + // 「其它动作」= 剩下的。独立筛选项必须在这里排掉,否则同一条记录会同时出现在两组里。 return ( - !LEAVE_NOTIFICATION_PURPOSES.includes(entry.purpose) && entry.purpose !== 'scheduled_report' + !LEAVE_NOTIFICATION_PURPOSES.includes(entry.purpose) && + entry.purpose !== 'scheduled_report' && + entry.purpose !== 'automation_report' ) } if (filter === 'leave_notification') { @@ -154,6 +177,7 @@ export function LogsWorkspace(): React.ReactElement { 全部类型 退群通知 定时日报 + 生成日报(@我) 其它动作 diff --git a/src/shared/report-history.ts b/src/shared/report-history.ts index 88626aa..52e378a 100644 --- a/src/shared/report-history.ts +++ b/src/shared/report-history.ts @@ -7,7 +7,17 @@ import type { ReportTemplateSelectionId } from './report-templates' import type { ReportTemplateRef } from './report-template-package' export type ReportAssetStatus = 'ready' | 'missing' -export type GeneratedReportSource = 'manual' | 'scheduled' +/** + * 日报的产出方式。 + * + * - `manual`:用户在日报页手动生成; + * - `scheduled`:定时日报(自动化里的时间驱动规则); + * - `automation`:消息型自动化「@我生成日报」触发产出。 + * + * 三种都写进**同一条日报历史**(`report-history-service` 是唯一出口), + * 这个字段只用于区分「谁触发的」,不参与任何可见性判断。 + */ +export type GeneratedReportSource = 'manual' | 'scheduled' | 'automation' export interface GeneratedReportRecord { id: string diff --git a/tests/unit/automation-action-runner.test.ts b/tests/unit/automation-action-runner.test.ts index d334f8e..3584d23 100644 --- a/tests/unit/automation-action-runner.test.ts +++ b/tests/unit/automation-action-runner.test.ts @@ -24,6 +24,10 @@ import { type AutomationStepKey } from '../../src/shared/automation' import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action' +import type { + SaveGeneratedReportRequest, + SaveGeneratedReportResult +} from '../../src/shared/report-history' import { AutomationActionRunner } from '../../src/main/services/automation-action-runner' import type { AgentGroupReportResult } from '../../src/main/services/agent-group-report-service' @@ -87,13 +91,16 @@ function buildRunner(options: { executeAction?: (request: WechatActionRequest) => Promise generateReport?: () => Promise delay?: (ms: number) => Promise + saveGeneratedReport?: (request: SaveGeneratedReportRequest) => Promise }): { runner: AutomationActionRunner calls: WechatActionRequest[] reports: Array<{ group: string; range?: string }> + saved: SaveGeneratedReportRequest[] } { const calls: WechatActionRequest[] = [] const reports: Array<{ group: string; range?: string }> = [] + const saved: SaveGeneratedReportRequest[] = [] const runner = new AutomationActionRunner({ now: fakeClock(), delay: options.delay ?? noDelay, @@ -104,9 +111,18 @@ function buildRunner(options: { generateReport: async (request) => { reports.push({ group: request.group, ...(request.range ? { range: request.range } : {}) }) return options.generateReport ? options.generateReport() : { success: true, pngPath: '/tmp/report.png' } + }, + /* + * 默认**不落盘**:真实的 `saveGeneratedReport` 会往 electron 提供的 userData + * 前缀(本文件 mock 成 `/tmp/wxe-automation-runner-fixture`)下写 json, + * 单测不该产生文件副作用。落库的磁盘语义由 `report-history-service.test.ts` 覆盖。 + */ + saveGeneratedReport: async (request) => { + saved.push(request) + return options.saveGeneratedReport ? options.saveGeneratedReport(request) : { success: true } } }) - return { runner, calls, reports } + return { runner, calls, reports, saved } } const run = ( @@ -201,6 +217,42 @@ describe('AutomationActionRunner', () => { expect(calls[0].content.type).toBe('text') }) + /* + * 「@我生成日报」产出的日报必须落进**日报历史**。 + * + * 这一条是回归防线:`run()` 曾经只把 PNG 交给发送、从不落库,于是图发出去了、 + * 日报历史里却永远查不到(用户报的"执行成功但历史里没有"就是这个)。 + */ + it('生成日报后把日报写进日报历史,来源标为 automation', async () => { + const { runner, saved } = buildRunner({}) + const result = await run(runner, makeRule()) + + expect(statusOf(result, 'report')).toBe('success') + expect(saved).toHaveLength(1) + expect(saved[0].source).toBe('automation') + expect(saved[0].contactId).toBe(GROUP_ID) + expect(saved[0].pngPath).toBe('/tmp/report.png') + expect(saved[0].generatedAt).toBeTruthy() + }) + + /* + * 落库失败**不阻断发送**(图片已经在手上,扣下不发对用户没有任何好处), + * 但**也不能假装没事** —— 失败必须写进步骤细节,用户在执行详情里看得见。 + */ + it('日报历史写入失败时照常发送,但把失败如实写进步骤细节', async () => { + const { runner, saved, calls } = buildRunner({ + saveGeneratedReport: async () => ({ success: false, error: 'ENOSPC: no space left' }) + }) + const result = await run(runner, makeRule()) + + expect(saved).toHaveLength(1) + expect(statusOf(result, 'report')).toBe('success') + expect(statusOf(result, 'send')).toBe('success') + expect(result.status).toBe('success') + expect(result.steps.find((step) => step.key === 'report')?.detail).toContain('未写入日报历史') + expect(calls.some((call) => call.purpose === AUTOMATION_SEND_PURPOSE.report)).toBe(true) + }) + it('生成日报抛异常时同样记 failed 并跳过发送', async () => { const { runner } = buildRunner({ generateReport: async () => {