From 38e87b8cbfd9d030e19704ac20a139b233f3d6a5 Mon Sep 17 00:00:00 2001 From: Forrest Date: Tue, 13 Jan 2026 00:19:59 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0LLM=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E5=8A=A0=E8=BD=BD=E5=92=8C=E9=87=8A=E6=94=BE=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=EF=BC=8C=E4=BC=98=E5=8C=96LLM=E6=8E=A8=E7=90=86?= =?UTF-8?q?=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- electron/services/cloneService.ts | 81 +++++++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 9 deletions(-) diff --git a/electron/services/cloneService.ts b/electron/services/cloneService.ts index d5249a8..38c7ab5 100644 --- a/electron/services/cloneService.ts +++ b/electron/services/cloneService.ts @@ -51,6 +51,9 @@ class CloneService { private worker: Worker | null = null private pending: Map = new Map() private requestId = 0 + private llmModel: any = null + private llmContext: any = null + private llmModelPath: string | null = null private resolveResourcesPath(): string { const candidate = app.isPackaged @@ -320,23 +323,83 @@ class CloneService { return { success: true, data: toneGuide } } - private async runLlm(prompt: string): Promise { + private async ensureLlmModel(): Promise<{ model: any; context: any; error?: string }> { const modelPath = this.configService.get('llmModelPath') if (!modelPath) { - return 'LLM 未配置,请设置 llmModelPath' + return { model: null, context: null, error: 'LLM 未配置,请设置 llmModelPath' } } + // 如果模型路径改变,需要重新加载 + if (this.llmModelPath !== modelPath) { + await this.releaseLlmModel() + this.llmModelPath = modelPath + } + + // 如果模型已加载,直接返回 + if (this.llmModel && this.llmContext) { + return { model: this.llmModel, context: this.llmContext } + } + + // 加载模型 const llama = await import('node-llama-cpp').catch(() => null) if (!llama) { - return 'node-llama-cpp 未安装' + return { model: null, context: null, error: 'node-llama-cpp 未安装' } } - const { LlamaModel, LlamaContext, LlamaChatSession } = llama as any - const model = new LlamaModel({ modelPath }) - const context = new LlamaContext({ model }) - const session = new LlamaChatSession({ context }) - const result = await session.prompt(prompt) - return typeof result === 'string' ? result : String(result) + try { + const { LlamaModel, LlamaContext } = llama as any + this.llmModel = new LlamaModel({ modelPath }) + this.llmContext = new LlamaContext({ model: this.llmModel }) + return { model: this.llmModel, context: this.llmContext } + } catch (err) { + await this.releaseLlmModel() + return { model: null, context: null, error: `模型加载失败: ${String(err)}` } + } + } + + private async releaseLlmModel(): Promise { + try { + if (this.llmContext) { + // LlamaContext 可能需要显式释放 + if (typeof this.llmContext.dispose === 'function') { + this.llmContext.dispose() + } + this.llmContext = null + } + if (this.llmModel) { + // LlamaModel 可能需要显式释放 + if (typeof this.llmModel.dispose === 'function') { + this.llmModel.dispose() + } + this.llmModel = null + } + this.llmModelPath = null + } catch (err) { + // 忽略释放错误 + console.error('释放 LLM 模型时出错:', err) + } + } + + private async runLlm(prompt: string): Promise { + const { model, context, error } = await this.ensureLlmModel() + if (error || !model || !context) { + return error || '模型加载失败' + } + + try { + const llama = await import('node-llama-cpp').catch(() => null) + if (!llama) { + return 'node-llama-cpp 未安装' + } + + const { LlamaChatSession } = llama as any + // 每次对话创建新的 session,但复用 model 和 context + const session = new LlamaChatSession({ context }) + const result = await session.prompt(prompt) + return typeof result === 'string' ? result : String(result) + } catch (err) { + return `LLM 推理失败: ${String(err)}` + } } } From cada00258708a698af7223eaa9753fa39db66c99 Mon Sep 17 00:00:00 2001 From: xuncha <1658671838@qq.com> Date: Tue, 13 Jan 2026 17:50:56 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E4=BA=86=E4=BC=81?= =?UTF-8?q?=E4=B8=9A=E5=BE=AE=E4=BF=A1=E4=BC=9A=E6=98=BE=E7=A4=BA=E5=87=BA?= =?UTF-8?q?id=E7=9A=84=E9=97=AE=E9=A2=98=20=E5=A2=9E=E5=8A=A0=E4=BA=86?= =?UTF-8?q?=E6=96=B0=E6=89=8B=E6=95=99=E7=A8=8B=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 6 +- src/pages/ChatPage.tsx | 162 ++++++++++++++++++++------------------ src/pages/WelcomePage.tsx | 1 + 3 files changed, 90 insertions(+), 79 deletions(-) diff --git a/.gitignore b/.gitignore index e6877f1..3433fcf 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,10 @@ release # OS Thumbs.db +# Electron dev cache +.electron/ +.cache/ + # 忽略 Visual Studio 临时文件夹 @@ -50,4 +54,4 @@ Thumbs.db *.ipch *.aps -wcdb/ \ No newline at end of file +wcdb/ diff --git a/src/pages/ChatPage.tsx b/src/pages/ChatPage.tsx index 000e346..767cf6d 100644 --- a/src/pages/ChatPage.tsx +++ b/src/pages/ChatPage.tsx @@ -97,7 +97,7 @@ const SessionItem = React.memo(function SessionItem({ formatTime: (timestamp: number) => string }) { // 缓存格式化的时间 - const timeText = useMemo(() => + const timeText = useMemo(() => formatTime(session.lastTimestamp || session.sortTimestamp), [formatTime, session.lastTimestamp, session.sortTimestamp] ) @@ -287,7 +287,7 @@ function ChatPage(_props: ChatPageProps) { const [highlightedMessageKeys, setHighlightedMessageKeys] = useState([]) const [isRefreshingSessions, setIsRefreshingSessions] = useState(false) const [hasInitialMessages, setHasInitialMessages] = useState(false) - + // 联系人信息加载控制 const isEnrichingRef = useRef(false) const enrichCancelledRef = useRef(false) @@ -407,28 +407,28 @@ function ChatPage(_props: ChatPageProps) { // 分批异步加载联系人信息(优化性能:防止重复加载,滚动时暂停,只在空闲时加载) const enrichSessionsContactInfo = async (sessions: ChatSession[]) => { if (sessions.length === 0) return - + // 防止重复加载 if (isEnrichingRef.current) { console.log('[性能监控] 联系人信息正在加载中,跳过重复请求') return } - + isEnrichingRef.current = true enrichCancelledRef.current = false - + console.log(`[性能监控] 开始加载联系人信息,会话数: ${sessions.length}`) const totalStart = performance.now() - + // 延迟启动,等待UI渲染完成 await new Promise(resolve => setTimeout(resolve, 500)) - + // 检查是否被取消 if (enrichCancelledRef.current) { isEnrichingRef.current = false return } - + try { // 找出需要加载联系人信息的会话(没有缓存的) const needEnrich = sessions.filter(s => !s.avatarUrl && (!s.displayName || s.displayName === s.username)) @@ -443,7 +443,7 @@ function ChatPage(_props: ChatPageProps) { // 进一步减少批次大小,每批3个,避免DLL调用阻塞 const batchSize = 3 let loadedCount = 0 - + for (let i = 0; i < needEnrich.length; i += batchSize) { // 如果正在滚动,暂停加载 if (isScrollingRef.current) { @@ -454,14 +454,14 @@ function ChatPage(_props: ChatPageProps) { } if (enrichCancelledRef.current) break } - + // 检查是否被取消 if (enrichCancelledRef.current) break - + const batchStart = performance.now() const batch = needEnrich.slice(i, i + batchSize) const usernames = batch.map(s => s.username) - + // 使用 requestIdleCallback 延迟执行,避免阻塞UI await new Promise((resolve) => { if ('requestIdleCallback' in window) { @@ -474,13 +474,13 @@ function ChatPage(_props: ChatPageProps) { }, 300) } }) - + loadedCount += batch.length const batchTime = performance.now() - batchStart if (batchTime > 200) { console.warn(`[性能监控] 批次 ${Math.floor(i / batchSize) + 1}/${Math.ceil(needEnrich.length / batchSize)} 耗时: ${batchTime.toFixed(2)}ms (已加载: ${loadedCount}/${needEnrich.length})`) } - + // 批次间延迟,给UI更多时间(DLL调用可能阻塞,需要更长的延迟) if (i + batchSize < needEnrich.length && !enrichCancelledRef.current) { // 如果不在滚动,可以延迟短一点 @@ -488,7 +488,7 @@ function ChatPage(_props: ChatPageProps) { await new Promise(resolve => setTimeout(resolve, delay)) } } - + const totalTime = performance.now() - totalStart if (!enrichCancelledRef.current) { console.log(`[性能监控] 联系人信息加载完成,总耗时: ${totalTime.toFixed(2)}ms, 已加载: ${loadedCount}/${needEnrich.length}`) @@ -570,19 +570,19 @@ function ChatPage(_props: ChatPageProps) { try { // 在 DLL 调用前让出控制权(使用 setTimeout 0 代替 setImmediate) await new Promise(resolve => setTimeout(resolve, 0)) - + const dllStart = performance.now() const result = await window.electronAPI.chat.enrichSessionsContactInfo(usernames) const dllTime = performance.now() - dllStart - + // DLL 调用后再次让出控制权 await new Promise(resolve => setTimeout(resolve, 0)) - + const totalTime = performance.now() - startTime if (dllTime > 50 || totalTime > 100) { console.warn(`[性能监控] DLL调用耗时: ${dllTime.toFixed(2)}ms, 总耗时: ${totalTime.toFixed(2)}ms, usernames: ${usernames.length}`) } - + if (result.success && result.contacts) { // 将更新加入队列,而不是立即更新 for (const [username, contact] of Object.entries(result.contacts)) { @@ -644,7 +644,7 @@ function ChatPage(_props: ChatPageProps) { const session = sessionMapRef.current.get(sessionId) const unreadCount = session?.unreadCount ?? 0 const messageLimit = offset === 0 && unreadCount > 99 ? 30 : 50 - + if (offset === 0) { setLoadingMessages(true) setMessages([]) @@ -742,7 +742,7 @@ function ChatPage(_props: ChatPageProps) { scrollTimeoutRef.current = requestAnimationFrame(() => { if (!messageListRef.current) return - + const { scrollTop, clientHeight, scrollHeight } = messageListRef.current // 显示回到底部按钮:距离底部超过 300px @@ -842,7 +842,7 @@ function ChatPage(_props: ChatPageProps) { if (!isConnected && !isConnecting) { connect() } - + // 组件卸载时清理 return () => { avatarLoadQueue.clear() @@ -906,7 +906,7 @@ function ChatPage(_props: ChatPageProps) { }) } if (payloads.length > 0) { - window.electronAPI.image.preload(payloads).catch(() => {}) + window.electronAPI.image.preload(payloads).catch(() => { }) } }, [currentSessionId, messages]) @@ -1114,7 +1114,7 @@ function ChatPage(_props: ChatPageProps) { ))} ) : Array.isArray(filteredSessions) && filteredSessions.length > 0 ? ( -
{ @@ -1195,56 +1195,56 @@ function ChatPage(_props: ChatPageProps) { ref={messageListRef} onScroll={handleScroll} > - {hasMoreMessages && ( -
- {isLoadingMore ? ( - <> - - 加载更多... - - ) : ( - 向上滚动加载更多 - )} -
- )} - - {messages.map((msg, index) => { - const prevMsg = index > 0 ? messages[index - 1] : undefined - const showDateDivider = shouldShowDateDivider(msg, prevMsg) - - // 显示时间:第一条消息,或者与上一条消息间隔超过5分钟 - const showTime = !prevMsg || (msg.createTime - prevMsg.createTime > 300) - const isSent = msg.isSend === 1 - const isSystem = msg.localType === 10000 - - // 系统消息居中显示 - const wrapperClass = isSystem ? 'system' : (isSent ? 'sent' : 'received') - - const messageKey = getMessageKey(msg) - return ( -
- {showDateDivider && ( -
- {formatDateDivider(msg.createTime)} -
- )} - -
- ) - })} - - {/* 回到底部按钮 */} -
- - 回到底部 + {hasMoreMessages && ( +
+ {isLoadingMore ? ( + <> + + 加载更多... + + ) : ( + 向上滚动加载更多 + )}
+ )} + + {messages.map((msg, index) => { + const prevMsg = index > 0 ? messages[index - 1] : undefined + const showDateDivider = shouldShowDateDivider(msg, prevMsg) + + // 显示时间:第一条消息,或者与上一条消息间隔超过5分钟 + const showTime = !prevMsg || (msg.createTime - prevMsg.createTime > 300) + const isSent = msg.isSend === 1 + const isSystem = msg.localType === 10000 + + // 系统消息居中显示 + const wrapperClass = isSystem ? 'system' : (isSent ? 'sent' : 'received') + + const messageKey = getMessageKey(msg) + return ( +
+ {showDateDivider && ( +
+ {formatDateDivider(msg.createTime)} +
+ )} + +
+ ) + })} + + {/* 回到底部按钮 */} +
+ + 回到底部
+
{/* 会话详情面板 */} {showDetailPanel && ( @@ -1434,7 +1434,7 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat }: bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) { return 'image/webp' } - } catch {} + } catch { } return 'image/jpeg' }, []) @@ -1501,7 +1501,7 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat }: setSenderAvatarUrl(result.avatarUrl) setSenderName(result.displayName) } - }).catch(() => {}).finally(() => { + }).catch(() => { }).finally(() => { senderAvatarLoading.delete(sender) }) } @@ -1597,7 +1597,7 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat }: } setImageHasUpdate(Boolean(result.hasUpdate)) } - }).catch(() => {}) + }).catch(() => { }) return () => { cancelled = true } @@ -1685,6 +1685,12 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat }: // 是否有引用消息 const hasQuote = message.quotedContent && message.quotedContent.length > 0 + // 去除企业微信 ID 前缀 + const cleanMessageContent = (content: string) => { + if (!content) return '' + return content.replace(/^[a-zA-Z0-9]+@openim:\n?/, '') + } + // 解析混合文本和表情 const renderTextWithEmoji = (text: string) => { if (!text) return text @@ -1895,14 +1901,14 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat }:
{message.quotedSender && {message.quotedSender}} - {renderTextWithEmoji(message.quotedContent || '')} + {renderTextWithEmoji(cleanMessageContent(message.quotedContent || ''))}
-
{renderTextWithEmoji(message.parsedContent)}
+
{renderTextWithEmoji(cleanMessageContent(message.parsedContent))}
) } // 普通消息 - return
{renderTextWithEmoji(message.parsedContent)}
+ return
{renderTextWithEmoji(cleanMessageContent(message.parsedContent))}
} return ( diff --git a/src/pages/WelcomePage.tsx b/src/pages/WelcomePage.tsx index d7a08de..c346569 100644 --- a/src/pages/WelcomePage.tsx +++ b/src/pages/WelcomePage.tsx @@ -506,6 +506,7 @@ function WelcomePage({ standalone = false }: WelcomePageProps) { {dbKeyStatus &&
{dbKeyStatus}
}
获取密钥会自动识别最近登录的账号
+
如果获取秘钥失败 请在微信打开后等待10秒后再登录
)} From f09ab1bbcceb7256b07e7d73309b52ea0f5dde7a Mon Sep 17 00:00:00 2001 From: xuncha <1658671838@qq.com> Date: Wed, 14 Jan 2026 13:31:51 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E4=BA=86=E7=BE=A4?= =?UTF-8?q?=E5=A4=B4=E5=83=8F=E5=AF=BC=E5=87=BA=E4=B8=A2=E5=A4=B1=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + electron/services/exportService.ts | 84 +++++++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 3433fcf..66440f0 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ dist dist-electron dist-ssr *.local +test/ # Editor directories and files .vscode/* diff --git a/electron/services/exportService.ts b/electron/services/exportService.ts index de87244..4a5550d 100644 --- a/electron/services/exportService.ts +++ b/electron/services/exportService.ts @@ -19,6 +19,7 @@ interface ChatLabMeta { platform: string type: 'group' | 'private' groupId?: string + groupAvatar?: string } interface ChatLabMember { @@ -425,6 +426,81 @@ class ExportService { return { rows, memberSet, firstTime, lastTime } } + // 补齐群成员,避免只导出发言者导致头像缺失 + private async mergeGroupMembers( + chatroomId: string, + memberSet: Map, + includeAvatars: boolean + ): Promise { + const result = await wcdbService.getGroupMembers(chatroomId) + if (!result.success || !result.members || result.members.length === 0) return + + const rawMembers = result.members as Array<{ + username?: string + avatarUrl?: string + nickname?: string + displayName?: string + remark?: string + originalName?: string + }> + const usernames = rawMembers + .map((member) => member.username) + .filter((username): username is string => Boolean(username)) + if (usernames.length === 0) return + + const lookupUsernames = new Set() + for (const username of usernames) { + lookupUsernames.add(username) + const cleaned = this.cleanAccountDirName(username) + if (cleaned && cleaned !== username) { + lookupUsernames.add(cleaned) + } + } + + const [displayNames, avatarUrls] = await Promise.all([ + wcdbService.getDisplayNames(Array.from(lookupUsernames)), + includeAvatars ? wcdbService.getAvatarUrls(Array.from(lookupUsernames)) : Promise.resolve({ success: true, map: {} }) + ]) + + for (const member of rawMembers) { + const username = member.username + if (!username) continue + + const cleaned = this.cleanAccountDirName(username) + const displayName = displayNames.success && displayNames.map + ? (displayNames.map[username] || (cleaned ? displayNames.map[cleaned] : undefined) || username) + : username + const groupNickname = member.nickname || member.displayName || member.remark || member.originalName + const avatarUrl = includeAvatars && avatarUrls.success && avatarUrls.map + ? (avatarUrls.map[username] || (cleaned ? avatarUrls.map[cleaned] : undefined) || member.avatarUrl) + : member.avatarUrl + + const existing = memberSet.get(username) + if (existing) { + if (displayName && existing.member.accountName === existing.member.platformId && displayName !== existing.member.platformId) { + existing.member.accountName = displayName + } + if (groupNickname && !existing.member.groupNickname) { + existing.member.groupNickname = groupNickname + } + if (!existing.avatarUrl && avatarUrl) { + existing.avatarUrl = avatarUrl + } + memberSet.set(username, existing) + continue + } + + const chatlabMember: ChatLabMember = { + platformId: username, + accountName: displayName + } + if (groupNickname) { + chatlabMember.groupNickname = groupNickname + } + memberSet.set(username, { member: chatlabMember, avatarUrl }) + } + } + private resolveAvatarFile(avatarUrl?: string): { data?: Buffer; sourcePath?: string; sourceUrl?: string; ext: string; mime?: string } | null { if (!avatarUrl) return null if (avatarUrl.startsWith('data:')) { @@ -567,6 +643,9 @@ class ExportService { const collected = await this.collectMessages(sessionId, cleanedMyWxid, options.dateRange) const allMessages = collected.rows + if (isGroup) { + await this.mergeGroupMembers(sessionId, collected.memberSet, options.exportAvatars === true) + } allMessages.sort((a, b) => a.createTime - b.createTime) @@ -585,6 +664,7 @@ class ExportService { return { sender: msg.senderUsername, accountName: memberInfo.accountName, + groupNickname: memberInfo.groupNickname, timestamp: msg.createTime, type: this.convertMessageType(msg.localType, msg.content), content: this.parseMessageContent(msg.content, msg.localType) @@ -603,6 +683,7 @@ class ExportService { ) : new Map() + const sessionAvatar = avatarMap.get(sessionId) const members = Array.from(collected.memberSet.values()).map((info) => { const avatar = avatarMap.get(info.member.platformId) return avatar ? { ...info.member, avatar } : info.member @@ -618,7 +699,8 @@ class ExportService { name: sessionInfo.displayName, platform: 'wechat', type: isGroup ? 'group' : 'private', - ...(isGroup && { groupId: sessionId }) + ...(isGroup && { groupId: sessionId }), + ...(sessionAvatar && { groupAvatar: sessionAvatar }) }, members, messages: chatLabMessages