mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
3865 lines
152 KiB
TypeScript
3865 lines
152 KiB
TypeScript
import path from 'node:path'
|
||
import { isWcdbDebugEnabled } from './wcdb-debug'
|
||
import {
|
||
isLegacyMigrationHelper,
|
||
isUserDataIsolated,
|
||
roots as appDataRoots
|
||
} from './app-data-bootstrap'
|
||
import './preload-env'
|
||
import {
|
||
app,
|
||
shell,
|
||
BrowserWindow,
|
||
ipcMain,
|
||
nativeImage,
|
||
clipboard,
|
||
Menu,
|
||
Tray,
|
||
dialog,
|
||
protocol,
|
||
screen
|
||
} from 'electron'
|
||
import { dirname, extname, join } from 'path'
|
||
import { existsSync, promises as fsPromises } from 'fs'
|
||
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
|
||
import icon from '../../resources/icon.png?asset'
|
||
import trayTemplateIcon from '../../resources/trayTemplate.png?asset'
|
||
import trayTemplateRetinaIcon from '../../resources/trayTemplate@2x.png?asset'
|
||
import { WechatDb } from './wechat-db'
|
||
import { createTrayImage } from './tray-icon'
|
||
import { bootstrapWcdbNativeAsync, Wcdb4Client } from './wcdb4-client'
|
||
import { VoiceService } from './voice-service'
|
||
import { StickerService } from './sticker-service'
|
||
import { parseMessageContent } from './message-parser'
|
||
import {
|
||
ImageDecryptService,
|
||
inspectImageDecoderExecutable,
|
||
inspectImageDecoderStatus,
|
||
resolveFfmpegExecutable,
|
||
type DecodedImage
|
||
} from './image-decrypt-service'
|
||
import { exportGroupReportSnapshot, extractGroupReportRenderSnapshot } from './group-report-service'
|
||
import {
|
||
deleteGeneratedReport,
|
||
listGeneratedReports,
|
||
prepareGeneratedReportTemplateSwitch,
|
||
saveGeneratedReport,
|
||
updateGeneratedReportTemplate
|
||
} from './report-history-service'
|
||
import { reportTemplateService } from './report-template-service'
|
||
import { registerReportTemplateIpc } from './report-template-ipc'
|
||
import type { GroupReportRenderSnapshotExportRequest } from '../shared/group-report'
|
||
import type {
|
||
SaveGeneratedReportRequest,
|
||
PrepareGeneratedReportTemplateSwitchRequest,
|
||
UpdateGeneratedReportTemplateRequest
|
||
} from '../shared/report-history'
|
||
import type {
|
||
AIChatRequestOptions,
|
||
AiSearchExternalAuthorizationRequest,
|
||
AIProviderConfig,
|
||
AIVisionTestRequest,
|
||
LegacyAIConfig
|
||
} from '../shared/ai-provider'
|
||
import { DatabaseKeyStore } from './database-key-store'
|
||
import { apiTokenStore } from './api-token-store'
|
||
import { ImageKeyConfigService } from './services/image-key-config-service'
|
||
import { AIProviderService } from './services/ai-provider-service'
|
||
import { imageInsightService } from './services/image-insight-service'
|
||
import { systemOcrService } from './services/system-ocr-service'
|
||
import type {
|
||
ImageAnalysisRequest,
|
||
ImageAnalysisResponse,
|
||
ImageCandidate,
|
||
ImageCandidateQuery,
|
||
ImageInsight
|
||
} from '../shared/image-insight'
|
||
import type { SystemOcrCapability, SystemOcrRequest, SystemOcrResult } from '../shared/system-ocr'
|
||
import { KeyServiceMac } from './key-service-mac'
|
||
import { getMacArchSnapshot } from './macos-arch'
|
||
import { shouldProbeIntelEnvironment } from '../shared/macos-arch'
|
||
import { KeyService as KeyServiceWin } from './key-service-win'
|
||
import * as chat from './services/chat-service'
|
||
import {
|
||
apiServer,
|
||
setLocalGroupStatsService,
|
||
setLocalQueryApiService,
|
||
setLocalVoiceTranscriptSnapshotProvider
|
||
} from './http-server'
|
||
import { skillResourceService } from './services/skill-resource-service'
|
||
import { buildLocalApiCurlCommand, testLocalApiRequest } from './services/local-api-test-service'
|
||
import { isWechatRunning } from './services/wechat-process-status'
|
||
import {
|
||
inspectImageDecryptionStatus,
|
||
testImageDecryption
|
||
} from './services/image-decryption-status-service'
|
||
import type { SaveImageKeyRequest, TestImageDecryptionRequest } from '../shared/image-decryption'
|
||
import { imageFileQuality } from '../shared/image-quality'
|
||
import {
|
||
IMAGE_DEBUG_KIND,
|
||
type ImageDebugInfoRequest,
|
||
type ImageDebugInfoResult,
|
||
type ImageDebugPayload,
|
||
type ImageDebugQuality
|
||
} from '../shared/image-debug-info'
|
||
import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
|
||
import {
|
||
loadSettings,
|
||
saveSettings,
|
||
updateSettings,
|
||
getSettingsPath,
|
||
normalizeSkippedUpdateVersion,
|
||
AppSettings,
|
||
validateDbRoot
|
||
} from './services/settings-store'
|
||
import {
|
||
detectDataStructureVersion,
|
||
detectWechatVersion,
|
||
getOsVersionLabel
|
||
} from './services/connection-diagnostics'
|
||
import { buildSafeDiagnosticSummary } from '../shared/connection-diagnostics'
|
||
import {
|
||
flushBootstrapCacheWritesSync,
|
||
getBootstrapCache,
|
||
getCachedMessagePage,
|
||
getCachedMessages,
|
||
mergeBootstrapAvatars,
|
||
mergeCachedContactAvatars,
|
||
mergeCachedSelfInfo,
|
||
saveBootstrapContacts,
|
||
saveBootstrapSelf,
|
||
saveCachedGroupSnapshot,
|
||
saveCachedMessages
|
||
} from './services/bootstrap-cache'
|
||
import { installSafeConsole } from './safe-log'
|
||
import { agentHubService } from './services/agent-hub-service'
|
||
import { WechatConnectorService } from './services/wechat-ilink'
|
||
import { wechatSendGateway } from './services/wechat-send-gateway'
|
||
import { groupExitMonitorService } from './services/group-exit-monitor-service'
|
||
import {
|
||
filterSendableFriendContacts,
|
||
leaveNotificationContactDisplayName
|
||
} from './services/leave-notification-target'
|
||
import { MessageListenerService } from './services/message-listener-service'
|
||
import { EXTENSION_IPC } from '../shared/extensions/ipc'
|
||
import { installExtensionProtocolHandler, registerExtensionScheme } from './extensions/extension-protocol'
|
||
import { registerExtensionIpc } from './extensions/extension-ipc'
|
||
import { getExtensionPaths } from './extensions/extension-paths'
|
||
import {
|
||
disposeExtensionSystem,
|
||
getExtensionManager,
|
||
hasExtensionManager,
|
||
initExtensionSystem
|
||
} from './extensions/extension-service'
|
||
import { automationRuleStore } from './services/automation-rule-store'
|
||
import { automationExecutionLogService } from './services/automation-execution-log-service'
|
||
import { initAutomationService, getAutomationService } from './services/automation-service'
|
||
import {
|
||
applyMsgInsertSwitch,
|
||
emptyMsgInsertStatus,
|
||
eventModeStatus,
|
||
readMsgInsertSwitches,
|
||
reconcileMsgInsertRules,
|
||
resolveHelperPath,
|
||
resolveTargetRooms,
|
||
type MsgInsertScopeInput,
|
||
type MsgInsertSwitchName,
|
||
type MsgInsertSwitchesSnapshot
|
||
} from './services/msg-insert-switch-service'
|
||
import type { MsgInsertErrorCode, MsgInsertSwitchStatus } from '../shared/msg-insert-switch'
|
||
import {
|
||
msgInsertCapabilityService,
|
||
type MessageInsertCapability
|
||
} from './services/msg-insert-capability-service'
|
||
import { resolveExternalComponent } from './services/external-component-locator'
|
||
import {
|
||
cleanupMacWechatResidualProcesses,
|
||
inspectMacWechatResidualProcesses
|
||
} from './services/mac-wechat-residual-cleanup'
|
||
import {
|
||
isDefinitelyBlocked,
|
||
isEntitlementBlocked,
|
||
resolveExitNoticeGate,
|
||
resolveSwitchPresentation
|
||
} from './services/exit-notice-gate'
|
||
import { GroupStatsService } from './services/group-stats-service'
|
||
import {
|
||
configureWechatLocalExitNotice,
|
||
wechatLocalExitNoticeService
|
||
} from './services/wechat-local-exit-notice-service'
|
||
|
||
/** 「微信内退群监控消息」覆盖的群聊数(开关卡片的范围说明用,不是覆盖率)。 */
|
||
function exitNoticeGroupCount(): number {
|
||
return groupExitMonitorService.getNoticeGroupCount()
|
||
}
|
||
|
||
/**
|
||
* 把「微信内退群监控消息」的开关状态同步给退群监控。
|
||
*
|
||
* 注入的只是**开关**:群清单由 monitor 自己在刷新群名时一并更新,
|
||
* 这里不维护第二份。检测范围会成为「勾选的群 ∪ 全部群聊」,两个消费者都能拿到事件。
|
||
*/
|
||
function syncExitNoticeScope(): void {
|
||
try {
|
||
groupExitMonitorService.setNoticeEnabled(wechatLocalExitNoticeService.isEnabled())
|
||
} catch (error) {
|
||
console.warn('[MsgInsert] 同步退群内提示范围失败:', error)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 微信消息插入开关的作用面输入。
|
||
*
|
||
* 防撤回用「全部可定位会话」;退群监控的勾选只服务自动化通知,不再是内提示的范围。
|
||
* 数据库没连上时返回 null,调用方据此禁用写入而不是假装能改。
|
||
*/
|
||
function resolveMsgInsertScopeInput(): MsgInsertScopeInput | null {
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (!client) return null
|
||
return {
|
||
client,
|
||
monitoredRoomIds: groupExitMonitorService.getState().monitoredRoomIds || []
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 组装「微信消息插入开关」的快照。**纯读**:不写微信库、不触发 DDL。
|
||
*
|
||
* 抽出来是为了让 GET 与「运行期刷新」共用同一份展示口径(含退群提示这个本地事件开关),
|
||
* 避免两处各拼一遍导致漂移。
|
||
*/
|
||
function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
|
||
const scope = resolveMsgInsertScopeInput()
|
||
if (scope) {
|
||
const snapshot = readMsgInsertSwitches(scope)
|
||
/* 退群提示的开关状态来自本地设置(事件驱动,不装规则),
|
||
* 不是微信库里的 _tm_config。 */
|
||
snapshot.switches.group_exit_notice = eventModeStatus(
|
||
'group_exit_notice',
|
||
wechatLocalExitNoticeService.isEnabled(),
|
||
exitNoticeGroupCount()
|
||
)
|
||
return snapshot
|
||
}
|
||
return {
|
||
success: false,
|
||
switches: {
|
||
recall_notice: emptyMsgInsertStatus('recall_notice'),
|
||
group_exit_notice: eventModeStatus(
|
||
'group_exit_notice',
|
||
wechatLocalExitNoticeService.isEnabled()
|
||
)
|
||
},
|
||
helperAvailable: resolveHelperPath() !== null,
|
||
detail: '微信数据库尚未连接'
|
||
}
|
||
}
|
||
|
||
/** 能力判定需要知道「微信库连没连」,但不需要知道发送是否就绪。 */
|
||
function capabilityDatabaseReady(): boolean {
|
||
return Boolean(chat.getChatDb()?.getWcdb4Client())
|
||
}
|
||
|
||
/**
|
||
* 退群提示与防撤回同为发送能力:授权/组件不成立时 desired 与 effective 一起压
|
||
* (UI 读 desired),探测失败不落盘,否则正常用户会被误关。
|
||
*/
|
||
/** 明确不可用时把本地开关落盘关掉;只写设置文件,不动监控范围。 */
|
||
function enforceExitNoticeGate(capability: MessageInsertCapability): void {
|
||
if (!isDefinitelyBlocked(capability)) return
|
||
if (!wechatLocalExitNoticeService.isEnabled()) return
|
||
const decision = resolveExitNoticeGate(capability, true)
|
||
if (!decision.persistDisable) return
|
||
const disabled = wechatLocalExitNoticeService.setEnabled(false)
|
||
syncExitNoticeScope()
|
||
appLogger.write({
|
||
level: 'warn',
|
||
scope: 'capability-gate',
|
||
message: '退群内提示已因发送能力不可用自动关闭',
|
||
details: {
|
||
reasonCode: capability.reasonCode,
|
||
entitlementState: capability.entitlementState,
|
||
nativeComponentState: capability.nativeComponentState,
|
||
persisted: !disabled.error
|
||
}
|
||
})
|
||
}
|
||
|
||
/** 把授权/组件判定挂到快照上;GET 仍是纯读,不写库不触发 DDL。 */
|
||
async function attachCapability(
|
||
snapshot: MsgInsertSwitchesSnapshot
|
||
): Promise<MsgInsertSwitchesSnapshot> {
|
||
const capability = await msgInsertCapabilityService.getCapability({
|
||
databaseReady: capabilityDatabaseReady()
|
||
})
|
||
enforceExitNoticeGate(capability)
|
||
|
||
/* 两个开关的呈现共用同一判定:授权不成立显示关闭,库没连只压 effective。 */
|
||
const switches = { ...snapshot.switches }
|
||
const applyPresentation = (
|
||
kind: 'recall_notice' | 'group_exit_notice',
|
||
status: MsgInsertSwitchStatus | undefined
|
||
): MsgInsertSwitchStatus | undefined => {
|
||
if (!status) return status
|
||
const current =
|
||
kind === 'group_exit_notice'
|
||
? wechatLocalExitNoticeService.isEnabled()
|
||
: status.desiredEnabled === true
|
||
const presentation = resolveSwitchPresentation(kind, current, capability)
|
||
if (presentation.effectiveEnabled) {
|
||
return {
|
||
...status,
|
||
desiredEnabled: true,
|
||
effectiveEnabled: true,
|
||
operationOk: true
|
||
}
|
||
}
|
||
/*
|
||
* 不要无脑覆盖 errorCode:授权没问题、只是暂时不生效时(库没连、分片没读到),
|
||
* 用 CAPABILITY_READY 盖上去会把真实原因擦掉,用户看到的是「授权与组件均已就绪」
|
||
* 配一个点不动的开关。
|
||
*/
|
||
const blocked = isEntitlementBlocked(capability)
|
||
return {
|
||
...status,
|
||
desiredEnabled: presentation.desiredEnabled,
|
||
effectiveEnabled: false,
|
||
operationOk: false,
|
||
errorCode: blocked
|
||
? (capability.reasonCode as MsgInsertErrorCode)
|
||
: (status.errorCode ?? (capability.reasonCode as MsgInsertErrorCode)),
|
||
message: blocked ? capability.message : (status.message ?? capability.message)
|
||
}
|
||
}
|
||
switches.recall_notice = applyPresentation('recall_notice', switches.recall_notice)!
|
||
switches.group_exit_notice = applyPresentation('group_exit_notice', switches.group_exit_notice)!
|
||
return {
|
||
...snapshot,
|
||
switches,
|
||
capability: capability,
|
||
/* 旧字段保留一个与真实判定一致的值,避免老调用方继续读到一个恒 true */
|
||
sendCapabilityAvailable: capability.canEnable
|
||
}
|
||
}
|
||
|
||
/** 能力原因 → 开关错误码。三种「不可用」必须能区分开。 */
|
||
function reasonToErrorCode(capability: MessageInsertCapability): MsgInsertErrorCode {
|
||
switch (capability.reasonCode) {
|
||
case 'LICENSE_REQUIRED':
|
||
return 'LICENSE_REQUIRED'
|
||
case 'LICENSE_PENDING':
|
||
return 'LICENSE_PENDING'
|
||
case 'LICENSE_EXPIRED':
|
||
return 'LICENSE_EXPIRED'
|
||
case 'COMPONENT_MISSING':
|
||
case 'COMPONENT_INVALID':
|
||
return 'COMPONENT_MISSING'
|
||
case 'DATABASE_UNAVAILABLE':
|
||
return 'DATABASE_UNAVAILABLE'
|
||
default:
|
||
return 'CAPABILITY_UNAVAILABLE'
|
||
}
|
||
}
|
||
|
||
/** 开启前的统一裁决:拿最新状态,不信页面缓存。 */
|
||
async function requireCapability(): Promise<{
|
||
ok: boolean
|
||
capability: MessageInsertCapability
|
||
}> {
|
||
const capability = await msgInsertCapabilityService.refresh({
|
||
databaseReady: capabilityDatabaseReady()
|
||
})
|
||
return { ok: capability.canEnable, capability }
|
||
}
|
||
|
||
/**
|
||
* 轻量 reconciliation —— 把退群监控选中的群缺失的规则补齐,不动开关值。
|
||
*
|
||
* 触发点:连库完成后 / 退群监控群列表变化后 / 用户打开开关时(那条在 service 里)。
|
||
* 不轮询。微信新建 message_4.db 并把目标群的新表放进去时,下一次触发就会补上。
|
||
*/
|
||
let lastMsgInsertReconciledShards = ''
|
||
|
||
/**
|
||
* 启动时补齐 —— 防撤回 reconciliation 的入口之一。
|
||
*
|
||
* 只在**持久化的开关已经是开**的时候跑(说明用户上次明确打开过)。开关是关的
|
||
* 就什么都不做,避免每次启动都扫一遍目标会话。
|
||
*
|
||
* 顺带覆盖「已启用时检测到新 shard / 新表」:分片清单变了就重新补齐,并把新的
|
||
* 清单记下来。渲染层读状态**不会**走到这里 —— GET 必须是纯读。
|
||
*/
|
||
async function reconcileMsgInsertRulesOnStart(): Promise<void> {
|
||
const scope = resolveMsgInsertScopeInput()
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (!scope || !client) return
|
||
|
||
let enabled = false
|
||
let shardSignature = ''
|
||
try {
|
||
const shards = client.listMessageShardPaths()
|
||
shardSignature = shards.map((item) => path.basename(item)).join(',')
|
||
if (lastMsgInsertReconciledShards && lastMsgInsertReconciledShards !== shardSignature) {
|
||
/* 微信新建了 message_N.db(或清理了旧的)—— 分片集合变了就重新补齐。 */
|
||
console.log('[MsgInsert] 检测到消息分片变化,重新补齐规则')
|
||
}
|
||
for (const shardPath of shards) {
|
||
const read = client.getMsgInsertSwitches(shardPath)
|
||
if (read.success && read.switches?.recall_notice) {
|
||
enabled = true
|
||
break
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.warn('[MsgInsert] 启动检查失败:', error)
|
||
return
|
||
}
|
||
if (!enabled) return
|
||
|
||
/*
|
||
* 授权前置:没有有效授权时不许 spawn helper 装规则。
|
||
* 指纹**不在这里更新** —— 没补成功就记指纹,会让「无授权跳过 → 后来激活 →
|
||
* 分片没变 → 永远不再补」这个死循环成立。
|
||
*/
|
||
const gate = await requireCapability()
|
||
if (!gate.ok) {
|
||
console.log(
|
||
`[MsgInsert] 启动补齐已跳过:${gate.capability.reasonCode}(${gate.capability.message})`
|
||
)
|
||
return
|
||
}
|
||
const done = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||
if (done) lastMsgInsertReconciledShards = shardSignature
|
||
}
|
||
|
||
function recallRoomsForReconcile(scope: MsgInsertScopeInput): string[] {
|
||
return resolveTargetRooms(scope, 'recall_notice').rooms
|
||
}
|
||
|
||
async function reconcileMsgInsertRulesNow(extraRooms: string[] = []): Promise<boolean> {
|
||
const scope = resolveMsgInsertScopeInput()
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (!scope || !client) return false
|
||
/*
|
||
* 底层兜底:不管从哪条路径进来(启动 / 刷新 / 清理 / 未来的新调用方),
|
||
* 装规则前都过一次发送能力校验。上层已经判过也不亏——命中 TTL 缓存几乎零成本。
|
||
*/
|
||
const gate = await requireCapability()
|
||
if (!gate.ok) {
|
||
console.warn(`[MsgInsert] 拒绝安装规则:${gate.capability.reasonCode}`)
|
||
return false
|
||
}
|
||
try {
|
||
const result = await reconcileMsgInsertRules({
|
||
...scope,
|
||
extraRooms,
|
||
myWxid: String(chat.getSelfAccountInfo()?.wxid || ''),
|
||
databaseKey: client.getKey()
|
||
})
|
||
if (result.rooms === 0) {
|
||
// 群列表还没就绪(或用户本来就没选群)—— 不算跑过,让下一次触发重试。
|
||
return false
|
||
}
|
||
if (!result.done) {
|
||
console.warn(`[MsgInsert] reconcile 未完成 errorCode=${result.errorCode || 'UNKNOWN'}`)
|
||
}
|
||
return true
|
||
} catch (error) {
|
||
console.warn('[MsgInsert] reconcile 失败:', error)
|
||
return true
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 清理老版防撤回保护(recall journal)留在微信库里的 `_wxe_capture_*` 触发器。
|
||
*
|
||
* 那批触发器装进库里就没人卸载(应用关闭该功能时直接 return),会一直抓取;而且它
|
||
* 和新机制的触发器挂在同一张 `Msg_*` 表上抢事件。
|
||
*
|
||
* 边界:先只读扫描、有残留才写库;只删触发器、不删老日志表(表里是微信已删、可能
|
||
* 只剩一份的副本);日志只记数量(对象名含 sha1(会话表名) 派生的稳定标识)。
|
||
*/
|
||
async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (!client) return
|
||
try {
|
||
const report = client.scanLegacyRecallResidue()
|
||
if (!report.found) return
|
||
|
||
console.log(
|
||
`[RecallResidue] 检测到老版防撤回残留 shards=${report.shards.length} triggers=${report.triggerCount}` +
|
||
` journals=${report.journalCount} blockingDelete=${report.blockingDeleteCount}` +
|
||
` blockingInsert=${report.blockingInsertCount} passive=${report.passiveCount}`
|
||
)
|
||
appLogger.write({
|
||
level: 'warn',
|
||
scope: 'recall-residue',
|
||
message: '检测到老版防撤回残留,开始清理',
|
||
details: {
|
||
shards: report.shards.length,
|
||
triggers: report.triggerCount,
|
||
journals: report.journalCount,
|
||
blockingDelete: report.blockingDeleteCount,
|
||
blockingInsert: report.blockingInsertCount,
|
||
passive: report.passiveCount
|
||
}
|
||
})
|
||
|
||
/*
|
||
* 删除必须借 helper 的可写连接:本进程对分片只有只读连接,自己发 DROP 一定失败。
|
||
* helper 那条链路会在装规则时顺手清掉残留,顺带把新规则铺到所有会话。
|
||
*/
|
||
/*
|
||
* 清理只能借 helper 的 ensure-rules 完成(没有独立的 drop-only 动作),
|
||
* 而 ensure-rules 会顺手把新规则铺到所有会话 —— 那属于写库动作。
|
||
* 所以没有授权时只保留残留、不执行清理,绝不拿「清理」当借口绕开门禁。
|
||
*/
|
||
const scope = resolveMsgInsertScopeInput()
|
||
let applied = false
|
||
if (scope) {
|
||
const gate = await requireCapability()
|
||
if (gate.ok) {
|
||
applied = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||
} else {
|
||
console.log(`[RecallResidue] 无有效授权,跳过残留清理(${gate.capability.reasonCode})`)
|
||
}
|
||
}
|
||
|
||
/* 收尾结论以「重新扫描」为准,不采信 helper 的自述。 */
|
||
const after = client.scanLegacyRecallResidue()
|
||
const cleared = after.triggerCount === 0
|
||
console.log(
|
||
`[RecallResidue] 清理${cleared ? '完成' : '未完成'} applied=${applied} remainingTriggers=${after.triggerCount}` +
|
||
` remainingJournals=${after.journalCount}`
|
||
)
|
||
appLogger.write({
|
||
level: cleared ? 'info' : 'warn',
|
||
scope: 'recall-residue',
|
||
message: cleared ? '老版防撤回残留清理完成' : '老版防撤回残留清理未完成',
|
||
details: {
|
||
requested: report.triggerCount,
|
||
remainingTriggers: after.triggerCount,
|
||
remainingJournals: after.journalCount,
|
||
helperApplied: applied
|
||
}
|
||
})
|
||
} catch (error) {
|
||
/* 清理失败绝不能挡住启动 —— 它只是收尾工作。 */
|
||
console.warn(
|
||
'[RecallResidue] 清理失败:',
|
||
isWcdbDebugEnabled() ? error : error instanceof Error ? error.message : String(error)
|
||
)
|
||
appLogger.write({
|
||
level: 'warn',
|
||
scope: 'recall-residue',
|
||
message: '老版防撤回残留清理失败',
|
||
details: { reason: error instanceof Error ? error.message : String(error) }
|
||
})
|
||
}
|
||
}
|
||
import { wechatActionLogService } from './services/wechat-action-log-service'
|
||
import { toPersonalWechatSendResult, wechatActionGateway } from './services/wechat-action-gateway'
|
||
import { personalWechatSendService } from './services/personal-wechat-send-service'
|
||
import { macWechatRuntimeManager } from './services/mac-wechat-runtime-manager'
|
||
import { getPersonalWechatSendCapability } from './services/personal-wechat-capability-service'
|
||
import { scheduledReportService } from './services/scheduled-report-service'
|
||
import { personalWechatVoiceEnvironmentService } from './services/personal-wechat-voice-environment-service'
|
||
import type {
|
||
PersonalWechatGeneratedTtsVoiceRequest,
|
||
PersonalWechatSendRequest,
|
||
PersonalWechatSendResult,
|
||
PersonalWechatSenderStatus
|
||
} from '../shared/personal-wechat'
|
||
import { isTruthyDebugFlag } from '../shared/debug-flags'
|
||
import { TextToSpeechSettingsService } from './services/text-to-speech-settings-service'
|
||
import type {
|
||
ListTextToSpeechVoicesRequest,
|
||
SaveTextToSpeechSettingsRequest,
|
||
SynthesizeTextToSpeechRequest
|
||
} from '../shared/text-to-speech'
|
||
import { appLogger } from './app-logger'
|
||
import { wcdbDebugLog } from './wcdb-debug'
|
||
|
||
let getMessagesRequestSequence = 0
|
||
|
||
function nextGetMessagesRequestId(): string {
|
||
getMessagesRequestSequence += 1
|
||
return `GETMSG-${String(getMessagesRequestSequence).padStart(3, '0')}`
|
||
}
|
||
import type { AppLogEntry } from '../shared/app-log'
|
||
import { appUpdateService } from './services/app-update-service'
|
||
import { clearCache, getCacheSummary, openKnowledgeDirectory } from './services/cache-service'
|
||
import { imageTextIndexService } from './services/image-text-index-service'
|
||
import {
|
||
IMAGE_TEXT_SEGMENT_MESSAGE_LIMIT,
|
||
type ImageTextIndexStartOptions
|
||
} from '../shared/image-text-index'
|
||
import type { CacheClearScope } from './services/cache-service'
|
||
import { configureRecallArchive, RecallArchiveMonitor } from './services/recall-archive-service'
|
||
import { VideoAssetService } from './video-asset-service'
|
||
import { cancelExport, revealExport, runExport } from './export-service'
|
||
import type { ExportRequest } from '../shared/export'
|
||
import { discoverAccounts } from './services/account-discovery'
|
||
import { VoiceRecognitionUseCase } from './voice-pipeline/voice-recognition-use-case'
|
||
import { VoiceBatchService } from './voice-pipeline/voice-batch-service'
|
||
import { VoiceTranscriptionGateway } from './voice-pipeline/voice-transcription-gateway'
|
||
import type { VoiceBatchRequest, VoiceMessageReference } from '../shared/voice-recognition'
|
||
import type { AiSearchPipelineRequest } from '../shared/ai-search'
|
||
import type {
|
||
AskWechatConfig,
|
||
AskWechatQueryRequest,
|
||
AskWechatQueryResult
|
||
} from '../shared/query-agent'
|
||
import type { KnowledgeSearchIpcRequest, KnowledgeSearchIpcResult } from '../shared/knowledge'
|
||
// 消息身份的规范化在 main / renderer 之间必须一致,所以只从 shared 取一份实现。
|
||
import { normalizeMessageIdentity } from '../shared/local-query-api'
|
||
import {
|
||
isWindowsVcRuntimeMissingError,
|
||
WINDOWS_VC_RUNTIME_ERROR_MESSAGE
|
||
} from '../shared/windows-runtime'
|
||
import { KnowledgeSearchService } from './knowledge/knowledge-search-service'
|
||
import {
|
||
MESSAGES_AROUND_MAX_WINDOW,
|
||
messagesAroundRadii,
|
||
normalizeRadiusSeconds,
|
||
sliceMessagesAroundWindow,
|
||
widenRadiusSeconds
|
||
} from './services/messages-around'
|
||
import { LocalQueryApiService } from './services/local-query-api-service'
|
||
import { AiSearchPipelineService } from './services/ai-search-pipeline-service'
|
||
import { QueryAgentService } from './services/query-agent-service'
|
||
import { AskWechatService } from './services/ask-wechat-service'
|
||
import { createLocalQueryToolExecutor } from './services/local-query-tool-executor'
|
||
import { runLegacySafeStorageHelper } from './legacy-safe-storage-helper'
|
||
import { runFirstLaunchMigration } from './app-data-migration'
|
||
import { WechatShareConfigStore } from './wechat-share-config-store'
|
||
import { WechatShareCardService } from './wechat-share-card-service'
|
||
import type {
|
||
PublishWechatShareCardRequest,
|
||
WechatShareServiceConfig
|
||
} from '../shared/wechat-share-card'
|
||
|
||
async function currentPersonalWechatSenderStatus(): Promise<PersonalWechatSenderStatus> {
|
||
return process.platform === 'darwin'
|
||
? macWechatRuntimeManager.buildSenderStatus()
|
||
: personalWechatSendService.getStatus()
|
||
}
|
||
|
||
// electron-vite can close the child's stdout/stderr after spawning Electron.
|
||
// Plain console.error then throws EPIPE on a closed pipe and crashes the IPC
|
||
// handler. Wrap console.* before any other module logs anything.
|
||
installSafeConsole()
|
||
|
||
/**
|
||
* 进程内微信 iLink 连接器:inbound 回调与 outbound 发送都在主进程内完成,
|
||
* 不依赖子进程,也不开本地 HTTP 端口。
|
||
*/
|
||
const wechatConnectorService = new WechatConnectorService()
|
||
|
||
let voiceService: VoiceService | null = null
|
||
let voiceRecognition: VoiceRecognitionUseCase | null = null
|
||
let voiceBatchService: VoiceBatchService | null = null
|
||
let knowledgeSearchService: KnowledgeSearchService | null = null
|
||
let groupStatsService: GroupStatsService | null = null
|
||
let localQueryApiService: LocalQueryApiService | null = null
|
||
let aiSearchPipelineService: AiSearchPipelineService | null = null
|
||
let queryAgentService: QueryAgentService | null = null
|
||
let askWechatService: AskWechatService | null = null
|
||
let imageDecryptService: ImageDecryptService | null = null
|
||
let stickerService: StickerService | null = null
|
||
let videoAssetService: VideoAssetService | null = null
|
||
const databaseKeyStore = new DatabaseKeyStore()
|
||
const imageKeyConfigService = new ImageKeyConfigService()
|
||
const aiProviderService = new AIProviderService()
|
||
const textToSpeechSettingsService = new TextToSpeechSettingsService()
|
||
const keyServiceMac = new KeyServiceMac()
|
||
const keyServiceWin = new KeyServiceWin()
|
||
const wechatShareConfigStore = new WechatShareConfigStore()
|
||
const wechatShareCardService = new WechatShareCardService(wechatShareConfigStore)
|
||
let tray: Tray | null = null
|
||
let recallArchiveMonitor: RecallArchiveMonitor | null = null
|
||
let recallProtectionGeneration = 0
|
||
let recallJournalTimer: NodeJS.Timeout | null = null
|
||
let wcdbBootstrapPromise: Promise<unknown> | null = null
|
||
type ColdImageLoadItem = {
|
||
priority: number
|
||
sequence: number
|
||
run: () => Promise<unknown>
|
||
resolve: (value: unknown) => void
|
||
reject: (reason: unknown) => void
|
||
}
|
||
const coldImageLoadQueue: ColdImageLoadItem[] = []
|
||
let activeColdImageLoads = 0
|
||
let coldImageLoadSequence = 0
|
||
let coldImageLoadTimer: NodeJS.Timeout | null = null
|
||
let nextColdImageLoadAt = 0
|
||
|
||
const COLD_IMAGE_LOAD_GAP_MS = 100
|
||
const MAX_CONCURRENT_COLD_IMAGE_LOADS = 2
|
||
|
||
function pumpColdImageLoads(): void {
|
||
if (activeColdImageLoads >= MAX_CONCURRENT_COLD_IMAGE_LOADS || coldImageLoadQueue.length === 0) {
|
||
return
|
||
}
|
||
|
||
const waitMs = Math.max(0, nextColdImageLoadAt - Date.now())
|
||
if (waitMs > 0) {
|
||
if (!coldImageLoadTimer) {
|
||
coldImageLoadTimer = setTimeout(() => {
|
||
coldImageLoadTimer = null
|
||
pumpColdImageLoads()
|
||
}, waitMs)
|
||
}
|
||
return
|
||
}
|
||
|
||
coldImageLoadQueue.sort(
|
||
(left, right) => left.priority - right.priority || left.sequence - right.sequence
|
||
)
|
||
const item = coldImageLoadQueue.shift()
|
||
if (!item) return
|
||
|
||
activeColdImageLoads += 1
|
||
nextColdImageLoadAt = Date.now() + COLD_IMAGE_LOAD_GAP_MS
|
||
void item
|
||
.run()
|
||
.then(item.resolve, item.reject)
|
||
.finally(() => {
|
||
activeColdImageLoads -= 1
|
||
pumpColdImageLoads()
|
||
})
|
||
pumpColdImageLoads()
|
||
}
|
||
|
||
function enqueueColdImageLoad<T>(task: () => Promise<T> | T, priority = 0): Promise<T> {
|
||
return new Promise<T>((resolve, reject) => {
|
||
coldImageLoadQueue.push({
|
||
priority,
|
||
sequence: coldImageLoadSequence++,
|
||
run: async () => task(),
|
||
resolve: (value) => resolve(value as T),
|
||
reject
|
||
})
|
||
pumpColdImageLoads()
|
||
})
|
||
}
|
||
|
||
function configureRecallProtection(
|
||
wcdb4Client: Wcdb4Client,
|
||
accountRoot: string,
|
||
enabled: boolean,
|
||
installJournal = false
|
||
): void {
|
||
recallProtectionGeneration += 1
|
||
const generation = recallProtectionGeneration
|
||
recallArchiveMonitor?.stop()
|
||
recallArchiveMonitor = null
|
||
if (recallJournalTimer) {
|
||
clearTimeout(recallJournalTimer)
|
||
recallJournalTimer = null
|
||
}
|
||
configureRecallArchive(enabled ? accountRoot : '')
|
||
/*
|
||
* 读取路径必须跟开关一起走:老 recall journal 的合并以前是无条件的,
|
||
* 于是「关掉防撤回」对用户等于没关(消息照样在,且不带撤回标记)。
|
||
*/
|
||
wcdb4Client.setRecallJournalEnabled(enabled)
|
||
if (!enabled) return
|
||
|
||
const monitor = new RecallArchiveMonitor(
|
||
() =>
|
||
wcdb4Client.getSessions().map((session) => ({
|
||
md5: wcdb4Client.md5(session.username),
|
||
m_nsUsrName: session.username,
|
||
type: session.username.endsWith('@chatroom') ? 'group' : 'user',
|
||
activityKey: [
|
||
session.raw['last_timestamp'],
|
||
session.raw['sort_timestamp'],
|
||
session.raw['last_msg_locald_id'],
|
||
session.raw['last_msg_type'],
|
||
session.raw['summary']
|
||
].join(':')
|
||
})),
|
||
(sessionMd5) =>
|
||
chat.listMessages(sessionMd5, Math.floor(Date.now() / 1000) - 10 * 60, undefined, {
|
||
limit: 500
|
||
})
|
||
)
|
||
recallArchiveMonitor = monitor
|
||
// Session indexing is not required to open the UI. Defer it so large databases
|
||
// do not make db:init wait for every conversation to be enumerated.
|
||
setImmediate(() => {
|
||
if (generation === recallProtectionGeneration && recallArchiveMonitor === monitor) {
|
||
monitor.seedAll()
|
||
}
|
||
})
|
||
if (!installJournal) return
|
||
// Creating recall triggers scans every message table and runs synchronously in
|
||
// the main process. Only do this after the user explicitly enables protection;
|
||
// existing installations remain active without repeating the scan at startup.
|
||
recallJournalTimer = setTimeout(() => {
|
||
recallJournalTimer = null
|
||
if (generation !== recallProtectionGeneration || recallArchiveMonitor !== monitor) return
|
||
const result = wcdb4Client.installRecallJournal(
|
||
wcdb4Client.getSessions().map((session) => session.username)
|
||
)
|
||
console.log(
|
||
`[WCDB4] recall journal ready installed=${result.installed} failed=${result.failed}`
|
||
)
|
||
}, 30_000)
|
||
}
|
||
|
||
const packagedIconPath = join(process.resourcesPath, 'resources', 'icon.png')
|
||
const appIconPath = existsSync(packagedIconPath) ? packagedIconPath : icon
|
||
const packagedTrayTemplateIconPath = join(process.resourcesPath, 'resources', 'trayTemplate.png')
|
||
const packagedTrayTemplateRetinaIconPath = join(
|
||
process.resourcesPath,
|
||
'resources',
|
||
'trayTemplate@2x.png'
|
||
)
|
||
const trayTemplateIconPath = existsSync(packagedTrayTemplateIconPath)
|
||
? packagedTrayTemplateIconPath
|
||
: trayTemplateIcon
|
||
const trayTemplateRetinaIconPath = existsSync(packagedTrayTemplateRetinaIconPath)
|
||
? packagedTrayTemplateRetinaIconPath
|
||
: trayTemplateRetinaIcon
|
||
|
||
protocol.registerSchemesAsPrivileged([
|
||
{
|
||
scheme: 'wxe-media',
|
||
privileges: { secure: true, standard: true, stream: true, supportFetchAPI: true }
|
||
}
|
||
])
|
||
|
||
let dbInitInFlight: Promise<{ success: boolean; monitoring?: boolean; error?: string }> | null =
|
||
null
|
||
let appShutdownRequested = false
|
||
let isQuitting = false
|
||
const BUILD_MARK = 'wechat4-local-http-api-2026-07-03'
|
||
const TRAY_MODE =
|
||
process.argv.includes('--tray') || (process.env['WXE_TRAY'] || '').toString() === '1'
|
||
|
||
function getConfiguredImageKeys(): { xorKey: string; aesKey: string } {
|
||
const config = imageKeyConfigService.getConfig()
|
||
return {
|
||
xorKey: config.xorKey || '0x40',
|
||
aesKey: config.aesKey || ''
|
||
}
|
||
}
|
||
|
||
function getImageMediaService(): VideoAssetService | null {
|
||
if (videoAssetService) return videoAssetService
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (!client) return null
|
||
videoAssetService = new VideoAssetService(client)
|
||
return videoAssetService
|
||
}
|
||
|
||
function getLocalMediaMimeType(filePath: string): string {
|
||
switch (extname(filePath).toLowerCase()) {
|
||
case '.mp4':
|
||
return 'video/mp4'
|
||
case '.jpg':
|
||
case '.jpeg':
|
||
return 'image/jpeg'
|
||
case '.png':
|
||
return 'image/png'
|
||
case '.gif':
|
||
return 'image/gif'
|
||
case '.webp':
|
||
return 'image/webp'
|
||
case '.bmp':
|
||
return 'image/bmp'
|
||
default:
|
||
return 'application/octet-stream'
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 导出用的三档质量(original/medium/thumbnail)与调试信息的两档命名不同:
|
||
* 调试侧用 normal 表示「中图」,避免与 ExportImageQuality 的 medium 混淆。
|
||
*/
|
||
function toDebugQuality(quality: 'original' | 'medium' | 'thumbnail'): ImageDebugQuality {
|
||
if (quality === 'original') return 'original'
|
||
if (quality === 'thumbnail') return 'thumbnail'
|
||
return 'normal'
|
||
}
|
||
|
||
/** 反转义以 HTML 实体形式存库的正文(& 必须最后处理)。 */
|
||
function unescapeXmlText(text: string): string {
|
||
return text
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/"/g, '"')
|
||
.replace(/'/g, "'")
|
||
.replace(/&/g, '&')
|
||
}
|
||
|
||
function buildImageResponse(
|
||
image: DecodedImage,
|
||
includeData = false
|
||
): {
|
||
success: true
|
||
data: string
|
||
isThumb: boolean
|
||
filePath: string
|
||
mimeType?: string
|
||
} {
|
||
const mediaService = image.cacheFilePath ? getImageMediaService() : null
|
||
const data =
|
||
!includeData && mediaService && image.cacheFilePath && existsSync(image.cacheFilePath)
|
||
? mediaService.createLocalMediaUrl(image.cacheFilePath)
|
||
: image.data
|
||
return {
|
||
success: true,
|
||
data,
|
||
isThumb: image.isThumbnail,
|
||
filePath: image.filePath,
|
||
mimeType: image.mimeType
|
||
}
|
||
}
|
||
|
||
async function createLocalMediaResponse(request: Request, filePath: string): Promise<Response> {
|
||
const { size } = await fsPromises.stat(filePath)
|
||
const mimeType = getLocalMediaMimeType(filePath)
|
||
const commonHeaders = {
|
||
'Accept-Ranges': 'bytes',
|
||
'Content-Type': mimeType,
|
||
'Cache-Control': 'private, max-age=300'
|
||
}
|
||
const range = request.headers.get('range')
|
||
|
||
if (!range) {
|
||
const body =
|
||
request.method === 'HEAD' ? null : Uint8Array.from(await fsPromises.readFile(filePath))
|
||
return new Response(body, {
|
||
status: 200,
|
||
headers: { ...commonHeaders, 'Content-Length': String(size) }
|
||
})
|
||
}
|
||
|
||
const match = /^bytes=(\d+)-(\d*)$/i.exec(range.trim())
|
||
if (!match) {
|
||
return new Response(null, {
|
||
status: 416,
|
||
headers: { ...commonHeaders, 'Content-Range': `bytes */${size}` }
|
||
})
|
||
}
|
||
const start = Number(match[1])
|
||
const requestedEnd = match[2] ? Number(match[2]) : size - 1
|
||
const end = Math.min(requestedEnd, size - 1)
|
||
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end || start >= size) {
|
||
return new Response(null, {
|
||
status: 416,
|
||
headers: { ...commonHeaders, 'Content-Range': `bytes */${size}` }
|
||
})
|
||
}
|
||
|
||
const length = end - start + 1
|
||
let body: Buffer | null = null
|
||
if (request.method !== 'HEAD') {
|
||
const handle = await fsPromises.open(filePath, 'r')
|
||
try {
|
||
body = Buffer.allocUnsafe(length)
|
||
await handle.read(body, 0, length, start)
|
||
} finally {
|
||
await handle.close()
|
||
}
|
||
}
|
||
return new Response(body ? Uint8Array.from(body) : null, {
|
||
status: 206,
|
||
headers: {
|
||
...commonHeaders,
|
||
'Content-Length': String(length),
|
||
'Content-Range': `bytes ${start}-${end}/${size}`
|
||
}
|
||
})
|
||
}
|
||
|
||
function createWindow(): void {
|
||
// 创建浏览器窗口
|
||
/*
|
||
* 初始尺寸按当前屏幕工作区的 60% 计算,不再用固定 1400×800。
|
||
* 两个夹逼都是必要的:
|
||
* - 下限:小屏上 60% 会算出比原固定值更小的窗口(1920×1080 的工作区高度
|
||
* 只有 ~985,60% 才 591 高),反而比改动前更糟;高度下限取 900,
|
||
* 即「高度拉大一点」的诉求。
|
||
* - 上限:不能超过工作区本身,否则初始尺寸会把标题栏顶出屏幕。
|
||
*/
|
||
const { workAreaSize } = screen.getPrimaryDisplay()
|
||
const initialWidth = Math.min(
|
||
Math.max(Math.round(workAreaSize.width * 0.6), 1400),
|
||
workAreaSize.width
|
||
)
|
||
const initialHeight = Math.min(
|
||
Math.max(Math.round(workAreaSize.height * 0.6), 900),
|
||
workAreaSize.height
|
||
)
|
||
const mainWindow = new BrowserWindow({
|
||
width: initialWidth,
|
||
height: initialHeight,
|
||
minWidth: 960,
|
||
minHeight: 640,
|
||
center: true,
|
||
show: false,
|
||
autoHideMenuBar: true,
|
||
icon: appIconPath,
|
||
webPreferences: {
|
||
preload: join(__dirname, '../preload/index.js'),
|
||
sandbox: false
|
||
}
|
||
})
|
||
let closePromptInFlight = false
|
||
|
||
mainWindow.on('ready-to-show', () => {
|
||
mainWindow.show()
|
||
})
|
||
|
||
/** 隐藏到托盘。关闭弹窗的"最小化"与"已记住托盘"两条路径共用同一套副作用。 */
|
||
const minimizeToTray = (): void => {
|
||
setupTray()
|
||
mainWindow.hide()
|
||
if (process.platform === 'darwin') app.dock?.hide()
|
||
}
|
||
|
||
mainWindow.on('close', (event) => {
|
||
if (isQuitting || appShutdownRequested) return
|
||
// 用户在关闭弹窗里勾过"记住我的选择"就照做,不再每次都弹。
|
||
const remembered = loadSettings().closeAction
|
||
if (remembered === 'quit') {
|
||
isQuitting = true
|
||
app.quit()
|
||
return
|
||
}
|
||
if (remembered === 'tray') {
|
||
event.preventDefault()
|
||
minimizeToTray()
|
||
return
|
||
}
|
||
event.preventDefault()
|
||
if (closePromptInFlight) return
|
||
closePromptInFlight = true
|
||
void dialog
|
||
.showMessageBox(mainWindow, {
|
||
type: 'question',
|
||
title: '关闭 TraceMemo',
|
||
message: '请选择关闭方式',
|
||
detail: '你可以将窗口隐藏到系统托盘,或退出整个应用进程。',
|
||
buttons: ['最小化到系统托盘', '关闭进程', '取消'],
|
||
defaultId: 0,
|
||
cancelId: 2,
|
||
// 勾了就记住这次的选择,之后不再弹窗;设置页里随时可以改回来。
|
||
checkboxLabel: '记住我的选择,下次不再询问',
|
||
checkboxChecked: false,
|
||
noLink: true
|
||
})
|
||
.then(({ response, checkboxChecked }) => {
|
||
if (response === 0) {
|
||
if (checkboxChecked) updateSettings({ closeAction: 'tray' })
|
||
minimizeToTray()
|
||
return
|
||
}
|
||
if (response === 1) {
|
||
if (checkboxChecked) updateSettings({ closeAction: 'quit' })
|
||
isQuitting = true
|
||
app.quit()
|
||
}
|
||
})
|
||
.catch((error) => {
|
||
console.warn('[Window] close prompt failed:', error)
|
||
})
|
||
.finally(() => {
|
||
closePromptInFlight = false
|
||
})
|
||
})
|
||
|
||
mainWindow.webContents.setWindowOpenHandler((details) => {
|
||
shell.openExternal(details.url)
|
||
return { action: 'deny' }
|
||
})
|
||
|
||
// 基于 electron-vite CLI 的渲染器热更新
|
||
// 加载开发环境的远程 URL,或生产环境的本地 HTML 文件
|
||
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
|
||
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
|
||
} else {
|
||
mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
|
||
}
|
||
}
|
||
|
||
// Electron 初始化完成并准备创建浏览器窗口后,将调用此方法
|
||
// 某些 API 只能在此事件发生后使用
|
||
/* 扩展页面走自定义协议;scheme 必须在 app ready 之前登记为特权协议。 */
|
||
registerExtensionScheme()
|
||
|
||
app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
|
||
try {
|
||
runLegacySafeStorageHelper()
|
||
app.exit(0)
|
||
} catch {
|
||
app.exit(1)
|
||
}
|
||
return
|
||
}
|
||
|
||
try {
|
||
const migration = isUserDataIsolated ? null : await runFirstLaunchMigration(appDataRoots)
|
||
apiTokenStore.setAutomaticGenerationBlocked(migration?.tokenBlockReason)
|
||
if (!migration) {
|
||
appLogger.write({
|
||
level: 'info',
|
||
scope: 'app-data-migration',
|
||
message: '隔离 userData 已启用,跳过真实用户数据迁移'
|
||
})
|
||
} else {
|
||
appLogger.write({
|
||
level: migration.assessment.selection.legacyConflict ? 'warn' : 'info',
|
||
scope: 'app-data-migration',
|
||
message: migration.assessment.selection.legacyConflict
|
||
? '检测到两个独立的 legacy userData,已按兼容优先级选择 WechatExplorer 作为迁移源'
|
||
: 'TraceMemo 数据身份检查完成',
|
||
details: {
|
||
action: migration.action,
|
||
reason: migration.assessment.reason,
|
||
sourceRoot: migration.assessment.sourceRoot,
|
||
targetRoot: appDataRoots.current,
|
||
legacyExists: migration.assessment.selection.directories.legacy,
|
||
legacyPackageExists: migration.assessment.selection.directories.legacyPackage,
|
||
legacyAssets: migration.assessment.selection.assets.legacy,
|
||
legacyPackageAssets: migration.assessment.selection.assets.legacyPackage,
|
||
legacyRootsEquivalent: migration.assessment.selection.legacyRootsEquivalent,
|
||
legacyConflict: migration.assessment.selection.legacyConflict,
|
||
migrationStatus: migration.execution?.state.status,
|
||
tokenGenerationBlocked: migration.tokenGenerationBlocked
|
||
}
|
||
})
|
||
}
|
||
} catch (error) {
|
||
const targetToken = join(appDataRoots.current, 'local-api-token.bin')
|
||
const legacyTokenExists = [appDataRoots.legacy, appDataRoots.legacyPackage].some((root) =>
|
||
existsSync(join(root, 'local-api-token.bin'))
|
||
)
|
||
if (!existsSync(targetToken) && legacyTokenExists) {
|
||
apiTokenStore.setAutomaticGenerationBlocked(
|
||
'旧版 API Token 迁移未完成,本地 API 已安全停用。请保留旧数据并重新启动迁移。'
|
||
)
|
||
}
|
||
appLogger.write({
|
||
level: 'error',
|
||
scope: 'app-data-migration',
|
||
message: 'TraceMemo 数据迁移初始化失败',
|
||
details: { error: error instanceof Error ? error.message : String(error) }
|
||
})
|
||
await dialog.showMessageBox({
|
||
type: 'warning',
|
||
title: 'TraceMemo 数据迁移',
|
||
message: '旧数据迁移未能启动',
|
||
detail:
|
||
'旧目录没有被修改或删除。请保留 WechatExplorer 数据并重新启动 TraceMemo;旧 API Token 不会被静默替换。',
|
||
buttons: ['好']
|
||
})
|
||
}
|
||
|
||
voiceRecognition = new VoiceRecognitionUseCase({
|
||
modelRoot: join(app.getPath('userData'), 'models', 'sensevoice-small-int8'),
|
||
databasePath: join(app.getPath('userData'), 'cache', 'voice-transcripts.sqlite'),
|
||
workerPath: join(__dirname, 'voiceRecognitionWorker.js')
|
||
})
|
||
knowledgeSearchService = new KnowledgeSearchService(
|
||
app.getPath('userData'),
|
||
join(__dirname, 'knowledgeWorker.js')
|
||
)
|
||
knowledgeSearchService.setVoiceTranscriptResolver(
|
||
(reference) => voiceRecognition?.getTranscriptSnapshot(reference) || { state: 'pending' }
|
||
)
|
||
voiceRecognition.onTranscriptUpdate((update) =>
|
||
knowledgeSearchService?.indexVoiceTranscript(update)
|
||
)
|
||
|
||
/**
|
||
* 确保图片解密服务可用(按需创建,与 `db:getImage` 冷路径同一套构造方式)。
|
||
*
|
||
* 提取成显式入口是因为原来它只存在于 `db:getImage` 的闭包里,
|
||
* 别的需要解密的路径(图片文字索引回填)拿不到、只能拿到 `null`。
|
||
*/
|
||
function ensureImageDecryptService(): ImageDecryptService | null {
|
||
if (imageDecryptService) return imageDecryptService
|
||
const { xorKey, aesKey } = getConfiguredImageKeys()
|
||
if (!aesKey) return null
|
||
imageDecryptService = new ImageDecryptService(
|
||
xorKey,
|
||
aesKey,
|
||
chat.getChatDb()?.getWcdb4Client(),
|
||
loadSettings().dbRoot
|
||
)
|
||
return imageDecryptService
|
||
}
|
||
|
||
// 图片文字索引(本地 System OCR 派生文本)。
|
||
// 与语音转写完全同构:派生文本在 main 进程解析后贴到消息上,Knowledge 侧只消费结果。
|
||
knowledgeSearchService.setImageOcrResolver((conversationId, messageId) =>
|
||
imageTextIndexService.getConversationOcr(conversationId).get(messageId)
|
||
)
|
||
/**
|
||
* 图片文字索引需要解密图片。
|
||
*
|
||
* 解密服务原本只在 `db:getImage`(用户点开某张图)里才懒加载,于是没点开过图片时
|
||
* 全量回填会拿到 `null`。这里改成显式"按需确保",凡是需要解密的路径都能自己建起来。
|
||
*/
|
||
imageTextIndexService.bind({
|
||
databaseRoot: join(app.getPath('userData'), 'image-text-index'),
|
||
resolveAccountId: () =>
|
||
chat.isReady()
|
||
? String(chat.getSelfAccountInfo()?.wxid || chat.getCurrentAccountRoot() || '')
|
||
: '',
|
||
resolveAccountRoot: () => chat.getCurrentAccountRoot() || loadSettings().dbRoot || '',
|
||
listContacts: async () => {
|
||
const contacts = await chat.listContactsAsync()
|
||
return contacts.map((contact) => ({
|
||
md5: contact.md5,
|
||
m_nsUsrName: contact.m_nsUsrName,
|
||
type: contact.type
|
||
}))
|
||
},
|
||
listMessages: (conversationId) =>
|
||
chat.listMessagesAsync(
|
||
conversationId,
|
||
undefined,
|
||
undefined,
|
||
undefined,
|
||
undefined,
|
||
'image-text-index'
|
||
),
|
||
/**
|
||
* 图片索引走**专用查询**:只读图片消息,不读整个会话。
|
||
*
|
||
* 全量读取一个 20 万条消息的会话实测要 15s 以上,而其中 99% 以上的行
|
||
* 图片索引根本不看 —— 那是数据边界错了,不是 OCR 慢。
|
||
*/
|
||
listImageMessages: (conversationId, window) =>
|
||
chat.listImageMessagesAsync(
|
||
conversationId,
|
||
{
|
||
...(window?.sinceMs !== undefined ? { sinceMs: window.sinceMs } : {}),
|
||
...(window?.beforeMs !== undefined ? { beforeMs: window.beforeMs } : {}),
|
||
limit: IMAGE_TEXT_SEGMENT_MESSAGE_LIMIT
|
||
},
|
||
'image-text-index'
|
||
),
|
||
countConversationImages: (conversationId, range) =>
|
||
chat.countImageMessagesAsync(conversationId, range),
|
||
imageWatermark: (conversationId, range) =>
|
||
chat.imageConversationWatermarkAsync(conversationId, range),
|
||
decryptService: () => ensureImageDecryptService(),
|
||
capability: () => systemOcrService.getCapability(),
|
||
/**
|
||
* OCR 并发度的运行时覆盖;不设置则走 `DEFAULT_IMAGE_TEXT_OCR_CONCURRENCY`。
|
||
*
|
||
* 同一份二进制、同一批图片只改这一个数,才能把并发度当作对照变量来比较。
|
||
* 非法值会被 `resolveImageTextOcrConcurrency` 收敛掉。
|
||
*/
|
||
...(process.env.TRACEMEMO_OCR_CONCURRENCY
|
||
? { ocrConcurrency: Number(process.env.TRACEMEMO_OCR_CONCURRENCY) }
|
||
: {}),
|
||
/** 低频性能画像:只写性能数字,不含图片内容 / 路径 / 会话标识。 */
|
||
logStageProfile: (profile) =>
|
||
appLogger.write({
|
||
level: 'info',
|
||
scope: 'image-text-index',
|
||
message: '图片文字索引性能画像',
|
||
details: { ...profile }
|
||
}),
|
||
recognize: async (imageDataUrl) => {
|
||
const result = await systemOcrService.recognize({ imageDataUrl })
|
||
return {
|
||
success: result.success,
|
||
text: result.text,
|
||
language: result.language,
|
||
...(result.errorCode ? { errorCode: result.errorCode } : {})
|
||
}
|
||
},
|
||
// 会话图片全部处理完 → 重建该会话索引,OCR 文本才可被 search_messages 检索。
|
||
onConversationIndexed: (conversationId) =>
|
||
knowledgeSearchService?.indexImageOcr(conversationId) ?? Promise.resolve()
|
||
})
|
||
aiSearchPipelineService = new AiSearchPipelineService(knowledgeSearchService, aiProviderService)
|
||
localQueryApiService = new LocalQueryApiService(knowledgeSearchService)
|
||
// 群员统计复用同一个 Knowledge 实例:它只是「读派生库 + 读成员名单」的编排,
|
||
// 不持有自己的数据库,也不新建索引。
|
||
groupStatsService = new GroupStatsService(knowledgeSearchService)
|
||
setLocalGroupStatsService(groupStatsService)
|
||
// 图片文字索引覆盖度是**独立覆盖维度**:接到 search_messages 的 tool result 上,
|
||
// 让 Query Agent 在图片索引没做完时不能凭 0 条证据断言"没有"。
|
||
localQueryApiService.setImageTextCoverageProvider(() =>
|
||
imageTextIndexService.getCoverageSnapshot()
|
||
)
|
||
/**
|
||
* 单条图片消息的 OCR 派生文本也要接到精确读消息路径上。
|
||
*
|
||
* 与覆盖度是**两件不同的事**:覆盖度回答"索引建了多少",这里回答
|
||
* "这一条图片已经识别出的文字是什么"。只接前者的话,图片索引建好了模型也读不到正文,
|
||
* 只能看到一个空的 `attachment`。
|
||
*
|
||
* 只读派生库,**不触发 OCR / 解密 / 读原图**。
|
||
*/
|
||
localQueryApiService.setImageOcrEntryProvider((conversationId, messageId) =>
|
||
imageTextIndexService.getConversationOcr(conversationId).get(messageId)
|
||
)
|
||
/**
|
||
* 语音转写:读消息时只读缓存快照;只有 query/voice-transcribe 会真正排队识别,
|
||
* 识别仍走同一个 VoiceRecognitionUseCase(同一份缓存、同一条串行队列)。
|
||
*/
|
||
const voiceTranscriptionGateway = new VoiceTranscriptionGateway(voiceRecognition)
|
||
localQueryApiService.setVoiceTranscriptionGateway(voiceTranscriptionGateway)
|
||
setLocalVoiceTranscriptSnapshotProvider((reference) =>
|
||
voiceTranscriptionGateway.snapshot(reference)
|
||
)
|
||
setLocalQueryApiService(localQueryApiService)
|
||
// Query Agent:生产 Runtime 只在这里实例化一次,桌面问问微信与 Agent Hub 共用同一个实例。
|
||
queryAgentService = new QueryAgentService(
|
||
aiProviderService,
|
||
createLocalQueryToolExecutor(localQueryApiService)
|
||
)
|
||
askWechatService = new AskWechatService(queryAgentService, {
|
||
entry: 'desktop',
|
||
// Legacy 仅在 Runtime 不可恢复错误时使用(见 AskWechatService 的 fallback 规则)。
|
||
runLegacy: (request) => {
|
||
if (!aiSearchPipelineService) throw new Error('本地搜索服务尚未初始化')
|
||
return aiSearchPipelineService.run(request, () => undefined)
|
||
},
|
||
log: (record) =>
|
||
appLogger.write({
|
||
level: record.level,
|
||
scope: 'query-agent',
|
||
message: record.message,
|
||
details: record.details
|
||
})
|
||
})
|
||
agentHubService.setQueryAgentService(queryAgentService)
|
||
// 微信 iLink 连接器直接跑在主进程内:inbound 回调与 outbound 发送都不经过本地 HTTP 桥。
|
||
agentHubService.setWechatConnector(wechatConnectorService)
|
||
wechatSendGateway.configureIlinkSender(async (request) => {
|
||
const target = {
|
||
to: request.to,
|
||
...(request.account_id ? { accountId: request.account_id } : {}),
|
||
...(request.context_token ? { contextToken: request.context_token } : {})
|
||
}
|
||
if (request.type === 'text') {
|
||
await wechatConnectorService.sendText({ ...target, text: request.msg })
|
||
return
|
||
}
|
||
if (request.type === 'image' || request.type === 'file') {
|
||
if (/^https?:\/\//i.test(request.msg)) {
|
||
await wechatConnectorService.sendMediaUrl({ ...target, mediaUrl: request.msg })
|
||
} else {
|
||
await wechatConnectorService.sendMediaPath({ ...target, filePath: request.msg })
|
||
}
|
||
return
|
||
}
|
||
throw new Error('iLink 通道暂不支持发送语音')
|
||
})
|
||
knowledgeSearchService.onStatusChange((status) => {
|
||
for (const window of BrowserWindow.getAllWindows()) {
|
||
if (!window.isDestroyed()) window.webContents.send('knowledge:status', status)
|
||
}
|
||
})
|
||
imageTextIndexService.onStatusChange((status) => {
|
||
for (const window of BrowserWindow.getAllWindows()) {
|
||
if (!window.isDestroyed()) window.webContents.send('image-text-index:status', status)
|
||
}
|
||
})
|
||
voiceRecognition.modelManager.setProgressListener((status) => {
|
||
for (const window of BrowserWindow.getAllWindows()) {
|
||
if (!window.isDestroyed()) window.webContents.send('voice:modelProgress', status)
|
||
}
|
||
})
|
||
protocol.handle('wxe-media', async (request) => {
|
||
const filePath = videoAssetService?.pathForUrl(request.url)
|
||
if (!filePath) return new Response('Not found', { status: 404 })
|
||
try {
|
||
return await createLocalMediaResponse(request, filePath)
|
||
} catch (error) {
|
||
console.warn('[Video] local media request failed:', error)
|
||
return new Response('Media unavailable', { status: 500 })
|
||
}
|
||
})
|
||
console.log(`TraceMemo main build: ${BUILD_MARK}`)
|
||
appLogger.write({
|
||
level: 'info',
|
||
scope: 'lifecycle',
|
||
message: 'TraceMemo 启动',
|
||
details: { build: BUILD_MARK, platform: process.platform, version: app.getVersion() }
|
||
})
|
||
/*
|
||
* 发送能力组件解析结果单独落一条日志。
|
||
* 现场排障时这是第一分界线:「组件没解析到」和「解析到了但授权不过」是两条完全不同的
|
||
* 排查路径,用户报「装了没生效」先看这一行,不要先去怀疑授权。
|
||
*/
|
||
const external = resolveExternalComponent()
|
||
console.log(
|
||
external
|
||
? `[Component] resolved version=${external.version} dirty=${external.dirty} dir=${external.dir}`
|
||
: '[Component] not resolved (no current.json, or manifest size/sha256 check failed)'
|
||
)
|
||
appLogger.write({
|
||
level: external ? 'info' : 'warn',
|
||
scope: 'component-locate',
|
||
message: external ? '已加载发送能力组件' : '未找到可用的发送能力组件',
|
||
details: external
|
||
? {
|
||
version: external.version,
|
||
dir: external.dir,
|
||
helper: external.helperPath,
|
||
worktreeDirty: external.dirty
|
||
}
|
||
: {
|
||
platform: process.platform,
|
||
expected: '%LOCALAPPDATA%\\TraceMemo\\Pro\\windows-x64\\current.json'
|
||
}
|
||
})
|
||
/* 启动即对齐本地开关,否则 enabled=true 会潜伏,授权一恢复就自己开跑。 */
|
||
void msgInsertCapabilityService
|
||
.refresh({ databaseReady: capabilityDatabaseReady() })
|
||
.then((capability) => {
|
||
enforceExitNoticeGate(capability)
|
||
})
|
||
.catch((error) => {
|
||
appLogger.write({
|
||
level: 'warn',
|
||
scope: 'capability-gate',
|
||
message: '启动对齐退群内提示失败',
|
||
details: { error: error instanceof Error ? error.message : String(error) }
|
||
})
|
||
})
|
||
process.on('uncaughtException', (error) => {
|
||
appLogger.write({
|
||
level: 'error',
|
||
scope: 'main-process',
|
||
message: error.message,
|
||
details: { stack: error.stack }
|
||
})
|
||
})
|
||
process.on('unhandledRejection', (reason) => {
|
||
appLogger.write({
|
||
level: 'error',
|
||
scope: 'main-process',
|
||
message: reason instanceof Error ? reason.message : 'Promise 未处理拒绝',
|
||
details: {
|
||
stack: reason instanceof Error ? reason.stack : undefined,
|
||
reason: reason instanceof Error ? undefined : String(reason)
|
||
}
|
||
})
|
||
})
|
||
|
||
// Create the renderer before native WCDB bootstrap so startup progress is visible immediately.
|
||
await reportTemplateService.recover()
|
||
registerReportTemplateIpc()
|
||
installExtensionProtocolHandler({
|
||
paths: getExtensionPaths(),
|
||
// 开发模式下代码在用户自己的目录里:协议必须走同一个解析器,
|
||
// 否则页面会读到旧的安装副本。管理器尚未就绪时回退到安装目录。
|
||
resolveRoot: (extensionId) => {
|
||
if (!hasExtensionManager()) return getExtensionPaths().installDir(extensionId)
|
||
try {
|
||
return getExtensionManager().resolveExtensionRoot(extensionId)
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
})
|
||
registerExtensionIpc({
|
||
getManager: getExtensionManager,
|
||
paths: getExtensionPaths(),
|
||
isTrustedSender: (senderId) =>
|
||
BrowserWindow.getAllWindows().some((window) => window.webContents.id === senderId)
|
||
})
|
||
createWindow()
|
||
void initExtensionSystem({
|
||
appVersion: app.getVersion(),
|
||
onChange: (extensionId, reason) => {
|
||
for (const window of BrowserWindow.getAllWindows()) {
|
||
if (!window.isDestroyed()) {
|
||
window.webContents.send(EXTENSION_IPC.changed, { extensionId, reason })
|
||
}
|
||
}
|
||
}
|
||
})
|
||
wcdbBootstrapPromise = bootstrapWcdbNativeAsync().then(() => {
|
||
console.log('[WCDB4] async bootstrap complete')
|
||
})
|
||
void wcdbBootstrapPromise.catch((error) => {
|
||
appLogger.write({
|
||
level: 'error',
|
||
scope: 'wcdb-bootstrap',
|
||
message: error instanceof Error ? error.message : String(error)
|
||
})
|
||
})
|
||
|
||
// 设置应用程序用户模型 ID
|
||
electronApp.setAppUserModelId('com.tracememo.app')
|
||
|
||
// 开发环境中默认使用 F12 打开或关闭 DevTools
|
||
// 生产环境中忽略 CommandOrControl + R
|
||
// 参见 https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
|
||
app.on('browser-window-created', (_, window) => {
|
||
optimizer.watchWindowShortcuts(window)
|
||
})
|
||
|
||
// IPC test
|
||
ipcMain.on('ping', () => console.log('pong'))
|
||
ipcMain.handle('app-log:write', (_, entry: AppLogEntry) => appLogger.write(entry))
|
||
ipcMain.handle('app-log:getPath', () => appLogger.logPath)
|
||
ipcMain.handle('app-log:reveal', () => appLogger.reveal())
|
||
ipcMain.handle('app-update:getState', () => appUpdateService.getState())
|
||
ipcMain.handle('app-update:check', () => appUpdateService.check())
|
||
ipcMain.handle('app-update:download', () => appUpdateService.download())
|
||
ipcMain.handle('app-update:install', () => appUpdateService.install())
|
||
ipcMain.handle('app-update:openDownloadPage', () => appUpdateService.openDownloadPage())
|
||
ipcMain.handle('app-update:getIgnoredVersion', () => loadSettings().skippedUpdateVersion)
|
||
/**
|
||
* 记录 / 清除「忽略此版本」。
|
||
*
|
||
* 传 null 或非法版本号 = 清除。校验放在主进程:渲染层传来的字符串不可信,
|
||
* 一个脏值会让「忽略」永远命中不了同一条记录,表现为每次都弹。
|
||
*/
|
||
ipcMain.handle('app-update:setIgnoredVersion', (_, version: unknown) => {
|
||
const normalized = normalizeSkippedUpdateVersion(version)
|
||
saveSettings({ ...loadSettings(), skippedUpdateVersion: normalized })
|
||
return normalized
|
||
})
|
||
appUpdateService.scheduleStartupCheck()
|
||
ipcMain.handle('cache:getSummary', () => getCacheSummary())
|
||
ipcMain.handle('cache:openKnowledgeDirectory', () => openKnowledgeDirectory())
|
||
ipcMain.handle('cache:clear', async (_, scope: CacheClearScope) => {
|
||
const allowedScopes: CacheClearScope[] = [
|
||
'bootstrap',
|
||
'electron',
|
||
'knowledge',
|
||
'image-text-index',
|
||
'all'
|
||
]
|
||
if (!allowedScopes.includes(scope)) return getCacheSummary()
|
||
imageDecryptService = null
|
||
// 这里刻意**不再**提前 resetAccount():清理钩子需要先读到派生库里的
|
||
// "哪些会话有 OCR 派生文本",才能把这些会话的 Knowledge 索引一起失效。
|
||
// 句柄由 beforeClearImageTextIndex 内部的 clear() 自己关闭(删文件前)。
|
||
return clearCache(scope, {
|
||
beforeClearKnowledge: () =>
|
||
knowledgeSearchService?.prepareForCacheClear() || Promise.resolve(),
|
||
beforeClearImageTextIndex: async () => {
|
||
await imageTextIndexService.prepareForCacheClear()
|
||
imageTextIndexService.resetAccount()
|
||
}
|
||
})
|
||
})
|
||
|
||
ipcMain.handle('db:init', async (_, key: string, accountRoot?: string) => {
|
||
if (appShutdownRequested) {
|
||
return { success: false, error: '应用正在退出,数据库连接已取消', monitoring: false }
|
||
}
|
||
if (dbInitInFlight) return dbInitInFlight
|
||
|
||
dbInitInFlight = (async () => {
|
||
const startedAt = Date.now()
|
||
try {
|
||
if (wcdbBootstrapPromise) await wcdbBootstrapPromise
|
||
if (appShutdownRequested) {
|
||
return { success: false, error: '应用正在退出,数据库连接已取消', monitoring: false }
|
||
}
|
||
const trimmedKey = String(key || '').trim()
|
||
console.log(`db:init build=${BUILD_MARK} keyLength=${trimmedKey.length}`)
|
||
const settings = loadSettings()
|
||
const selectedRoot = String(accountRoot || settings.dbRoot || '').trim()
|
||
const rootValidation = validateDbRoot(selectedRoot)
|
||
if (!rootValidation.valid) {
|
||
return {
|
||
success: false,
|
||
code: 'ROOT_UNAVAILABLE',
|
||
error: rootValidation.error,
|
||
monitoring: false
|
||
}
|
||
}
|
||
if (!existsSync(join(selectedRoot, 'db_storage'))) {
|
||
return {
|
||
success: false,
|
||
code: 'ACCOUNT_SELECTION_REQUIRED',
|
||
error: '请先明确选择一个微信账号',
|
||
monitoring: false
|
||
}
|
||
}
|
||
if (
|
||
chat.isReady() &&
|
||
chat.getCurrentKey().replace(/^0x/i, '').trim() === trimmedKey.replace(/^0x/i, '') &&
|
||
chat.getCurrentAccountRoot() === selectedRoot
|
||
) {
|
||
console.log('[WCDB4] db:init reuse current connection')
|
||
void groupExitMonitorService.start(true)
|
||
return { success: true, monitoring: true }
|
||
}
|
||
const nextWechatDb = await WechatDb.create(key, selectedRoot)
|
||
if (appShutdownRequested) {
|
||
await nextWechatDb.closeAsync()
|
||
return { success: false, error: '应用正在退出,数据库连接已取消', monitoring: false }
|
||
}
|
||
groupExitMonitorService.stop()
|
||
const resolvedRoot = nextWechatDb.getWcdb4Client().getAccountRoot()
|
||
if (resolvedRoot) {
|
||
// 同步更新 imageKeyRoot,避免自动获取图片密钥时扫描到错误目录
|
||
saveSettings({
|
||
...settings,
|
||
dbRoot: resolvedRoot,
|
||
imageKeyRoot: resolvedRoot
|
||
})
|
||
}
|
||
if (!chat.setChatDb(nextWechatDb)) {
|
||
return { success: false, error: '应用正在退出,数据库连接已取消', monitoring: false }
|
||
}
|
||
const wcdb4Client = nextWechatDb.getWcdb4Client()
|
||
/**
|
||
* 正式 MessageListener(Observation Mode 接入)。
|
||
*
|
||
* 只监听、回读、规范化、去重、统计,不触发任何业务:
|
||
* 不匹配关键词、不判断 @我、不出日报、不回复、不调 AI / Agent、不发送。
|
||
* 业务响应由上层消费者自行订阅,不在监听层实现。
|
||
*/
|
||
const messageListener = new MessageListenerService(wcdb4Client)
|
||
/**
|
||
* Automation v1(@我生成日报)。
|
||
*
|
||
* `isListening` 反映 `startMonitor` 的实际结果,因此通过闭包读取,
|
||
* 而不是在初始化时传入快照。
|
||
*/
|
||
let automationListening = false
|
||
initAutomationService(wcdb4Client, { isListening: () => automationListening })
|
||
|
||
/**
|
||
* 旧「定时日报任务」迁移所需的会话解析器。
|
||
*
|
||
* **必须在数据库就绪之后注入**:旧 `task.group` 可能是会话 md5、群名或 roomId
|
||
* 三种形态,只有 `resolveMd5` 能收敛成稳定会话 id。
|
||
* 注入前若渲染层已经读过一次规则(`automation:listRules`),迁移会**整体推迟**
|
||
* 而不落盘 —— 注入这一步会立刻补跑(见 `AutomationRuleStore.setLegacyConversationResolver`)。
|
||
*
|
||
* 这样设计的原因:拿不到解析器时如果把旧数据判成「无法无损映射」,
|
||
* 用户的定时日报会被**无辜停用**,而事实只是"数据库还没打开"。
|
||
*/
|
||
automationRuleStore.setLegacyConversationResolver((raw) => {
|
||
const key = String(raw || '').trim()
|
||
if (!key) return undefined
|
||
// 已经是稳定会话 id 就直接用,不查库。
|
||
if (key.endsWith('@chatroom')) return key
|
||
try {
|
||
const username = String(chat.resolveMd5(key)?.m_nsUsrName || '').trim()
|
||
return username || undefined
|
||
} catch {
|
||
return undefined
|
||
}
|
||
})
|
||
/**
|
||
* 退群通知的唯一通路:**退群监控只负责产生事件,自动化负责发送**。
|
||
*
|
||
* `handleGroupExit` 自己吞掉异常,这里再兜一层 `.catch` 是防御性的 ——
|
||
* 未捕获的 rejection 会污染监控循环,而退群事实早就已经记录成功了。
|
||
*/
|
||
/* 退群本地提示的运行时依赖:密钥 / wxid / 账号目录都由主进程提供,
|
||
* 服务自己不依赖 chat-service 的具体形态。 */
|
||
configureWechatLocalExitNotice({
|
||
resolveDatabaseKey: () => chat.getChatDb()?.getWcdb4Client()?.getKey() || '',
|
||
resolveMyWxid: () => String(chat.getSelfAccountInfo()?.wxid || ''),
|
||
resolveAccountRoot: () => {
|
||
const shards = chat.getChatDb()?.getWcdb4Client()?.listMessageShardPaths() || []
|
||
if (shards.length > 0) return path.dirname(path.dirname(path.dirname(shards[0])))
|
||
return String(chat.getCurrentAccountRoot() || '')
|
||
}
|
||
})
|
||
|
||
/*
|
||
* 防撤回 reconciliation 的启动入口:只有当持久化的开关已经是「开」时才会跑。
|
||
* 渲染层读状态、群列表变化都不会触发 DDL。
|
||
*/
|
||
void reconcileMsgInsertRulesOnStart()
|
||
/*
|
||
* 老防撤回残留收尾:只读扫描 → 有残留才写库(清理走 helper 的可写通道,
|
||
* 判定规则与边界见函数注释)。
|
||
*/
|
||
void cleanupLegacyRecallResidueOnStart()
|
||
|
||
groupExitMonitorService.setGroupExitHandler((event) => {
|
||
/*
|
||
* 同一个退群事件按**各自的范围**分发给两个消费者:
|
||
*
|
||
* - 微信内退群监控消息:范围 = 全部群聊(开关开着就全覆盖);
|
||
* - 自动化退群通知:范围 = 退群监控里勾选的群。
|
||
*
|
||
* 两者互不依赖:内提示不抛异常、不 await(handleExitEvent 内部兜底),
|
||
* 插入失败不会影响自动化通知,反之亦然。
|
||
*/
|
||
if (groupExitMonitorService.isNoticeRoom(event.conversationId)) {
|
||
void wechatLocalExitNoticeService.handleExitEvent(event)
|
||
}
|
||
if (!groupExitMonitorService.isMonitoredRoom(event.conversationId)) return undefined
|
||
try {
|
||
return getAutomationService()
|
||
.handleGroupExit(event)
|
||
.catch((error) => {
|
||
console.warn(
|
||
`[Automation] handleGroupExit failed: ${
|
||
error instanceof Error ? error.message : String(error)
|
||
}`
|
||
)
|
||
})
|
||
} catch (error) {
|
||
console.warn(
|
||
`[Automation] 退群通知未初始化,已跳过本次事件: ${
|
||
error instanceof Error ? error.message : String(error)
|
||
}`
|
||
)
|
||
return undefined
|
||
}
|
||
})
|
||
/* 把「微信内退群监控消息」的开关交给 monitor:开着时检测范围扩到全部群聊。 */
|
||
syncExitNoticeScope()
|
||
messageListener.onMessage((message) => {
|
||
// 日志只允许出现「类型 / 群或私聊 / 是否自己发 / @ 数量」这类不可逆标识,
|
||
// 不含 wxid、昵称、群名、正文与 source。
|
||
console.log(
|
||
`[MessageListener] incoming messageType=${message.messageType}` +
|
||
` group=${message.isGroup} self=${message.isSelf}` +
|
||
` mentions=${message.mentionTargets.length}`
|
||
)
|
||
// Automation 自带 isSelf / cooldown / 同消息幂等三重闸,不会形成回复循环。
|
||
// 用 try 包住同步那一段:`getAutomationService()` 在未初始化时会抛,
|
||
// 而 `.catch()` 只能接住异步拒绝 —— 漏了这层就会把异常抛进 MessageListener 的投递循环。
|
||
try {
|
||
void getAutomationService()
|
||
.handleMessage(message)
|
||
.catch((error) => {
|
||
console.warn(
|
||
`[Automation] handleMessage failed: ${
|
||
error instanceof Error ? error.message : String(error)
|
||
}`
|
||
)
|
||
})
|
||
} catch (error) {
|
||
console.warn(
|
||
`[Automation] 未初始化,已跳过本次消息: ${
|
||
error instanceof Error ? error.message : String(error)
|
||
}`
|
||
)
|
||
}
|
||
/*
|
||
* 扩展事件分发:与 Automation 并行、互不影响。
|
||
* 扩展侧的异常不能污染 MessageListener 的投递循环,也不能阻断 Automation。
|
||
*/
|
||
if (hasExtensionManager()) {
|
||
try {
|
||
getExtensionManager().handleMessage(message)
|
||
} catch (error) {
|
||
console.warn(
|
||
`[Extension] handleMessage failed: ${
|
||
error instanceof Error ? error.message : String(error)
|
||
}`
|
||
)
|
||
}
|
||
}
|
||
})
|
||
const sessions = await wcdb4Client.getSessionsAsync({ hydrateDisplayNames: false })
|
||
configureRecallProtection(wcdb4Client, resolvedRoot, settings.recallProtectionEnabled)
|
||
voiceService = new VoiceService(wcdb4Client, resolvedRoot)
|
||
voiceRecognition?.connect(voiceService, resolvedRoot)
|
||
stickerService = new StickerService(wcdb4Client)
|
||
videoAssetService = new VideoAssetService(wcdb4Client)
|
||
const monitoring = await wcdb4Client.startMonitor((event) => {
|
||
wcdb4Client.invalidateSessionCache()
|
||
// 正式 MessageListener:只做 coalesce + 有界回读 + dedup + 投递,不触发业务。
|
||
// v2 事件带 sessionId ⇒ 回读不再依赖「最近活跃会话」。
|
||
messageListener.handleNativeChange(event)
|
||
groupExitMonitorService.notifyDatabaseChanged(event.raw)
|
||
recallArchiveMonitor?.handleDatabaseChange(event.raw)
|
||
for (const window of BrowserWindow.getAllWindows()) {
|
||
if (!window.isDestroyed()) {
|
||
window.webContents.send('wcdb-change', { type: event.type, json: event.raw })
|
||
}
|
||
}
|
||
})
|
||
automationListening = monitoring === true
|
||
void groupExitMonitorService.start(monitoring)
|
||
const recentSession = sessions[0]
|
||
if (recentSession?.username) {
|
||
void wcdb4Client
|
||
.getMessagesAsync(recentSession.username, undefined, undefined, { limit: 1 })
|
||
.catch((error) => console.warn('[WCDB4] message cursor warmup failed:', error))
|
||
}
|
||
imageDecryptService = null
|
||
// 派生库按 accountId 分目录,切账号必须换句柄,否则会串账号。
|
||
imageTextIndexService.resetAccount()
|
||
console.log(
|
||
`[WCDB4] db:init ready sessions=${sessions.length} monitoring=${monitoring} cost=${Date.now() - startedAt}ms`
|
||
)
|
||
return { success: true, monitoring }
|
||
} catch (error) {
|
||
const detail = error instanceof Error ? error.message : String(error)
|
||
if (isWcdbDebugEnabled()) {
|
||
console.error('Failed to init DB:', error)
|
||
} else {
|
||
console.error('Failed to init DB:', detail)
|
||
}
|
||
if (isWindowsVcRuntimeMissingError(detail, process.platform)) {
|
||
return {
|
||
success: false,
|
||
code: 'VC_RUNTIME_MISSING',
|
||
error: WINDOWS_VC_RUNTIME_ERROR_MESSAGE,
|
||
monitoring: false
|
||
}
|
||
}
|
||
return { success: false, error: detail }
|
||
} finally {
|
||
dbInitInFlight = null
|
||
}
|
||
})()
|
||
|
||
return dbInitInFlight
|
||
})
|
||
|
||
ipcMain.handle('accounts:discover', (_, inputPath: string) =>
|
||
discoverAccounts(inputPath, databaseKeyStore, chat.getCurrentAccountRoot())
|
||
)
|
||
|
||
ipcMain.handle('key:getSavedDbKey', async (_, accountRoot: string) => {
|
||
const selectedRoot = String(accountRoot || '').trim()
|
||
const scoped = await databaseKeyStore.load(selectedRoot)
|
||
if (scoped.saved || !selectedRoot) return scoped
|
||
const legacy = await databaseKeyStore.loadLegacy()
|
||
if (!legacy.success || !legacy.key) return scoped
|
||
const validation = await chat.testConnection(legacy.key, selectedRoot)
|
||
if (!validation.success) return scoped
|
||
const migrated = await databaseKeyStore.save(selectedRoot, legacy.key)
|
||
if (migrated.success) await databaseKeyStore.clearLegacy()
|
||
return migrated
|
||
})
|
||
|
||
ipcMain.handle('key:getEnvironment', async () => {
|
||
const storage = await databaseKeyStore.getStatus(
|
||
chat.getCurrentAccountRoot() || loadSettings().dbRoot
|
||
)
|
||
const self = chat.getSelfAccountInfo()
|
||
const settings = loadSettings()
|
||
const arch = getMacArchSnapshot()
|
||
// 只有真正的 Intel Mac 才需要探测 Intel 运行环境。
|
||
// Apple 芯片上的 x64 进程(Rosetta)不能走这条路径,否则每次刷新环境都会起一个 x86 子进程。
|
||
const intelMac = shouldProbeIntelEnvironment(arch.macKeyFlow)
|
||
const intelEnvironment = intelMac ? await keyServiceMac.getIntelEnvironmentStatus() : undefined
|
||
const environment = {
|
||
platform: process.platform,
|
||
architecture: process.arch,
|
||
hardwareArchitecture: arch.hardwareArch,
|
||
underARM64Translation: arch.underARM64Translation,
|
||
macKeyFlow: arch.macKeyFlow,
|
||
archAnomalies: arch.anomalies,
|
||
osVersion: getOsVersionLabel(),
|
||
appVersion: `v${app.getVersion()}`,
|
||
wechatVersion: await detectWechatVersion(),
|
||
dataStructureVersion: detectDataStructureVersion(settings.dbRoot),
|
||
dataDirectoryDetected: validateDbRoot(settings.dbRoot).valid,
|
||
autoDetectSupported: process.platform === 'win32' || process.platform === 'darwin',
|
||
wechatRunning: await isWechatRunning(),
|
||
accountIdentified: Boolean(self?.wxid),
|
||
dbConnected: chat.isReady(),
|
||
encryptionAvailable: storage.encryptionAvailable,
|
||
...(intelEnvironment || {})
|
||
}
|
||
return { ...environment, diagnosticSummary: buildSafeDiagnosticSummary(environment) }
|
||
})
|
||
|
||
ipcMain.handle('key:readClipboardDbKey', () => {
|
||
try {
|
||
return { success: true, value: clipboard.readText().trim() }
|
||
} catch {
|
||
return { success: false, error: '无法读取剪贴板' }
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('key:installIntelMacRuntime', async (event) => {
|
||
const onStatus = (message: string): void => {
|
||
if (!event.sender.isDestroyed()) event.sender.send('key:dbKeyStatus', { message })
|
||
}
|
||
return keyServiceMac.installIntelKeyRuntime(onStatus)
|
||
})
|
||
|
||
ipcMain.handle('key:pasteAndSaveDbKey', async (_, accountRoot: string) => {
|
||
const clipboardKey = clipboard.readText().trim()
|
||
return databaseKeyStore.save(String(accountRoot || ''), clipboardKey)
|
||
})
|
||
|
||
ipcMain.handle('key:saveDbKey', async (_, accountRoot: string, key: string) =>
|
||
databaseKeyStore.save(String(accountRoot || ''), String(key || ''))
|
||
)
|
||
|
||
ipcMain.handle('key:clearSavedDbKey', async (_, accountRoot: string) =>
|
||
databaseKeyStore.clear(String(accountRoot || ''))
|
||
)
|
||
|
||
ipcMain.handle(
|
||
'key:autoGetDbKey',
|
||
async (event, accountRoot: string, options?: { save?: boolean }) => {
|
||
const onStatus = (message: string): void => {
|
||
if (!event.sender.isDestroyed()) event.sender.send('key:dbKeyStatus', { message })
|
||
}
|
||
const result =
|
||
process.platform === 'win32'
|
||
? await keyServiceWin.autoGetDbKey(60_000, onStatus)
|
||
: await keyServiceMac.autoGetDbKey(onStatus, 60_000, accountRoot)
|
||
if (!result.success || !result.key) return result
|
||
|
||
const selectedRoot = String(accountRoot || '').trim()
|
||
if (!selectedRoot) return { success: false, error: '请先选择微信账号' }
|
||
const validation = await chat.testConnection(result.key, selectedRoot)
|
||
if (!validation.success) {
|
||
return {
|
||
...result,
|
||
success: false,
|
||
key: undefined,
|
||
error:
|
||
'获取到的密钥不属于所选账号, 也可能是选择错误的目录了, 请打开微信设置 左下角确认目录是否和软件内填写一致'
|
||
}
|
||
}
|
||
if (options?.save === false) return result
|
||
|
||
const saved = await databaseKeyStore.save(selectedRoot, result.key)
|
||
return {
|
||
...result,
|
||
saved: saved.success,
|
||
warning: saved.success ? undefined : saved.error
|
||
}
|
||
}
|
||
)
|
||
// 日报等系统动作仍复用现有发送服务;普通聊天不再暴露这个入口。
|
||
ipcMain.handle('wechat-personal:send', async (_, request: PersonalWechatSendRequest) => {
|
||
// 项目规则:**所有发送都必须经过 WechatActionGateway**(审计 + 幂等 + 同一个 Send Log)。
|
||
// 手动发送在改造前从这里直连 `PersonalWechatSendService`,于是完全不留痕 ——
|
||
// 排查「消息到底发没发出去」时恰好缺的就是那份证据。
|
||
// 普通手动发送保持 triggerType=user;带 postfixText 的日报图片由 Gateway 编排成
|
||
// 两个 automation action,以复用同一条 3s 队列,并严格在图片 sent 后才发后置词。
|
||
if (
|
||
request.type === 'text' ||
|
||
request.type === 'image' ||
|
||
request.type === 'video' ||
|
||
request.type === 'file'
|
||
) {
|
||
const to = String(request.to || '').trim()
|
||
const recipient = {
|
||
type:
|
||
request.isGroup || to.endsWith('@chatroom') ? ('group' as const) : ('contact' as const),
|
||
id: to
|
||
}
|
||
if (request.type === 'image' && request.postfixText !== undefined) {
|
||
const sequence = await wechatActionGateway.executeReportImageSequence({
|
||
recipient,
|
||
imagePath: String(request.filePath || ''),
|
||
postfixText: request.postfixText
|
||
})
|
||
const imageResult = toPersonalWechatSendResult(
|
||
sequence.image,
|
||
await currentPersonalWechatSenderStatus()
|
||
)
|
||
if (!imageResult.success || !sequence.postfix) return imageResult
|
||
return {
|
||
...imageResult,
|
||
postfixSent: sequence.postfix.status === 'sent',
|
||
...(sequence.postfix.status === 'sent'
|
||
? {}
|
||
: { postfixError: sequence.postfix.reason || '后置词发送失败' })
|
||
}
|
||
}
|
||
const action = await wechatActionGateway.execute({
|
||
origin: 'user_manual',
|
||
purpose:
|
||
request.type === 'text'
|
||
? 'manual_text'
|
||
: request.type === 'video'
|
||
? 'manual_video'
|
||
: request.type === 'file'
|
||
? 'manual_file'
|
||
: 'manual_image',
|
||
triggerType: 'user',
|
||
recipient,
|
||
content:
|
||
request.type === 'text'
|
||
? {
|
||
type: 'text',
|
||
text: String(request.text || ''),
|
||
...(request.at ? { at: request.at } : {})
|
||
}
|
||
: request.type === 'video'
|
||
? { type: 'video', path: String(request.filePath || '') }
|
||
: request.type === 'file'
|
||
? {
|
||
type: 'file',
|
||
path: String(request.filePath || ''),
|
||
...(request.fileName ? { name: request.fileName } : {})
|
||
}
|
||
: { type: 'image', path: String(request.filePath || '') }
|
||
})
|
||
// 返回契约保持 `PersonalWechatSendResult`,界面判读不用改。
|
||
return toPersonalWechatSendResult(action, await currentPersonalWechatSenderStatus())
|
||
}
|
||
|
||
// 语音仍走既有分支:它有自己的网关入口 `wechat-personal:sendGeneratedTtsVoice`,
|
||
// 且需要先解析当前账号 wxid 才能编码。
|
||
if (String(request.fromId || '').trim()) {
|
||
return personalWechatSendService.send(request)
|
||
}
|
||
let fromId = ''
|
||
try {
|
||
const self = await chat.getSelfAccountInfoAsync()
|
||
fromId = String(self?.wxid || '').trim()
|
||
} catch {
|
||
// 无法读取账号 wxid 时仍交给发送服务返回规范化错误。
|
||
}
|
||
return personalWechatSendService.send(fromId ? { ...request, fromId } : request)
|
||
})
|
||
|
||
ipcMain.handle('key:autoGetImageKey', async (event, options?: { save?: boolean }) => {
|
||
const settings = loadSettings()
|
||
const self = chat.getSelfAccountInfo()
|
||
// 优先级:chat 真实识别到的根 → self.accountRoot → settings.imageKeyRoot → settings.dbRoot
|
||
// 必须先看 chat.getCurrentAccountRoot(),否则 settings 缓存漂移会导致扫错目录。
|
||
const accountRoot =
|
||
chat.getCurrentAccountRoot() || self?.accountRoot || settings.imageKeyRoot || settings.dbRoot
|
||
const wxid = self?.wxid
|
||
const onStatus = (message: string): void => {
|
||
if (!event.sender.isDestroyed()) event.sender.send('key:imageKeyStatus', { message })
|
||
}
|
||
const result =
|
||
process.platform === 'win32'
|
||
? await keyServiceWin.autoGetImageKey(accountRoot, onStatus, wxid)
|
||
: await keyServiceMac.autoGetImageKey(accountRoot, onStatus, wxid)
|
||
|
||
if (!result.success || !result.aesKey) return result
|
||
if (process.platform === 'win32') {
|
||
onStatus('发现候选密钥,图片模板验证通过')
|
||
}
|
||
|
||
const imageXorKey = `0x${Number(result.xorKey ?? 0x40)
|
||
.toString(16)
|
||
.toUpperCase()
|
||
.padStart(2, '0')}`
|
||
const verified = result.verified ?? process.platform === 'win32'
|
||
if (options?.save === false) {
|
||
return { ...result, verified, imageXorKey, imageAesKey: result.aesKey }
|
||
}
|
||
const saved = imageKeyConfigService.save({
|
||
resourceRoot: accountRoot,
|
||
xorKey: imageXorKey,
|
||
aesKey: result.aesKey
|
||
})
|
||
if (saved.success) imageDecryptService = null
|
||
// 派生库按 accountId 分目录,切账号必须换句柄,否则会串账号。
|
||
imageTextIndexService.resetAccount()
|
||
return {
|
||
...result,
|
||
success: saved.success,
|
||
error: saved.success ? undefined : saved.error,
|
||
verified,
|
||
imageXorKey,
|
||
imageAesKey: result.aesKey,
|
||
settings: imageKeyConfigService.getLegacySettingsView()
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('image:getConfig', () => imageKeyConfigService.getConfig())
|
||
|
||
/**
|
||
* 复制图片调试定位信息。
|
||
*
|
||
* 只回答「用户点中的是哪一条消息、当前展示的是哪份本地资源」。
|
||
* 刻意不返回资源密钥、完整 XML、fileid 或任何 CDN 凭据。
|
||
*/
|
||
ipcMain.handle(
|
||
'image:getDebugInfo',
|
||
async (_, request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> => {
|
||
try {
|
||
const service = ensureImageDecryptService()
|
||
const self = chat.getSelfAccountInfo()
|
||
const accountRoot = self?.accountRoot || loadSettings().dbRoot || ''
|
||
const sessionId = String(request?.sessionId || '').trim() || null
|
||
const localId =
|
||
typeof request?.localId === 'number' && Number.isFinite(request.localId)
|
||
? String(request.localId)
|
||
: null
|
||
const serverId = String(request?.serverId || '').trim() || null
|
||
const createTimeSeconds =
|
||
typeof request?.createTime === 'number' && Number.isFinite(request.createTime)
|
||
? request.createTime
|
||
: null
|
||
|
||
const md5 = String(request?.imageMd5 || '').trim() || null
|
||
const datName = String(request?.imageDatName || '').trim() || null
|
||
|
||
// 复用真实选图逻辑;找不到就是 null,不根据文件名猜。
|
||
const filePath = service
|
||
? service.findImageFile(md5 || undefined, datName || undefined, {
|
||
sessionId: sessionId || undefined
|
||
})
|
||
: null
|
||
const quality = filePath ? toDebugQuality(imageFileQuality(filePath)) : 'unknown'
|
||
const relativePath =
|
||
filePath && accountRoot && filePath.startsWith(accountRoot)
|
||
? path.relative(accountRoot, filePath).split(path.sep).join('/')
|
||
: null
|
||
const evidence = filePath ? path.basename(filePath) : null
|
||
|
||
const payload: ImageDebugPayload = {
|
||
kind: IMAGE_DEBUG_KIND,
|
||
message: {
|
||
accountId: self?.wxid || null,
|
||
conversationId: sessionId,
|
||
localId,
|
||
serverId,
|
||
createTimeSeconds
|
||
},
|
||
image: { md5, datName },
|
||
display: {
|
||
quality,
|
||
evidence,
|
||
path: relativePath
|
||
}
|
||
}
|
||
return { success: true, payload }
|
||
} catch (error) {
|
||
return {
|
||
success: false,
|
||
error: error instanceof Error ? error.message : String(error)
|
||
}
|
||
}
|
||
}
|
||
)
|
||
|
||
/** 取回一条图片消息的原始 XML。需 sessionId + localId 定位。 */
|
||
ipcMain.handle(
|
||
'image:getMessageXml',
|
||
async (_, request: ImageMessageXmlRequest): Promise<ImageMessageXmlResult> => {
|
||
const sessionId = String(request?.sessionId || '').trim()
|
||
const localId = Math.trunc(Number(request?.localId) || 0)
|
||
const createTime = Math.trunc(Number(request?.createTime) || 0)
|
||
if (!sessionId) return { success: false, error: '缺少会话标识,无法定位消息' }
|
||
if (localId <= 0) return { success: false, error: '缺少消息序号,无法定位消息' }
|
||
|
||
try {
|
||
const db = chat.getChatDb()
|
||
const client = db ? db.getWcdb4Client() : null
|
||
if (!client) return { success: false, error: '数据库尚未连接' }
|
||
|
||
const raw = client.getRawMessageContent(sessionId, localId, createTime || undefined)
|
||
if (!raw) return { success: false, error: '这条消息没有可读取的正文' }
|
||
const xml = raw.trim().includes('<') ? raw.trim() : unescapeXmlText(raw.trim())
|
||
return { success: true, xml }
|
||
} catch (error) {
|
||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||
}
|
||
}
|
||
)
|
||
|
||
ipcMain.handle('image:getStatus', async () =>
|
||
inspectImageDecryptionStatus(imageKeyConfigService.getConfig())
|
||
)
|
||
ipcMain.handle('image:saveConfig', (_, request: SaveImageKeyRequest) => {
|
||
const result = imageKeyConfigService.save(request)
|
||
if (result.success) imageDecryptService = null
|
||
// 派生库按 accountId 分目录,切账号必须换句柄,否则会串账号。
|
||
imageTextIndexService.resetAccount()
|
||
return result
|
||
})
|
||
|
||
ipcMain.handle('image:testConfig', (_, request: TestImageDecryptionRequest) =>
|
||
testImageDecryption(request)
|
||
)
|
||
|
||
ipcMain.handle('image:clearConfig', () => {
|
||
const result = imageKeyConfigService.clear()
|
||
if (result.success) imageDecryptService = null
|
||
// 派生库按 accountId 分目录,切账号必须换句柄,否则会串账号。
|
||
imageTextIndexService.resetAccount()
|
||
return result
|
||
})
|
||
|
||
ipcMain.handle('image:selectDecoder', async (event) => {
|
||
const settings = loadSettings()
|
||
const owner = BrowserWindow.fromWebContents(event.sender)
|
||
const result = await dialog.showOpenDialog(owner!, {
|
||
title: '选择 FFmpeg 解压或安装目录',
|
||
defaultPath: settings.ffmpegPath ? dirname(settings.ffmpegPath) : app.getPath('downloads'),
|
||
properties: ['openDirectory']
|
||
})
|
||
if (result.canceled) return { success: false, canceled: true }
|
||
|
||
const selectedDirectory = result.filePaths[0]
|
||
if (!selectedDirectory) return { success: false, canceled: true }
|
||
|
||
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
|
||
const candidates = [
|
||
join(selectedDirectory, executable),
|
||
join(selectedDirectory, 'bin', executable)
|
||
]
|
||
let selectedPath = ''
|
||
for (const candidate of candidates) {
|
||
if (!existsSync(candidate)) continue
|
||
const inspection = await inspectImageDecoderExecutable(candidate)
|
||
if (inspection.installed) {
|
||
selectedPath = candidate
|
||
break
|
||
}
|
||
}
|
||
|
||
if (!selectedPath) {
|
||
return {
|
||
success: false,
|
||
canceled: false,
|
||
error: '所选目录中没有找到 FFmpeg,请选择解压后的文件夹或其中的 bin 文件夹。'
|
||
}
|
||
}
|
||
|
||
saveSettings({ ...settings, ffmpegPath: selectedPath })
|
||
return {
|
||
success: true,
|
||
canceled: false,
|
||
status: await inspectImageDecoderStatus(selectedPath)
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('image:getDecoderStatus', () => inspectImageDecoderStatus())
|
||
|
||
ipcMain.handle('image:openDecoderDownload', async () => {
|
||
const url =
|
||
process.platform === 'win32'
|
||
? 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip'
|
||
: process.platform === 'darwin'
|
||
? 'https://brew.sh/'
|
||
: 'https://ffmpeg.org/download.html'
|
||
try {
|
||
await shell.openExternal(url)
|
||
return { success: true }
|
||
} catch {
|
||
return { success: false, error: '无法打开下载页面,请检查系统默认浏览器设置。' }
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('db:getBootstrapCache', () => {
|
||
if (!chat.isReady()) return null
|
||
return getBootstrapCache(chat.getCurrentAccountRoot())
|
||
})
|
||
|
||
ipcMain.handle('db:getStartupCache', () => {
|
||
const settings = loadSettings()
|
||
return settings.dbRoot ? getBootstrapCache(settings.dbRoot) : null
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'db:getCachedMessages',
|
||
(_, userMd5: string, startTime?: number, endTime?: number) => {
|
||
const accountRoot = chat.isReady() ? chat.getCurrentAccountRoot() : loadSettings().dbRoot
|
||
return accountRoot ? getCachedMessages(accountRoot, userMd5, startTime, endTime) : []
|
||
}
|
||
)
|
||
|
||
ipcMain.handle(
|
||
'db:getCachedMessagePage',
|
||
(_, userMd5: string, startTime?: number, endTime?: number) => {
|
||
const accountRoot = chat.isReady() ? chat.getCurrentAccountRoot() : loadSettings().dbRoot
|
||
return accountRoot
|
||
? getCachedMessagePage(accountRoot, userMd5, startTime, endTime)
|
||
: { hit: false, messages: [] }
|
||
}
|
||
)
|
||
|
||
ipcMain.handle('db:getContacts', async (_, filter?: string) => {
|
||
const accountRoot = chat.getCurrentAccountRoot()
|
||
const contacts = accountRoot
|
||
? mergeCachedContactAvatars(accountRoot, await chat.listContactsAsync(filter))
|
||
: await chat.listContactsAsync(filter)
|
||
if (!filter && chat.isReady() && accountRoot) {
|
||
saveBootstrapContacts(accountRoot, contacts)
|
||
}
|
||
return contacts
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'db:getContactAvatars',
|
||
async (_, usernames: string[], options?: { refresh?: boolean }) => {
|
||
const avatars = await chat.getContactAvatars(usernames, options)
|
||
if (chat.isReady()) mergeBootstrapAvatars(chat.getCurrentAccountRoot(), avatars)
|
||
return avatars
|
||
}
|
||
)
|
||
|
||
ipcMain.handle(
|
||
'db:getMessages',
|
||
async (
|
||
_,
|
||
userMd5: string,
|
||
startTime?: number,
|
||
endTime?: number,
|
||
options?: { limit?: number }
|
||
) => {
|
||
const requestId = nextGetMessagesRequestId()
|
||
const startedAt = Date.now()
|
||
wcdbDebugLog(
|
||
`[${requestId}] IPC db:getMessages start start=${startTime || 0} end=${endTime || 0} limit=${options?.limit || 0}`
|
||
)
|
||
try {
|
||
const messages = await chat.listMessagesAsync(
|
||
userMd5,
|
||
startTime,
|
||
endTime,
|
||
options,
|
||
requestId
|
||
)
|
||
if (chat.isReady()) {
|
||
saveCachedMessages(chat.getCurrentAccountRoot(), userMd5, startTime, endTime, messages)
|
||
}
|
||
wcdbDebugLog(
|
||
`[${requestId}] IPC db:getMessages end rows=${messages.length} cost=${Date.now() - startedAt}ms`
|
||
)
|
||
return messages
|
||
} catch (error) {
|
||
wcdbDebugLog(`[${requestId}] IPC db:getMessages error cost=${Date.now() - startedAt}ms`)
|
||
throw error
|
||
}
|
||
}
|
||
)
|
||
|
||
/**
|
||
* 「跳转到原聊天」的锚点读取。
|
||
*
|
||
* 与 `db:getMessages` 的区别:目标是**某一条消息**,不是"某个时间段"。
|
||
* 以 `anchorSeconds` 为中心读一个**有界**窗口(默认 ±6h,找不到再放宽到 ±3d),
|
||
* 在窗口内按规范化消息 id 精确匹配。
|
||
*
|
||
* 不整段加载会话历史:最大会话可达数十万条消息,整段读既慢又会挤爆 IPC;
|
||
* 而时间窗口在真实数据上是稀疏的,±6h 的量级很小。
|
||
*
|
||
* `found: false` 表示"已打开会话但无法定位原消息",调用方必须走降级文案,
|
||
* 不能假装跳转成功。
|
||
*/
|
||
ipcMain.handle(
|
||
'db:getMessagesAround',
|
||
async (
|
||
_,
|
||
userMd5: string,
|
||
messageId: string,
|
||
anchorSeconds?: number,
|
||
radiusSeconds?: number
|
||
) => {
|
||
const requestId = nextGetMessagesRequestId()
|
||
const startedAt = Date.now()
|
||
const target = normalizeMessageIdentity(userMd5, messageId)
|
||
if (!target) return { messages: [], found: false, radiusSeconds: 0, truncated: false }
|
||
const baseRadius = normalizeRadiusSeconds(radiusSeconds)
|
||
const widenRadius = widenRadiusSeconds(baseRadius)
|
||
const maxWindowMessages = MESSAGES_AROUND_MAX_WINDOW
|
||
const radii = messagesAroundRadii(anchorSeconds, baseRadius, widenRadius)
|
||
if (!radii.length) {
|
||
// 没有时间锚点时**不能**退化成整段加载会话历史(最大会话可达数十万条,
|
||
// 整段读既慢又会挤爆 IPC)。诚实返回"未定位到",由调用方给出降级文案。
|
||
wcdbDebugLog(`[${requestId}] IPC db:getMessagesAround skipped reason=no-anchor`)
|
||
return { messages: [], found: false, radiusSeconds: 0, truncated: false }
|
||
}
|
||
wcdbDebugLog(
|
||
`[${requestId}] IPC db:getMessagesAround start messageId=${target.messageId} anchor=${anchorSeconds || 0}`
|
||
)
|
||
for (const radius of radii) {
|
||
const start = Math.max(0, (anchorSeconds as number) - radius)
|
||
const end = (anchorSeconds as number) + radius
|
||
let messages: Awaited<ReturnType<typeof chat.listMessagesAsync>>
|
||
try {
|
||
messages = await chat.listMessagesAsync(userMd5, start, end, undefined, requestId)
|
||
} catch (error) {
|
||
wcdbDebugLog(`[${requestId}] IPC db:getMessagesAround error radius=${radius}`)
|
||
throw error
|
||
}
|
||
const { window, index, truncated } = sliceMessagesAroundWindow(
|
||
messages,
|
||
userMd5,
|
||
target.messageId,
|
||
maxWindowMessages
|
||
)
|
||
if (index >= 0) {
|
||
if (chat.isReady()) {
|
||
saveCachedMessages(chat.getCurrentAccountRoot(), userMd5, start, end, window)
|
||
}
|
||
wcdbDebugLog(
|
||
`[${requestId}] IPC db:getMessagesAround found radius=${radius} rows=${window.length} cost=${Date.now() - startedAt}ms`
|
||
)
|
||
return { messages: window, found: true, radiusSeconds: radius, truncated }
|
||
}
|
||
// 窗口内没有这条消息:可能是时间戳口径漂移,也可能是它已经被删除/清理。
|
||
// 只有还值得放宽时才继续,避免把一次点击变成全库扫描。
|
||
if (radius === radii[radii.length - 1]) {
|
||
wcdbDebugLog(
|
||
`[${requestId}] IPC db:getMessagesAround not-found rows=${window.length} cost=${Date.now() - startedAt}ms`
|
||
)
|
||
return { messages: window, found: false, radiusSeconds: radius, truncated }
|
||
}
|
||
}
|
||
return { messages: [], found: false, radiusSeconds: 0, truncated: false }
|
||
}
|
||
)
|
||
|
||
ipcMain.handle('db:getGroupSnapshot', async (_, userMd5: string) => {
|
||
const snapshot = await chat.getGroupSnapshotAsync(userMd5)
|
||
if (snapshot && chat.isReady()) {
|
||
return saveCachedGroupSnapshot(chat.getCurrentAccountRoot(), userMd5, snapshot)
|
||
}
|
||
return snapshot
|
||
})
|
||
|
||
/**
|
||
* 群员统计(单群)。
|
||
*
|
||
* 时间单位刻意用 epoch **毫秒**:这一路完全走 Knowledge,而 Knowledge 内部口径就是毫秒。
|
||
* 沿用聊天消息的秒级口径会在 service 内部凭空多出一次换算 —— 而单位换错是**静默读 0 条**,
|
||
* 不会报错。
|
||
*/
|
||
ipcMain.handle(
|
||
'group-stats:getMemberStats',
|
||
async (_, request: { userMd5?: unknown; startTime?: unknown; endTime?: unknown }) => {
|
||
if (!groupStatsService) throw new Error('群员统计服务尚未就绪')
|
||
const userMd5 = String(request?.userMd5 || '').trim()
|
||
if (!userMd5) throw new Error('缺少会话标识')
|
||
const startTime = Number(request?.startTime)
|
||
const endTime = Number(request?.endTime)
|
||
if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime < startTime) {
|
||
throw new Error('统计时间范围无效')
|
||
}
|
||
return groupStatsService.getMemberStats({ userMd5, startTime, endTime })
|
||
}
|
||
)
|
||
|
||
ipcMain.handle('group-exit-monitor:getState', () => groupExitMonitorService.getState())
|
||
ipcMain.handle('group-exit-monitor:setEnabled', (_, enabled: boolean) =>
|
||
groupExitMonitorService.setEnabled(enabled === true)
|
||
)
|
||
/**
|
||
* 保存**监控范围**。
|
||
*
|
||
* 只有一个参数:旧版第二个参数(通知群聊)已经迁到「自动化 → 退群通知」,
|
||
* 退群监控不再持有任何通知配置。
|
||
*/
|
||
/* 监控范围变化不再触发任何规则补齐:防撤回的目标是「全部有消息表的会话」,
|
||
* 与退群监控选中的群无关;退群提示也已经改成事件驱动、不依赖 per-room 规则。 */
|
||
ipcMain.handle('group-exit-monitor:setGroups', (_, roomIds: string[]) =>
|
||
groupExitMonitorService.setMonitoredRoomIds(Array.isArray(roomIds) ? roomIds : [])
|
||
)
|
||
ipcMain.handle('group-exit-monitor:checkNow', () => groupExitMonitorService.checkNow())
|
||
/**
|
||
* 按群查退群事件(档案合并展示用)。
|
||
*
|
||
* 时间参数是 epoch **毫秒**,与事件的 `detectedAt` 同口径。
|
||
*/
|
||
ipcMain.handle('group-exit-monitor:listEvents', (_, query: unknown) => {
|
||
const input = (query || {}) as {
|
||
roomId?: unknown
|
||
sinceMs?: unknown
|
||
untilMs?: unknown
|
||
limit?: unknown
|
||
}
|
||
return groupExitMonitorService.listEvents({
|
||
roomId: typeof input.roomId === 'string' ? input.roomId : undefined,
|
||
sinceMs: Number(input.sinceMs),
|
||
untilMs: Number(input.untilMs),
|
||
limit: Number(input.limit)
|
||
})
|
||
})
|
||
ipcMain.handle('group-exit-monitor:clearEvents', () => groupExitMonitorService.clearEvents())
|
||
ipcMain.handle('group-exit-monitor:markRead', (_, readAt?: number) =>
|
||
groupExitMonitorService.markRead(readAt)
|
||
)
|
||
ipcMain.handle('wechat-action-log:list', () => wechatActionLogService.list())
|
||
|
||
/**
|
||
* Automation v1(@我生成日报)。
|
||
*
|
||
* 规则与执行日志都是纯文件存储,**不依赖数据库**,所以这两组 handler 在数据库
|
||
* 解锁前也可以安全调用;只有 `getStatus` / `listGroups` 需要会话数据,因此用
|
||
* `tryAutomationService()` 兜底,避免渲染层在启动阶段拿到一个 rejected promise。
|
||
*/
|
||
const tryAutomationService = (): ReturnType<typeof getAutomationService> | null => {
|
||
try {
|
||
return getAutomationService()
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
ipcMain.handle('automation:listRules', () => automationRuleStore.listRules())
|
||
ipcMain.handle('automation:createRule', (_, draft: unknown) =>
|
||
automationRuleStore.createRule(draft)
|
||
)
|
||
ipcMain.handle('automation:updateRule', (_, input: unknown) => {
|
||
const payload = (input || {}) as { id?: unknown; draft?: unknown }
|
||
return automationRuleStore.updateRule(String(payload.id || ''), payload.draft) ?? null
|
||
})
|
||
ipcMain.handle('automation:deleteRule', (_, id: string) => automationRuleStore.deleteRule(id))
|
||
ipcMain.handle('automation:setRuleEnabled', (_, input: unknown) => {
|
||
const payload = (input || {}) as { id?: unknown; enabled?: unknown }
|
||
return (
|
||
automationRuleStore.setRuleEnabled(String(payload.id || ''), payload.enabled === true) ?? null
|
||
)
|
||
})
|
||
ipcMain.handle('automation:listExecutions', (_, query: unknown) => {
|
||
const input = (query || {}) as { limit?: unknown }
|
||
return automationExecutionLogService.list({ limit: Number(input.limit) })
|
||
})
|
||
ipcMain.handle('automation:clearExecutions', () => automationExecutionLogService.clear())
|
||
ipcMain.handle('automation:listGroups', () => tryAutomationService()?.listGroups() ?? [])
|
||
/**
|
||
* 微信消息插入开关 —— 读取。
|
||
*
|
||
* 只走本进程只读路径(分片目录 + 开关值),不持有任何写权限。
|
||
* 状态里同时给出 desiredEnabled / effectiveEnabled:开关值写成功不等于功能
|
||
* 真的生效(规则可能没装齐),渲染层不能只看前者。
|
||
*/
|
||
ipcMain.handle('automation:getMsgInsertSwitches', async () => {
|
||
/* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。
|
||
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。
|
||
* 授权判定只走本机 HTTP + 文件 stat,同样不碰数据库。 */
|
||
return attachCapability(buildMsgInsertSwitchesSnapshot())
|
||
})
|
||
/**
|
||
* 微信消息插入开关 —— **运行期刷新**(允许在分片集合变化时补一次规则)。
|
||
*
|
||
* 与 GET 的分工:GET 必须纯读;但"微信运行期间新建了 message_N.db"这种情况需要补规则,
|
||
* 否则新分片里的会话永远显示未就绪 —— 而规则补齐只在**启动时**跑过一次。
|
||
* 用户侧看到的表现就是"计数变了,但分子追不上分母"。
|
||
*
|
||
* 成本控制:分片清单指纹没变 → 只做纯读立刻返回;变了才 spawn 一次 helper。
|
||
*/
|
||
ipcMain.handle('automation:refreshMsgInsertSwitches', async () => {
|
||
const scope = resolveMsgInsertScopeInput()
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (scope && client) {
|
||
try {
|
||
const signature = client
|
||
.listMessageShardPaths()
|
||
.map((item) => path.basename(item))
|
||
.join(',')
|
||
/*
|
||
* 分片变了只在「确实有授权」时补齐。
|
||
* 指纹必须**补齐成功之后**才更新:否则无授权跳过一次,等用户激活回来
|
||
* 分片没变,就再也不会补了(这正是原实现的坑)。
|
||
*/
|
||
if (signature !== lastMsgInsertReconciledShards) {
|
||
const gate = await requireCapability()
|
||
if (gate.ok) {
|
||
console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则')
|
||
const done = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||
if (done) lastMsgInsertReconciledShards = signature
|
||
} else {
|
||
console.log(
|
||
`[MsgInsert] 跳过运行期补齐:${gate.capability.reasonCode}(授权恢复后会自动重试)`
|
||
)
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.warn('[MsgInsert] 运行期补齐失败:', error)
|
||
}
|
||
}
|
||
return attachCapability(buildMsgInsertSwitchesSnapshot())
|
||
})
|
||
/**
|
||
* 微信消息插入开关 —— 写入。
|
||
*
|
||
* 绝不使用本进程的 WCDB 句柄写(只读池会把它钉死)。这里 spawn 一次性 helper:
|
||
* 先补齐目标会话的规则 → 再写开关值 → 读回校验 → 本进程只读复核。
|
||
* 失败不伪装成功:partial 会带 failedShards / notReadyRooms 回渲染层。
|
||
*/
|
||
ipcMain.handle('automation:setMsgInsertSwitch', async (_, input: unknown) => {
|
||
const payload = (input || {}) as { name?: unknown; enabled?: unknown }
|
||
const name = String(payload.name || '') as MsgInsertSwitchName
|
||
if (name !== 'recall_notice' && name !== 'group_exit_notice') {
|
||
return {
|
||
success: false,
|
||
status: emptyMsgInsertStatus('recall_notice'),
|
||
errorCode: 'UNSUPPORTED_SWITCH',
|
||
message: '未知的开关'
|
||
}
|
||
}
|
||
/* 只拦开启;关闭永远放行,否则规则会永久锁在微信库里。 */
|
||
if (payload.enabled === true) {
|
||
const gate = await requireCapability()
|
||
if (!gate.ok) {
|
||
const code = reasonToErrorCode(gate.capability)
|
||
return {
|
||
success: false,
|
||
status: emptyMsgInsertStatus(name, code, gate.capability.message),
|
||
errorCode: code,
|
||
message: gate.capability.message
|
||
}
|
||
}
|
||
}
|
||
/*
|
||
* 退群提示是**事件驱动**的(GroupExitMonitorService 发事件 → 一次性插一条),
|
||
* 不装任何 per-room 规则。所以它的开关只是本地设置:
|
||
* 既不 spawn helper,也不碰微信库。
|
||
*/
|
||
if (name === 'group_exit_notice') {
|
||
const toggled = wechatLocalExitNoticeService.setEnabled(payload.enabled === true)
|
||
if (toggled.error) {
|
||
return {
|
||
success: false,
|
||
status: eventModeStatus(name, toggled.enabled, exitNoticeGroupCount()),
|
||
errorCode: 'UNKNOWN',
|
||
message: '保存开关状态失败'
|
||
}
|
||
}
|
||
/* 开关一变,检测范围随之变(开 → 全部群聊;关 → 只剩勾选的群)。 */
|
||
syncExitNoticeScope()
|
||
return {
|
||
success: true,
|
||
status: eventModeStatus(name, toggled.enabled, exitNoticeGroupCount())
|
||
}
|
||
}
|
||
|
||
const scope = resolveMsgInsertScopeInput()
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (!scope || !client) {
|
||
return {
|
||
success: false,
|
||
status: emptyMsgInsertStatus(name),
|
||
errorCode: 'DATABASE_UNAVAILABLE',
|
||
message: '微信数据库尚未连接'
|
||
}
|
||
}
|
||
return applyMsgInsertSwitch({
|
||
...scope,
|
||
name,
|
||
enabled: payload.enabled === true,
|
||
myWxid: String(chat.getSelfAccountInfo()?.wxid || ''),
|
||
/* 密钥只在这里读一次,随后直接进 helper 的 stdin,绝不落盘 / 进 argv */
|
||
databaseKey: client.getKey()
|
||
})
|
||
})
|
||
/**
|
||
* 保存「退群通知」规则(singleton upsert)。
|
||
*
|
||
* 单独一个通道而不是复用 `updateRule`:这条规则是系统规则,
|
||
* 保存语义是"存在即更新、不存在即创建",且 id 固定 —— 不允许渲染层自己拼 id。
|
||
*/
|
||
ipcMain.handle('automation:saveLeaveNotificationRule', (_, draft: unknown) =>
|
||
automationRuleStore.saveLeaveNotificationRule(draft)
|
||
)
|
||
/**
|
||
* 「指定好友」的可选项。
|
||
*
|
||
* 过滤(群聊 / 公众号 / 文件传输助手 / 自己)在 main 侧完成 ——
|
||
* 只有这里知道当前登录账号是谁,渲染层再筛一遍必然会漂移。
|
||
*/
|
||
ipcMain.handle('automation:listSendableContacts', () => {
|
||
try {
|
||
const selfWxid = String(chat.getSelfAccountInfo()?.wxid || '')
|
||
return filterSendableFriendContacts(chat.listContacts(), selfWxid).map((contact) => ({
|
||
id: String(contact.m_nsUsrName || ''),
|
||
name: leaveNotificationContactDisplayName(contact)
|
||
}))
|
||
} catch (error) {
|
||
console.warn(
|
||
`[Automation] 读取可选联系人失败: ${error instanceof Error ? error.message : String(error)}`
|
||
)
|
||
return []
|
||
}
|
||
})
|
||
ipcMain.handle('automation:getStatus', async () => {
|
||
const service = tryAutomationService()
|
||
if (service) return service.getStatus()
|
||
// 数据库尚未就绪:如实返回「未监听 + 能力未知」,而不是假装一切正常。
|
||
const todayStart = new Date()
|
||
todayStart.setHours(0, 0, 0, 0)
|
||
const counts = automationExecutionLogService.countSince(todayStart.getTime())
|
||
return {
|
||
listening: false,
|
||
listeningDegraded: true,
|
||
todayExecutions: counts.total,
|
||
todaySuccesses: counts.success,
|
||
sendCapability: {
|
||
supported: false,
|
||
ready: false,
|
||
canSendText: false,
|
||
canSendImage: false,
|
||
message: '数据库尚未就绪,暂时无法获知微信发送能力'
|
||
}
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('db:search', (_, keyword: string) => chat.searchMessages(keyword))
|
||
ipcMain.handle(
|
||
'knowledge:search',
|
||
(_, request: KnowledgeSearchIpcRequest): Promise<KnowledgeSearchIpcResult> => {
|
||
if (!knowledgeSearchService) {
|
||
throw new Error('本地知识库服务尚未初始化')
|
||
}
|
||
return knowledgeSearchService.search(request)
|
||
}
|
||
)
|
||
ipcMain.handle('knowledge:getStatus', () => {
|
||
if (!knowledgeSearchService) throw new Error('本地知识库服务尚未初始化')
|
||
return knowledgeSearchService.getStatus()
|
||
})
|
||
ipcMain.handle('knowledge:startIndex', () => {
|
||
if (!knowledgeSearchService) throw new Error('本地知识库服务尚未初始化')
|
||
return knowledgeSearchService.startCurrentAccountIndex()
|
||
})
|
||
/**
|
||
* 取消正在跑的索引 pass。
|
||
*
|
||
* - 只中止**索引**:并发的交互查询用另一套 Abort scope,不会被连带取消;
|
||
* - 当前 batch 安全收尾:已提交的会话保留,**不回滚**;
|
||
* - `run_state` 落到 `cancelled`,不残留 `indexing`;
|
||
* - 取消 ≠ 清空:下一次同步从 per-conversation checkpoint 继续,不从头全量重扫。
|
||
*/
|
||
ipcMain.handle('knowledge:cancelIndex', () => {
|
||
if (!knowledgeSearchService) throw new Error('本地知识库服务尚未初始化')
|
||
return knowledgeSearchService.cancelCurrentAccountIndex()
|
||
})
|
||
// ---- 图片文字索引(本地 System OCR 派生文本,非 AI Provider)----
|
||
ipcMain.handle('image-text-index:getStatus', () => imageTextIndexService.getStatus())
|
||
/**
|
||
* 点击索引前的快速统计:纯 SQL COUNT,**不解密任何图片**。
|
||
* 这是「先告诉用户有多少张图片再决定是否开始」能足够快的前提。
|
||
*/
|
||
ipcMain.handle('image-text-index:count', (_, sinceMs?: number) =>
|
||
imageTextIndexService.countImageMessages(sinceMs)
|
||
)
|
||
ipcMain.handle('image-text-index:start', (_, options?: ImageTextIndexStartOptions) =>
|
||
imageTextIndexService.startPass(options ?? {})
|
||
)
|
||
ipcMain.handle('image-text-index:pause', () => imageTextIndexService.pause())
|
||
ipcMain.handle('image-text-index:resume', (_, options?: ImageTextIndexStartOptions) =>
|
||
imageTextIndexService.resume(options ?? {})
|
||
)
|
||
ipcMain.handle('image-text-index:cancel', () => imageTextIndexService.cancel())
|
||
ipcMain.handle('image-text-index:clear', () => imageTextIndexService.clear())
|
||
// 只重置失败记录(成功记录与其它数据一律不动),供"修好代码后重跑"使用。
|
||
ipcMain.handle('image-text-index:resetFailures', () =>
|
||
imageTextIndexService.resetRetriableFailures()
|
||
)
|
||
// 派生索引修复:只重建 Knowledge 里的图片派生条目(L3),**不重新 OCR**(L1 不动)。
|
||
ipcMain.handle('image-text-index:repair', () => imageTextIndexService.repairKnowledgeIndex())
|
||
ipcMain.handle('ai-search:run', (event, request: AiSearchPipelineRequest) => {
|
||
if (!aiSearchPipelineService) throw new Error('本地搜索服务尚未初始化')
|
||
return aiSearchPipelineService.run(request, (progress) => {
|
||
if (!event.sender.isDestroyed()) event.sender.send('ai-search:progress', progress)
|
||
})
|
||
})
|
||
ipcMain.handle('ai-search:cancel', (_, requestId: string) => {
|
||
if (!aiSearchPipelineService) throw new Error('本地搜索服务尚未初始化')
|
||
return aiSearchPipelineService.cancel(requestId)
|
||
})
|
||
voiceBatchService = new VoiceBatchService(voiceRecognition)
|
||
voiceBatchService.onProgress((progress) => {
|
||
for (const window of BrowserWindow.getAllWindows()) {
|
||
if (!window.isDestroyed()) window.webContents.send('voice:batchProgress', progress)
|
||
}
|
||
})
|
||
ipcMain.handle('ai-search:getProviderStatus', () => aiProviderService.getAiSearchProviderStatus())
|
||
// 问问微信主路径:查询大脑走 Query Agent Runtime(与 Agent Hub 同一实现)。
|
||
ipcMain.handle(
|
||
'ask-wechat:getConfig',
|
||
(): AskWechatConfig => ({ queryAgentEnabled: loadSettings().queryAgentEnabled !== false })
|
||
)
|
||
ipcMain.handle(
|
||
'ask-wechat:query',
|
||
(event, request: AskWechatQueryRequest): Promise<AskWechatQueryResult> => {
|
||
if (!askWechatService) throw new Error('本地查询服务尚未初始化')
|
||
// 进度事件只在真实 Runtime 边界产生,并且**带 requestId** 回传:
|
||
// UI 可以据此忽略过期请求的进度(用户连问两次时不会串台)。
|
||
return askWechatService.ask(request, 'default', (progress) => {
|
||
if (!event.sender.isDestroyed()) {
|
||
event.sender.send('ask-wechat:progress', request.requestId, progress)
|
||
}
|
||
})
|
||
}
|
||
)
|
||
ipcMain.handle('ask-wechat:forgetConversation', () => {
|
||
askWechatService?.forgetConversation()
|
||
})
|
||
ipcMain.handle(
|
||
'ai-search:authorizeExternalProvider',
|
||
(_, request: AiSearchExternalAuthorizationRequest) => {
|
||
if (!aiSearchPipelineService) throw new Error('本地搜索服务尚未初始化')
|
||
return aiSearchPipelineService.authorizeExternalProvider(request)
|
||
}
|
||
)
|
||
|
||
ipcMain.handle(
|
||
'ai:chat',
|
||
async (_, messages: { role: string; content: string }[], options?: AIChatRequestOptions) =>
|
||
aiProviderService.chat(messages, options)
|
||
)
|
||
|
||
ipcMain.handle('ai:listProviders', () => aiProviderService.list())
|
||
ipcMain.handle('ai:getRuntimeConfig', () => aiProviderService.getRuntimeConfig())
|
||
ipcMain.handle('ai:getVisionRuntimeConfig', () => aiProviderService.getVisionRuntimeConfig())
|
||
ipcMain.handle('ai:saveProvider', (_, provider: AIProviderConfig) =>
|
||
aiProviderService.save(provider)
|
||
)
|
||
ipcMain.handle('ai:deleteProvider', (_, providerId: string) =>
|
||
aiProviderService.delete(providerId)
|
||
)
|
||
ipcMain.handle('ai:setDefaultProvider', (_, providerId: string) =>
|
||
aiProviderService.setDefault(providerId)
|
||
)
|
||
ipcMain.handle('ai:testProvider', (_, providerId: string) => aiProviderService.test(providerId))
|
||
ipcMain.handle('ai:testVision', (_, request: AIVisionTestRequest) =>
|
||
aiProviderService.testVision(request)
|
||
)
|
||
ipcMain.handle('ai:migrateLegacy', (_, config: LegacyAIConfig) =>
|
||
aiProviderService.migrateLegacy(config)
|
||
)
|
||
|
||
ipcMain.handle('tts:getSettings', () => textToSpeechSettingsService.get())
|
||
ipcMain.handle('tts:saveSettings', (_, request: SaveTextToSpeechSettingsRequest) =>
|
||
textToSpeechSettingsService.save(request)
|
||
)
|
||
ipcMain.handle('tts:listVoices', (_, request?: ListTextToSpeechVoicesRequest) =>
|
||
textToSpeechSettingsService.listVoices(request)
|
||
)
|
||
ipcMain.handle('tts:synthesize', (_, request: SynthesizeTextToSpeechRequest) =>
|
||
textToSpeechSettingsService.synthesize(request)
|
||
)
|
||
ipcMain.handle('tts:removeGeneratedAudio', (_, filePath: string) =>
|
||
textToSpeechSettingsService.removeGeneratedAudio(String(filePath || ''))
|
||
)
|
||
ipcMain.handle('tts:openApiKeys', async () => {
|
||
try {
|
||
await shell.openExternal('https://fish.audio/app/api-keys/')
|
||
return { success: true }
|
||
} catch {
|
||
return { success: false, error: '无法打开 Fish Audio API Key 页面' }
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('copy-image', async (_, imageSource: unknown) => {
|
||
try {
|
||
if (typeof imageSource !== 'string' || !imageSource) {
|
||
return { success: false, error: 'Image source is empty' }
|
||
}
|
||
const image = imageSource.startsWith('wxe-media://')
|
||
? nativeImage.createFromPath(getImageMediaService()?.pathForUrl(imageSource) || '')
|
||
: nativeImage.createFromDataURL(imageSource)
|
||
if (image.isEmpty()) return { success: false, error: 'Image source is invalid' }
|
||
clipboard.writeImage(image)
|
||
return { success: true }
|
||
} catch (error: unknown) {
|
||
return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }
|
||
}
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'report:exportSnapshot',
|
||
async (_, request: GroupReportRenderSnapshotExportRequest) => exportGroupReportSnapshot(request)
|
||
)
|
||
|
||
ipcMain.handle('export:start', async (event, request: ExportRequest) => {
|
||
const window = BrowserWindow.fromWebContents(event.sender)
|
||
if (!window) return { success: false, error: '窗口不可用' }
|
||
return runExport(request, window, voiceRecognition || undefined)
|
||
})
|
||
ipcMain.handle('export:selectDirectory', async (event) => {
|
||
const window = BrowserWindow.fromWebContents(event.sender)
|
||
const result = await dialog.showOpenDialog(window!, {
|
||
properties: ['openDirectory', 'createDirectory']
|
||
})
|
||
return result.canceled ? { canceled: true } : { canceled: false, path: result.filePaths[0] }
|
||
})
|
||
ipcMain.handle('export:cancel', (_, jobId: string) => {
|
||
cancelExport(jobId)
|
||
return { success: true }
|
||
})
|
||
ipcMain.handle('export:reveal', async (_, path: string) => {
|
||
try {
|
||
await revealExport(path)
|
||
return { success: true }
|
||
} catch (error) {
|
||
return { success: false, error: String(error) }
|
||
}
|
||
})
|
||
ipcMain.handle('report:listGenerated', async () => {
|
||
return listGeneratedReports()
|
||
})
|
||
|
||
ipcMain.handle('report:saveGenerated', async (_, request: SaveGeneratedReportRequest) => {
|
||
return saveGeneratedReport(request)
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'report:updateGeneratedTemplate',
|
||
async (_, request: UpdateGeneratedReportTemplateRequest) => {
|
||
return updateGeneratedReportTemplate(request)
|
||
}
|
||
)
|
||
|
||
ipcMain.handle(
|
||
'report:prepareTemplateSwitch',
|
||
async (_, request: PrepareGeneratedReportTemplateSwitchRequest) =>
|
||
prepareGeneratedReportTemplateSwitch(request.reportId, extractGroupReportRenderSnapshot)
|
||
)
|
||
|
||
ipcMain.handle('report:deleteGenerated', async (_, reportId: string) => {
|
||
return deleteGeneratedReport(reportId)
|
||
})
|
||
|
||
ipcMain.handle('wechat-personal:getSendCapability', () => getPersonalWechatSendCapability())
|
||
|
||
/**
|
||
* 定时日报(Automation 的 `scheduled_report` 规则类型)。
|
||
*
|
||
* 规则本身的 CRUD 走上面的 `automation:*`;这里只补三块**专属**能力:
|
||
* 1. 「立即执行」—— 走 `AutomationService.executeScheduledRule(ruleId,'manual')`,
|
||
* 与 scheduler 触发**同一条链路**(生成 → 落库 → 解析目标 → Gateway 发图);
|
||
* 2. 微信异常通知 —— 定时日报失败时的 Agent Hub 推送,随功能保留;
|
||
* 3. 旧执行记录**只读存档** —— 旧记录无法无损转换,原样保留给 UI 展示。
|
||
*/
|
||
ipcMain.handle('automation:runScheduledReportRule', async (_, ruleId: string) => {
|
||
const service = tryAutomationService()
|
||
if (!service) return { success: false, error: '数据库尚未就绪,暂时无法执行定时日报' }
|
||
const outcome = await service.executeScheduledRule(String(ruleId || ''), { trigger: 'manual' })
|
||
if (outcome.executed) {
|
||
return { success: outcome.status !== 'failed', data: outcome }
|
||
}
|
||
// 「没执行」的每一种原因都要能翻译成用户看得懂的一句话 —— 否则点了按钮没反应,无从排查。
|
||
const skipMessages: Record<string, string> = {
|
||
missing_rule: '规则 id 无效',
|
||
rule_not_found: '未找到这条定时日报规则',
|
||
disabled: '这条定时日报已停用,请先启用再执行',
|
||
target_needs_review: '这条规则的发送目标需要重新选择后才能执行',
|
||
in_flight: '这条规则正在执行中,请稍后再试',
|
||
store_error: '读取规则失败,请稍后再试'
|
||
}
|
||
return {
|
||
success: false,
|
||
error: skipMessages[outcome.reason || ''] || '定时日报未执行',
|
||
data: outcome
|
||
}
|
||
})
|
||
ipcMain.handle('automation:listScheduledReportLegacyExecutions', (_, ruleId?: string) =>
|
||
scheduledReportService.listLegacyExecutions(ruleId)
|
||
)
|
||
ipcMain.handle('automation:getScheduledReportNotificationSettings', () =>
|
||
scheduledReportService.getNotificationSettings()
|
||
)
|
||
ipcMain.handle('automation:getScheduledReportNotificationCapability', () =>
|
||
scheduledReportService.checkNotificationCapability()
|
||
)
|
||
ipcMain.handle('automation:setScheduledReportNotificationEnabled', (_, enabled: boolean) =>
|
||
scheduledReportService.setNotificationEnabled(Boolean(enabled))
|
||
)
|
||
ipcMain.handle('automation:testScheduledReportErrorNotification', (_, ruleId: string) => {
|
||
if (!isTruthyDebugFlag(import.meta.env.VITE_SCHEDULED_REPORT_DEBUG)) {
|
||
return Promise.resolve({
|
||
success: false,
|
||
error: '调试测试按钮未开启,请在 .env 中设置 VITE_SCHEDULED_REPORT_DEBUG=true。'
|
||
})
|
||
}
|
||
return scheduledReportService.testScheduledReportErrorNotification(ruleId)
|
||
})
|
||
|
||
ipcMain.handle('report:reveal', async (_, filePath: string) => {
|
||
try {
|
||
shell.showItemInFolder(filePath)
|
||
return { success: true }
|
||
} catch (error) {
|
||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('wechat-share:getConfig', async () => wechatShareConfigStore.status())
|
||
ipcMain.handle('wechat-share:saveConfig', async (_, config: WechatShareServiceConfig) =>
|
||
wechatShareConfigStore.save(config)
|
||
)
|
||
ipcMain.handle('wechat-share:publish', async (_, request: PublishWechatShareCardRequest) =>
|
||
wechatShareCardService.publish(request)
|
||
)
|
||
|
||
ipcMain.handle(
|
||
'db:getVoiceData',
|
||
async (_, sessionId: string, localId: number, createTime: number, svrId?: string | number) => {
|
||
if (!voiceService) {
|
||
return { success: false, error: 'VoiceService 未初始化' }
|
||
}
|
||
return voiceService.resolveVoice(sessionId, localId, createTime, svrId)
|
||
}
|
||
)
|
||
|
||
ipcMain.handle(
|
||
'voice:showSourceContextMenu',
|
||
(
|
||
event,
|
||
reference: { sessionId: string; localId: number; createTime: number; svrId?: string | number }
|
||
) => {
|
||
const window = BrowserWindow.fromWebContents(event.sender)
|
||
if (!window || !voiceService) return { success: false, error: '语音服务未初始化' }
|
||
|
||
const revealSource = async (): Promise<void> => {
|
||
try {
|
||
const result = await voiceService!.resolveSource(
|
||
reference.sessionId,
|
||
reference.localId,
|
||
reference.createTime,
|
||
reference.svrId
|
||
)
|
||
if (!result.success) throw new Error(result.error)
|
||
|
||
const directory = join(app.getPath('userData'), 'voice-sources')
|
||
await fsPromises.mkdir(directory, { recursive: true })
|
||
const fileName = `voice_${reference.localId}_${reference.createTime}_${result.source.sourceHash.slice(0, 12)}.silk`
|
||
const filePath = join(directory, fileName)
|
||
await fsPromises.writeFile(filePath, result.source.data)
|
||
shell.showItemInFolder(filePath)
|
||
} catch (error) {
|
||
await dialog.showMessageBox(window, {
|
||
type: 'error',
|
||
title: '查找语音源文件失败',
|
||
message: '无法提取这条语音的源文件',
|
||
detail: error instanceof Error ? error.message : String(error)
|
||
})
|
||
}
|
||
}
|
||
|
||
Menu.buildFromTemplate([
|
||
{
|
||
label: '查找语音源文件',
|
||
click: () => void revealSource()
|
||
}
|
||
]).popup({ window })
|
||
return { success: true }
|
||
}
|
||
)
|
||
|
||
ipcMain.handle('voice:getModelStatus', async () => {
|
||
if (!voiceRecognition) throw new Error('Voice recognition is not initialized')
|
||
return voiceRecognition.getModelStatus()
|
||
})
|
||
|
||
ipcMain.handle('voice:downloadModel', async () => {
|
||
if (!voiceRecognition) throw new Error('Voice recognition is not initialized')
|
||
return voiceRecognition.downloadModel()
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'voice:cancelModelDownload',
|
||
() => voiceRecognition?.cancelModelDownload() || { success: false }
|
||
)
|
||
|
||
ipcMain.handle('voice:removeModel', async () => {
|
||
if (!voiceRecognition) throw new Error('Voice recognition is not initialized')
|
||
return voiceRecognition.removeModel()
|
||
})
|
||
|
||
ipcMain.handle('voice:openModelDirectory', async () => {
|
||
if (!voiceRecognition) return { success: false, error: '语音识别服务尚未初始化' }
|
||
const directory = voiceRecognition.modelManager.directory
|
||
await fsPromises.mkdir(directory, { recursive: true })
|
||
const error = await shell.openPath(directory)
|
||
return error ? { success: false, error } : { success: true }
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'voice:recognize',
|
||
(_, reference: VoiceMessageReference, options?: { force?: boolean }) => {
|
||
if (!voiceRecognition) {
|
||
return { success: false, code: 'NOT_CONNECTED', error: '语音识别服务尚未初始化' }
|
||
}
|
||
return voiceRecognition.recognize(reference, options)
|
||
}
|
||
)
|
||
|
||
ipcMain.handle('voice:getTranscriptSnapshot', (_, reference: VoiceMessageReference) => {
|
||
return voiceRecognition?.getTranscriptSnapshot(reference) || { state: 'pending' as const }
|
||
})
|
||
|
||
ipcMain.handle('voice:getBatchPreflight', (_, request: VoiceBatchRequest) => {
|
||
if (!voiceBatchService) throw new Error('Voice recognition is not initialized')
|
||
return voiceBatchService.preflight(request)
|
||
})
|
||
|
||
ipcMain.handle('voice:getBatchConversationSummaries', (_, request: VoiceBatchRequest) => {
|
||
if (!voiceBatchService) throw new Error('Voice recognition is not initialized')
|
||
return voiceBatchService.conversationSummaries(request)
|
||
})
|
||
|
||
ipcMain.handle('voice:getBatchProgress', () => voiceBatchService?.getProgress())
|
||
|
||
ipcMain.handle('voice:startBatch', (_, request: VoiceBatchRequest) => {
|
||
if (!voiceBatchService) throw new Error('Voice recognition is not initialized')
|
||
return voiceBatchService.start(request)
|
||
})
|
||
|
||
ipcMain.handle('voice:cancelBatch', () => ({ success: voiceBatchService?.cancel() || false }))
|
||
|
||
ipcMain.handle('voice:retryFailedBatch', () => {
|
||
if (!voiceBatchService) throw new Error('Voice recognition is not initialized')
|
||
return voiceBatchService.retryFailed()
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'voice:cancelRecognition',
|
||
(_, reference: VoiceMessageReference) =>
|
||
voiceRecognition?.cancelRecognition(reference) || { success: false }
|
||
)
|
||
|
||
ipcMain.handle('db:parseMessage', async (_, content: string, messageType: number) => {
|
||
return parseMessageContent(content, messageType)
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'db:getImage',
|
||
async (
|
||
_,
|
||
imageMd5?: string,
|
||
imageDatNameOrThumb?: string | boolean,
|
||
_sessionId?: string,
|
||
options?: {
|
||
force?: boolean
|
||
preferThumbnail?: boolean
|
||
priority?: number
|
||
includeData?: boolean
|
||
}
|
||
) => {
|
||
let service = imageDecryptService
|
||
if (!service) {
|
||
const { xorKey, aesKey } = getConfiguredImageKeys()
|
||
// Reading an already-decoded cache entry does not require the AES key.
|
||
// Before db:init resolves the account identity, secure storage may not
|
||
// expose that key yet, so keep this cache-only service local.
|
||
service = new ImageDecryptService(
|
||
xorKey,
|
||
aesKey,
|
||
chat.getChatDb()?.getWcdb4Client(),
|
||
loadSettings().dbRoot
|
||
)
|
||
if (aesKey) imageDecryptService = service
|
||
}
|
||
|
||
const imageDatName = typeof imageDatNameOrThumb === 'string' ? imageDatNameOrThumb : undefined
|
||
const force = options?.force === true
|
||
const preferThumbnail = options?.preferThumbnail === true
|
||
const includeData = options?.includeData === true
|
||
const priority = Number.isFinite(options?.priority) ? Number(options?.priority) : 0
|
||
const imageCacheKey = [
|
||
imageMd5 || '',
|
||
imageDatName || '',
|
||
force ? 'original' : preferThumbnail ? 'thumbnail' : 'auto'
|
||
].join('|')
|
||
const mediaService = getImageMediaService()
|
||
const cachedImage = await service.getCachedDecodedImage(imageCacheKey, {
|
||
includeData: includeData || !mediaService
|
||
})
|
||
if (cachedImage && (!force || !cachedImage.isThumbnail)) {
|
||
return buildImageResponse(cachedImage, includeData)
|
||
}
|
||
|
||
return enqueueColdImageLoad(async () => {
|
||
// Disk cache was already checked without waiting for database startup.
|
||
// Only a real miss needs the initialized WCDB client and hardlink index.
|
||
if (dbInitInFlight) {
|
||
await dbInitInFlight.catch(() => undefined)
|
||
}
|
||
|
||
let coldService = imageDecryptService
|
||
if (!coldService) {
|
||
const { xorKey, aesKey } = getConfiguredImageKeys()
|
||
if (!aesKey) return { success: false, error: '未配置图片解密密钥' }
|
||
coldService = new ImageDecryptService(
|
||
xorKey,
|
||
aesKey,
|
||
chat.getChatDb()?.getWcdb4Client(),
|
||
loadSettings().dbRoot
|
||
)
|
||
imageDecryptService = coldService
|
||
}
|
||
|
||
// A previous queued request may have populated the cache while this one waited.
|
||
const queuedMediaService = getImageMediaService()
|
||
const queuedCacheHit = await coldService.getCachedDecodedImage(imageCacheKey, {
|
||
includeData: includeData || !queuedMediaService
|
||
})
|
||
if (queuedCacheHit && (!force || !queuedCacheHit.isThumbnail)) {
|
||
return buildImageResponse(queuedCacheHit, includeData)
|
||
}
|
||
|
||
let filePath = force
|
||
? await coldService.findImageFileAsync(imageMd5, imageDatName, {
|
||
allowThumbnail: false,
|
||
sessionId: _sessionId
|
||
})
|
||
: null
|
||
if (!filePath) {
|
||
filePath = await coldService.findImageFileAsync(imageMd5, imageDatName, {
|
||
allowThumbnail: true,
|
||
preferThumbnail,
|
||
sessionId: _sessionId
|
||
})
|
||
}
|
||
if (!filePath) {
|
||
return {
|
||
success: false,
|
||
error: force ? '未找到原图或缩略图文件' : '未找到图片文件'
|
||
}
|
||
}
|
||
|
||
const decrypted = await coldService.decryptImageToBase64WithFallbackAsync(filePath, true)
|
||
if (!decrypted) {
|
||
return { success: false, error: '图片解密失败' }
|
||
}
|
||
|
||
const decodedImage: DecodedImage = {
|
||
data: decrypted.data,
|
||
filePath: decrypted.filePath,
|
||
isThumbnail: coldService.isThumbnailFile(decrypted.filePath)
|
||
}
|
||
await coldService.cacheDecodedImage(imageCacheKey, decodedImage)
|
||
return buildImageResponse(decodedImage, includeData)
|
||
}, priority)
|
||
}
|
||
)
|
||
|
||
// ============================================================
|
||
// 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
|
||
}
|
||
})
|
||
|
||
// System OCR 是独立的本地 Runtime(不是 AI Provider):只注入项目统一的 ffmpeg
|
||
// 解析逻辑(GIF/BMP/WebP/TIFF → PNG 归一化)和系统 locale(OCR 语言包探测)。
|
||
systemOcrService.bind({
|
||
resolveFfmpegExecutable,
|
||
locale: () => app.getLocale()
|
||
})
|
||
|
||
/** 日报入口:取会话 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<ImageAnalysisResponse> => {
|
||
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 模型不存在' }
|
||
}
|
||
// Capability metadata is stored per machine. A model verified on macOS
|
||
// may still be unmarked on Windows, so do not reject before making the
|
||
// real multimodal request. The provider response remains authoritative.
|
||
// 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) }
|
||
}
|
||
)
|
||
|
||
// ============================================================
|
||
// 本地图片文字识别(System OCR Runtime:Windows 系统 OCR / macOS 系统 OCR)
|
||
// ============================================================
|
||
// 这是本地 Runtime,不是 AI Vision Provider:
|
||
// - 不联网、不上传原图;
|
||
// - 不读写 AI Provider / Vision 模型配置;
|
||
// - 本 IPC 只返回识别文本、不落库:派生文本的持久化由图片文字索引负责。
|
||
ipcMain.handle('system-ocr:getCapability', async (): Promise<SystemOcrCapability> => {
|
||
return imageInsightService.getSystemOcrCapability()
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'system-ocr:recognize',
|
||
async (_, request: SystemOcrRequest): Promise<SystemOcrResult> => {
|
||
// 单图识别是用户主动触发的一次操作,结果里已经带了 text / durationMs / errorCode,
|
||
// 调用方直接用返回值判断即可,这里不再打日志(尤其不打稳定的图片标识)。
|
||
return imageInsightService.extractLocalText(request)
|
||
}
|
||
)
|
||
|
||
ipcMain.handle('db:getSticker', async (_, cdnUrl?: string, md5?: string) => {
|
||
if (!stickerService) {
|
||
stickerService = new StickerService(chat.getChatDb()?.getWcdb4Client())
|
||
}
|
||
return stickerService.resolveSticker(cdnUrl, md5)
|
||
})
|
||
|
||
ipcMain.handle(
|
||
'db:getVideo',
|
||
async (
|
||
_,
|
||
hashes: string[],
|
||
options?: {
|
||
createTime?: number
|
||
byteLength?: number
|
||
duration?: number
|
||
width?: number
|
||
height?: number
|
||
}
|
||
) => {
|
||
if (!videoAssetService) {
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (!client) return { success: false, error: '数据库尚未连接' }
|
||
videoAssetService = new VideoAssetService(client)
|
||
}
|
||
return videoAssetService.resolve(Array.isArray(hashes) ? hashes : [], options)
|
||
}
|
||
)
|
||
|
||
// -------- Settings & API service --------
|
||
|
||
ipcMain.handle('settings:get', () => ({
|
||
settings: imageKeyConfigService.getLegacySettingsView(),
|
||
settingsPath: getSettingsPath()
|
||
}))
|
||
|
||
ipcMain.handle('settings:set', (_, patch: Partial<AppSettings>) => {
|
||
const before = loadSettings()
|
||
const current = imageKeyConfigService.getConfig()
|
||
const resourceRoot = patch.imageKeyRoot ?? before.imageKeyRoot
|
||
const xorKey = patch.imageXorKey ?? current.xorKey ?? '0x40'
|
||
const aesKey = patch.imageAesKey ?? current.aesKey ?? ''
|
||
const includesImageKey = 'imageXorKey' in patch || 'imageAesKey' in patch
|
||
const nextSettings = saveSettings({ ...before, ...patch, imageXorKey: '', imageAesKey: '' })
|
||
if (includesImageKey) {
|
||
if (aesKey) imageKeyConfigService.save({ resourceRoot, xorKey, aesKey })
|
||
else imageKeyConfigService.clear()
|
||
imageDecryptService = null
|
||
// 派生库按 accountId 分目录,切账号必须换句柄,否则会串账号。
|
||
imageTextIndexService.resetAccount()
|
||
}
|
||
if ('recallProtectionEnabled' in patch && chat.isReady()) {
|
||
const currentDb = chat.getChatDb()
|
||
if (currentDb) {
|
||
configureRecallProtection(
|
||
currentDb.getWcdb4Client(),
|
||
chat.getCurrentAccountRoot(),
|
||
nextSettings.recallProtectionEnabled,
|
||
nextSettings.recallProtectionEnabled && !before.recallProtectionEnabled
|
||
)
|
||
}
|
||
}
|
||
return {
|
||
settings: imageKeyConfigService.getLegacySettingsView(),
|
||
settingsPath: getSettingsPath()
|
||
}
|
||
})
|
||
|
||
ipcMain.handle('settings:getSelf', async () => {
|
||
const rawInfo = await chat.getSelfAccountInfoAsync()
|
||
if (!rawInfo) return { ready: false }
|
||
const info = mergeCachedSelfInfo(rawInfo.accountRoot, rawInfo)
|
||
if (chat.isReady()) saveBootstrapSelf(chat.getCurrentAccountRoot(), info)
|
||
return { ready: true, info }
|
||
})
|
||
|
||
ipcMain.handle('db:testConnection', (_, key: string, accountRoot?: string) => {
|
||
return chat.testConnection(key, accountRoot)
|
||
})
|
||
|
||
ipcMain.handle('db:reopenWithRoot', async (_, accountRoot: string) => {
|
||
groupExitMonitorService.stop()
|
||
const ok = chat.reopenWithRoot(accountRoot)
|
||
if (!ok) return { success: false, error: '数据库未初始化或重新打开失败' }
|
||
const client = chat.getChatDb()?.getWcdb4Client()
|
||
if (client) {
|
||
voiceService = new VoiceService(client, client.getAccountRoot())
|
||
voiceRecognition?.connect(voiceService, client.getAccountRoot())
|
||
const monitoring = await client.startMonitor((event) => {
|
||
client.invalidateSessionCache()
|
||
groupExitMonitorService.notifyDatabaseChanged(event.raw)
|
||
for (const window of BrowserWindow.getAllWindows()) {
|
||
if (!window.isDestroyed()) {
|
||
window.webContents.send('wcdb-change', { type: event.type, json: event.raw })
|
||
}
|
||
}
|
||
})
|
||
void groupExitMonitorService.start(monitoring)
|
||
}
|
||
// 同步 imageKeyRoot,避免自动获取扫描到旧目录
|
||
const settings = loadSettings()
|
||
if (accountRoot && accountRoot !== settings.imageKeyRoot) {
|
||
saveSettings({ ...settings, imageKeyRoot: accountRoot })
|
||
}
|
||
const rawInfo = await chat.getSelfAccountInfoAsync()
|
||
const info = rawInfo ? mergeCachedSelfInfo(rawInfo.accountRoot, rawInfo) : null
|
||
return { success: true, info }
|
||
})
|
||
|
||
ipcMain.handle('settings:selectDbRoot', async (event) => {
|
||
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender)!, {
|
||
title: '选择微信数据库目录',
|
||
defaultPath: loadSettings().dbRoot || undefined,
|
||
properties: ['openDirectory']
|
||
})
|
||
return result.canceled ? { canceled: true } : { canceled: false, path: result.filePaths[0] }
|
||
})
|
||
|
||
ipcMain.handle('settings:openAccountRoot', async () => {
|
||
const accountRoot = chat.getCurrentAccountRoot()
|
||
if (!accountRoot) return { success: false, error: '当前没有可打开的账号目录' }
|
||
const error = await shell.openPath(accountRoot)
|
||
return error ? { success: false, error } : { success: true }
|
||
})
|
||
|
||
ipcMain.handle('db:disconnect', (_, options?: { closeNative?: boolean }) => {
|
||
// 断开操作保持幂等:渲染进程可能已标记断开,或主进程连接已先行失效。
|
||
// 即使当前未就绪,也应让用户正常返回登录页。
|
||
voiceBatchService?.cancel()
|
||
voiceRecognition?.disconnect()
|
||
voiceService = null
|
||
groupExitMonitorService.stop()
|
||
if (options?.closeNative !== false && chat.isReady()) chat.setChatDb(null)
|
||
return { success: true }
|
||
})
|
||
|
||
ipcMain.handle('api:getStatus', () => apiServer.getState())
|
||
|
||
ipcMain.handle('api:tokenStatus', () => apiTokenStore.ensureToken())
|
||
ipcMain.handle('api:revealToken', () => apiTokenStore.revealToken())
|
||
ipcMain.handle('api:copyToken', () => {
|
||
const result = apiTokenStore.revealToken()
|
||
if (!result.token) return { ...result, success: false }
|
||
try {
|
||
clipboard.writeText(result.token)
|
||
return {
|
||
success: true,
|
||
available: result.available,
|
||
hasToken: result.hasToken,
|
||
maskedToken: result.maskedToken
|
||
}
|
||
} catch {
|
||
return { ...apiTokenStore.getStatus(), success: false, error: 'API Token 复制失败' }
|
||
}
|
||
})
|
||
ipcMain.handle('api:rotateToken', () => apiTokenStore.rotateToken())
|
||
|
||
ipcMain.handle('api:start', async (_, host?: string, port?: number) => {
|
||
const settings = loadSettings()
|
||
const target = {
|
||
host: host || settings.apiHost,
|
||
port: port || settings.apiPort
|
||
}
|
||
if (host || port) saveSettings({ ...settings, ...target })
|
||
return apiServer.start(target.host, target.port)
|
||
})
|
||
|
||
ipcMain.handle('api:stop', async () => apiServer.stop())
|
||
|
||
ipcMain.handle('api:toggle', async (_, enabled: boolean) => {
|
||
const settings = saveSettings({ ...loadSettings(), apiEnabled: enabled })
|
||
if (enabled) {
|
||
return apiServer.start(settings.apiHost, settings.apiPort)
|
||
}
|
||
return apiServer.stop()
|
||
})
|
||
|
||
ipcMain.handle('api:skillStatus', () => skillResourceService.getStatus())
|
||
ipcMain.handle('api:readSkill', () => skillResourceService.read())
|
||
ipcMain.handle('api:revealSkill', () => skillResourceService.reveal())
|
||
ipcMain.handle('api:openSkillGithub', () => skillResourceService.openGithub())
|
||
ipcMain.handle('api:testLocalRequest', (_, request) => testLocalApiRequest(request))
|
||
ipcMain.handle('api:copyCurl', (_, request) => {
|
||
const result = buildLocalApiCurlCommand(request)
|
||
if (!result.success || !result.command) return { success: false, error: result.error }
|
||
try {
|
||
clipboard.writeText(result.command)
|
||
return { success: true }
|
||
} catch {
|
||
return { success: false, error: 'curl 命令复制失败' }
|
||
}
|
||
})
|
||
ipcMain.handle('api:copyText', (_, text: unknown) => {
|
||
if (typeof text !== 'string' || text.length > 1024 * 1024) {
|
||
return { success: false, error: '复制内容无效或过大' }
|
||
}
|
||
try {
|
||
clipboard.writeText(text)
|
||
return { success: true }
|
||
} catch (error) {
|
||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||
}
|
||
})
|
||
ipcMain.handle('agent-hub:getStatus', () => agentHubService.getStatus())
|
||
ipcMain.handle('agent-hub:getLogs', () => agentHubService.getLogs())
|
||
ipcMain.handle('agent-hub:clearLogs', () => agentHubService.clearLogs())
|
||
ipcMain.handle('agent-hub:startLogin', () => agentHubService.startLogin())
|
||
ipcMain.handle('agent-hub:cancelLogin', () => agentHubService.cancelLogin())
|
||
ipcMain.handle('agent-hub:reconnect', () => agentHubService.reconnect())
|
||
ipcMain.handle('agent-hub:disconnect', () => agentHubService.disconnect())
|
||
// 对话记录:完整收发回看,仅本机,不进日志。
|
||
ipcMain.handle('agent-hub:getConversations', () => agentHubService.listConversations())
|
||
ipcMain.handle('agent-hub:getConversation', (_, userId: string) =>
|
||
agentHubService.getConversation(String(userId || ''))
|
||
)
|
||
ipcMain.handle('agent-hub:clearConversations', () => {
|
||
agentHubService.clearConversations()
|
||
return { success: true }
|
||
})
|
||
ipcMain.handle('wechat-personal:getStatus', () => currentPersonalWechatSenderStatus())
|
||
ipcMain.handle('wechat-personal:getMacLicenseStatus', () =>
|
||
macWechatRuntimeManager.getMacLicenseStatus()
|
||
)
|
||
ipcMain.handle('wechat-personal:getMacSendRuntimeAvailability', () =>
|
||
macWechatRuntimeManager.getSendRuntimeAvailability()
|
||
)
|
||
ipcMain.handle('wechat-personal:startMacSendRuntime', () => {
|
||
if (process.platform !== 'darwin') throw new Error('仅 macOS 支持微信发送组件')
|
||
return macWechatRuntimeManager.startAfterResidualCleanup()
|
||
})
|
||
ipcMain.handle('wechat-personal:listMacResidualProcesses', () =>
|
||
inspectMacWechatResidualProcesses()
|
||
)
|
||
ipcMain.handle('wechat-personal:cleanupMacResidualProcesses', async (_, pids: unknown) => {
|
||
if (process.platform !== 'darwin') throw new Error('仅 macOS 支持清理微信残留进程')
|
||
if (!Array.isArray(pids)) throw new Error('清理目标无效')
|
||
const requestedTargets = pids.filter(
|
||
(target): target is { pid: number; confirmationToken: string } =>
|
||
Boolean(target) &&
|
||
typeof target === 'object' &&
|
||
Number.isSafeInteger((target as { pid?: unknown }).pid) &&
|
||
typeof (target as { confirmationToken?: unknown }).confirmationToken === 'string'
|
||
)
|
||
if (requestedTargets.length === 0) throw new Error('没有确认的清理目标')
|
||
const currentTargets = await inspectMacWechatResidualProcesses()
|
||
const confirmedTargets = requestedTargets.filter((requested) =>
|
||
currentTargets.some(
|
||
(current) =>
|
||
current.pid === requested.pid && current.confirmationToken === requested.confirmationToken
|
||
)
|
||
)
|
||
if (confirmedTargets.length === 0) {
|
||
return { stopped: [], remaining: currentTargets }
|
||
}
|
||
let runtimeStopped = false
|
||
const result = await cleanupMacWechatResidualProcesses(
|
||
confirmedTargets,
|
||
undefined,
|
||
(targets) => {
|
||
if (
|
||
targets.some(
|
||
(target) =>
|
||
target.targets.includes('host') ||
|
||
target.targets.includes('frida_helper') ||
|
||
(macWechatRuntimeManager.getPort() === 4290 &&
|
||
target.targets.includes('port_4290'))
|
||
)
|
||
) {
|
||
macWechatRuntimeManager.prepareForResidualCleanup()
|
||
runtimeStopped = true
|
||
}
|
||
}
|
||
)
|
||
return { ...result, runtimeStopped }
|
||
})
|
||
ipcMain.handle('wechat-personal:refreshMacLicense', () =>
|
||
macWechatRuntimeManager.refreshMacLicense()
|
||
)
|
||
ipcMain.handle('wechat-personal:checkStatus', (_, port?: string) =>
|
||
personalWechatSendService.checkWindowsStatus(port)
|
||
)
|
||
ipcMain.handle('wechat-personal:checkVoiceEnvironment', () =>
|
||
personalWechatVoiceEnvironmentService.check()
|
||
)
|
||
ipcMain.handle('wechat-personal:installPilk', () =>
|
||
personalWechatVoiceEnvironmentService.installPilk()
|
||
)
|
||
ipcMain.handle('wechat-personal:openVoicePythonDownload', async () => {
|
||
try {
|
||
await shell.openExternal('https://www.python.org/downloads/macos/')
|
||
return { success: true }
|
||
} catch {
|
||
return { success: false, error: '无法打开 Python 下载页面' }
|
||
}
|
||
})
|
||
ipcMain.handle('wechat-personal:openVoiceFfmpegDownload', async () => {
|
||
try {
|
||
await shell.openExternal('https://brew.sh/')
|
||
return { success: true }
|
||
} catch {
|
||
return { success: false, error: '无法打开 FFmpeg 安装页面' }
|
||
}
|
||
})
|
||
ipcMain.handle('wechat-personal:rebind', async () => {
|
||
if (process.platform !== 'darwin') return personalWechatSendService.rebind()
|
||
|
||
const result = await macWechatRuntimeManager.bind()
|
||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||
if (result.ok) return status
|
||
|
||
return {
|
||
...status,
|
||
state: 'error',
|
||
message: result.message,
|
||
error: result.message
|
||
}
|
||
})
|
||
ipcMain.handle(
|
||
'wechat-personal:sendGeneratedTtsVoice',
|
||
async (_, request: PersonalWechatGeneratedTtsVoiceRequest) => {
|
||
const to = String(request?.to || '').trim()
|
||
const filePath = String(request?.filePath || '').trim()
|
||
let fromId = ''
|
||
try {
|
||
const self = await chat.getSelfAccountInfoAsync()
|
||
fromId = String(self?.wxid || '').trim()
|
||
} catch {
|
||
// Windows 语音发送需要当前账号 wxid;Gateway 会继续规范化失败结果。
|
||
}
|
||
const action = await wechatActionGateway.execute({
|
||
origin: 'user_tts',
|
||
purpose: 'tts_voice',
|
||
triggerType: 'user',
|
||
recipient: {
|
||
type: request?.isGroup || to.endsWith('@chatroom') ? 'group' : 'contact',
|
||
id: to
|
||
},
|
||
content: { type: 'voice', path: filePath },
|
||
metadata: fromId ? { fromId } : undefined
|
||
})
|
||
const sendResult =
|
||
action.sendResult && typeof action.sendResult === 'object'
|
||
? (action.sendResult as PersonalWechatSendResult)
|
||
: undefined
|
||
const status = sendResult?.status || (await currentPersonalWechatSenderStatus())
|
||
return { action, status }
|
||
}
|
||
)
|
||
ipcMain.handle('wechat-personal:getVoiceDiagnostic', () =>
|
||
personalWechatSendService.getLatestVoiceDiagnostic()
|
||
)
|
||
ipcMain.handle('wechat-personal:selectFile', async (event) => {
|
||
const window = BrowserWindow.fromWebContents(event.sender)
|
||
const result = await dialog.showOpenDialog(window!, {
|
||
title: '选择要发送的文件',
|
||
properties: ['openFile']
|
||
})
|
||
if (result.canceled || result.filePaths.length === 0) return { canceled: true }
|
||
const filePath = result.filePaths[0]
|
||
let size = 0
|
||
try {
|
||
size = (await fsPromises.stat(filePath)).size
|
||
} catch {
|
||
return { canceled: true }
|
||
}
|
||
return { canceled: false, path: filePath, name: path.basename(filePath), size }
|
||
})
|
||
ipcMain.handle('agent-hub:selectTestImage', async (event) => {
|
||
const window = BrowserWindow.fromWebContents(event.sender)
|
||
const result = await dialog.showOpenDialog(window!, {
|
||
title: '选择要发送的图片',
|
||
properties: ['openFile'],
|
||
filters: [
|
||
{ name: '图片', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'] },
|
||
{ name: '所有文件', extensions: ['*'] }
|
||
]
|
||
})
|
||
return result.canceled ? { canceled: true } : { canceled: false, path: result.filePaths[0] }
|
||
})
|
||
|
||
// 启动本地 HTTP API(由 settings.apiEnabled 控制)
|
||
const settings = loadSettings()
|
||
// v2.1.8 and earlier did not have an API token. Generate it once during
|
||
// upgrade/startup without changing any existing API or database settings.
|
||
apiTokenStore.ensureToken()
|
||
if (settings.apiEnabled) {
|
||
await apiServer.start(settings.apiHost, settings.apiPort)
|
||
}
|
||
|
||
await agentHubService.start(settings)
|
||
await scheduledReportService.start()
|
||
|
||
setupTray()
|
||
if (TRAY_MODE) app.dock?.hide()
|
||
|
||
app.on('activate', function () {
|
||
// 在 macOS 上点击 Dock 图标且没有其他窗口打开时,
|
||
// 通常会在应用程序中重新创建一个窗口。
|
||
if (BrowserWindow.getAllWindows().length === 0) createWindow()
|
||
})
|
||
})
|
||
|
||
// 除 macOS 外,所有窗口关闭时退出应用。在 macOS 上,
|
||
// 应用程序及其菜单栏通常会保持活动状态,直到用户
|
||
// 明确使用 Cmd + Q 退出。
|
||
app.on('window-all-closed', () => {
|
||
if (TRAY_MODE) return
|
||
if (process.platform !== 'darwin') {
|
||
app.quit()
|
||
}
|
||
})
|
||
|
||
let quitCleanupStarted = false
|
||
let quitCleanupComplete = false
|
||
|
||
app.on('before-quit', (event) => {
|
||
if (quitCleanupComplete) return
|
||
isQuitting = true
|
||
appShutdownRequested = true
|
||
event.preventDefault()
|
||
if (quitCleanupStarted) return
|
||
quitCleanupStarted = true
|
||
voiceBatchService?.cancel()
|
||
console.log('[Shutdown] cleanup started')
|
||
|
||
void (async () => {
|
||
agentHubService.stop()
|
||
scheduledReportService.stop()
|
||
groupExitMonitorService.stop()
|
||
await disposeExtensionSystem().catch(() => undefined)
|
||
flushBootstrapCacheWritesSync()
|
||
const [, nativeCallsDrained] = await Promise.all([
|
||
apiServer.stop().catch(() => undefined),
|
||
chat.closeChatDbForQuit().catch(() => false),
|
||
voiceRecognition?.dispose().catch(() => undefined),
|
||
knowledgeSearchService?.dispose().catch(() => undefined),
|
||
/*
|
||
* Deliberately do NOT stop the macOS native runtime here.
|
||
*
|
||
* The host is designed to outlive TraceMemo ("保留发送能力进程"): keeping
|
||
* it alive preserves the bound frida session, so relaunching the app —
|
||
* including every dev-mode restart — re-adopts it and works immediately
|
||
* instead of forcing the user to bind WeChat again.
|
||
*
|
||
* Stopping it on quit threw that away and, worse, gave teardown a chance
|
||
* to hang mid-unload while the app was already exiting. The host has its
|
||
* own lifecycle instead: it exits itself once WeChat is gone ("stale" ->
|
||
* self-shutdown), and it can be restarted explicitly from the settings
|
||
* card ("重新加载组件").
|
||
*/
|
||
Promise.resolve()
|
||
])
|
||
if (!nativeCallsDrained) {
|
||
console.warn('[Shutdown] WCDB async calls did not fully drain before quit')
|
||
}
|
||
if (tray) {
|
||
tray.destroy()
|
||
tray = null
|
||
}
|
||
console.log('[Shutdown] cleanup completed')
|
||
})()
|
||
.catch((error) => {
|
||
console.warn('[Shutdown] cleanup failed:', error)
|
||
})
|
||
.finally(() => {
|
||
quitCleanupComplete = true
|
||
// The first quit request has already been cancelled so cleanup can finish safely.
|
||
// app.exit() avoids starting a second before-quit cycle that can leave Electron alive
|
||
// on macOS even after every application service has stopped.
|
||
console.log('[Shutdown] exiting application')
|
||
app.exit(0)
|
||
})
|
||
})
|
||
|
||
function showMainWindow(): void {
|
||
if (process.platform === 'darwin') app.dock?.show().catch(() => undefined)
|
||
const wins = BrowserWindow.getAllWindows()
|
||
if (wins.length === 0) {
|
||
createWindow()
|
||
return
|
||
}
|
||
const win = wins[0]
|
||
if (win.isMinimized()) win.restore()
|
||
win.show()
|
||
win.focus()
|
||
}
|
||
|
||
function buildTrayMenu(): Menu {
|
||
return Menu.buildFromTemplate([
|
||
{
|
||
label: '打开主窗口',
|
||
click: () => showMainWindow()
|
||
},
|
||
{ type: 'separator' },
|
||
{
|
||
label: '退出 TraceMemo',
|
||
click: () => {
|
||
tray?.destroy()
|
||
tray = null
|
||
app.quit()
|
||
}
|
||
}
|
||
])
|
||
}
|
||
|
||
function setupTray(): void {
|
||
if (tray) return
|
||
try {
|
||
const trayImage = createTrayImage(
|
||
process.platform,
|
||
appIconPath,
|
||
{ oneX: trayTemplateIconPath, twoX: trayTemplateRetinaIconPath },
|
||
nativeImage
|
||
)
|
||
tray = new Tray(trayImage)
|
||
tray.setToolTip('TraceMemo')
|
||
// macOS may show a Tray context menu on a primary click when it is set
|
||
// directly on the Tray. Keep the menu for an explicit secondary click so
|
||
// the primary click only restores the main window.
|
||
tray.on('click', () => showMainWindow())
|
||
tray.on('right-click', () => tray?.popUpContextMenu(buildTrayMenu()))
|
||
} catch (error) {
|
||
console.warn('[Tray] Failed to create tray:', error)
|
||
}
|
||
}
|