From 515348b6d8fa8f616b9de4c712df91fa7d2d88c1 Mon Sep 17 00:00:00 2001 From: Wxw-Gu Date: Wed, 15 Jul 2026 16:29:25 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84=E7=BE=A4=E8=81=8A?= =?UTF-8?q?=E6=97=A5=E6=8A=A5=E6=A8=A1=E6=9D=BF=E4=B8=8E=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E7=90=86=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + resources/mobile_daily_report.html | 59 ++ resources/mobile_daily_report_v1.html | 592 +++++++++++++ resources/mobile_daily_report_v2.html | 829 ++++++++++++++++++ src/main/db/image-insights-store.ts | 101 +++ src/main/group-report-service.ts | 114 ++- src/main/image-decrypt-service.ts | 37 +- src/main/index.ts | 106 ++- src/main/services/ai-provider-service.ts | 102 ++- src/main/services/chat-service.ts | 12 +- src/main/services/image-insight-prompt.ts | 94 ++ src/main/services/image-insight-service.ts | 279 ++++++ src/main/wcdb4-client.ts | 32 +- src/preload/index.d.ts | 30 +- src/preload/index.ts | 26 +- src/renderer/src/App.tsx | 15 +- src/renderer/src/assets/main.css | 219 +++++ src/renderer/src/components/ChatWindow.tsx | 577 +++--------- .../components/reports/AiReportWorkspace.tsx | 45 +- .../reports/ReportMemberNameSelector.tsx | 61 ++ .../reports/ReportTemplateSelector.tsx | 139 +++ .../settings/ai-model/AIProviderEditor.tsx | 24 +- .../src/features/settings/ai-model/presets.ts | 2 +- .../src/hooks/useGroupReportGeneration.ts | 120 ++- src/renderer/src/utils/group-report-facts.ts | 190 +++- src/renderer/src/utils/group-report.ts | 310 ++++++- src/shared/ai-provider.ts | 7 + src/shared/group-report.ts | 29 + src/shared/image-insight.ts | 110 +++ 29 files changed, 3702 insertions(+), 560 deletions(-) create mode 100644 resources/mobile_daily_report_v1.html create mode 100644 resources/mobile_daily_report_v2.html create mode 100644 src/main/db/image-insights-store.ts create mode 100644 src/main/services/image-insight-prompt.ts create mode 100644 src/main/services/image-insight-service.ts create mode 100644 src/renderer/src/components/reports/ReportMemberNameSelector.tsx create mode 100644 src/renderer/src/components/reports/ReportTemplateSelector.tsx create mode 100644 src/shared/image-insight.ts diff --git a/.gitignore b/.gitignore index 5312024..d196c22 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules +*.tsbuildinfo dist out .env diff --git a/resources/mobile_daily_report.html b/resources/mobile_daily_report.html index 40d35e4..9962a6c 100644 --- a/resources/mobile_daily_report.html +++ b/resources/mobile_daily_report.html @@ -495,6 +495,60 @@ grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } + /* AI 图片识别板块 */ + .vision-card { + display: grid; + grid-template-columns: 132px 1fr; + gap: 14px; + margin-top: 10px; + padding: 12px; + background: linear-gradient(135deg, #edf9f1 0%, #f7fbf8 100%); + border: 1px solid #d6efde; + border-radius: 14px; + } + .vision-image { + width: 132px; + height: 132px; + border-radius: 12px; + object-fit: cover; + background: #e5e7eb; + } + .vision-description { + margin-top: 6px; + font-size: 13px; + line-height: 1.5; + color: #1f2933; + } + .vision-ocr { + margin-top: 6px; + padding: 6px 10px; + background: #eef5ff; + color: #1677ff; + font-size: 11px; + border-radius: 8px; + word-break: break-all; + } + .vision-tags { + margin-top: 8px; + display: flex; + flex-wrap: wrap; + gap: 4px; + } + .vision-tag { + display: inline-block; + padding: 3px 8px; + background: #07c160; + color: #fff; + font-size: 10px; + font-weight: 700; + border-radius: 999px; + } + .vision-label { + margin-top: 6px; + font-size: 10px; + color: #07a352; + font-weight: 600; + } .badge-card { background: linear-gradient(180deg, #fdfdfd 0%, #f6fbf8 100%); border: 1px solid #edf0f2; @@ -742,6 +796,11 @@ {{REVERSALS_MORE_NOTE}} +
+
{{VISION_TITLE}}
+ {{VISION_CARDS}} +
+
今日群相册
{{GALLERY_CARDS}} diff --git a/resources/mobile_daily_report_v1.html b/resources/mobile_daily_report_v1.html new file mode 100644 index 0000000..e80e5cb --- /dev/null +++ b/resources/mobile_daily_report_v1.html @@ -0,0 +1,592 @@ + + + + + + {{REPORT_TITLE}} + + + +
+
+
+
+

{{GROUP_NAME}}日报

+
+
{{DATE_RANGE}}
+
{{RECORD_NOTE}}
+
{{OVERVIEW}}
+
+
+
{{HERO_AVATARS}}
+
+
+
{{MESSAGE_COUNT}}消息数
+
{{ACTIVE_USERS}}活跃人数
+
{{TIME_SPAN}}持续时长
+
{{TOPIC_COUNT}}主要话题
+
+
+ +
+
今日讨论热点
+ {{TOPIC_CARDS}} +
+ +
+
{{VISION_TITLE}}
+ {{VISION_CARDS}} +
+ +
+
实用信息与资源
+ {{RESOURCE_ITEMS}} +
+ +
+
重要消息汇总
+ {{IMPORTANT_MESSAGES}} +
+ +
+
有趣对话或金句
+ {{QUOTE_BLOCKS}} +
+ +
+
问题与解答
+ {{QA_CARDS}} +
+ +
+
群内数据可视化
+ {{HEAT_BARS}} +
+
+ 话唠榜 TOP5(基于已读取记录估算) +
+ {{RANK_ITEMS}} +
+
+

活跃时间线:{{ACTIVITY_TIMELINE}}

+
+
+ +
+
词云/关键词
+
{{CLOUD_TAGS}}
+
+ +
+ 数据来源:WechatExplorer · 微信群聊记录
+ 生成时间:{{GENERATED_AT}}
+ {{FOOTER_NOTE}} +
+
+ + diff --git a/resources/mobile_daily_report_v2.html b/resources/mobile_daily_report_v2.html new file mode 100644 index 0000000..38d173d --- /dev/null +++ b/resources/mobile_daily_report_v2.html @@ -0,0 +1,829 @@ + + + + + + {{REPORT_TITLE}} + + + +
+
+
+
+

{{GROUP_NAME}}日报

+
{{DATE_RANGE}}
{{RECORD_NOTE}}
+
+
{{HERO_AVATARS}}
+
+
+ {{HERO_HEADLINE}} +

{{HERO_SUMMARY}}

+
+
{{HERO_STATUS_LINE}}
+
+
{{HERO_TAKEAWAY}}
+
{{HERO_PENDING}}
+
+
+
{{MESSAGE_COUNT}}消息数
+
{{ACTIVE_USERS}}活跃人数
+
{{TOPIC_COUNT}}话题数
+
{{MEDIA_COUNT}}媒体消息
+
+
+ +
+
今日讨论热点
+ {{TOPIC_CARDS}} + {{TOPICS_MORE_NOTE}} +
+ +
+
重要消息
+ {{IMPORTANT_MESSAGES}} + {{MESSAGES_MORE_NOTE}} +
+ +
+
待办事项和未解决问题
+
待办事项
+
{{TODO_CARDS}}
+
尚未解决
+
{{UNRESOLVED_CARDS}}
+ {{ACTIONS_MORE_NOTE}} +
+ +
+
今日名场面
+ {{QUOTE_BLOCKS}} + {{QUOTES_MORE_NOTE}} +
+ +
+
今日群数据
+
+
+
话唠榜 TOP5
+ {{RANK_ITEMS}} +
+
+

最活跃时段:{{ACTIVITY_TIMELINE}}

+

今日状态:形成 {{CONCLUSION_COUNT}} 个结论,待办 {{TODO_COUNT}} 项,未解决 {{UNRESOLVED_COUNT}} 项。

+
+
+
+ +
+
关键词
+
{{CLOUD_TAGS}}
+ {{KEYWORDS_MORE_NOTE}} +
+ +
+
实用信息与资源
+ {{RESOURCE_ITEMS}} + {{RESOURCES_MORE_NOTE}} +
+ +
+
问题与解答
+ {{QA_CARDS}} + {{QA_MORE_NOTE}} +
+ +
+
今日剧情时间线
+ {{STORYLINE_CARDS}} + {{STORYLINES_MORE_NOTE}} +
+ +
+
群聊反转现场
+ {{REVERSAL_CARDS}} + {{REVERSALS_MORE_NOTE}} +
+ +
+
{{VISION_TITLE}}
+ {{VISION_CARDS}} +
+ +
+
今日群相册
+ {{GALLERY_CARDS}} + {{GALLERY_MORE_NOTE}} +
+ +
+
语音之最
+ {{VOICE_CARDS}} + {{VOICE_MORE_NOTE}} +
+ +
+
语音时长榜
+
{{VOICE_RANK_CARDS}}
+
+ +
+
今日临时人设
+
{{BADGE_CARDS}}
+ {{BADGES_MORE_NOTE}} +
+ +
+
话题参与链路
+ {{CHAIN_CARDS}} + {{CHAINS_MORE_NOTE}} +
+ +
+ 数据来源:WechatExplorer · 微信群聊记录
+ 生成时间:{{GENERATED_AT}}
+ {{FOOTER_NOTE}} +
+
+ + diff --git a/src/main/db/image-insights-store.ts b/src/main/db/image-insights-store.ts new file mode 100644 index 0000000..c9220d1 --- /dev/null +++ b/src/main/db/image-insights-store.ts @@ -0,0 +1,101 @@ +// src/main/db/image-insights-store.ts +// 持久化 ImageInsight 到 JSON 文件(userData/image-insights.json) +// 跟项目现有风格一致(ai-provider-service 用 ai-providers.json) + +import { app } from 'electron' +import fs from 'fs-extra' +import path from 'path' +import type { ImageInsight } from '../../shared/image-insight' + +interface ImageInsightsFile { + version: 1 + /** imageHash -> ImageInsight 索引(缓存查询 O(1)) */ + byHash: Record + /** messageId -> imageHash 反向索引(防止同一 message 重复入库) */ + byMessageId: Record +} + +const EMPTY_FILE: ImageInsightsFile = { + version: 1, + byHash: {}, + byMessageId: {} +} + +class ImageInsightsStore { + private cache: ImageInsightsFile | null = null + + private get filePath(): string { + return path.join(app.getPath('userData'), 'image-insights.json') + } + + private ensureLoaded(): ImageInsightsFile { + if (this.cache) return this.cache + try { + if (fs.existsSync(this.filePath)) { + const raw = fs.readJsonSync(this.filePath) as Partial + this.cache = { + version: 1, + byHash: raw.byHash || {}, + byMessageId: raw.byMessageId || {} + } + return this.cache + } + } catch (error) { + console.warn('[ImageInsightsStore] failed to load, fallback to empty:', error) + } + this.cache = { ...EMPTY_FILE } + return this.cache + } + + private persist(): void { + if (!this.cache) return + try { + fs.ensureDirSync(path.dirname(this.filePath)) + fs.writeJsonSync(this.filePath, this.cache, { spaces: 2 }) + } catch (error) { + console.error('[ImageInsightsStore] failed to persist:', error) + } + } + + /** 通过 imageHash 查询缓存 */ + getByHash(imageHash: string): ImageInsight | null { + return this.ensureLoaded().byHash[imageHash] || null + } + + /** 列出某会话的所有 insights(按时间倒序) */ + listBySession(sessionId: string, limit?: number): ImageInsight[] { + const data = this.ensureLoaded() + const items = Object.values(data.byHash) + .filter((it) => it.sessionId === sessionId) + .sort((a, b) => b.sentAt - a.sentAt) + return typeof limit === 'number' ? items.slice(0, limit) : items + } + + /** + * 写入或更新 Insight。 + * - 同 imageHash 已存在:更新 description/ocrText/tags/category/importance/provider/model/updatedAt(保留 createdAt) + * - 新 hash:插入 + * 同步维护 byMessageId 反向索引。 + */ + upsert(insight: ImageInsight): void { + const data = this.ensureLoaded() + const existing = data.byHash[insight.imageHash] + const now = Date.now() + if (existing) { + data.byHash[insight.imageHash] = { + ...existing, + ...insight, + id: existing.id, // 保留 id + createdAt: existing.createdAt, // 保留首次分析时间 + updatedAt: now + } + } else { + data.byHash[insight.imageHash] = { ...insight, createdAt: now, updatedAt: now } + data.byMessageId[insight.messageId] = insight.imageHash + } + this.persist() + } + +} + +export const imageInsightsStore = new ImageInsightsStore() diff --git a/src/main/group-report-service.ts b/src/main/group-report-service.ts index 203ce96..8f79818 100644 --- a/src/main/group-report-service.ts +++ b/src/main/group-report-service.ts @@ -6,11 +6,29 @@ import { GroupReportExportRequest, GroupReportExportResult, GroupReportMetadata, - ReportHeat + ReportHeat, + ReportSectionMeta } from '../shared/group-report' import { resolveMd5, getGroupSnapshot } from './services/chat-service' +import { imageInsightService } from './services/image-insight-service' -const TEMPLATE_NAME = 'mobile_daily_report.html' +const TEMPLATE_FILES: Record = { + v1: 'mobile_daily_report_v1.html', + v2: 'mobile_daily_report_v2.html' +} +const DEFAULT_TEMPLATE = TEMPLATE_FILES.v1 + +const templatePath = (templateId?: string): string => { + const name = TEMPLATE_FILES[templateId || ''] || DEFAULT_TEMPLATE + const candidates = [ + path.join(process.resourcesPath, 'resources', name), + path.join(app.getAppPath(), 'resources', name), + path.join(process.cwd(), 'resources', name) + ] + const found = candidates.find((candidate) => fs.existsSync(candidate)) + if (!found) throw new Error(`日报模板不存在: ${candidates.join(' | ')}`) + return found +} const escapeHtml = (value: unknown): string => String(value ?? '') @@ -75,17 +93,6 @@ const embedAvatar = async (source: string | undefined, name: string): Promise { - const candidates = [ - path.join(process.resourcesPath, 'resources', TEMPLATE_NAME), - path.join(app.getAppPath(), 'resources', TEMPLATE_NAME), - path.join(process.cwd(), 'resources', TEMPLATE_NAME) - ] - const found = candidates.find((candidate) => fs.existsSync(candidate)) - if (!found) throw new Error(`日报模板不存在: ${candidates.join(' | ')}`) - return found -} - /** * 从群成员快照反推真头像,填进 metadata.avatars。 * - 没传 talker → 跳过(向后兼容) @@ -138,13 +145,10 @@ const heatClass = (heat: ReportHeat): string => { const replacePlaceholder = (html: string, key: string, value: string): string => html.replaceAll(`{{${key}}}`, value) -const modeLabel = (mode: GroupReportMetadata['reportMode']): string => - mode === 'full' ? '完整版' : '精简版' - const sectionMeta = ( request: GroupReportExportRequest, key: keyof NonNullable -) => request.report.sectionMeta?.[key] +): ReportSectionMeta | undefined => request.report.sectionMeta?.[key] const sectionClass = ( request: GroupReportExportRequest, @@ -205,8 +209,25 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise热点图片
${escapeHtml(topic.image.note)}
` + topic.image + ? (() => { + // 优先用已有 imageUrl;若有 imageHash(来自 visionGallery),按 hash 取原图 + let imageUrl = topic.image.imageUrl + if (!imageUrl && topic.image.imageHash) { + const insight = imageInsightService.getInsight(topic.image.imageHash) + if (insight) { + // insight 不含 imageUrl,需要按 md5/datName 重新拿;这里通过 ImageDecryptService 间接获取 + // 走 ImageDecryptService.findImageFile + decryptImageToBase64 + const decryptService = (globalThis as { __imageDecrypt?: { findImageFile: (md5?: string, dat?: string) => string | null; decryptImageToBase64: (p: string) => string | null } }).__imageDecrypt + if (decryptService) { + const filePath = decryptService.findImageFile(insight.md5, insight.datName) + if (filePath) imageUrl = decryptService.decryptImageToBase64(filePath) || undefined + } + } + } + if (!imageUrl) return '' + return `
热点图片
${escapeHtml(topic.image.note)}
` + })() : '' }
${topic.participants @@ -325,6 +346,24 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise item.imageUrl) // 只显示加载成功的图 + .map( + (item) => `
+ AI 识别的图片 +
+
${escapeHtml(item.sender)}${escapeHtml(item.time)}
+
${escapeHtml(item.description)}
+ ${item.ocrText ? `
📝 ${escapeHtml(item.ocrText)}
` : ''} + ${item.tags.length ? `
${item.tags.map((t) => `${escapeHtml(t)}`).join('')}
` : ''} +
AI 图片识别
+
+
` + ) + .join('') + const voiceCards = (report.media?.voiceHighlights || []) .map( (item) => `
@@ -362,6 +401,20 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise { + const count = Math.max(0, speaker.count) + const width = Math.min(100, count * 12) + return `
+ ${escapeHtml(speaker.name)} + + ${count} +
` + }) + .join('') + const cloudTags = report.keywords .slice(0, 15) .map( @@ -390,14 +443,16 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise = { REPORT_TITLE: escapeHtml(`${metadata.groupName}日报`), REPORT_MODE_CLASS: metadata.reportMode === 'full' ? 'full' : 'compact', GROUP_NAME: escapeHtml(metadata.groupName), DATE_RANGE: escapeHtml(metadata.dateRange), RECORD_NOTE: escapeHtml(metadata.recordNote), - REPORT_MODE_LABEL: escapeHtml(modeLabel(metadata.reportMode)), + // v1 模板使用的 OVERVIEW(经典版以概览段落呈现) + OVERVIEW: escapeHtml(report.overview || report.hero?.summary || '基于已读取聊天记录生成的群聊日报'), + // v2 模板使用的 hero-* HERO_HEADLINE: escapeHtml(report.hero?.headline || '今日群聊速览'), HERO_SUMMARY: escapeHtml(report.hero?.summary || report.overview), HERO_TAKEAWAY: escapeHtml(report.hero?.keyTakeaway || ''), @@ -442,6 +497,14 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise 0), CHAIN_CARDS: chainCards, CHAINS_MORE_NOTE: overflowNote(request, 'chains'), + // AI 图片识别板块 + VISION_EMPTY_CLASS: sectionClass( + request, + 'vision', + (report.media?.visionGallery?.length ?? 0) > 0 + ), + VISION_CARDS: visionCards, + VISION_TITLE: '📸 AI 识别的图片精选', GALLERY_EMPTY_CLASS: sectionClass(request, 'gallery', report.media?.gallery?.length > 0), GALLERY_CARDS: galleryCards, GALLERY_MORE_NOTE: overflowNote(request, 'gallery'), @@ -463,9 +526,13 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise allowThumbnail || !this.isThumbnailName(name)) + .map((name) => join(dir, name)) + .filter((candidate) => existsSync(candidate)) + .sort((left, right) => { + const leftThumb = this.isThumbnailName(basename(left)) ? 1 : 0 + const rightThumb = this.isThumbnailName(basename(right)) ? 1 : 0 + if (leftThumb !== rightThumb) return leftThumb - rightThumb + return statSync(right).size - statSync(left).size + }) + candidates.push(...siblings) + } + + for (const candidate of this.uniq(candidates)) { + const data = this.decryptImageToBase64(candidate) + if (data) return { data, filePath: candidate } + } + console.warn('[ImageDecrypt] all variants failed:', this.uniq(candidates)) + return null + } + /** * 检测 DAT 文件版本 */ @@ -485,7 +518,9 @@ export class ImageDecryptService { }) .sort((left, right) => right.size - left.size) - const nonThumb = toSized(paths.filter((candidate) => !this.isThumbnailName(basename(candidate)))) + const nonThumb = toSized( + paths.filter((candidate) => !this.isThumbnailName(basename(candidate))) + ) if (nonThumb[0]) return nonThumb[0].candidate if (!allowThumbnail) return null diff --git a/src/main/index.ts b/src/main/index.ts index 8965673..a39a1b9 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -37,6 +37,14 @@ import type { import { DatabaseKeyStore } from './database-key-store' import { ImageKeyConfigService } from './services/image-key-config-service' import { AIProviderService } from './services/ai-provider-service' +import { imageInsightService } from './services/image-insight-service' +import type { + ImageAnalysisRequest, + ImageAnalysisResponse, + ImageCandidate, + ImageCandidateQuery, + ImageInsight +} from '../shared/image-insight' import { KeyServiceMac } from './key-service-mac' import { KeyService as KeyServiceWin } from './key-service-win' import * as chat from './services/chat-service' @@ -475,20 +483,108 @@ app.whenReady().then(async () => { return { success: false, error: force ? '未找到原图或缩略图文件' : '未找到图片文件' } } - const base64 = imageDecryptService.decryptImageToBase64(filePath) - if (!base64) { + const decrypted = imageDecryptService.decryptImageToBase64WithFallback(filePath, true) + if (!decrypted) { return { success: false, error: '图片解密失败' } } return { success: true, - data: base64, - isThumb: imageDecryptService.isThumbnailFile(filePath), - filePath + data: decrypted.data, + isThumb: imageDecryptService.isThumbnailFile(decrypted.filePath), + filePath: decrypted.filePath } } ) + // ============================================================ + // AI 图片理解基础设施(ImageInsightService) + // ============================================================ + // 注入依赖(用闭包捕获当前 db:getImage 已经初始化过的 imageDecryptService) + // 同时把 imageDecryptService 暴露到 globalThis,供 group-report-service 渲染时按 imageHash 取图 + ;(globalThis as { __imageDecrypt?: typeof imageDecryptService }).__imageDecrypt = + imageDecryptService + imageInsightService.bind({ + providerService: aiProviderService, + decryptService: { + findImageFile: (md5, datName, opts) => + imageDecryptService?.findImageFile(md5, datName, opts) ?? null, + decryptImageToBase64: (filePath) => + imageDecryptService?.decryptImageToBase64(filePath) ?? null + } + }) + + /** 日报入口:取会话 Top N 热点图片 + 已缓存的 Insight */ + ipcMain.handle( + 'image:listCandidates', + async ( + _, + query: ImageCandidateQuery + ): Promise<{ success: boolean; candidates: ImageCandidate[]; error?: string }> => { + console.log('[IPC] image:listCandidates query=%j', query) + try { + const inputs = (query as ImageCandidateQuery & { inputs?: unknown[] }).inputs || [] + console.log('[IPC] image:listCandidates received %d inputs', inputs.length) + const candidates = await imageInsightService.listTopHotImages(query, inputs as never) + console.log('[IPC] image:listCandidates returned %d candidates', candidates.length) + return { success: true, candidates } + } catch (error) { + console.warn('[IPC] image:listCandidates failed:', error) + return { + success: false, + candidates: [], + error: error instanceof Error ? error.message : String(error) + } + } + } + ) + + /** 单图分析:缓存命中即返回,未命中调 AI;失败不抛 */ + ipcMain.handle( + 'image:analyze', + async (_, request: ImageAnalysisRequest): Promise => { + console.log('[IPC] image:analyze hash=%s messageId=%s', request.imageHash, request.messageId) + // 校验 provider 是否支持 vision + const runtime = aiProviderService.getRuntimeConfig() + if (!runtime.configured) { + return { success: false, error: '尚未配置 AI Provider' } + } + const list = aiProviderService.list() + const provider = list.providers.find((p) => p.id === runtime.providerId) + const model = provider?.models.find((m) => m.id === runtime.model) + if (!provider || !model) { + return { success: false, error: '当前 AI 模型不存在' } + } + if (!model.capabilities.vision) { + return { success: false, error: '当前模型不支持图片理解' } + } + // request 来自 renderer,imageHash 是 md5(优先)或 sha256(...),dataUrl 在内部算出 + // 这里直接调 service,dataUrl 由 renderer 通过 window.api.getImage 拿到再传进来 + return imageInsightService.analyze(request) + } + ) + + /** 单图查询缓存 */ + ipcMain.handle( + 'image:getInsight', + async (_, imageHash: string): Promise<{ success: boolean; insight?: ImageInsight }> => { + const insight = imageInsightService.getInsight(imageHash) + return { success: true, insight: insight || undefined } + } + ) + + /** 列出某会话所有已分析的 insights */ + ipcMain.handle( + 'image:listInsights', + async ( + _, + sessionId: string, + limit?: number + ): Promise<{ success: boolean; insights: ImageInsight[] }> => { + return { success: true, insights: imageInsightService.listBySession(sessionId, limit) } + } + ) + ipcMain.handle('db:getSticker', async (_, cdnUrl?: string, md5?: string) => { if (!stickerService) { stickerService = new StickerService(chat.getChatDb()?.getWcdb4Client()) diff --git a/src/main/services/ai-provider-service.ts b/src/main/services/ai-provider-service.ts index 5c93aaf..14a5c10 100644 --- a/src/main/services/ai-provider-service.ts +++ b/src/main/services/ai-provider-service.ts @@ -69,7 +69,8 @@ export class AIProviderService { configured: Boolean( provider && provider.models.length && (provider.hasApiKey || !needsApiKey(provider)) ), - status: provider?.status || 'untested' + status: provider?.status || 'untested', + timeoutMs: provider?.advanced.timeoutMs } } @@ -169,6 +170,37 @@ export class AIProviderService { } } + /** + * 多模态图片理解。 + * 输入:text + image parts 的 messages,返回 AI 文本响应。 + * 与 testVision 区别:不校验 prompt,不写入 capability marker(供 ImageInsightService 复用)。 + */ + async analyzeImage( + messages: Array<{ + role: string + content: string | Array<{ type: 'text'; text: string } | { type: 'image'; dataUrl: string }> + }>, + options?: AIChatRequestOptions + ): Promise<{ + success: boolean + data?: string + usage?: { input?: number; output?: number; total?: number; estimated?: boolean } + error?: string + }> { + try { + const imagePart = messages + .flatMap((message) => (typeof message.content === 'string' ? [] : message.content)) + .find((part) => part.type === 'image') + if (!imagePart || imagePart.type !== 'image') throw new Error('图片识别请求缺少图片数据') + const imageError = validateVisionImage(imagePart.dataUrl) + if (imageError) throw new Error(imageError) + const result = await this.request(messages as AIMessage[], options) + return { success: true, ...result } + } catch (error) { + return { success: false, error: safeAIError(error) } + } + } + async testVision(request: AIVisionTestRequest): Promise { const startedAt = Date.now() const imageError = validateVisionImage(request.imageDataUrl) @@ -215,7 +247,13 @@ export class AIProviderService { }> { if (options?.apiKey) return this.requestLegacy(messages, options) const resolved = this.resolveProvider(options) - return requestProvider(resolved.provider, resolved.key, resolved.model, messages, testing) + const provider = options?.timeoutMs + ? { + ...resolved.provider, + advanced: { ...resolved.provider.advanced, timeoutMs: options.timeoutMs } + } + : resolved.provider + return requestProvider(provider, resolved.key, resolved.model, messages, testing) } private resolveProvider(options?: { providerId?: string; modelId?: string }): { @@ -263,12 +301,38 @@ export class AIProviderService { } private markVisionCapability(providerId: string, modelId: string): void { + this.markCapabilities(providerId, modelId, { vision: true, ocr: true }) + } + + /** + * 标记模型已验证的 capabilities(已存在则跳过)。 + * OCR 跟随 vision:几乎所有 vision 模型都能 OCR,标记 vision 时同步标记 ocr。 + */ + private markCapabilities( + providerId: string, + modelId: string, + caps: { vision?: boolean; ocr?: boolean } + ): void { const data = this.readMetadata() const provider = data.providers.find((item) => item.id === providerId) const model = provider?.models.find((item) => item.id === modelId) - if (!provider || !model || model.capabilities.vision) return - model.capabilities.vision = true - this.writeMetadata(data) + if (!provider || !model) return + // 老配置可能没有 ocr 字段,补默认 false + if (typeof model.capabilities.ocr !== 'boolean') model.capabilities.ocr = false + let changed = false + if (caps.vision === true && !model.capabilities.vision) { + model.capabilities.vision = true + // vision 开启默认带 ocr(派生能力) + if (!model.capabilities.ocr) { + model.capabilities.ocr = true + } + changed = true + } + if (caps.ocr === true && !model.capabilities.ocr) { + model.capabilities.ocr = true + changed = true + } + if (changed) this.writeMetadata(data) } private ensureEnvironmentMigration(): void { @@ -300,6 +364,14 @@ export class AIProviderService { const data = fs.readJsonSync(filePath) as AIProviderMetadataFile if (data.version !== 1 || !Array.isArray(data.providers)) throw new Error('invalid provider metadata') + // 老配置兼容:补 capabilities.ocr 默认值(vision 派生 OCR) + for (const provider of data.providers) { + for (const model of provider.models) { + if (typeof model.capabilities.ocr !== 'boolean') { + model.capabilities.ocr = model.capabilities.vision === true + } + } + } return data } @@ -325,7 +397,7 @@ function deepSeekProvider(baseUrl?: string, model?: string): AIProviderSummary { { name: modelId === 'deepseek-chat' ? 'DeepSeek Chat' : modelId, id: modelId, - capabilities: { chat: true, vision: false, longContext: true } + capabilities: { chat: true, vision: false, ocr: false, longContext: true } } ], defaultModel: modelId, @@ -454,7 +526,7 @@ async function requestOpenAICompatible( }, provider.advanced.timeoutMs ) - const payload = (await response.json()) as OpenAIResponsePayload + const payload = await parseJsonResponse(response) if (!response.ok) throw new Error(payload.error?.message || `AI 请求失败 (${response.status})`) return { data: String(payload.choices?.[0]?.message?.content || ''), @@ -508,7 +580,7 @@ async function requestAnthropic( }, provider.advanced.timeoutMs ) - const payload = (await response.json()) as AnthropicResponsePayload + const payload = await parseJsonResponse(response) if (!response.ok) throw new Error(payload.error?.message || `Anthropic 请求失败 (${response.status})`) return { @@ -543,6 +615,20 @@ async function fetchWithTimeout( } } +async function parseJsonResponse(response: Response): Promise { + const body = await response.text() + try { + return JSON.parse(body) as T + } catch { + const looksLikeHtml = /^\s*(?: = { @@ -292,6 +299,9 @@ export function getGroupSnapshot(userMd5: string): GroupSnapshot | null { .map((member) => ({ wxid: member.m_nsUsrName, nickname: member.nickname || '', + groupNickname: member.groupNickname || '', + wechatNickname: member.wechatNickname || '', + remark: member.remark || '', avatar: member.m_nsHeadImgUrl || '' })) diff --git a/src/main/services/image-insight-prompt.ts b/src/main/services/image-insight-prompt.ts new file mode 100644 index 0000000..d7e4163 --- /dev/null +++ b/src/main/services/image-insight-prompt.ts @@ -0,0 +1,94 @@ +// src/main/services/image-insight-prompt.ts +// 图片理解 prompt 模板 — 输出严格的 JSON,便于程序化解析 + +export const IMAGE_ANALYSIS_SYSTEM_PROMPT = `你是微信群聊的图片分析助手。 +请根据用户提供的图片和图片前后的聊天上下文,生成对该图片的结构化理解。 + +输出要求(严格遵守): +1. 必须输出 JSON,不要用 markdown 代码块包裹 +2. description:1-2 句中文,30-80 字,描述图片核心内容 +3. ocrText:如果图片含文字(截图、文档、票据等),提取出来;纯风景/表情包可填空字符串 +4. tags:3-6 个中文关键词标签 +5. category:screenshot / photo / meme / document / chart / other 之一 +6. importance:low / medium / high — 根据图片的信息密度和后续讨论热度判断 + +禁止: +- 不要猜测图片中未明确可见的内容 +- 不要复述聊天上下文本身(那是 description 之外的事) +- 不要输出 markdown 标记` + +export interface ImageAnalysisContext { + sender: string + sentAt: number + contextBefore: string[] // 图片前 1-3 条消息 + contextAfter: string[] // 图片后 1-3 条消息 +} + +export function buildImageAnalysisUserText(ctx: ImageAnalysisContext): string { + const before = ctx.contextBefore.length + ? ctx.contextBefore.map((m, i) => ` ${i + 1}. ${m}`).join('\n') + : ' (无前文)' + const after = ctx.contextAfter.length + ? ctx.contextAfter.map((m, i) => ` ${i + 1}. ${m}`).join('\n') + : ' (无后续讨论)' + const time = new Date(ctx.sentAt * 1000).toLocaleString('zh-CN', { hour12: false }) + + return `发送者:${ctx.sender} +时间:${time} + +图片前的聊天: +${before} + +图片后的聊天: +${after} + +请输出 JSON(严格遵守 system 要求): +{"description":"...","ocrText":"...","tags":["..."],"category":"...","importance":"..."}` +} + +/** + * 把 AI 文本响应解析成结构化字段。 + * 容忍:无 markdown 包裹、有 markdown 包裹、尾部有杂质等。 + */ +export function parseImageAnalysisResponse(raw: string): { + description: string + ocrText: string + tags: string[] + category: 'screenshot' | 'photo' | 'meme' | 'document' | 'chart' | 'other' + importance: 'low' | 'medium' | 'high' +} { + const text = raw.trim() + // 提取 JSON 段 + const jsonMatch = text.match(/\{[\s\S]*\}/) + if (!jsonMatch) { + throw new Error('AI 未返回合法 JSON') + } + let parsed: Record + try { + parsed = JSON.parse(jsonMatch[0]) + } catch { + throw new Error('AI 返回的 JSON 无法解析') + } + + const description = String(parsed.description || '').trim() + if (!description) throw new Error('AI 未返回 description') + + const ocrText = String(parsed.ocrText || '').trim() + const tagsRaw = parsed.tags + const tags = Array.isArray(tagsRaw) + ? tagsRaw.map((t) => String(t).trim()).filter(Boolean).slice(0, 8) + : [] + + const categoryRaw = String(parsed.category || 'other').toLowerCase() + const category: 'screenshot' | 'photo' | 'meme' | 'document' | 'chart' | 'other' = + ['screenshot', 'photo', 'meme', 'document', 'chart'].includes(categoryRaw) + ? (categoryRaw as 'screenshot' | 'photo' | 'meme' | 'document' | 'chart') + : 'other' + + const importanceRaw = String(parsed.importance || 'medium').toLowerCase() + const importance: 'low' | 'medium' | 'high' = ['low', 'medium', 'high'].includes(importanceRaw) + ? (importanceRaw as 'low' | 'medium' | 'high') + : 'medium' + + return { description, ocrText, tags, category, importance } +} \ No newline at end of file diff --git a/src/main/services/image-insight-service.ts b/src/main/services/image-insight-service.ts new file mode 100644 index 0000000..39b0836 --- /dev/null +++ b/src/main/services/image-insight-service.ts @@ -0,0 +1,279 @@ +// src/main/services/image-insight-service.ts +// WechatExplorer AI 图片理解基础设施 +// +// 设计原则: +// 1. base64 不走 IPC,只在 main 内部流转(renderer 只看到 ImageInsight 结构化结果) +// 2. 同图(imageHash)走缓存,绝不重复调 AI +// 3. 失败不抛,日志记录 + 返回原状(不阻塞日报) +// 4. 第一阶段:Top 3 热点图 + 缓存命中即返回,未命中并发调 AI + +import crypto from 'crypto' +import { randomUUID } from 'crypto' +import { imageInsightsStore } from '../db/image-insights-store' +import { + buildImageAnalysisUserText, + IMAGE_ANALYSIS_SYSTEM_PROMPT, + parseImageAnalysisResponse +} from './image-insight-prompt' +import type { + ImageAnalysisRequest, + ImageAnalysisResponse, + ImageCandidate, + ImageCandidateQuery, + ImageInsight +} from '../../shared/image-insight' + +/** + * 单张图片的最小信息(由 renderer 从已加载的 messages 中提取并传入 main)。 + * 这样可以避免 ImageInsightService 自己重新查询消息,且参数语义清晰。 + */ +export interface ImageCandidateInput { + messageId: string + md5?: string + datName?: string + sessionId: string + sender: string + sentAt: number + /** 图片发出后 8 条消息内、不同发言人的回复数(由 renderer 计算) */ + responseCount: number + /** 表情/语音互动条数 */ + interactionCount: number +} + +interface ProviderServiceLike { + list(): ProviderSummaryLike + analyzeImage( + messages: Array<{ + role: string + content: string | Array<{ type: 'text'; text: string } | { type: 'image'; dataUrl: string }> + }>, + options?: { providerId?: string; modelId?: string } + ): Promise<{ + success: boolean + data?: string + error?: string + }> +} + +interface DecryptServiceLike { + findImageFile( + md5?: string, + imageDatName?: string, + options?: { allowThumbnail?: boolean } + ): string | null + decryptImageToBase64(datPath: string): string | null +} + +interface ProviderSummaryLike { + providers: Array<{ + id: string + isDefault: boolean + defaultModel: string + models: Array<{ id: string; capabilities: { vision: boolean; ocr: boolean } }> + }> + defaultProviderId?: string +} + +class ImageInsightService { + private providerService: ProviderServiceLike | null = null + private decryptService: DecryptServiceLike | null = null + /** 最近一次实际使用的默认 AI provider/model,仅用于写入分析元数据 */ + private runtimeProviderId: string | undefined = undefined + private runtimeModelId: string | undefined = undefined + + /** 注入依赖(由 main/index.ts 在 app ready 后调用) */ + bind(deps: { + providerService: ProviderServiceLike & { list(): ProviderSummaryLike } + decryptService: DecryptServiceLike + }): void { + this.providerService = deps.providerService + this.decryptService = deps.decryptService + console.log( + '[ImageInsightService] bind ok, default provider=%s model=%s', + this.runtimeProviderId, + this.runtimeModelId + ) + // 读取默认 provider/model(后续 analyze 时使用) + try { + const list = deps.providerService.list() + const provider = + list.providers.find((p) => p.id === list.defaultProviderId) || list.providers[0] + this.runtimeProviderId = provider?.id + this.runtimeModelId = provider?.defaultModel + console.log( + '[ImageInsightService] bind loaded default provider=%s model=%s', + this.runtimeProviderId, + this.runtimeModelId + ) + } catch (error) { + console.warn('[ImageInsightService] bind list failed:', error) + } + } + + /** + * 计算图片缓存 key:imageHash。 + * 策略:优先微信原始 md5,无 md5 才用 sha256(rawBytes).slice(0, 32) + */ + private async computeImageHash( + md5: string | undefined, + datName: string | undefined + ): Promise { + if (md5 && md5.trim()) return md5.trim().toLowerCase() + if (!this.decryptService) return null + const filePath = this.decryptService.findImageFile(undefined, datName, { allowThumbnail: true }) + if (!filePath) return null + // 一次性读盘 + sha256(只在没有 md5 时才付出 IO) + try { + const fs = await import('fs-extra') + const buf = await fs.readFile(filePath) + const sha = crypto.createHash('sha256').update(buf).digest('hex').slice(0, 32) + return `sha256:${sha}` + } catch (error) { + console.warn('[ImageInsightService] computeImageHash failed:', error) + return null + } + } + + /** 通过 hash 拿 Insight(只读缓存,无 AI 调用) */ + getInsight(imageHash: string): ImageInsight | null { + return imageInsightsStore.getByHash(imageHash) + } + + /** + * 主入口:分析一张图片。 + * 1. 通过 imageHash 查缓存,命中即返回 + * 2. 未命中:解密图片 → 调 AI → 解析响应 → 落库 → 返回 + * 3. 任意步骤失败:记录日志,返回 success=false,**不抛** + */ + async analyze(request: ImageAnalysisRequest): Promise { + try { + if (!request.force) { + const cached = imageInsightsStore.getByHash(request.imageHash) + if (cached) { + return { success: true, insight: cached, fromCache: true } + } + } + + if (!this.providerService) { + return { success: false, error: 'AI Provider 未初始化' } + } + + const messages = [ + { + role: 'system', + content: IMAGE_ANALYSIS_SYSTEM_PROMPT + }, + { + role: 'user', + content: [ + { + type: 'text' as const, + text: buildImageAnalysisUserText({ + sender: request.sender, + sentAt: request.sentAt, + contextBefore: [], + contextAfter: [] + }) + }, + { type: 'image' as const, dataUrl: request.imageDataUrl } + ] + } + ] + + const list = this.providerService.list() + const provider = + list.providers.find((item) => item.id === list.defaultProviderId) || list.providers[0] + this.runtimeProviderId = provider?.id + this.runtimeModelId = provider?.defaultModel + const result = await this.providerService.analyzeImage(messages, { + providerId: this.runtimeProviderId, + modelId: this.runtimeModelId + }) + if (!result.success || !result.data) { + console.warn('[ImageInsightService] analyze vision failed: %s', result.error || 'no data') + return { success: false, error: result.error || 'AI 未返回内容' } + } + console.log('[ImageInsightService] analyze ok, description=%s', result.data.slice(0, 80)) + + const parsed = parseImageAnalysisResponse(result.data) + const insight: ImageInsight = { + id: randomUUID(), + messageId: request.messageId, + imageHash: request.imageHash, + md5: undefined, + datName: undefined, + description: parsed.description, + ocrText: parsed.ocrText || undefined, + tags: parsed.tags, + category: parsed.category, + importance: parsed.importance, + provider: this.runtimeProviderId || '', + model: this.runtimeModelId || '', + createdAt: Date.now(), + updatedAt: Date.now(), + sender: request.sender, + sentAt: request.sentAt, + sessionId: request.sessionId + } + imageInsightsStore.upsert(insight) + return { success: true, insight, fromCache: false } + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.warn('[ImageInsightService] analyze failed:', message) + return { success: false, error: message } + } + } + + /** + * 日报入口:从 renderer 传入的图片消息候选中挑 Top N + 命中缓存的 Insight。 + * + * 设计:不自己查 chat-service(参数语义不清),而是由 renderer 从已加载的 messages 中 + * 提取图片消息 + 计算热度后传入。这样既复用现有数据,又避免 userMd5/sessionId 混淆。 + */ + async listTopHotImages( + query: ImageCandidateQuery, + inputs: ImageCandidateInput[] = [] + ): Promise { + const limit = query.limit ?? 3 + const candidates: ImageCandidate[] = [] + console.log('[ImageInsightService] listTopHotImages received %d inputs', inputs.length) + for (const input of inputs) { + const hash = await this.computeImageHash(input.md5, input.datName) + if (!hash) { + console.log( + '[ImageInsightService] skip %s: hash empty (md5=%s datName=%s)', + input.messageId, + input.md5, + input.datName + ) + continue + } + const heatScore = input.responseCount * 3 + input.interactionCount * 2 + 1 + const candidate: ImageCandidate = { + messageId: input.messageId, + imageHash: hash, + md5: input.md5, + datName: input.datName, + sessionId: input.sessionId, + sender: input.sender, + sentAt: input.sentAt, + heatScore + } + const cached = imageInsightsStore.getByHash(hash) + if (cached) candidate.insight = cached + candidates.push(candidate) + } + candidates.sort((a, b) => b.heatScore - a.heatScore) + return candidates.slice(0, limit) + } + + /** + * 列出会话所有 insights(按时间倒序,供未来 UI 复用) + */ + listBySession(sessionId: string, limit?: number): ImageInsight[] { + return imageInsightsStore.listBySession(sessionId, limit) + } + +} + +export const imageInsightService = new ImageInsightService() diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts index 6388b0f..e943752 100644 --- a/src/main/wcdb4-client.ts +++ b/src/main/wcdb4-client.ts @@ -32,6 +32,9 @@ export interface Wcdb4MessageQueryOptions { export interface Wcdb4GroupMember { m_nsUsrName: string nickname: string + groupNickname: string + wechatNickname: string + remark: string m_nsHeadImgUrl: string } @@ -930,17 +933,24 @@ export class Wcdb4Client { 'member_username', 'm_nsUsrName' ]) - const memberNickname = this.pickString(row, [ + const wechatNickname = this.pickString(row, [ 'nickname', 'nickName', + 'wechatNickname', + 'wechat_nickname', + 'm_nsNickName' + ]) + const remark = this.pickString(row, [ + 'remark', + 'remarkName', + 'remark_name', + 'contactRemark', + 'contact_remark' + ]) + const memberNickname = this.pickString(row, [ 'displayName', 'display_name', - 'groupNickname', - 'group_nickname', - 'roomNickname', - 'room_nickname', - 'remark', - 'm_nsNickName' + 'name' ]) const avatar = this.pickString(row, [ 'avatarUrl', @@ -955,7 +965,11 @@ export class Wcdb4Client { return { m_nsUsrName: username, - nickname: groupNicknames.get(username) || memberNickname, + nickname: + groupNicknames.get(username) || remark || wechatNickname || memberNickname, + groupNickname: groupNicknames.get(username) || '', + wechatNickname: wechatNickname || memberNickname, + remark, m_nsHeadImgUrl: avatar } }) @@ -975,6 +989,8 @@ export class Wcdb4Client { ...member, nickname: member.nickname || this.displayNameCache.get(member.m_nsUsrName) || member.m_nsUsrName, + wechatNickname: + member.wechatNickname || this.displayNameCache.get(member.m_nsUsrName) || '', m_nsHeadImgUrl: member.m_nsHeadImgUrl || this.avatarCache.get(member.m_nsUsrName) || '' })) } catch { diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 8301c11..a914428 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -30,6 +30,13 @@ import type { AIVisionTestResult, LegacyAIConfig } from '../shared/ai-provider' +import type { + ImageAnalysisRequest, + ImageAnalysisResponse, + ImageCandidate, + ImageCandidateQuery, + ImageInsight +} from '../shared/image-insight' export type ParsedContent = | { type: 'text'; content: string } @@ -87,7 +94,14 @@ declare global { getGroupSnapshot: (userMd5: string) => Promise<{ roomId: string memberCount: number - members: { wxid: string; nickname: string; avatar: string }[] + members: { + wxid: string + nickname: string + groupNickname: string + wechatNickname: string + remark: string + avatar: string + }[] } | null> search: (keyword: string) => Promise aiChat: ( @@ -270,6 +284,20 @@ declare global { openReaderSkillGithub: () => Promise<{ success: boolean; error?: string }> testLocalApiRequest: (request: LocalApiTestRequest) => Promise copyText: (text: string) => Promise<{ success: boolean; error?: string }> + // ============================================================ + // AI 图片理解基础设施(ImageInsightService) + // ============================================================ + imageListCandidates: (query: ImageCandidateQuery) => Promise<{ + success: boolean + candidates: ImageCandidate[] + error?: string + }> + imageAnalyze: (request: ImageAnalysisRequest) => Promise + getImageInsight: (imageHash: string) => Promise<{ success: boolean; insight?: ImageInsight }> + listImageInsights: ( + sessionId: string, + limit?: number + ) => Promise<{ success: boolean; insights: ImageInsight[] }> } } } diff --git a/src/preload/index.ts b/src/preload/index.ts index a4b3a07..b7e9f96 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -8,6 +8,13 @@ import type { AIVisionTestRequest, LegacyAIConfig } from '../shared/ai-provider' +import type { + ImageAnalysisRequest, + ImageAnalysisResponse, + ImageCandidate, + ImageCandidateQuery, + ImageInsight +} from '../shared/image-insight' // 渲染器的自定义 API const api = { @@ -108,7 +115,24 @@ const api = { revealReaderSkill: () => ipcRenderer.invoke('api:revealSkill'), openReaderSkillGithub: () => ipcRenderer.invoke('api:openSkillGithub'), testLocalApiRequest: (request) => ipcRenderer.invoke('api:testLocalRequest', request), - copyText: (text: string) => ipcRenderer.invoke('api:copyText', text) + copyText: (text: string) => ipcRenderer.invoke('api:copyText', text), + // ============================================================ + // AI 图片理解基础设施(ImageInsightService) + // ============================================================ + imageListCandidates: (query: ImageCandidateQuery): Promise<{ + success: boolean + candidates: ImageCandidate[] + error?: string + }> => ipcRenderer.invoke('image:listCandidates', query), + imageAnalyze: (request: ImageAnalysisRequest): Promise => + ipcRenderer.invoke('image:analyze', request), + getImageInsight: (imageHash: string): Promise<{ success: boolean; insight?: ImageInsight }> => + ipcRenderer.invoke('image:getInsight', imageHash), + listImageInsights: ( + sessionId: string, + limit?: number + ): Promise<{ success: boolean; insights: ImageInsight[] }> => + ipcRenderer.invoke('image:listInsights', sessionId, limit) } if (process.contextIsolated) { diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 53d751f..77a5640 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -81,7 +81,14 @@ const areMessagesEquivalent = (left: Message[], right: Message[]): boolean => { type GroupSnapshot = { roomId: string memberCount: number - members: { wxid: string; nickname: string; avatar: string }[] + members: { + wxid: string + nickname: string + groupNickname: string + wechatNickname: string + remark: string + avatar: string + }[] } type GroupMemberMeta = { nickname: string; avatar: string } @@ -1137,6 +1144,12 @@ function App(): React.ReactElement { onRevealReport={reportGeneration.revealReport} onViewResult={openReportResult} hasReportResult={generatedReports.length > 0} + templateId={reportGeneration.templateId} + onTemplateIdChange={reportGeneration.setTemplateId} + memberNamePreference={reportGeneration.memberNamePreference} + onMemberNamePreferenceChange={reportGeneration.setMemberNamePreference} + reportTimeoutSeconds={reportGeneration.reportTimeoutSeconds} + onReportTimeoutSecondsChange={reportGeneration.setReportTimeoutSeconds} /> .report-section + .report-section { + margin-top: 28px; +} + .report-empty-state, .report-config-section, .report-privacy-note, @@ -3040,6 +3044,39 @@ body { font: 700 15px/20px var(--wxex-font); } +.report-timeout-section { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; +} + +.report-timeout-section p { + margin: 6px 0 0; + color: var(--wxex-text-secondary); + font-size: 12px; +} + +.report-timeout-section label { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 8px; + color: var(--wxex-text-secondary); + font-size: 13px; +} + +.report-timeout-section input { + width: 96px; + height: 36px; + padding: 0 10px; + border: 1px solid var(--wxex-border); + border-radius: var(--wxex-radius-md); + background: #fff; + color: var(--wxex-text-primary); + font: 500 13px var(--wxex-font); +} + .report-empty-state p, .report-privacy-note p { margin: 6px 0 0; @@ -4390,3 +4427,185 @@ body { flex-direction: column; } } + +/* ============================================================ */ +/* 日报模板选择器 + 预览器 */ +/* ============================================================ */ +.report-section-desc { + margin: 0 0 12px; + color: var(--wxex-text-secondary); + font-size: 12px; + line-height: 1.6; +} + +.report-template-list { + display: grid; + gap: 10px; +} + +.report-template-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 14px; + border: 1.5px solid var(--wxex-border); + border-radius: 12px; + background: #fff; + transition: border-color 0.2s, background 0.2s; +} + +.report-template-item.active { + border-color: var(--wxex-primary, #07c160); + background: #f0fbf3; +} + +.report-template-item.disabled { + opacity: 0.6; + cursor: not-allowed; +} + +.report-template-item > label { + flex: 1; + display: flex; + align-items: center; + gap: 10px; + cursor: pointer; + min-width: 0; +} + +.report-template-item input[type='radio'] { + accent-color: var(--wxex-primary, #07c160); +} + +.report-template-body { + flex: 1; + min-width: 0; +} + +.report-template-title { + font-size: 14px; + font-weight: 700; + color: var(--wxex-text-primary, #1f2933); +} + +.report-template-tagline { + margin-top: 4px; + font-size: 12px; + color: var(--wxex-text-secondary, #485465); + line-height: 1.5; +} + +.report-template-preview-btn { + padding: 6px 12px; + font-size: 12px; + font-weight: 600; + border-radius: 8px; + border: 1px solid var(--wxex-border); + background: #fff; + color: var(--wxex-text-primary, #1f2933); + cursor: pointer; + transition: background 0.2s, color 0.2s, border-color 0.2s; +} + +.report-template-preview-btn:hover { + background: var(--wxex-primary, #07c160); + color: #fff; + border-color: var(--wxex-primary, #07c160); +} + +/* 预览遮罩 */ +.report-template-preview-mask { + position: fixed; + inset: 0; + background: rgba(15, 23, 42, 0.5); + display: flex; + align-items: center; + justify-content: center; + z-index: 999; + padding: 20px; +} + +.report-template-preview-card { + background: #f3f5f7; + border-radius: 18px; + padding: 18px; + width: min(380px, 100%); + max-height: 90vh; + overflow-y: auto; + box-shadow: 0 16px 60px rgba(15, 23, 42, 0.25); +} + +.report-template-preview-card h4 { + margin: 0 0 6px; + font-size: 17px; + font-weight: 800; +} + +.report-template-preview-card p.muted { + margin: 0 0 14px; + font-size: 12px; + color: var(--wxex-text-secondary, #485465); + line-height: 1.5; +} + +.report-template-preview-frame { + display: grid; + gap: 8px; + background: #fff; + border-radius: 14px; + padding: 12px; + border: 1px solid var(--wxex-border); +} + +.fake-card { + background: #f7faf9; + border-radius: 10px; + padding: 10px 12px; +} + +.fake-hero { + background: linear-gradient(135deg, #edf9f1 0%, #f7fbf8 100%); +} + +.fake-title { + font-size: 14px; + font-weight: 800; + color: #076c39; +} + +.fake-sub { + margin-top: 2px; + font-size: 11px; + color: #485465; +} + +.fake-section { + display: flex; + align-items: center; + gap: 8px; +} + +.fake-bar { + width: 4px; + height: 14px; + border-radius: 2px; + background: var(--wxex-primary, #07c160); +} + +.fake-section-title { + font-size: 12px; + font-weight: 700; + color: #1f2933; +} + +.report-template-preview-close { + margin-top: 14px; + width: 100%; + padding: 10px; + border-radius: 10px; + border: none; + background: var(--wxex-primary, #07c160); + color: #fff; + font-weight: 700; + cursor: pointer; +} diff --git a/src/renderer/src/components/ChatWindow.tsx b/src/renderer/src/components/ChatWindow.tsx index ac2cf3d..024728f 100644 --- a/src/renderer/src/components/ChatWindow.tsx +++ b/src/renderer/src/components/ChatWindow.tsx @@ -1,124 +1,111 @@ -import React, { useEffect, useRef, useState } from 'react' +import React, { useCallback, useEffect, useRef, useState } from 'react' import { Message, Contact } from '../../../shared/types' -import { VoicePlayer } from './VoicePlayer' -import { RichMessageBubble } from './RichMessageBubble' -import { ImageBubble } from './ImageBubble' -import { - buildGroupReportInput, - GROUP_REPORT_SYSTEM_PROMPT, - parseGroupDailyReport -} from '../utils/group-report' -import type { ReportMode } from '../../../shared/group-report' +import { ChatHeader } from './chat/ChatHeader' +import { ChatStatusBar } from './chat/ChatStatusBar' +import { DataTrustBar } from './chat/DataTrustBar' +import { EmptyConversationState } from './chat/EmptyConversationState' +import { ExportRange } from './chat/ExportMenu' +import { MessageList } from './chat/MessageList' interface ChatWindowProps { contact: Contact | null messages: Message[] + isLoadingMessages?: boolean contentFilter?: string + dateRange?: string + onContentFilterChange?: (keyword: string) => void onRefresh?: () => void onRefreshData?: () => void + onCreateGroupReport?: () => void + isAiLoading?: boolean } -type SummaryDateRange = 'today' | 'yesterday' | '7days' -type SummaryMessageType = 'text' | 'image' | 'sticker' | 'video' | 'voice' | 'share' | 'system' +const MAX_RENDERED_MESSAGES = 600 +const DATE_RANGE_LABELS: Record = { + today: '今天', + yesterday: '昨日', + '7': '7 天', + '30': '30 天', + all: '全部' +} -const SUMMARY_DATE_OPTIONS: { value: SummaryDateRange; label: string }[] = [ - { value: 'today', label: '今天' }, - { value: 'yesterday', label: '昨日' }, - { value: '7days', label: '最近 7 天' } -] +const formatClock = (date: Date): string => + `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` -const SUMMARY_TYPE_OPTIONS: { - value: SummaryMessageType - label: string - messageTypes: string[] -}[] = [ - { value: 'text', label: '文本', messageTypes: ['普通文本'] }, - { value: 'image', label: '图片', messageTypes: ['图片'] }, - { value: 'sticker', label: '表情包', messageTypes: ['表情包'] }, - { value: 'video', label: '视频', messageTypes: ['视频'] }, - { value: 'voice', label: '语音', messageTypes: ['语音'] }, - { value: 'share', label: '分享/引用', messageTypes: ['分享消息', '名片', '位置', '通话'] }, - { value: 'system', label: '系统消息', messageTypes: ['系统消息'] } -] +const formatRangeDate = (date: Date, now: Date): string => { + const clock = formatClock(date) + if (date.getFullYear() === now.getFullYear()) { + return `${date.getMonth() + 1} 月 ${date.getDate()} 日 ${clock}` + } + return `${date.getFullYear()} 年 ${date.getMonth() + 1} 月 ${date.getDate()} 日 ${clock}` +} -const getSummaryDateRange = (range: SummaryDateRange): { startTime: number; endTime: number } => { +const getChatHeaderRangeLabel = (range: string): string => { const now = new Date() - const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime() / 1000 - const endTime = Math.floor(Date.now() / 1000) - if (range === 'yesterday') { - return { startTime: startOfToday - 86400, endTime: startOfToday - 1 } + const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()) + const endOfYesterday = new Date(startOfToday.getTime() - 60_000) + + if (range === 'today') return `今天 00:00—现在` + if (range === 'yesterday') return `昨天 00:00—${formatClock(endOfYesterday)}` + if (range === '7') { + const start = new Date(Date.now() - 7 * 86400000) + return `${formatRangeDate(start, now)}—现在` } - if (range === '7days') { - return { startTime: startOfToday - 6 * 86400, endTime } + if (range === '30') { + const start = new Date(Date.now() - 30 * 86400000) + return `${formatRangeDate(start, now)}—现在` } - return { startTime: startOfToday, endTime } + if (range === 'all') return '全部记录' + return DATE_RANGE_LABELS[range] || '当前范围' } const ChatWindow: React.FC = ({ contact, messages, + isLoadingMessages, contentFilter, + dateRange = 'today', + onContentFilterChange, onRefresh, - onRefreshData + onRefreshData, + onCreateGroupReport, + isAiLoading = false }) => { const isGroupChat = Boolean( contact?.type === 'group' || contact?.m_nsUsrName?.endsWith('@chatroom') ) + const messageListRef = useRef(null) const messagesEndRef = useRef(null) - const [generatedImage, setGeneratedImage] = useState(null) - const [reportPaths, setReportPaths] = useState<{ htmlPath: string; pngPath: string } | null>(null) const [previewImage, setPreviewImage] = useState(null) const [imageScale, setImageScale] = useState(0.75) const [imageRotation, setImageRotation] = useState(0) const [imageOffset, setImageOffset] = useState({ x: 0, y: 0 }) + const imageViewerStageRef = useRef(null) const imageDragRef = useRef<{ x: number; y: number; offsetX: number; offsetY: number } | null>( null ) const [showAvatar, setShowAvatar] = useState(true) + const [isAtLatest, setIsAtLatest] = useState(true) - // AI Settings - const [showSettingsModal, setShowSettingsModal] = useState(false) - const [apiKey, setApiKey] = useState(() => localStorage.getItem('ai_api_key') || '') - const [baseURL, setBaseURL] = useState( - () => localStorage.getItem('ai_base_url') || 'https://api.deepseek.com' - ) - const [model, setModel] = useState(() => localStorage.getItem('ai_model') || 'deepseek-v4-flash') - const [summaryDateRange, setSummaryDateRange] = useState('today') - const [summaryMessageTypes, setSummaryMessageTypes] = useState(['text']) - const [reportMode, setReportMode] = useState( - () => (localStorage.getItem('group_report_mode') as ReportMode) || 'compact' - ) - - const handleSaveSettings = (): void => { - if (!summaryMessageTypes.length) { - alert('请至少选择一种消息类型') - return - } - localStorage.setItem('ai_api_key', apiKey) - localStorage.setItem('ai_base_url', baseURL) - localStorage.setItem('ai_model', model) - localStorage.setItem('group_report_mode', reportMode) - setShowSettingsModal(false) - AIChat() - } - - const toggleSummaryMessageType = (type: SummaryMessageType): void => { - setSummaryMessageTypes((current) => - current.includes(type) ? current.filter((item) => item !== type) : [...current, type] - ) - } - - const scrollToBottom = (): void => { + const scrollToBottom = useCallback((): void => { messagesEndRef.current?.scrollIntoView({ behavior: 'auto' }) - } + setIsAtLatest(true) + }, []) + + const handleMessageListScroll = useCallback((event: React.UIEvent): void => { + const target = event.currentTarget + const distanceToBottom = target.scrollHeight - target.scrollTop - target.clientHeight + setIsAtLatest(distanceToBottom <= 24) + }, []) useEffect(() => { - scrollToBottom() - }, [messages]) + const frame = window.requestAnimationFrame(() => scrollToBottom()) + return () => window.cancelAnimationFrame(frame) + }, [messages, scrollToBottom]) const openImagePreview = (imageUrl: string): void => { setPreviewImage(imageUrl) - setImageScale(0.75) + setImageScale(1) setImageRotation(0) setImageOffset({ x: 0, y: 0 }) } @@ -129,17 +116,18 @@ const ChatWindow: React.FC = ({ } const zoomImage = (delta: number): void => { - setImageScale((prev) => Math.min(3, Math.max(0.25, Number((prev + delta).toFixed(2))))) + setImageScale((prev) => Math.min(8, Math.max(0.1, Number((prev + delta).toFixed(2))))) } const resetImageTransform = (): void => { - setImageScale(0.75) + setImageScale(1) setImageRotation(0) setImageOffset({ x: 0, y: 0 }) } const handleViewerWheel = (event: React.WheelEvent): void => { event.preventDefault() + event.stopPropagation() zoomImage(event.deltaY > 0 ? -0.1 : 0.1) } @@ -166,7 +154,25 @@ const ChatWindow: React.FC = ({ imageDragRef.current = null } - const handleExport = (days: number | 'all'): void => { + useEffect(() => { + if (!previewImage) return + + const previousOverflow = document.body.style.overflow + document.body.style.overflow = 'hidden' + + const stage = imageViewerStageRef.current + const preventBackgroundWheel = (event: WheelEvent): void => { + event.preventDefault() + } + stage?.addEventListener('wheel', preventBackgroundWheel, { passive: false }) + + return () => { + document.body.style.overflow = previousOverflow + stage?.removeEventListener('wheel', preventBackgroundWheel) + } + }, [previewImage]) + + const handleExport = (days: ExportRange): void => { if (!messages.length) return let filtered = messages @@ -225,67 +231,6 @@ const ChatWindow: React.FC = ({ document.body.removeChild(link) } - const [isLoading, setIsLoading] = useState(false) - - const AIChat = async (): Promise => { - if (!contact) return - if (!summaryMessageTypes.length) { - alert('请至少选择一种消息类型') - return - } - setIsLoading(true) - try { - const { startTime, endTime } = getSummaryDateRange(summaryDateRange) - const rangeMessages = await window.api.getMessages(contact.md5, startTime, endTime) - const allowedTypes = new Set( - SUMMARY_TYPE_OPTIONS.filter((option) => summaryMessageTypes.includes(option.value)).flatMap( - (option) => option.messageTypes - ) - ) - const reportMessages = rangeMessages.filter((message) => allowedTypes.has(message.type)) - if (!reportMessages.length) throw new Error('当前条件下没有可总结的消息') - - const input = await buildGroupReportInput(reportMessages, contact, isGroupChat, reportMode) - console.log('🚀 ~ AIChat ~ input:', input) - console.log('🚀 ~ AIChat ~ input.prompt:', input.prompt) - const result = await window.api.aiChat( - [ - { role: 'system', content: GROUP_REPORT_SYSTEM_PROMPT }, - { role: 'user', content: input.prompt } - ], - { apiKey, model, baseURL } - ) - - if (!result.success || !result.data) throw new Error(result.error || 'AI 请求失败') - const report = parseGroupDailyReport( - result.data, - input.topSpeakers, - input.activeTimeline, - input.voiceLeaderboard, - input.metadata, - input.media - ) - const exported = await window.api.exportGroupReport({ report, metadata: input.metadata }) - if (!exported.success || !exported.imageDataUrl || !exported.htmlPath || !exported.pngPath) { - throw new Error(exported.error || '日报文件生成失败') - } - setGeneratedImage(exported.imageDataUrl) - setReportPaths({ htmlPath: exported.htmlPath, pngPath: exported.pngPath }) - } catch (error) { - console.error('AI Call Failed:', error) - alert(`AI 日报生成失败:${error instanceof Error ? error.message : String(error)}`) - } finally { - setIsLoading(false) - } - } - const handleCopyImage = async (): Promise => { - if (!generatedImage) return - const result = await window.api.copyImage(generatedImage) - if (result.success) { - alert('复制成功') - } - } - const filteredMessages = React.useMemo(() => { return messages.filter((msg) => { const filterTypes = (import.meta.env.VITE_FILTER_MSG_TYPES || '') @@ -297,194 +242,53 @@ const ChatWindow: React.FC = ({ return typeMatch && contentMatch }) }, [messages, contentFilter]) + const hiddenMessageCount = Math.max(0, filteredMessages.length - MAX_RENDERED_MESSAGES) + const renderedMessages = React.useMemo( + () => filteredMessages.slice(-MAX_RENDERED_MESSAGES), + [filteredMessages] + ) - if (!contact) { - return ( -
-
选择一条消息
-
- ) - } + if (!contact) return + + const dateRangeLabel = getChatHeaderRangeLabel(dateRange) return (
-
-

{contact.m_nsNickName}

-
-
- -
- {filteredMessages.map((msg) => { - const isMine = msg.from === 'assistant' - const isSystem = msg.from === 'system' || msg.type === '系统消息' - const displayName = isMine - ? '我' - : isGroupChat - ? msg.name || msg.from - : contact.m_nsNickName - const avatarSrc = isMine ? msg.img : msg.img || contact.avatar - const isVoice = msg.type === '语音' - const isImage = msg.type === '图片' - const isRichMedia = ['名片', '位置', '分享消息', '通话', '表情包', '系统消息'].includes( - msg.type - ) - - if (isSystem) { - return ( -
-
{msg.content}
-
{msg.datetime}
-
- ) - } - - return ( -
- {!isMine && showAvatar && ( -
- {avatarSrc ? ( - {displayName} - ) : ( - (displayName || '?').charAt(0) - )} -
- )} -
- {!isMine && isGroupChat &&
{displayName}
} -
- {isVoice && msg.sessionId ? ( - - ) : isImage && msg.contentData && msg.contentData.type === 'image' ? ( - - ) : isRichMedia && msg.contentData ? ( - - ) : ( -
{msg.content}
- )} -
-
- {msg.datetime} - {msg.type} -
-
- {isMine && showAvatar && ( -
- {avatarSrc ? 我 : '我'} -
- )} -
- ) - })} -
-
- -
- - - - - - - - - -
- - {/* 加载模态框 */} - {isLoading && ( -
-
-
🤖
-
正在生成群聊日报...
-
- 正在分析记录、处理头像并生成 HTML 和长图 -
-
-
- )} - - {/* 图片预览模态框 */} - {generatedImage && ( -
setGeneratedImage(null)}> -
e.stopPropagation()}> -
-
- Generated Summary -
-
-
- - {reportPaths && ( - - )} - -
-
-
- )} + 0} + onContentFilterChange={onContentFilterChange || (() => undefined)} + onRefresh={onRefresh} + onRefreshData={onRefreshData} + onExport={handleExport} + onOpenAiSettings={onCreateGroupReport || (() => undefined)} + /> + + + {previewImage && (
@@ -515,6 +319,7 @@ const ChatWindow: React.FC = ({
= ({
)} - - {/* AI Settings Modal */} - {showSettingsModal && ( -
setShowSettingsModal(false)}> -
e.stopPropagation()}> -

AI 设置

-
-
时间范围
-
- {SUMMARY_DATE_OPTIONS.map((option) => ( - - ))} -
-
-
-
报告模式
-
- - -
-
-
-
消息类型
-
- {SUMMARY_TYPE_OPTIONS.map((option) => ( - - ))} -
-
-
- - -
-
- - setBaseURL(e.target.value)} - placeholder="https://api.deepseek.com" - style={{ width: '95%', padding: '8px' }} - /> -
-
- - setApiKey(e.target.value)} - placeholder="Enter your API Key" - style={{ width: '95%', padding: '8px' }} - /> -
-
- - -
-
-
- )}
) } diff --git a/src/renderer/src/components/reports/AiReportWorkspace.tsx b/src/renderer/src/components/reports/AiReportWorkspace.tsx index 8e8782b..863dba0 100644 --- a/src/renderer/src/components/reports/AiReportWorkspace.tsx +++ b/src/renderer/src/components/reports/AiReportWorkspace.tsx @@ -3,6 +3,7 @@ import { Contact } from '../../../../shared/types' import { AiModelConfig, RangeMessageState, + ReportMemberNamePreference, ReportGenerationPhase, ReportPaths } from '../../hooks/useGroupReportGeneration' @@ -11,7 +12,9 @@ import { MessageTypeSelector } from './MessageTypeSelector' import { ModelSummary } from './ModelSummary' import { ReportDensitySelector } from './ReportDensitySelector' import { ReportRangeSelector } from './ReportRangeSelector' +import { ReportMemberNameSelector } from './ReportMemberNameSelector' import { ReportSectionSelector } from './ReportSectionSelector' +import { ReportTemplateId, ReportTemplateSelector } from './ReportTemplateSelector' interface AiReportWorkspaceProps { sourceContact: Contact | null @@ -36,6 +39,12 @@ interface AiReportWorkspaceProps { onRevealReport: () => Promise<{ success: boolean; error?: string }> onViewResult: () => void hasReportResult: boolean + templateId: ReportTemplateId + onTemplateIdChange: (value: ReportTemplateId) => void + memberNamePreference: ReportMemberNamePreference + onMemberNamePreferenceChange: (value: ReportMemberNamePreference) => void + reportTimeoutSeconds: number + onReportTimeoutSecondsChange: (value: number) => void } const rangeLabel = (range: SummaryDateRange): string => { @@ -76,7 +85,13 @@ export function AiReportWorkspace({ onCopyImage, onRevealReport, onViewResult, - hasReportResult + hasReportResult, + templateId, + onTemplateIdChange, + memberNamePreference, + onMemberNamePreferenceChange, + reportTimeoutSeconds, + onReportTimeoutSecondsChange }: AiReportWorkspaceProps): React.ReactElement { const [actionStatus, setActionStatus] = useState('') const groupName = sourceContact?.m_nsNickName || sourceContact?.m_nsUsrName || '未选择群聊' @@ -144,7 +159,35 @@ export function AiReportWorkspace({ /> + + +
+
+

日报生成超时

+

大群聊和图片识别耗时较长,可单独设置本次日报最多等待时间。

+
+ +

隐私说明

微信数据库和聊天记录默认从本机读取。

diff --git a/src/renderer/src/components/reports/ReportMemberNameSelector.tsx b/src/renderer/src/components/reports/ReportMemberNameSelector.tsx new file mode 100644 index 0000000..40ac94b --- /dev/null +++ b/src/renderer/src/components/reports/ReportMemberNameSelector.tsx @@ -0,0 +1,61 @@ +import React from 'react' +import { ReportMemberNamePreference } from '../../hooks/useGroupReportGeneration' + +const OPTIONS: { + value: ReportMemberNamePreference + label: string + description: string +}[] = [ + { + value: 'groupNickname', + label: '群昵称', + description: '优先使用成员在当前群设置的昵称。' + }, + { + value: 'wechatNickname', + label: '微信昵称', + description: '优先使用对方公开的微信昵称。' + }, + { + value: 'remark', + label: '通讯录备注', + description: '优先使用你为对方设置的备注。' + } +] + +export function ReportMemberNameSelector({ + value, + disabled, + onChange +}: { + value: ReportMemberNamePreference + disabled?: boolean + onChange: (value: ReportMemberNamePreference) => void +}): React.ReactElement { + return ( +
+

成员名称

+

选择日报中群成员的显示名称,默认使用群昵称。

+
+ {OPTIONS.map((option) => ( + + ))} +
+
+ ) +} diff --git a/src/renderer/src/components/reports/ReportTemplateSelector.tsx b/src/renderer/src/components/reports/ReportTemplateSelector.tsx new file mode 100644 index 0000000..05977d4 --- /dev/null +++ b/src/renderer/src/components/reports/ReportTemplateSelector.tsx @@ -0,0 +1,139 @@ +import React, { useState } from 'react' + +export type ReportTemplateId = 'v1' | 'v2' + +interface TemplateMeta { + id: ReportTemplateId + label: string + tagline: string + preview: { title: string; sections: string[] } +} + +const TEMPLATES: TemplateMeta[] = [ + { + id: 'v1', + label: '模板1 · 经典日报', + tagline: '实用信息 / 重要消息 / 金句 / 问答 / 数据可视化', + preview: { + title: '经典日报', + sections: [ + '今日讨论热点', + 'AI 识别的图片精选', + '实用信息与资源', + '重要消息汇总', + '有趣对话或金句', + '问题与解答', + '群内数据可视化', + '词云/关键词' + ] + } + }, + { + id: 'v2', + label: '模板2 · 支持图片板块', + tagline: '包含热点图片与上下文;需要模型服务商支持图片识别', + preview: { + title: '支持图片板块', + sections: [ + '今日讨论热点', + '重要消息', + '待办事项和未解决问题', + '今日名场面', + '今日群数据', + '关键词', + '实用信息与资源', + '问题与解答', + '今日剧情时间线', + '群聊反转现场', + 'AI 识别的图片精选', + '今日群相册', + '语音之最', + '语音时长榜', + '今日临时人设', + '话题参与链路' + ] + } + } +] + +interface ReportTemplateSelectorProps { + value: ReportTemplateId + onChange: (value: ReportTemplateId) => void + disabled?: boolean +} + +export const ReportTemplateSelector: React.FC = ({ + value, + onChange, + disabled +}) => { + const [previewing, setPreviewing] = useState(null) + return ( +
+

日报模板

+

+ 选择日报呈现风格。模板2 支持图片板块,但需要 AI 模型服务商支持图片识别。 +

+
+ {TEMPLATES.map((tpl) => { + const active = value === tpl.id + return ( +
+ + +
+ ) + })} +
+ {previewing && ( +
setPreviewing(null)}> +
e.stopPropagation()}> +

{previewing.preview.title}

+

{previewing.tagline}

+
+
+
群聊日报 · 预览
+
2026-xx-xx · 基于已加载记录
+
+ {previewing.preview.sections.map((s) => ( +
+
+
{s}
+
+ ))} +
+ +
+
+ )} +
+ ) +} diff --git a/src/renderer/src/features/settings/ai-model/AIProviderEditor.tsx b/src/renderer/src/features/settings/ai-model/AIProviderEditor.tsx index 0e98c5b..8906017 100644 --- a/src/renderer/src/features/settings/ai-model/AIProviderEditor.tsx +++ b/src/renderer/src/features/settings/ai-model/AIProviderEditor.tsx @@ -174,13 +174,31 @@ export function AIProviderEditor({ { + const vision = event.target.checked + // OCR 是 vision 的派生能力:勾 vision 时自动带 OCR + patchModel(index, { + capabilities: { + ...model.capabilities, + vision, + ocr: vision ? true : model.capabilities.ocr + } + }) + }} + /> + 图片理解 + +