Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop

This commit is contained in:
Wxw-Gu committed 2026-11-05 17:10:20 +08:00
commit 39753d7784
51 files changed
+4986 -554

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
import { app } from 'electron'
import fs from 'node:fs'
import path from 'node:path'
import ffmpegStaticPath from 'ffmpeg-static'
export function resolveBundledFfmpegPath(): string {
if (process.platform === 'darwin' && app.isPackaged) {
const editionFfmpeg = path.join(process.resourcesPath, 'resources', 'ffmpeg', 'ffmpeg')
if (fs.existsSync(editionFfmpeg)) return editionFfmpeg
}
return String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked').trim()
}
+2 -4
View File
@@ -5,7 +5,7 @@ import os from 'os'
import { app } from 'electron'
import { execFile } from 'child_process'
import { Worker } from 'worker_threads'
import ffmpegStaticPath from 'ffmpeg-static'
import { resolveBundledFfmpegPath } from './ffmpeg-path'
import type { ImageDecoderSource, ImageDecoderStatus } from '../shared/image-decryption'
import { imageFileQuality, imageQualityRank } from '../shared/image-quality'
import { loadSettings } from './services/settings-store'
@@ -78,9 +78,7 @@ function getFfmpegCandidates(selectedPath = loadSettings().ffmpegPath): FfmpegCa
const selected = String(selectedPath || '').trim()
const environment = String(process.env['FFMPEG_BIN'] || '').trim()
const executable = process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'
const staticExecutable = String(ffmpegStaticPath || '')
.replace('app.asar', 'app.asar.unpacked')
.trim()
const staticExecutable = resolveBundledFfmpegPath()
const candidates: FfmpegCandidate[] = [
...(selected ? [{ executable: selected, source: 'selected' as const }] : []),
...(environment ? [{ executable: environment, source: 'environment' as const }] : []),
+269 -22
View File
@@ -1,4 +1,5 @@
import path from 'node:path'
import { isWcdbDebugEnabled } from './wcdb-debug'
import {
isLegacyMigrationHelper,
isUserDataIsolated,
@@ -152,6 +153,18 @@ import {
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 {
isDefinitelyBlocked,
isEntitlementBlocked,
resolveExitNoticeGate,
resolveSwitchPresentation
} from './services/exit-notice-gate'
import { GroupStatsService } from './services/group-stats-service'
import {
configureWechatLocalExitNotice,
@@ -225,6 +238,126 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
}
}
/** 能力判定需要知道「微信库连没连」,但不需要知道发送是否就绪。 */
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 —— 把退群监控选中的群缺失的规则补齐,不动开关值。
*
@@ -248,14 +381,14 @@ async function reconcileMsgInsertRulesOnStart(): Promise<void> {
if (!scope || !client) return
let enabled = false
let shardSignature = ''
try {
const shards = client.listMessageShardPaths()
const shardSignature = shards.map((item) => path.basename(item)).join(',')
shardSignature = shards.map((item) => path.basename(item)).join(',')
if (lastMsgInsertReconciledShards && lastMsgInsertReconciledShards !== shardSignature) {
/* 微信新建了 message_N.db(或清理了旧的)—— 分片集合变了就重新补齐。 */
console.log('[MsgInsert] 检测到消息分片变化,重新补齐规则')
}
lastMsgInsertReconciledShards = shardSignature
for (const shardPath of shards) {
const read = client.getMsgInsertSwitches(shardPath)
if (read.success && read.switches?.recall_notice) {
@@ -268,15 +401,23 @@ async function reconcileMsgInsertRulesOnStart(): Promise<void> {
return
}
if (!enabled) return
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
/*
* 授权前置:没有有效授权时不许 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
}
/**
* 防撤回的作用面 = 全部可定位会话(群聊 + 私聊)。
*
* native 侧有「定义漂移就 DROP + 重建」的能力,但只有显式复核时才会跑;
* 规则定义变了不自动铺开,用户就得手动关-开一次开关。
*/
function recallRoomsForReconcile(scope: MsgInsertScopeInput): string[] {
return resolveTargetRooms(scope, 'recall_notice').rooms
}
@@ -285,6 +426,15 @@ async function reconcileMsgInsertRulesNow(extraRooms: string[] = []): Promise<bo
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,
@@ -345,8 +495,21 @@ async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
* 删除必须借 helper 的可写连接:本进程对分片只有只读连接,自己发 DROP 一定失败。
* helper 那条链路会在装规则时顺手清掉残留,顺带把新规则铺到所有会话。
*/
/*
* 清理只能借 helper 的 ensure-rules 完成(没有独立的 drop-only 动作),
* 而 ensure-rules 会顺手把新规则铺到所有会话 —— 那属于写库动作。
* 所以没有授权时只保留残留、不执行清理,绝不拿「清理」当借口绕开门禁。
*/
const scope = resolveMsgInsertScopeInput()
const applied = scope ? await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope)) : false
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()
@@ -368,7 +531,10 @@ async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
})
} catch (error) {
/* 清理失败绝不能挡住启动 —— 它只是收尾工作。 */
console.warn('[RecallResidue] 清理失败:', error)
console.warn(
'[RecallResidue] 清理失败:',
isWcdbDebugEnabled() ? error : error instanceof Error ? error.message : String(error)
)
appLogger.write({
level: 'warn',
scope: 'recall-residue',
@@ -1208,6 +1374,47 @@ app.whenReady().then(async () => {
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',
@@ -1354,15 +1561,16 @@ app.whenReady().then(async () => {
/**
* 正式 MessageListener(Observation Mode 接入)。
*
* 本轮**只监听、回读、规范化、去重、统计**,不触发任何业务:
* 只监听、回读、规范化、去重、统计,不触发任何业务:
* 不匹配关键词、不判断 @我、不出日报、不回复、不调 AI / Agent、不发送。
* 下一层的 Trigger 由后续任务接入。
* 业务响应由上层消费者自行订阅,不在监听层实现。
*/
const messageListener = new MessageListenerService(wcdb4Client)
/**
* Automation v1(@我生成日报)。
*
* `isListening` 要等下面 `startMonitor` 有结果才知道,所以先用闭包变量占位。
* `isListening` 反映 `startMonitor` 的实际结果,因此通过闭包读取,
* 而不是在初始化时传入快照。
*/
let automationListening = false
initAutomationService(wcdb4Client, { isListening: () => automationListening })
@@ -1518,8 +1726,12 @@ app.whenReady().then(async () => {
)
return { success: true, monitoring }
} catch (error) {
console.error('Failed to init DB:', 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,
@@ -2200,10 +2412,11 @@ app.whenReady().then(async () => {
* 状态里同时给出 desiredEnabled / effectiveEnabled:开关值写成功不等于功能
* 真的生效(规则可能没装齐),渲染层不能只看前者。
*/
ipcMain.handle('automation:getMsgInsertSwitches', () => {
ipcMain.handle('automation:getMsgInsertSwitches', async () => {
/* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。 */
return buildMsgInsertSwitchesSnapshot()
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。
* 授权判定只走本机 HTTP + 文件 stat,同样不碰数据库。 */
return attachCapability(buildMsgInsertSwitchesSnapshot())
})
/**
* 微信消息插入开关 —— **运行期刷新**(允许在分片集合变化时补一次规则)。
@@ -2223,16 +2436,28 @@ app.whenReady().then(async () => {
.listMessageShardPaths()
.map((item) => path.basename(item))
.join(',')
/*
* 分片变了只在「确实有授权」时补齐。
* 指纹必须**补齐成功之后**才更新:否则无授权跳过一次,等用户激活回来
* 分片没变,就再也不会补了(这正是原实现的坑)。
*/
if (signature !== lastMsgInsertReconciledShards) {
lastMsgInsertReconciledShards = signature
console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则')
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
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 buildMsgInsertSwitchesSnapshot()
return attachCapability(buildMsgInsertSwitchesSnapshot())
})
/**
* 微信消息插入开关 —— 写入。
@@ -2252,6 +2477,19 @@ app.whenReady().then(async () => {
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 规则。所以它的开关只是本地设置:
@@ -3213,6 +3451,15 @@ app.whenReady().then(async () => {
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:refreshMacLicense', () =>
macWechatRuntimeManager.refreshMacLicense()
)
ipcMain.handle('wechat-personal:checkStatus', (_, port?: string) =>
personalWechatSendService.checkWindowsStatus(port)
)
+90
View File
@@ -0,0 +1,90 @@
import fs from 'node:fs'
import path from 'node:path'
import { app } from 'electron'
import { findResource } from './resource-paths'
export type NativeRuntimeProfile = 'public' | 'native'
const BUILD_MARKER = 'tracememo-build.json'
const RUNTIME_RELATIVE = 'runtime/darwin-arm64'
let cachedProfile: NativeRuntimeProfile | null = null
let cachedMarkerRead = false
function getNativeRuntimeProfile(): NativeRuntimeProfile {
const envProfile = !app.isPackaged ? process.env.TRACEMEMO_RUNTIME_PROFILE : undefined
if (envProfile === 'public' || envProfile === 'native') return envProfile
if (cachedMarkerRead && cachedProfile) return cachedProfile
cachedMarkerRead = true
const marker = findResource(BUILD_MARKER)
if (marker) {
try {
const parsed = JSON.parse(fs.readFileSync(marker, 'utf8')) as { profile?: unknown }
if (parsed.profile === 'public' || parsed.profile === 'native') {
cachedProfile = app.isPackaged ? parsed.profile : 'native'
return cachedProfile
}
} catch {
// Packaged builds fail closed below when the marker cannot be read.
}
}
cachedProfile = app.isPackaged ? 'public' : 'native'
return cachedProfile
}
export function hasMacNativeBundle(): boolean {
return process.platform === 'darwin' && getNativeRuntimeProfile() === 'native'
}
export function isMacNativeRuntimeUnavailable(): boolean {
return process.platform === 'darwin' && !hasMacNativeBundle()
}
export function resolveWcdbLibrary(): string | null {
if (process.platform !== 'darwin') return null
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
return findResource(`wcdb/macos/${arch}/libwcdb_api.dylib`)
}
export function resolveWcdbDependency(): string | null {
const library = resolveWcdbLibrary()
if (!library) return null
const dependency = path.join(path.dirname(library), 'libWCDB.dylib')
return fs.existsSync(dependency) ? dependency : null
}
export function resolveWcdbConfigHelper(): string | null {
if (isMacNativeRuntimeUnavailable()) return null
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
return findResource(`wcdb/macos/${arch}/tm-wcdb-config-helper`)
}
export function resolveWechatRuntimeDirectory(): string | null {
if (!hasMacNativeBundle()) return null
const manifest =
findResource(`${RUNTIME_RELATIVE}/runtime-manifest.json`) ||
(!app.isPackaged ? findResource('runtime/darwin-arm64/runtime-manifest.json') : null)
return manifest ? path.dirname(manifest) : null
}
export function resolveWechatHost(): string | null {
const directory = resolveWechatRuntimeDirectory()
if (!directory) return null
const candidate = path.join(directory, 'tm-wechat-host')
return fs.existsSync(candidate) ? candidate : null
}
export function resolveWechatDylib(): string | null {
const directory = resolveWechatRuntimeDirectory()
if (!directory) return null
const candidate = path.join(directory, 'libtmwechat.dylib')
return fs.existsSync(candidate) ? candidate : null
}
export function resolveWechatRuntimeManifest(): string | null {
const directory = resolveWechatRuntimeDirectory()
if (!directory) return null
const candidate = path.join(directory, 'runtime-manifest.json')
return fs.existsSync(candidate) ? candidate : null
}
+4
View File
@@ -7,6 +7,10 @@ function unique(values: string[]): string[] {
}
export function getResourceRoots(): string[] {
if (app.isPackaged && process.platform === 'darwin') {
const packagedResources = join(process.resourcesPath || '', 'resources')
return existsSync(packagedResources) ? [packagedResources] : []
}
const appPath = app.getAppPath()
const appPathDir = dirname(appPath)
const execDir = dirname(process.execPath)
+11 -21
View File
@@ -15,6 +15,7 @@ import {
WINDOWS_VC_RUNTIME_ERROR_MESSAGE
} from '../../shared/windows-runtime'
import { hasPermissionDeniedText, isPermissionDeniedError } from './path-access-probe'
import { getNativeErrorCode } from '../wcdb4-client'
import { mergeRecallArchiveMessages, recordRecallArchiveMessages } from './recall-archive-service'
import type { ExportImageQuality } from '../../shared/image-quality'
import type { ImageMessageCountProbe } from '../../shared/image-text-index'
@@ -1297,27 +1298,7 @@ export function databaseKeyErrorMessage(
return DATABASE_KEY_ERROR_MESSAGES[code]
}
/**
* 把底层抛出物归类成机器可读的错误码。
*
* 顺序是有约束的,别随意调整:
* 1. VC runtime —— Windows 专属,特征明确,先摘掉;
* 2. 账号不匹配 —— `-1005` 是 native 给出的确定信号;
* 3. **权限不足** —— 必须排在"文件缺失"之前。原因见下;
* 4. 文件缺失 / 根目录不可用 / 打开失败 —— 按文本兜底。
*
* 为什么权限要排在缺失之前:底层探测用的是 `fs.existsSync()`,它对 EPERM 也返回
* `false`,所以走到这里时错误文本常常已经变成「未找到 … session.db」这种**缺失**措辞。
* 只按文本判断就会永远归到 `DATABASE_FILE_MISSING`,把用户指向错误的方向。
* 因此 errno 优先(调用方在探测层用 `statSync` 补问过),文本特征只作兜底。
*
* 判断文本时逐个列举显式模式,不用 `includes('permission')` 这类过宽匹配 ——
* 那会把 "permission config not found" 之类无关错误也算进来。
*
* 导出是为了让分类规则本身可被回归测试钉住:这条链路上任何一处顺序调整都会让
* 权限问题重新落回"文件缺失",而那正是本函数要防的回归。
* `platform` 可注入,否则 Windows 专属分支在测试里无法触发(`process.platform` 是只读的)。
*/
// 顺序有约束:原生码先于文本匹配,权限先于文件缺失(existsSync 对 EPERM 返回 false)。
export function mapConnectionError(
error: unknown,
platform: NodeJS.Platform = process.platform
@@ -1325,6 +1306,15 @@ export function mapConnectionError(
const detail = error instanceof Error ? error.message : String(error)
const normalized = detail.toLowerCase()
if (isWindowsVcRuntimeMissingError(detail, platform)) return 'VC_RUNTIME_MISSING'
const nativeCode = getNativeErrorCode(error)
if (nativeCode !== null) {
if (nativeCode === -2003) return 'DATABASE_OPEN_FAILED'
if (nativeCode === -3003 || nativeCode === -3004) return 'ACCOUNT_MISMATCH'
if (nativeCode === -3006) return 'DATABASE_OPEN_FAILED'
if (nativeCode === -3005) return 'UNKNOWN_VALIDATION_ERROR'
}
if (normalized.includes('-1005') || normalized.includes('不匹配')) return 'ACCOUNT_MISMATCH'
if (isPermissionDeniedError(error) || hasPermissionDeniedText(normalized)) {
return 'DATABASE_PERMISSION_DENIED'
+78
View File
@@ -0,0 +1,78 @@
import type { MessageInsertCapability } from './msg-insert-capability-service'
/** 退群内提示开关的判定:授权或组件不成立时必须显示关闭;库没连只压 effective。 */
export interface ExitNoticeGateDecision {
/** 界面开关值 */
desiredEnabled: boolean
/** 是否真的在生效 */
effectiveEnabled: boolean
/** 只在明确否定时落盘;探测失败不落盘,避免误关正常用户的开关。 */
persistDisable: boolean
}
/** 授权维度是否成立(不含微信库连接)。 */
export function isEntitlementBlocked(capability: MessageInsertCapability): boolean {
return capability.entitlementState !== 'valid' || capability.nativeComponentState !== 'ready'
}
/** 明确否定(不含 unavailable:那是「不知道」,不是「不行」)。 */
export function isDefinitelyBlocked(capability: MessageInsertCapability): boolean {
return (
capability.entitlementState === 'invalid' ||
capability.entitlementState === 'unsupported' ||
capability.nativeComponentState === 'missing' ||
capability.nativeComponentState === 'invalid' ||
capability.nativeComponentState === 'incompatible'
)
}
export function resolveExitNoticeGate(
capability: MessageInsertCapability,
runtimeEnabled: boolean
): ExitNoticeGateDecision {
if (isEntitlementBlocked(capability)) {
return {
desiredEnabled: false,
effectiveEnabled: false,
persistDisable: isDefinitelyBlocked(capability) && runtimeEnabled
}
}
/*
* 授权与组件都就绪,只是微信库没连:用户意愿保留(连上自动恢复),
* 但此刻没有真的在跑。
*/
if (runtimeEnabled && !capability.canEnable) {
return { desiredEnabled: true, effectiveEnabled: false, persistDisable: false }
}
return {
desiredEnabled: runtimeEnabled,
effectiveEnabled: runtimeEnabled && capability.canEnable,
persistDisable: false
}
}
/** 界面呈现结果(只有开关的两个布尔值,不含落盘决策)。 */
export interface SwitchPresentation {
desiredEnabled: boolean
effectiveEnabled: boolean
}
/** 两个开关共用这套呈现判定:授权不成立时都显示关闭,但关闭操作永远放行。 */
export function resolveSwitchPresentation(
kind: 'recall_notice' | 'group_exit_notice',
currentDesired: boolean,
capability: MessageInsertCapability
): SwitchPresentation {
if (kind === 'group_exit_notice') {
const gate = resolveExitNoticeGate(capability, currentDesired)
return { desiredEnabled: gate.desiredEnabled, effectiveEnabled: gate.effectiveEnabled }
}
if (isEntitlementBlocked(capability)) {
return { desiredEnabled: false, effectiveEnabled: false }
}
return {
desiredEnabled: currentDesired,
effectiveEnabled: currentDesired && capability.canEnable
}
}
@@ -0,0 +1,133 @@
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
/**
* 发送能力组件定位:读 current.json 找目录,按 manifest 校验 size/sha256,不过当没装。
* 组件放用户目录,避免被自动更新清掉。
*/
export interface ComponentLocation {
dir: string
helperPath: string
version: string
/** 打包时工作区是否 dirty(内部调试构建标识,正式发布不应出现) */
dirty: boolean
}
interface ManifestFile {
path?: unknown
size?: unknown
sha256?: unknown
}
const HELPER_NAME = 'tm-wcdb-config-helper.exe'
const verifyCache = new Map<string, { stamp: string; ok: boolean; dirty: boolean }>()
function sha256File(filePath: string): string | null {
try {
const hash = crypto.createHash('sha256')
hash.update(fs.readFileSync(filePath))
return hash.digest('hex')
} catch {
return null
}
}
function verifyManifest(dir: string): { ok: boolean; dirty: boolean } {
const manifestPath = path.join(dir, 'manifest.json')
let stat: fs.Stats
try {
stat = fs.statSync(manifestPath)
} catch {
return { ok: false, dirty: false }
}
const stamp = `${dir}|${stat.mtimeMs}|${stat.size}`
const cached = verifyCache.get(dir)
if (cached && cached.stamp === stamp) return { ok: cached.ok, dirty: cached.dirty }
let ok = false
let dirty = false
try {
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as {
worktreeDirty?: unknown
files?: ManifestFile[]
}
dirty = manifest.worktreeDirty === true
const files = Array.isArray(manifest.files) ? manifest.files : []
if (files.length === 0) {
ok = false
} else {
ok = files.every((entry) => {
const name = typeof entry.path === 'string' ? entry.path : ''
if (!name) return false
const target = path.join(dir, name)
let size = -1
try {
size = fs.statSync(target).size
} catch {
return false
}
if (typeof entry.size === 'number' && size !== entry.size) return false
if (typeof entry.sha256 === 'string' && entry.sha256.length === 64) {
return sha256File(target) === entry.sha256
}
return true
})
}
} catch {
ok = false
}
verifyCache.set(dir, { stamp, ok, dirty })
return { ok, dirty }
}
/**
* 返回发送能力组件位置;不存在、校验失败、非 Windows 一律返回 null。
* 调用方拿到 null 时应当把它当作「组件没装」,而不是「没授权」。
*/
export function resolveExternalComponent(
env: NodeJS.ProcessEnv = process.env,
platform: NodeJS.Platform = process.platform
): ComponentLocation | null {
if (platform !== 'win32') return null
const localAppData = env.LOCALAPPDATA
if (!localAppData) return null
const root = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64')
const pointerPath = path.join(root, 'current.json')
if (!fs.existsSync(pointerPath)) return null
let version = ''
let dir = ''
try {
const pointer = JSON.parse(fs.readFileSync(pointerPath, 'utf8')) as {
version?: unknown
dir?: unknown
}
version = typeof pointer.version === 'string' ? pointer.version : ''
dir = typeof pointer.dir === 'string' ? pointer.dir : ''
} catch {
return null
}
if (!version || !dir) return null
try {
if (!fs.statSync(dir).isDirectory()) return null
} catch {
return null
}
const helperPath = path.join(dir, HELPER_NAME)
if (!fs.existsSync(helperPath)) return null
const verified = verifyManifest(dir)
if (!verified.ok) return null
return { dir, helperPath, version, dirty: verified.dirty }
}
/** 测试用:清掉校验缓存 */
export function resetComponentCache(): void {
verifyCache.clear()
}
+287 -28
View File
@@ -1,20 +1,30 @@
import { spawn, type ChildProcess } from 'child_process'
import { chmodSync, existsSync } from 'fs'
import { get } from 'http'
import { get, request as httpRequest } from 'http'
import { join } from 'path'
import { app } from 'electron'
import { appLogger } from '../app-logger'
import { isPackagedRuntime } from '../runtime-mode'
import {
isMacNativeRuntimeUnavailable,
resolveWechatRuntimeDirectory
} from '../native-runtime-paths'
import type { MacLicenseStatus } from '../../shared/personal-wechat-mac-license'
import {
offlineMacLicenseStatus,
parseMacLicenseStatus
} from '../../shared/personal-wechat-mac-license'
import type {
MacWechatBindResult,
MacWechatBindingStatus,
MacWechatRuntimeManifest,
MacWechatRuntimeLifecycle,
MacWechatRuntimeSnapshot
MacWechatRuntimeSnapshot,
MacWechatSendRuntimeAvailabilityResult
} from '../../shared/personal-wechat-mac-runtime'
import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat'
import { hasValidWechatLicense } from '../../shared/personal-wechat-mac-send-action'
import {
bindingMatchesRuntimeManifest,
readMacWechatRuntimeManifest
@@ -43,6 +53,10 @@ const HOST = '127.0.0.1'
const START_TIMEOUT_MS = 15_000
const REQUEST_TIMEOUT_MS = 30_000
const CRASH_RESTART_DELAY_MS = 1_500
/* /license/status is a local cache read; keep it snappy. /license/refresh runs a
* real challenge->sign->check cycle inside the host, which is bounded at 15s. */
const LICENSE_STATUS_TIMEOUT_MS = 8_000
const LICENSE_REFRESH_TIMEOUT_MS = 20_000
interface MacWechatSenderStatusInput {
snapshot: MacWechatRuntimeSnapshot
@@ -66,6 +80,16 @@ export function deriveMacWechatSenderStatus({
}: MacWechatSenderStatusInput): PersonalWechatSenderStatus {
const identityMatches = binding !== null && bindingMatchesRuntimeManifest(binding, manifest)
const stale = binding?.bindingState === 'stale'
const versionCapabilities = binding?.wechatVersion
? manifest.capabilitiesByVersion?.[binding.wechatVersion]
: undefined
const nativeMechanism = versionCapabilities?.textMechanism === 'native-msg-object'
const nativeBindingReady =
identityMatches &&
nativeMechanism &&
binding?.runtimeState === 'ready' &&
binding.sessionAttached &&
binding.scriptLoaded
let state: PersonalWechatSenderStatus['state'] = 'stopped'
let message = '正在初始化微信发送能力'
@@ -78,12 +102,17 @@ export function deriveMacWechatSenderStatus({
} else if (binding && !binding.wechatRunning) {
state = 'wechat_not_running'
message = '微信未运行'
} else if (binding?.bindingState === 'ready') {
} else if (binding?.runtimeState === 'unsupported_version') {
state = 'error'
message = binding.wechatVersion
? `当前微信版本是 ${binding.wechatVersion},不在支持列表`
: '当前微信版本不在支持列表'
} else if (binding?.bindingState === 'ready' || nativeBindingReady) {
state = 'online'
message = '个人微信已准备好发送日报'
} else if (binding?.bindingState === 'bound' || binding?.bindingState === 'binding') {
state = 'hook_not_ready'
message = '已绑定,等待捕获微信发送上下文'
message = nativeMechanism ? '已绑定,等待原生发送 hook 就绪' : '已绑定,等待捕获微信发送上下文'
} else if (stale) {
state = 'stopped'
message = '检测到微信已重启,请重新绑定'
@@ -96,13 +125,17 @@ export function deriveMacWechatSenderStatus({
}
const runtimeCapabilities = new Set(manifest.capabilities)
const bindingReady = identityMatches && state === 'online' && binding?.sendContextReady === true
const canSendText =
bindingReady && runtimeCapabilities.has('text') && binding?.canSendText === true
const canSendImage =
bindingReady && runtimeCapabilities.has('image') && binding?.canSendImage === true
const canSendVoice =
bindingReady && runtimeCapabilities.has('voice') && binding?.canSendVoice === true
const supportsCapability = (name: 'text' | 'image' | 'voice'): boolean => {
if (manifest.capabilitiesByVersion) return versionCapabilities?.[name] === 'verified'
return runtimeCapabilities.has(name)
}
const bindingReady =
identityMatches &&
state === 'online' &&
(binding?.sendContextReady === true || nativeBindingReady)
const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -135,6 +168,25 @@ export function deriveMacWechatSenderStatus({
}
}
/**
* 在线刷新失败时的返回策略:
* 缓存里还有可用授权就保留它(只把失败写进 message),否则明确报告网络故障。
* 单独抽出来是因为这两条分支都必须可测 —— 把网络故障错报成「已撤销」会让
* 用户去找客服,错报成「有效」又会掩盖真实故障。
*/
export function resolveLicenseRefreshFailure(
snapshot: MacLicenseStatus | null,
diagnostic: string
): MacLicenseStatus {
if (snapshot?.authorized) {
return {
...snapshot,
message: `本次刷新失败:${diagnostic}(仍使用本地缓存授权)`
}
}
return offlineMacLicenseStatus('server_unavailable', diagnostic)
}
class MacWechatRuntimeManager {
private child: ChildProcess | null = null
private lifecycle: MacWechatRuntimeLifecycle = 'stopped'
@@ -158,43 +210,74 @@ class MacWechatRuntimeManager {
wechatRestartRequired: this.wechatRestartRequired,
endpoint: `http://${HOST}:${PORT}`,
port: PORT,
runtimeDir: this.resolveRuntimeDir(),
manifest: this.manifest ?? undefined,
runtimeDir: this.resolveRuntimeDir() ?? undefined,
error: this.lastError ?? undefined,
binding: this.lastBinding ?? undefined
}
}
private resolveRuntimeDir(): string {
const base = isPackagedRuntime() ? process.resourcesPath : app.getAppPath()
return join(base, 'resources', 'runtime', 'darwin-arm64')
private resolveRuntimeDir(): string | null {
if (isMacNativeRuntimeUnavailable()) return null
const resolved = resolveWechatRuntimeDirectory()
if (resolved) return resolved
if (app.isPackaged) return null
return join(app.getAppPath(), 'resources', 'runtime', 'darwin-arm64')
}
private resolveHostPath(): string {
return join(this.resolveRuntimeDir(), 'tm-wechat-host')
return join(this.resolveRuntimeDir() || '', 'tm-wechat-host')
}
/** Runtime binaries present and executable? Cheap check for the settings UI. */
isRuntimePresent(): boolean {
if (isMacNativeRuntimeUnavailable()) return false
try {
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) return false
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
return true
} catch {
return false
}
}
getSendRuntimeAvailability(): MacWechatSendRuntimeAvailabilityResult {
if (isMacNativeRuntimeUnavailable()) {
return { state: 'unavailable', message: '当前版本没有微信发送能力' }
}
try {
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('发送 Runtime 目录缺失')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
return { state: 'available', message: '微信发送组件可用' }
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
return { state: 'component_error', message: `发送组件缺失或异常:${detail}` }
}
}
/**
* Start the host if it is not already running. Deliberately lazy: the host
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
* online" and "WeChat bound" stay two independent states.
*/
async ensureStarted(): Promise<MacWechatRuntimeSnapshot> {
if (isMacNativeRuntimeUnavailable()) {
this.manifest = null
this.lifecycle = 'stopped'
this.lastError = '当前环境不包含微信发送能力'
return this.getSnapshot()
}
if (this.lifecycle === 'starting') {
return this.getSnapshot()
}
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) {
this.lifecycle = 'stopped'
this.lastError = '暂无发送能力'
return this.getSnapshot()
}
try {
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
appLogger.write({
@@ -385,11 +468,28 @@ class MacWechatRuntimeManager {
private request(
method: string,
path: string,
timeoutMs = REQUEST_TIMEOUT_MS
timeoutMs = REQUEST_TIMEOUT_MS,
body?: string
): Promise<{ status: number | null; body: string }> {
return new Promise((resolve) => {
const request = get(
{ host: HOST, port: PORT, path, method, timeout: timeoutMs },
const payload = body !== undefined ? Buffer.from(body, 'utf8') : undefined
// GET keeps using `get()` (auto-end); POST goes through `request()` so we
// can attach a JSON body. Both funnel into the same resolve contract.
const transport = method === 'GET' || method === 'HEAD' ? get : httpRequest
const req = transport(
{
host: HOST,
port: PORT,
path,
method,
timeout: timeoutMs,
headers: payload
? {
'Content-Type': 'application/json',
'Content-Length': payload.length
}
: undefined
},
(response) => {
let body = ''
response.on('data', (chunk) => {
@@ -400,14 +500,15 @@ class MacWechatRuntimeManager {
})
}
)
request.on('timeout', () => {
request.destroy()
req.on('timeout', () => {
req.destroy()
resolve({ status: null, body: '' })
})
request.on('error', () => {
req.on('error', () => {
resolve({ status: null, body: '' })
})
request.end()
if (payload) req.write(payload)
req.end()
})
}
@@ -450,7 +551,11 @@ class MacWechatRuntimeManager {
const { status, body } = await this.request('GET', '/bindingStatus')
if (status !== 200) return null
try {
this.lastBinding = JSON.parse(body) as MacWechatBindingStatus
const binding = JSON.parse(body) as MacWechatBindingStatus & {
supportedVersions?: string
}
delete binding.supportedVersions
this.lastBinding = binding
/*
* A 20s bind timeout is NOT proof of the orphan-agent wall: in the
* stale-rebind path the host worker waits up to 45s for the old session
@@ -485,6 +590,97 @@ class MacWechatRuntimeManager {
return this.lastBinding
}
// GET reads the local snapshot; POST runs one real online check.
// Neither touches the WeChat binding.
/** Local snapshot. Never attaches to WeChat, never forces a network refresh.
* 404 means the host predates these endpoints — not "unlicensed". */
async getMacLicenseStatus(): Promise<MacLicenseStatus> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
}
if (availability.state !== 'available') {
return offlineMacLicenseStatus('runtime_missing', availability.message)
}
if (this.lifecycle === 'stopped') await this.ensureStarted()
const { status, body } = await this.request('GET', '/license/status', LICENSE_STATUS_TIMEOUT_MS)
if (status === null) {
return offlineMacLicenseStatus('runtime_missing', 'Mac 发送组件未运行,请先启动发送组件')
}
if (status === 404) {
return offlineMacLicenseStatus(
'unsupported',
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
)
}
if (status !== 200) {
return offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`)
}
try {
return parseMacLicenseStatus(JSON.parse(body))
} catch {
return offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析')
}
}
/**
* One real online check; re-entrant calls return the current snapshot instead
* of minting a duplicate challenge. Network failure maps to server_unavailable,
* never to revoked.
*/
async refreshMacLicense(): Promise<MacLicenseStatus> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
}
if (availability.state !== 'available') {
return offlineMacLicenseStatus('runtime_missing', availability.message)
}
if (this.lifecycle === 'stopped') await this.ensureStarted()
if (this.licenseRefreshInFlight) {
// A refresh is already running; answer from the local snapshot so the
// button click is a no-op instead of stacking a second online check.
return this.getMacLicenseStatus()
}
this.licenseRefreshInFlight = true
try {
const { status, body } = await this.request(
'POST',
'/license/refresh',
LICENSE_REFRESH_TIMEOUT_MS,
'{}'
)
if (status === null) {
const snapshot = await this.getMacLicenseStatus().catch(() => null)
return resolveLicenseRefreshFailure(snapshot, '无法连接授权服务器,请检查网络后重试')
}
if (status === 404) {
return offlineMacLicenseStatus(
'unsupported',
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
)
}
let envelope: Record<string, unknown>
try {
envelope = JSON.parse(body) as Record<string, unknown>
} catch {
return offlineMacLicenseStatus('runtime_missing', '授权刷新响应无法解析')
}
// The host wraps the result: { ok, code, message, status: MacLicenseStatus }
const nested = envelope.status ?? envelope
const parsed = parseMacLicenseStatus(nested)
if (typeof envelope.errorCode === 'number' && parsed.errorCode == null) {
parsed.errorCode = envelope.errorCode
}
return parsed
} finally {
this.licenseRefreshInFlight = false
}
}
private licenseRefreshInFlight = false
/*
* Build the legacy PersonalWechatSenderStatus contract from the live mac
* runtime state. Lives here (not in the capability service) so BOTH the
@@ -492,6 +688,32 @@ class MacWechatRuntimeManager {
* circular import.
*/
async buildSenderStatus(): Promise<PersonalWechatSenderStatus> {
if (isMacNativeRuntimeUnavailable()) {
const message = '当前环境不包含微信发送能力'
return {
state: 'runtime_missing',
platform: 'darwin',
arch: process.arch,
sipDisabled: true,
wechatRunning: false,
endpoint: `http://${HOST}:${PORT}`,
endpointReady: false,
runtimeReady: false,
attachReady: false,
baseAddressReady: false,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false,
message,
error: message
}
}
/*
* Lazy-start the host from status reads.
*
@@ -509,7 +731,9 @@ class MacWechatRuntimeManager {
/* Self-heal the status card too: if WeChat was restarted, drop the stale
* restartRequired before it is read into the UI as an error. */
try {
this.manifest = readMacWechatRuntimeManifest(this.resolveRuntimeDir())
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('runtime missing')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
appLogger.write({
@@ -580,6 +804,18 @@ class MacWechatRuntimeManager {
* live WeChat pid again returns attached=false and never double-attaches.
*/
async bind(): Promise<MacWechatBindResult> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return {
ok: false,
attached: false,
state: 'runtime_offline',
message: '当前环境不包含微信发送能力'
}
}
if (availability.state !== 'available') {
return { ok: false, attached: false, state: 'runtime_offline', message: availability.message }
}
if (this.lifecycle !== 'online') {
const snapshot = await this.ensureStarted()
if (snapshot.lifecycle !== 'online') {
@@ -606,6 +842,28 @@ class MacWechatRuntimeManager {
}
}
const license = await this.getMacLicenseStatus()
const licenseAllowed = hasValidWechatLicense(license)
if (!licenseAllowed) {
const tokenExpiresAt = license.tokenExpiresAt
? Date.parse(license.tokenExpiresAt)
: Number.NaN
const message =
license.state === 'revoked'
? 'LICENSE_REVOKED: 微信发送授权已撤销'
: license.state === 'expired' ||
(Number.isFinite(tokenExpiresAt) && tokenExpiresAt <= Date.now())
? 'LICENSE_EXPIRED: 微信发送授权已过期'
: license.state === 'device_mismatch'
? 'LICENSE_DEVICE_MISMATCH: 授权与当前设备不匹配'
: license.state === 'identity_error'
? 'LICENSE_IDENTITY_ERROR: 设备身份异常'
: license.authorized && !license.features.includes('wechat')
? 'LICENSE_FEATURE_DENIED: 未开通微信发送'
: 'LICENSE_REQUIRED: 需要有效的微信发送授权'
return { ok: false, attached: false, state: 'host_error', message }
}
const { status, body } = await this.request('POST', '/bindWeChat')
await this.refreshBinding().catch(() => null)
@@ -662,6 +920,7 @@ class MacWechatRuntimeManager {
* leave its injected agent inside WeChat and make the next attach hang.
*/
async shutdown(): Promise<void> {
if (isMacNativeRuntimeUnavailable()) return
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
@@ -0,0 +1,393 @@
import fs from 'node:fs'
import http from 'node:http'
import type { CapabilityReasonCode } from '../../shared/msg-insert-switch'
import { hasMacNativeBundle, isMacNativeRuntimeUnavailable } from '../native-runtime-paths'
import { resolveHelperPath } from './msg-insert-switch-service'
/**
* 发送能力的唯一判定入口:授权、原生组件、库连接分开算,任一项不确定都不许开启。
* 4290 的 JSON 本机可伪造,这里只是应用层门禁,真正的校验在原生 helper。
*/
export type { CapabilityReasonCode }
export type EntitlementState = 'valid' | 'invalid' | 'pending' | 'unavailable' | 'unsupported'
export type NativeComponentState = 'ready' | 'missing' | 'invalid' | 'incompatible'
export interface MessageInsertCapability {
/** 授权 */
entitlementState: EntitlementState
/** 发送能力组件 */
nativeComponentState: NativeComponentState
/** 微信数据库是否已连接(不代表发送能力) */
databaseReady: boolean
/** 是否允许「开启」发送能力 */
canEnable: boolean
/** 关闭永远不因授权被拒,否则用户没法把自己开过的功能关掉。 */
canDisable: boolean
reasonCode: CapabilityReasonCode
/** 给人看的一句话 */
message: string
/** Hook 原始状态名,仅用于诊断展示 */
licenseStatus?: string
/** 判定时间戳 */
checkedAt: number
}
export interface CapabilityInput {
/** 微信库是否已连接(由主进程按 chat 状态传入) */
databaseReady: boolean
}
export interface LicenseProbeResult {
ok: boolean
status?: string
error?: string
}
export interface CapabilityDeps {
platform: NodeJS.Platform
/** mac:是否 native 包 */
hasMacNativeBundle: () => boolean
/** mac:是否 public 包(拿不到 native 运行时) */
isMacRuntimeUnavailable: () => boolean
/** 发送能力组件路径;null = 缺失 */
resolveNativeComponent: () => string | null
/** 授权探测(Windows) */
probeLicense: (timeoutMs: number) => Promise<LicenseProbeResult>
/** 组件文件探测(便于测试注入) */
statFile?: (filePath: string) => { size: number } | null
now?: () => number
}
const DEFAULT_TTL_MS = 30_000
const PROBE_TIMEOUT_MS = 1_200
/** Hook 的 LicenseStatus → 授权状态。只有明确可接受的结果才算 valid。 */
export function mapLicenseStatus(status: string | undefined): {
entitlement: EntitlementState
reasonCode: CapabilityReasonCode
message: string
} {
switch (status) {
case 'LICENSE_OK':
return { entitlement: 'valid', reasonCode: 'CAPABILITY_READY', message: '授权有效' }
case 'LICENSE_CHECKING':
return {
entitlement: 'pending',
reasonCode: 'LICENSE_PENDING',
message: '授权正在验证,请稍候'
}
case 'LICENSE_EXPIRED':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_EXPIRED',
message: '授权已过期,请重新激活后再开启'
}
case 'LICENSE_MACHINE_MISMATCH':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_MACHINE_MISMATCH',
message: '这份授权不属于本机'
}
case 'LICENSE_REVOKED':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_REVOKED',
message: '授权已被吊销'
}
case 'LICENSE_INVALID':
case 'LICENSE_TAMPERED':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_INVALID',
message: '授权无效,请重新激活'
}
case 'LICENSE_NOT_FOUND':
return {
entitlement: 'invalid',
reasonCode: 'LICENSE_REQUIRED',
message: '未检测到有效授权'
}
case 'LICENSE_NETWORK_ERROR':
case 'LICENSE_SERVER_ERROR':
return {
entitlement: 'unavailable',
reasonCode: 'LICENSE_UNAVAILABLE',
message: '授权服务暂时不可用,稍后再试'
}
default:
// 未知状态一律 fail-closed,但要说清「是未知」而不是「你没买」
return {
entitlement: 'unavailable',
reasonCode: 'LICENSE_UNAVAILABLE',
message: '暂时无法确认授权状态'
}
}
}
/** 探测本机 Hook 的授权接口。失败只报失败,不臆测状态。 */
export function probeLicenseStatus(timeoutMs = PROBE_TIMEOUT_MS): Promise<LicenseProbeResult> {
return new Promise((resolve) => {
let settled = false
const done = (result: LicenseProbeResult): void => {
if (settled) return
settled = true
resolve(result)
}
let req: http.ClientRequest
try {
req = http.get(
{ host: '127.0.0.1', port: 4290, path: '/license/status', timeout: timeoutMs },
(res) => {
const chunks: Buffer[] = []
res.on('data', (chunk: Buffer) => chunks.push(chunk))
res.on('end', () => {
try {
const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as {
status?: unknown
}
done({ ok: true, status: typeof body.status === 'string' ? body.status : '' })
} catch {
done({ ok: false, error: 'BAD_JSON' })
}
})
res.on('error', () => done({ ok: false, error: 'RESPONSE_ERROR' }))
}
)
} catch (error) {
done({ ok: false, error: error instanceof Error ? error.message : String(error) })
return
}
req.on('timeout', () => {
req.destroy()
done({ ok: false, error: 'TIMEOUT' })
})
req.on('error', (error: Error) => done({ ok: false, error: error.message }))
})
}
/** 粗检组件:非 PE 或架构不符判 invalid,不做哈希白名单。 */
export function inspectNativeComponent(
filePath: string | null,
arch: string,
statFile: (p: string) => { size: number } | null
): NativeComponentState {
if (!filePath) return 'missing'
const stat = statFile(filePath)
if (!stat || stat.size < 1024) return 'missing'
try {
const fd = fs.openSync(filePath, 'r')
try {
const head = Buffer.alloc(0x40)
fs.readSync(fd, head, 0, 0x40, 0)
if (head[0] !== 0x4d || head[1] !== 0x5a) return 'invalid' // "MZ"
const peOffset = head.readUInt32LE(0x3c)
const pe = Buffer.alloc(6)
fs.readSync(fd, pe, 0, 6, peOffset)
if (pe[0] !== 0x50 || pe[1] !== 0x45) return 'invalid' // "PE"
const machine = pe.readUInt16LE(4)
const expected = arch === 'arm64' ? 0xaa64 : 0x8664
return machine === expected ? 'ready' : 'incompatible'
} finally {
fs.closeSync(fd)
}
} catch {
return 'invalid'
}
}
export class MessageInsertCapabilityService {
private cached: MessageInsertCapability | null = null
private inflight: Promise<MessageInsertCapability> | null = null
private readonly now: () => number
constructor(private readonly deps: CapabilityDeps) {
this.now = deps.now || (() => Date.now())
}
/** 读缓存(页面刷新用);过期或从未算过就重新评估。 */
async getCapability(input: CapabilityInput): Promise<MessageInsertCapability> {
const now = this.now()
if (this.cached && now - this.cached.checkedAt < DEFAULT_TTL_MS) {
/* 数据库连接状态可能瞬间变化,缓存命中时也要用最新入参重算这一项 */
const merged = this.compose(input, this.cached.entitlementState, this.cached.licenseStatus)
this.cached = merged
return merged
}
return this.refresh(input)
}
/** 强制重新评估(写库前必须调用,不能相信页面上那份缓存)。 */
async refresh(input: CapabilityInput): Promise<MessageInsertCapability> {
if (this.inflight) return this.inflight
this.inflight = this.evaluate(input).finally(() => {
this.inflight = null
})
const result = await this.inflight
this.cached = result
return result
}
/** 供主进程做「开启」前的最终裁决。 */
async ensureCanEnable(input: CapabilityInput): Promise<MessageInsertCapability> {
return this.refresh(input)
}
/** 测试与设置变化时清缓存。 */
invalidate(): void {
this.cached = null
}
private async evaluate(input: CapabilityInput): Promise<MessageInsertCapability> {
const platform = this.deps.platform
if (platform !== 'win32' && platform !== 'darwin') {
return this.build({
input,
entitlement: 'unsupported',
licenseStatus: undefined,
reasonCode: 'UNSUPPORTED_PLATFORM',
message: '微信内消息写入目前仅支持 Windows 与 macOS'
})
}
if (platform === 'darwin') {
if (!this.deps.hasMacNativeBundle()) {
// OSS 包:如实说不提供,不假装「未授权」
return this.build({
input,
entitlement: 'unsupported',
licenseStatus: undefined,
reasonCode: 'UNSUPPORTED_PLATFORM',
message: '当前版本不包含微信内消息发送能力'
})
}
return this.build({
input,
entitlement: 'valid',
licenseStatus: undefined,
reasonCode: 'CAPABILITY_READY',
message: '授权有效'
})
}
const probe = await this.deps.probeLicense(PROBE_TIMEOUT_MS)
if (!probe.ok) {
return this.build({
input,
entitlement: 'unavailable',
licenseStatus: undefined,
reasonCode: 'LICENSE_UNAVAILABLE',
message: '暂时无法确认授权状态'
})
}
const mapped = mapLicenseStatus(probe.status)
return this.build({
input,
entitlement: mapped.entitlement,
licenseStatus: probe.status,
reasonCode: mapped.reasonCode,
message: mapped.message
})
}
private build(args: {
input: CapabilityInput
entitlement: EntitlementState
licenseStatus?: string
reasonCode: CapabilityReasonCode
message: string
}): MessageInsertCapability {
return this.compose(args.input, args.entitlement, args.licenseStatus, args.reasonCode, args.message)
}
private compose(
input: CapabilityInput,
entitlement: EntitlementState,
licenseStatus: string | undefined,
reasonCode?: CapabilityReasonCode,
message?: string
): MessageInsertCapability {
const platform = this.deps.platform
const supportedPlatform = platform === 'win32' || platform === 'darwin'
const component = supportedPlatform
? inspectNativeComponent(
this.deps.resolveNativeComponent(),
process.arch,
this.deps.statFile || defaultStat
)
: 'missing'
const databaseReady = input.databaseReady === true
let code: CapabilityReasonCode = reasonCode || 'CAPABILITY_READY'
let text = message || ''
if (!code || code === 'CAPABILITY_READY') {
if (entitlement === 'unsupported') {
code = 'UNSUPPORTED_PLATFORM'
text = text || '当前版本不包含微信内消息发送能力'
} else if (entitlement === 'unavailable') {
code = 'LICENSE_UNAVAILABLE'
text = text || '暂时无法确认授权状态'
} else if (entitlement === 'pending') {
code = 'LICENSE_PENDING'
text = text || '授权正在验证,请稍候'
} else if (entitlement === 'invalid') {
code = 'LICENSE_REQUIRED'
text = text || '未检测到有效授权'
} else if (component !== 'ready') {
code = component === 'missing' ? 'COMPONENT_MISSING' : 'COMPONENT_INVALID'
text =
component === 'missing'
? '未安装发送能力组件'
: '发送能力组件不完整或版本不匹配'
} else if (!databaseReady) {
code = 'DATABASE_UNAVAILABLE'
text = '微信数据库尚未连接'
} else {
code = 'CAPABILITY_READY'
text = '授权与组件均已就绪'
}
}
const canEnable =
supportedPlatform &&
entitlement === 'valid' &&
component === 'ready' &&
databaseReady &&
code === 'CAPABILITY_READY'
/* 关闭不受授权限制:用户丢了授权也必须能把已有规则关掉 */
const canDisable = supportedPlatform
return {
entitlementState: entitlement,
nativeComponentState: component,
databaseReady,
canEnable,
canDisable,
reasonCode: code,
message: text,
...(licenseStatus ? { licenseStatus } : {}),
checkedAt: this.now()
}
}
}
function defaultStat(filePath: string): { size: number } | null {
try {
const stat = fs.statSync(filePath)
return stat.isFile() ? { size: stat.size } : null
} catch {
return null
}
}
export const msgInsertCapabilityService = new MessageInsertCapabilityService({
platform: process.platform,
hasMacNativeBundle,
isMacRuntimeUnavailable: isMacNativeRuntimeUnavailable,
resolveNativeComponent: resolveHelperPath,
probeLicense: probeLicenseStatus
})
+19 -2
View File
@@ -29,6 +29,8 @@ import { createHash } from 'node:crypto'
import path from 'node:path'
import { findResource } from '../resource-paths'
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
import { resolveExternalComponent } from './external-component-locator'
import type { Wcdb4Client } from '../wcdb4-client'
import {
MSG_INSERT_SWITCHES,
@@ -156,10 +158,14 @@ export function emptyMsgInsertStatus(
* 开发态与打包态都靠 findResource 解析,不依赖当前工作目录。
*/
export function resolveHelperPath(): string | null {
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
/* 优先用外置目录里的发送能力组件,避免自动更新清掉;校验不过当没装。 */
const external = resolveExternalComponent()
if (external) return external.helperPath
/*
* 平台/架构都要分。Windows 交付在 `resources/wcdb/win32/x64/`(注意是 win32 不是 windows),
* 文件名带 `.exe`。以前这里三个候选全写死 macos —— Windows 上会恒返回 null,
* 表现为「缺少写入组件」+ 开关永久置灰。
* 表现为「缺少发送能力组件」+ 开关永久置灰。
*
* 同目录还有 wcdb_api.dll / WCDB.dll / SDL2.dll,MSVC 运行库在 resources/runtime/win32/,
* 两者都由 preload-env.ts 加进 DLL 搜索路径,所以 helper.exe 能直接加载。
@@ -640,6 +646,14 @@ export async function applyMsgInsertSwitch(
}
}
if (isMacNativeRuntimeUnavailable()) {
return {
success: false,
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '微信内消息插入仅在 TraceMemo 具备发送能力时开放'),
errorCode: 'HELPER_NOT_FOUND',
message: '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响'
}
}
const helperPath = resolveHelperPath()
if (!helperPath) {
return {
@@ -647,7 +661,7 @@ export async function applyMsgInsertSwitch(
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '暂无法使用'),
errorCode: 'HELPER_NOT_FOUND',
/* 面向用户是能力语义;errorCode 仍是 HELPER_NOT_FOUND,门禁/授权层照旧能判。 */
message: '暂无法使用:当前安装不包含微信内消息写入组件'
message: '暂无法使用:当前安装不包含发送能力组件'
}
}
@@ -716,6 +730,9 @@ export async function applyMsgInsertSwitch(
export async function reconcileMsgInsertRules(
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] }
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
if (isMacNativeRuntimeUnavailable()) {
return { done: false, rooms: 0, written: 0, errorCode: 'HELPER_NOT_FOUND' }
}
const helperPath = resolveHelperPath()
if (!helperPath || !input.databaseKey) {
return {
@@ -12,7 +12,7 @@ import {
} from 'fs'
import { homedir, tmpdir } from 'os'
import { delimiter, dirname, extname, join, sep } from 'path'
import ffmpegStaticPath from 'ffmpeg-static'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { promisify } from 'util'
import type {
PersonalWechatSendRequest,
@@ -64,9 +64,7 @@ function windowsHookHost(port?: unknown): string | null {
export function buildPersonalWechatRuntimePath(): string {
const existing = String(process.env['PATH'] || '')
const bundledFfmpeg = String(ffmpegStaticPath || '')
.replace('app.asar', 'app.asar.unpacked')
.trim()
const bundledFfmpeg = resolveBundledFfmpegPath()
if (!bundledFfmpeg || !existsSync(bundledFfmpeg)) return existing
return [dirname(bundledFfmpeg), existing].filter(Boolean).join(delimiter)
}
@@ -174,7 +172,7 @@ async function detectVoiceDurationMs(filePath: string): Promise<number | undefin
}
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
const ffmpegPath = resolveBundledFfmpegPath()
if (!ffmpegPath || !existsSync(ffmpegPath)) return undefined
let output = ''
try {
@@ -203,7 +201,7 @@ async function prepareWindowsVoiceFile(filePath: string): Promise<{
return { filePath, durationMs: await detectVoiceDurationMs(filePath), temporary: false }
}
const ffmpegPath = String(ffmpegStaticPath || '').replace('app.asar', 'app.asar.unpacked')
const ffmpegPath = resolveBundledFfmpegPath()
if (!ffmpegPath || !existsSync(ffmpegPath)) {
throw new Error('Windows 语音发送需要可用的 FFmpeg 才能转换为 SILK')
}
+2 -1
View File
@@ -36,6 +36,7 @@
// - macOS 没有"语言包缺失"这一失败模式。
import crypto from 'node:crypto'
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
import { spawn } from 'node:child_process'
import {
SYSTEM_OCR_CACHE_TTL_MS,
@@ -125,7 +126,7 @@ const defaultResolveFfmpegExecutable = (): string => {
const fromEnvironment = String(process.env['FFMPEG_BIN'] || '').trim()
if (fromEnvironment) return fromEnvironment
try {
const bundled = require('ffmpeg-static') as string | null
const bundled = resolveBundledFfmpegPath()
if (bundled) return bundled
} catch {
// 忽略:退回到 PATH 上的 ffmpeg
@@ -33,7 +33,9 @@ import { app } from 'electron'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { renderLeaveNotificationText } from '../../shared/group-exit-event'
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
import { findResource } from '../resource-paths'
import { resolveWcdbConfigHelper } from '../native-runtime-paths'
import { msgInsertCapabilityService } from './msg-insert-capability-service'
import { resolveHelperPath } from './msg-insert-switch-service'
export type LocalExitNoticeOutcome =
| 'inserted'
@@ -57,27 +59,18 @@ interface StoredState {
enabled?: boolean
}
const HELPER_NAME = 'tm-wcdb-config-helper'
const HELPER_TIMEOUT_MS = 20_000
/** 最近若干次插入结果,只用于诊断展示,不参与判定 */
const RECENT_LIMIT = 50
function helperPath(): string | null {
/* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致:
* Windows 走 wcdb/win32/<arch>/ 且文件名带 .exe。 */
const arch = process.arch === 'x64' ? 'x64' : 'arm64'
const other = arch === 'arm64' ? 'x64' : 'arm64'
const platformDir = process.platform === 'win32' ? 'win32' : 'macos'
const suffix = process.platform === 'win32' ? '.exe' : ''
for (const candidate of [
`wcdb/${platformDir}/${arch}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${other}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${HELPER_NAME}${suffix}`
]) {
const resolved = findResource(candidate)
if (resolved) return resolved
}
return null
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
/*
* 不在这里重复一份 resources 搜索逻辑。
* Windows 上 helper 可能被部署到外置目录,
* 只有一处解析入口,两条链路才不会各解析各的。
*/
return resolveHelperPath()
}
/**
@@ -150,6 +143,13 @@ export class WechatLocalExitNoticeService {
try {
this.ensureLoaded()
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
/* 判定走统一服务;未授权或超时一律不写,普通退群检测不受影响。 */
const capability = await msgInsertCapabilityService.getCapability({
databaseReady: true
})
if (!capability.canEnable) {
return this.finish({ ...base, outcome: 'disabled', code: capability.reasonCode })
}
if (!event.eventId || !event.conversationId) {
return this.finish({ ...base, outcome: 'failed', code: 'EVENT_INCOMPLETE' })
}
+133 -27
View File
@@ -5,7 +5,8 @@ import crypto from 'crypto'
import { createRequire } from 'module'
import { createConnection, Socket } from 'net'
import { getResourceRoots } from './resource-paths'
import { wcdbDebugLog } from './wcdb-debug'
import { resolveWcdbLibrary } from './native-runtime-paths'
import { wcdbDebugLog, isWcdbDebugEnabled } from './wcdb-debug'
import { looksLikePermissionDenied, PathAccessDeniedError } from './services/path-access-probe'
import type { ImageMessageCountProbe } from '../shared/image-text-index'
import { imageTextWindowToSeconds } from '../shared/image-text-index'
@@ -147,6 +148,71 @@ type KoffiModule = {
// library reference for every Wcdb4Client instance.
let wcdbBootstrapLib: KoffiLibrary | null = null
const DB_COMPONENT_UNAVAILABLE_MESSAGE = '本地数据库组件初始化失败,请确认应用安装完整。'
class NativeDbInitError extends Error {
readonly nativeCode: number
readonly phase: string
constructor(message: string, nativeCode: number, phase: string) {
super(message)
this.name = 'NativeDbInitError'
this.nativeCode = nativeCode
this.phase = phase
}
}
// -3002 一码四因(密钥错、不存在、不可读、损坏),先看文件系统事实再判码。
function describeDbOpenFailure(code: number, sessionDbPath: string): string {
if (code === -2003) return DB_COMPONENT_UNAVAILABLE_MESSAGE
let exists = false
try {
exists = Boolean(sessionDbPath) && fs.existsSync(sessionDbPath)
} catch {
exists = false
}
if (!exists) {
return '未找到微信数据库文件,请确认微信已登录目标账号,并重新选择数据目录。'
}
try {
fs.accessSync(sessionDbPath, fs.constants.R_OK)
} catch {
return '数据库文件不可读,请在系统设置中授予文件访问权限后重试。'
}
if (code === -3002) {
return '数据库无法打开:密钥与当前账号不匹配,或数据库文件已损坏。'
}
return '本地数据库初始化失败,请稍后重试。'
}
class NativeWcdbError extends Error {
readonly nativeCode: number
readonly phase = 'query'
constructor(nativeCode: number) {
super(describeWcdbQueryFailure(nativeCode))
this.name = 'NativeWcdbError'
this.nativeCode = nativeCode
}
}
function describeWcdbQueryFailure(code: number): string {
if (code === -2003) return DB_COMPONENT_UNAVAILABLE_MESSAGE
if (code === -3003 || code === -3004) {
return '读取微信数据库失败:密钥可能与该账号不匹配,或数据库文件已损坏。'
}
if (code === -3006) return '数据库连接已失效,请重新连接。'
return '本地数据库读取失败,请稍后重试。'
}
export function getNativeErrorCode(error: unknown): number | null {
const code = (error as { nativeCode?: unknown } | null | undefined)?.nativeCode
return typeof code === 'number' ? code : null
}
let wcdbBootstrapAsyncPromise: Promise<KoffiLibrary> | null = null
export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string): KoffiLibrary {
@@ -205,16 +271,28 @@ export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string):
}
}
if (!initOk) {
console.warn(
`[WCDB4] bootstrap InitProtection 返回 ${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
)
if (lastCode === -2003) {
// -2003 重试无效;其他非 0 仍要继续,兼容旧构建。
throw new NativeDbInitError(DB_COMPONENT_UNAVAILABLE_MESSAGE, lastCode, 'InitProtection')
}
if (isWcdbDebugEnabled()) {
console.warn(
`[WCDB4] bootstrap InitProtection rc=${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
)
} else {
console.warn('[WCDB4] bootstrap InitProtection 未成功,继续尝试后续初始化')
}
} else {
const wcdbInit = lib.func('int32 wcdb_init()') as () => number
console.log('[WCDB4] bootstrap wcdb_init begin')
const initRc = Number(wcdbInit())
console.log(`[WCDB4] bootstrap wcdb_init rc=${initRc}`)
if (initRc !== 0) {
console.warn(`[WCDB4] bootstrap wcdb_init 返回 ${initRc},继续尝试 wcdb_open_account`)
console.warn(
isWcdbDebugEnabled()
? `[WCDB4] bootstrap wcdb_init rc=${initRc},继续尝试 wcdb_open_account`
: '[WCDB4] bootstrap wcdb_init 未成功,继续尝试打开数据库'
)
}
}
@@ -261,9 +339,11 @@ export function bootstrapWcdbNativeAsync(
)
)
let initOk = false
let lastInitCode = -1
for (const resourceRoot of resourceRoots) {
try {
if (Number(initProtection(resourceRoot)) === 0) {
lastInitCode = Number(initProtection(resourceRoot))
if (lastInitCode === 0) {
initOk = true
break
}
@@ -271,6 +351,9 @@ export function bootstrapWcdbNativeAsync(
// Try the next resource root.
}
}
if (!initOk && lastInitCode === -2003) {
throw new NativeDbInitError(DB_COMPONENT_UNAVAILABLE_MESSAGE, lastInitCode, 'InitProtection')
}
if (initOk) {
const wcdbInit = lib.func('int32 wcdb_init()') as KoffiAsyncFunction
await new Promise<void>((resolve, reject) => {
@@ -779,12 +862,16 @@ export class Wcdb4Client {
openResult = this.wcdbOpenAccount(this.sessionDbPath, this.key, handleOut)
if (openResult !== 0 || handleOut[0] <= 0) {
const hint =
openResult === -1005
? ';这通常表示密钥与当前账号数据库不匹配,请确认微信已登录目标账号,并重新自动获取密钥'
: ''
throw new Error(
`wcdb_open_account 失败,错误码: ${openResult}${hint}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
// message 只放分类文案;路径与 wxid 不进 message,原生码在 nativeCode 字段上。
if (isWcdbDebugEnabled()) {
console.warn(
`[WCDB4] wcdb_open_account rc=${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
)
}
throw new NativeDbInitError(
describeDbOpenFailure(openResult, this.sessionDbPath),
openResult,
'wcdb_open_account'
)
}
@@ -812,8 +899,15 @@ export class Wcdb4Client {
handleOut
)
if (openResult !== 0 || handleOut[0] <= 0) {
throw new Error(
`wcdb_open_account failed, code=${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
if (isWcdbDebugEnabled()) {
console.warn(
`[WCDB4] wcdb_open_account(async) rc=${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
)
}
throw new NativeDbInitError(
describeDbOpenFailure(openResult, this.sessionDbPath),
openResult,
'wcdb_open_account_async'
)
}
this.handle = handleOut[0]
@@ -920,7 +1014,11 @@ export class Wcdb4Client {
)
if (startResult !== 0) {
this.monitorCallback = null
console.warn(`[WCDB4] wcdb_start_monitor_pipe 失败,错误码: ${startResult}`)
console.warn(
isWcdbDebugEnabled()
? `[WCDB4] wcdb_start_monitor_pipe rc=${startResult}`
: '[WCDB4] 消息监听启动失败,将退回轮询'
)
return false
}
this.monitorStarted = true
@@ -935,7 +1033,11 @@ export class Wcdb4Client {
outName
)
if (nameResult !== 0 || !outName[0]) {
console.warn(`[WCDB4] wcdb_get_monitor_pipe_name 失败,错误码: ${nameResult}`)
console.warn(
isWcdbDebugEnabled()
? `[WCDB4] wcdb_get_monitor_pipe_name rc=${nameResult}`
: '[WCDB4] 消息监听通道不可用,将退回轮询'
)
this.stopMonitor()
return false
}
@@ -3532,16 +3634,14 @@ export class Wcdb4Client {
}
static resolveNativeLibrary(): string {
const libName =
process.platform === 'darwin'
? 'libwcdb_api.dylib'
: process.platform === 'linux'
? 'libwcdb_api.so'
: 'wcdb_api.dll'
if (process.platform === 'darwin') {
const library = resolveWcdbLibrary()
if (library) return library
throw new Error('找不到当前发行版对应的 WCDB native 库')
}
const libName = process.platform === 'linux' ? 'libwcdb_api.so' : 'wcdb_api.dll'
const platformDir =
process.platform === 'darwin'
? 'macos'
: process.platform === 'win32'
process.platform === 'win32'
? 'win32'
: process.platform
const archDir = process.arch === 'arm64' ? 'arm64' : 'x64'
@@ -3618,7 +3718,10 @@ export class Wcdb4Client {
const outJson: WcdbVoidOut = [null]
const result = call(handle, outJson)
if (result !== 0 || !outJson[0]) {
throw new Error(`WCDB 调用失败,错误码: ${result}`)
if (isWcdbDebugEnabled()) {
console.warn(`[WCDB4] native query rc=${result} handle=${handle}`)
}
throw new NativeWcdbError(result)
}
try {
@@ -3640,7 +3743,10 @@ export class Wcdb4Client {
}
const code = Number(result)
if (code !== 0 || !outJson[0]) {
reject(new Error(`WCDB async call failed, code: ${code}`))
if (isWcdbDebugEnabled()) {
console.warn(`[WCDB4] native query(async) rc=${code} handle=${handle}`)
}
reject(new NativeWcdbError(code))
return
}
try {
+5
View File
@@ -84,6 +84,8 @@ import type {
PersonalWechatVoiceDiagnostic
} from '../shared/personal-wechat'
import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from '../shared/personal-wechat-mac-runtime'
import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats'
import type {
ScheduledReportExecution,
@@ -751,6 +753,9 @@ declare global {
repairImageTextIndex: () => Promise<ImageTextIndexRepairResult>
onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void
getPersonalWechatSenderStatus: () => Promise<PersonalWechatSenderStatus>
getMacLicenseStatus: () => Promise<MacLicenseStatus>
getMacSendRuntimeAvailability: () => Promise<MacWechatSendRuntimeAvailabilityResult>
refreshMacLicense: () => Promise<MacLicenseStatus>
getPersonalWechatSendCapability: () => Promise<PersonalWechatSendCapability>
checkPersonalWechatSenderStatus: (port?: string) => Promise<PersonalWechatSenderStatus>
checkPersonalWechatVoiceEncodingEnvironment: () => Promise<PersonalWechatVoiceEncodingEnvironment>
+8
View File
@@ -14,6 +14,8 @@ import type {
SaveGeneratedReportRequest,
UpdateGeneratedReportTemplateRequest
} from '../shared/report-history'
import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from '../shared/personal-wechat-mac-runtime'
import type {
AIChatRequestOptions,
AiSearchExternalAuthorizationRequest,
@@ -585,6 +587,12 @@ const api = {
},
getPersonalWechatSenderStatus: (): Promise<PersonalWechatSenderStatus> =>
ipcRenderer.invoke('wechat-personal:getStatus'),
getMacLicenseStatus: (): Promise<MacLicenseStatus> =>
ipcRenderer.invoke('wechat-personal:getMacLicenseStatus'),
getMacSendRuntimeAvailability: (): Promise<MacWechatSendRuntimeAvailabilityResult> =>
ipcRenderer.invoke('wechat-personal:getMacSendRuntimeAvailability'),
refreshMacLicense: (): Promise<MacLicenseStatus> =>
ipcRenderer.invoke('wechat-personal:refreshMacLicense'),
getPersonalWechatSendCapability: (): Promise<PersonalWechatSendCapability> =>
ipcRenderer.invoke('wechat-personal:getSendCapability'),
checkPersonalWechatSenderStatus: (port?: string): Promise<PersonalWechatSenderStatus> =>
@@ -8,19 +8,20 @@ interface PersonalWechatSetupGuideProps {
binding: boolean
detecting: boolean
sessionBound: boolean
onBind: () => void
onStartSending: () => void
onBind?: () => void
onStartSending?: () => void
onOpenTextToSpeechSettings?: () => void
}
function capabilityLabel(ready: boolean, initializing: boolean): string {
if (ready) return '已就绪'
return initializing ? '初始化中' : '未就绪'
showBindAction?: boolean
showStartSendingAction?: boolean
showCapabilityStatus?: boolean
showBindingInstructionsInInitialization?: boolean
showAuthorizationWarning?: boolean
canBind?: boolean
}
function bindingHint(status: PersonalWechatSenderStatus): string {
if (status.state === 'wechat_not_running') {
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
}
if (status.state === 'unsupported_platform') return '当前系统暂不支持个人微信发送。'
if (status.state === 'unsupported_version')
@@ -29,7 +30,7 @@ function bindingHint(status: PersonalWechatSenderStatus): string {
return '请先完成发送运行时准备。'
}
if (status.state === 'error') return '连接微信时遇到问题,请稍后重试。'
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
}
function isWechatBound(status: PersonalWechatSenderStatus): boolean {
@@ -41,6 +42,11 @@ function isWechatBound(status: PersonalWechatSenderStatus): boolean {
)
}
function capabilityLabel(ready: boolean, initializing: boolean): string {
if (ready) return '已就绪'
return initializing ? '初始化中' : '未就绪'
}
export function PersonalWechatSetupGuide({
senderStatus,
binding,
@@ -48,7 +54,13 @@ export function PersonalWechatSetupGuide({
sessionBound,
onBind,
onStartSending,
onOpenTextToSpeechSettings
onOpenTextToSpeechSettings,
showBindAction = true,
showStartSendingAction = true,
showCapabilityStatus = true,
showBindingInstructionsInInitialization = false,
showAuthorizationWarning = true,
canBind = true
}: PersonalWechatSetupGuideProps): React.ReactElement {
const runtimeUnavailable = senderStatus?.state === 'runtime_missing'
const runtimeLabel = '发送运行时'
@@ -76,7 +88,7 @@ export function PersonalWechatSetupGuide({
<strong>准备 {runtimeLabel}</strong>
<p>
{runtimeUnavailable
? `个人微信发送需要${runtimeLabel},授权后即可使用。`
? '当前版本没有微信发送能力。'
: `${runtimeLabel}随 TraceMemo 一起提供,无需额外安装。`}
</p>
{runtimeReady ? (
@@ -89,65 +101,79 @@ export function PersonalWechatSetupGuide({
</div>
</li>
<li
className={
connected
? 'is-complete'
: binding
? 'is-active'
: runtimeReady
? 'is-current'
: 'is-pending'
}
>
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
<div className="personal-wechat-step-content">
<strong>绑定个人微信</strong>
<p>请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
{connected ? (
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
) : (
<Button
size="sm"
variant="outline"
onClick={onBind}
disabled={runtimeUnavailable || !runtimeReady || binding}
>
{binding ? '正在绑定…' : '绑定微信'}
</Button>
)}
{!connected && senderStatus && !runtimeUnavailable && (
<p className="personal-wechat-step-hint">{bindingHint(senderStatus)}</p>
)}
{!connected && runtimeUnavailable && (
<div className="personal-wechat-authorization-warning" role="alert">
<span aria-hidden>!</span>
<p>
发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。
进群请点击{' '}
<a href={GROUP_README_URL} target="_blank" rel="noreferrer">
这里
</a>{' '}
跳转。
</p>
</div>
)}
{!connected && !runtimeUnavailable && (
<p className="personal-wechat-step-warning" role="note">
绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。
{showBindAction ? (
<li
className={
connected
? 'is-complete'
: binding
? 'is-active'
: runtimeReady
? 'is-current'
: 'is-pending'
}
>
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
<div className="personal-wechat-step-content">
<strong>绑定个人微信</strong>
<p>
4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。
<br />
微信总是自动更新?请在微信左下角打开“设置 →
通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。
4.1.13以上登录状态微信直接点击“绑定微信”
</p>
)}
</div>
</li>
{connected ? (
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
) : (
<Button
size="sm"
variant="outline"
onClick={() => onBind?.()}
disabled={!canBind || runtimeUnavailable || !runtimeReady || binding}
>
{binding ? '正在绑定…' : '绑定微信'}
</Button>
)}
{!connected && senderStatus && !runtimeUnavailable ? (
<p className="personal-wechat-step-hint">{bindingHint(senderStatus)}</p>
) : null}
{!connected && runtimeUnavailable && showAuthorizationWarning ? (
<div className="personal-wechat-authorization-warning" role="alert">
<span aria-hidden>!</span>
<p>
发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。
进群请点击{' '}
<a href={GROUP_README_URL} target="_blank" rel="noreferrer">
这里
</a>{' '}
跳转。
</p>
</div>
) : null}
{!connected && !runtimeUnavailable ? (
<p className="personal-wechat-step-warning" role="note">
绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。
<br />
微信总是自动更新?请在微信左下角打开“设置 →
通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。
</p>
) : null}
</div>
</li>
) : null}
<li className={allReady ? 'is-complete' : connected ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">{allReady ? '✓' : '3'}</span>
<span className="personal-wechat-step-number">
{allReady ? '✓' : showBindAction ? '3' : '2'}
</span>
<div className="personal-wechat-step-content">
<strong>初始化发送能力</strong>
<p>绑定微信后,TraceMemo 会自动完成文字、图片和语音发送所需的初始化。</p>
<p>每个微信进程只能绑定一次</p>
{showBindingInstructionsInInitialization && (
<>
<p>4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
<p>4.1.13以上登录状态微信直接点击“绑定微信”</p>
</>
)}
{initializing && (
<p className="personal-wechat-step-hint" role="status">
{detecting ? '正在初始化发送能力…' : '正在等待发送运行时完成初始化…'}
@@ -161,37 +187,43 @@ export function PersonalWechatSetupGuide({
</div>
</li>
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">{allReady ? '✓' : '4'}</span>
<div className="personal-wechat-step-content">
<strong>能力检测</strong>
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
{[
['文字消息', Boolean(senderStatus?.canSendText)],
['图片消息', Boolean(senderStatus?.canSendImage)],
['语音消息', canSendVoice]
].map(([label, ready]) => (
<span key={String(label)} className={ready ? 'is-ready' : ''}>
<b aria-hidden>{ready ? '✓' : '−'}</b>
{label}
<small>{capabilityLabel(Boolean(ready), initializing)}</small>
</span>
))}
{showCapabilityStatus ? (
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">
{allReady ? '✓' : showBindAction ? '4' : '3'}
</span>
<div className="personal-wechat-step-content">
<strong>能力检测</strong>
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
{[
['文字消息', Boolean(senderStatus?.canSendText)],
['图片消息', Boolean(senderStatus?.canSendImage)],
['语音消息', canSendVoice]
].map(([label, ready]) => (
<span key={String(label)} className={ready ? 'is-ready' : ''}>
<b aria-hidden>{ready ? '✓' : '−'}</b>
{label}
<small>{capabilityLabel(Boolean(ready), initializing)}</small>
</span>
))}
</div>
{allReady ? (
<>
<span className="personal-wechat-step-status">微信消息发送已配置完成</span>
{showStartSendingAction && (
<Button size="sm" onClick={() => onStartSending?.()}>
开始发送
</Button>
)}
</>
) : initializing ? (
<p className="personal-wechat-step-hint" role="status">
发送能力准备完成后会自动进入已就绪状态。
</p>
) : null}
</div>
{allReady ? (
<>
<span className="personal-wechat-step-status">微信消息发送已配置完成</span>
<Button size="sm" onClick={onStartSending}>
开始发送
</Button>
</>
) : initializing ? (
<p className="personal-wechat-step-hint" role="status">
发送能力准备完成后会自动进入已就绪状态。
</p>
) : null}
</div>
</li>
</li>
) : null}
</ol>
{!runtimeReady && runtimeUnavailable && onOpenTextToSpeechSettings && (
@@ -122,7 +122,7 @@ export function MessageInsertSwitches(): React.JSX.Element {
/** 把结果里的失败原因翻成人话;native code 只进日志。 */
const humanize = React.useCallback((result: MsgInsertApplyResult): string => {
const status = result.status
if (result.errorCode === 'HELPER_NOT_FOUND') return '缺少写入组件,请重新安装或更新 TraceMemo'
if (result.errorCode === 'HELPER_NOT_FOUND') return '缺少发送能力组件,请重新安装或更新 TraceMemo'
if (result.errorCode === 'DATABASE_UNAVAILABLE') return '微信数据库未连接'
if (result.errorCode === 'NO_TARGET_ROOMS') return '没有可作用的目标会话'
if (status && status.failedShards > 0) {
@@ -174,29 +174,61 @@ export function MessageInsertSwitches(): React.JSX.Element {
[humanize, pending, refresh, toast]
)
/*
* helper 缺失时**提前**禁用,而不是等用户点了再弹「缺少写入组件」。
* 写开关必须靠那个一次性子进程,缺了它这个开关根本没法工作 ——
* 让人点了才失败是最差的一种交互。
*/
/*
* 写入组件缺失 = **这个能力还没开放**,不是安装坏了。
*
* 主进程对微信库只有只读连接,任何写入都要 spawn 那个一次性写入组件;当前分发的
* 安装包不带它(它随发送运行时按需分发),所以「微信内防撤回提示」与
* 「微信内退群监控消息」一律按"下个版本开放"呈现 —— 不该让用户去排查自己的安装。
* (machine-readable 的原因仍然是 snapshot.helperAvailable,授权层可以据此判断。)
*/
/* 开启要全绿,关闭永远放行——授权过期后关不掉比开不了更糟。 */
const capability = snapshot?.capability
const helperMissing = snapshot?.helperAvailable === false
const blocked = blockedReason ?? (helperMissing ? '该能力将在下个版本开放' : null)
const disabled = blocked !== null
const noticeForEnable = ((): string | null => {
if (capability) {
if (capability.canEnable) return blockedReason ?? null
switch (capability.reasonCode) {
case 'LICENSE_REQUIRED':
return '需要有效授权才能开启'
case 'LICENSE_PENDING':
return '授权正在验证,稍等片刻再试'
case 'LICENSE_EXPIRED':
return '授权已过期,重新激活后可开启'
case 'LICENSE_INVALID':
return '授权无效,请重新激活'
case 'LICENSE_MACHINE_MISMATCH':
return '这份授权不属于本机'
case 'LICENSE_REVOKED':
return '授权已被吊销'
case 'LICENSE_UNAVAILABLE':
return '暂时无法确认授权状态'
case 'COMPONENT_MISSING':
return '当前安装未包含发送能力组件'
case 'COMPONENT_INVALID':
return '发送能力组件不完整,请重新安装'
case 'DATABASE_UNAVAILABLE':
return '微信数据库尚未连接'
case 'UNSUPPORTED_PLATFORM':
return '当前版本不包含此能力'
default:
return capability.message || null
}
}
if (helperMissing) return '该能力暂不可用'
return blockedReason ?? null
})()
const anyEnabled = MSG_INSERT_SWITCH_LABELS.some(
({ name }) => snapshot?.switches?.[name]?.desiredEnabled === true
)
/* 顶部只给「想开但开不了」的场景一条总提示,避免每个开关重复一遍 */
const capabilityNotice = noticeForEnable && !anyEnabled ? noticeForEnable : null
return (
<div className="automation-msg-insert-switches" title={blocked ?? undefined}>
<div className="automation-msg-insert-switches" title={capabilityNotice ?? undefined}>
{capabilityNotice ? <p className="automation-notice warning" role="status">{capabilityNotice}</p> : null}
{loading ? <Spinner /> : null}
{MSG_INSERT_SWITCH_LABELS.map(({ name, label, hint }) => {
const status: MsgInsertSwitchStatus | undefined = snapshot?.switches?.[name]
const busy = pending === name
const desired = status?.desiredEnabled === true
/* 已开启 → 允许关;未开启 → 必须满足开启条件 */
const switchNotice = desired ? null : noticeForEnable
const switchDisabled = pending !== null || (!desired && switchNotice !== null)
/* rules 型:显示「已就绪 / 可安装」;事件驱动型没有覆盖率这个概念。 */
const showCoverage = status?.mode === 'rules' && status.totalInstallableRooms > 0
const partial =
@@ -214,8 +246,8 @@ export function MessageInsertSwitches(): React.JSX.Element {
于是「点文字」也会切换开关。写微信库的开关不该这么容易被误触。 */
<span
key={name}
className={`automation-msg-insert-switch ${disabled ? 'is-disabled' : ''}`}
title={[hint, status?.message].filter(Boolean).join('\n') || blocked || hint}
className={`automation-msg-insert-switch ${switchDisabled ? 'is-disabled' : ''}`}
title={[hint, status?.message, switchNotice].filter(Boolean).join('\n') || hint}
>
<span className="automation-msg-insert-switch-label">{label}</span>
{/* 写微信库要 spawn 子进程 + 装规则,耗时以秒计。
@@ -227,8 +259,8 @@ export function MessageInsertSwitches(): React.JSX.Element {
</span>
) : null}
<Switch
checked={status?.desiredEnabled === true}
disabled={disabled || pending !== null}
checked={desired}
disabled={switchDisabled}
onCheckedChange={(checked) => void handleToggle(name, checked === true)}
aria-label={label}
/>
@@ -1,8 +1,14 @@
import { useCallback, useEffect, useState, type ReactElement } from 'react'
import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react'
import type {
PersonalWechatSendCapability,
PersonalWechatSenderStatus
} from '../../../../../shared/personal-wechat'
import type {
MacLicenseState,
MacLicenseStatus
} from '../../../../../shared/personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from '../../../../../shared/personal-wechat-mac-runtime'
import { resolveMacSendPrimaryAction } from '../../../../../shared/personal-wechat-mac-send-action'
import { Button, Input, Skeleton } from '../../../components/ui'
import { PersonalWechatSetupGuide } from '../../../components/chat/PersonalWechatSetupGuide'
import { isMac, isWindows } from '../../../utils/runtime-environment'
@@ -60,6 +66,190 @@ function SendCapabilityAuthorizationCard(): ReactElement {
)
}
const macLicenseStateLabel: Record<MacLicenseState, string> = {
unlicensed: '当前设备暂无发送能力授权',
valid: '已授权',
cached: '授权有效(本地缓存)',
expired: '授权已过期',
revoked: '授权已撤销',
device_mismatch: '授权与当前设备不匹配',
identity_error: '设备身份异常',
server_unavailable: '授权服务器不可用',
checking: '检测中…',
unsupported: '发送组件版本较旧',
runtime_missing: '发送组件未运行',
platform_unsupported: '当前构建不支持'
}
const macLicenseFeatureLabel: Record<string, string> = {
basic: '基础功能',
wechat: '微信发送',
advanced: '高级功能',
api: 'API 接口'
}
function licenseTone(state: MacLicenseState): string {
if (state === 'valid' || state === 'cached') return 'is-ready'
if (state === 'revoked' || state === 'expired' || state === 'identity_error') return 'is-error'
return 'is-neutral'
}
function formatMacLicenseDateTime(iso: string | null): string {
if (!iso) return '—'
const parsed = new Date(iso)
if (Number.isNaN(parsed.getTime())) return iso
return parsed.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
}
function formatMacLicenseDate(iso: string | null): string {
if (!iso) return '—'
const parsed = new Date(iso)
if (Number.isNaN(parsed.getTime())) return iso
return parsed.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
function summarizeDeviceId(deviceId: string): string {
return deviceId.length === 68 ? `${deviceId.slice(0, 12)}…${deviceId.slice(-6)}` : deviceId
}
/** 展示当前设备的授权状态,并提供刷新与复制设备 ID 的操作。 */
export function MacProLicenseCard({
onNotice,
onStatusChange
}: {
onNotice: (message: string) => void
onStatusChange: (status: MacLicenseStatus) => void
}): ReactElement {
const [license, setLicense] = useState<MacLicenseStatus | null>(null)
const [refreshing, setRefreshing] = useState(false)
const [copied, setCopied] = useState(false)
const load = useCallback(async (): Promise<void> => {
try {
const next = await window.api.getMacLicenseStatus()
setLicense(next)
onStatusChange(next)
} catch {
setLicense(null)
}
}, [onStatusChange])
useEffect(() => {
void load()
}, [load])
const refresh = async (): Promise<void> => {
if (refreshing) return
setRefreshing(true)
try {
const next = await window.api.refreshMacLicense()
setLicense(next)
onStatusChange(next)
if (next.authorized) {
onNotice('授权检测完成:已授权')
} else {
onNotice(next.message || '授权检测完成')
}
} catch (reason) {
onNotice(reason instanceof Error ? reason.message : '授权检测失败')
} finally {
setRefreshing(false)
}
}
const copyDeviceId = async (): Promise<void> => {
if (!license?.deviceId) return
try {
await navigator.clipboard.writeText(license.deviceId)
setCopied(true)
onNotice('设备 ID 已复制')
window.setTimeout(() => setCopied(false), 2_000)
} catch {
onNotice('复制失败,请手动选择设备 ID 复制')
}
}
if (!license) {
return <Skeleton className="h-24 w-full" />
}
// OSS 构建走到这里(platform_unsupported)时不渲染卡片,保证免费版不出现授权入口。
if (license.state === 'platform_unsupported') {
return <></>
}
return (
<section className="settings-card mac-pro-license-card" aria-label="发送能力授权">
<header className="mac-pro-license-header">
<strong>发送能力授权</strong>
<span className={`mac-pro-license-status ${licenseTone(license.state)}`}>
{license.state === 'valid' || license.state === 'cached'
? '设备已授权'
: macLicenseStateLabel[license.state]}
</span>
</header>
<div className="mac-pro-device-row">
<div className="mac-pro-device-value">
<span>本机设备 ID</span>
<code title={license.deviceId || undefined}>
{license.deviceId ? summarizeDeviceId(license.deviceId) : '(尚未生成)'}
</code>
</div>
<Button
variant="ghost"
size="sm"
disabled={!license.deviceId}
aria-label="复制完整设备 ID"
onClick={() => void copyDeviceId()}
>
{copied ? '已复制' : '复制'}
</Button>
</div>
{license.deviceId && !license.authorized ? (
<p className="mac-pro-license-hint">
将设备 ID 提供给授权管理员,完成授权后点击「重新检测授权」。
</p>
) : null}
{license.authorized && license.features.length > 0 ? (
<div className="mac-pro-license-features" aria-label="已开通功能">
{license.features.map((feature) => (
<span key={feature}>{macLicenseFeatureLabel[feature] || feature}</span>
))}
</div>
) : null}
<div className="mac-pro-license-meta">
<span>
授权到期 <strong>{formatMacLicenseDate(license.licenseExpiresAt)}</strong>
</span>
<span>
最近检测 <strong>{formatMacLicenseDateTime(license.lastCheckedAt)}</strong>
</span>
</div>
<div className="mac-pro-license-footer">
<span />
<Button
variant="outline"
size="sm"
disabled={refreshing || license.state === 'unsupported'}
onClick={() => void refresh()}
>
{refreshing ? '检测中…' : '重新检测授权'}
</Button>
</div>
</section>
)
}
export function PersonalWechatSendPage({
onNotice,
onOpenTextToSpeechSettings
@@ -79,6 +269,11 @@ export function PersonalWechatSendPage({
const [windowsPortInput, setWindowsPortInput] = useState('')
const [windowsDetectedPort, setWindowsDetectedPort] = useState('')
const [windowsEndpointBusy, setWindowsEndpointBusy] = useState(false)
const [setupExpanded, setSetupExpanded] = useState<boolean | null>(null)
const [macLicenseStatus, setMacLicenseStatus] = useState<MacLicenseStatus | null>(null)
const [macRuntimeAvailability, setMacRuntimeAvailability] =
useState<MacWechatSendRuntimeAvailabilityResult | null>(null)
const setupDefaultInitialized = useRef(false)
const refresh = useCallback(async (): Promise<void> => {
if (isWindows) {
setLoading(false)
@@ -101,7 +296,59 @@ export function PersonalWechatSendPage({
useEffect(() => {
if (isWindows) return
void refresh()
let active = true
const loadMacStatus = async (): Promise<void> => {
try {
const availability = await window.api.getMacSendRuntimeAvailability()
if (!active) return
setMacRuntimeAvailability(availability)
if (availability.state !== 'available') {
setSenderStatus({
state: 'runtime_missing',
platform: 'darwin',
arch: 'arm64',
sipDisabled: true,
wechatRunning: false,
endpoint: '',
endpointReady: false,
runtimeReady: false,
attachReady: false,
baseAddressReady: false,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false,
message: availability.message,
error: availability.message
})
setLoading(false)
return
}
const [nextCapability, nextSender, license] = await Promise.all([
window.api.getPersonalWechatSendCapability(),
window.api.getPersonalWechatSenderStatus(),
window.api.getMacLicenseStatus()
])
if (!active) return
setCapability(nextCapability)
setSenderStatus(nextSender)
setMacLicenseStatus(license)
} catch (reason) {
if (!active) return
setError(reason instanceof Error ? reason.message : '微信发送能力读取失败')
} finally {
if (active) setLoading(false)
}
}
void loadMacStatus()
return () => {
active = false
}
}, [refresh])
useEffect(() => {
@@ -266,7 +513,27 @@ export function PersonalWechatSendPage({
const pageMessage = isWindows
? windowsSenderStatus?.message || '请输入端口并检测 Windows 微信发送能力'
: capability?.message || '微信发送能力暂不可用'
const macUnavailable = isMac && senderStatus?.state === 'runtime_missing'
const macUnavailable = isMac && macRuntimeAvailability?.state === 'unavailable'
const macComponentError = isMac && macRuntimeAvailability?.state === 'component_error'
const macBound = boundToCurrentWechat(senderStatus)
const macEnvironmentReady = Boolean(
senderStatus?.runtimeReady && macBound && senderStatus.canSend
)
useEffect(() => {
if (isMac && senderStatus && !setupDefaultInitialized.current) {
setSetupExpanded(!macEnvironmentReady)
setupDefaultInitialized.current = true
}
}, [macEnvironmentReady, senderStatus])
const setupBodyId = 'personal-wechat-first-use-setup'
const macPrimaryAction = resolveMacSendPrimaryAction({
runtime: macRuntimeAvailability,
license: macLicenseStatus,
senderStatus,
binding,
detecting: loading || detecting
})
return (
<>
@@ -279,7 +546,13 @@ export function PersonalWechatSendPage({
<span
className={`settings-status-badge ${loading ? 'checking' : pageReady ? '' : pageStatus === 'unsupported' ? 'unavailable' : 'warning'}`}
>
{loading ? '检测中' : macUnavailable ? '暂不可用' : capabilityLabel[pageStatus]}
{loading
? '检测中'
: macUnavailable
? '没有微信发送能力'
: macComponentError
? '发送组件异常'
: capabilityLabel[pageStatus]}
</span>
</header>
<div className="settings-page-scroll">
@@ -407,18 +680,129 @@ export function PersonalWechatSendPage({
</>
) : isMac ? (
<>
<h2 className="settings-section-heading">配置状态</h2>
<PersonalWechatSetupGuide
senderStatus={senderStatus}
binding={binding}
detecting={detecting}
sessionBound={boundToCurrentWechat(senderStatus)}
onBind={() => void bindWechat()}
onStartSending={() =>
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
}
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
/>
{/* 发送能力授权卡片:仅在加载了发送组件的档位渲染。
OSS(runtime_missing)下不渲染,保证免费版不出现授权入口。 */}
{macRuntimeAvailability?.state === 'available' ? (
<MacProLicenseCard onNotice={onNotice} onStatusChange={setMacLicenseStatus} />
) : null}
<section
className="settings-card mac-wechat-environment-card"
aria-label="微信发送环境"
>
<header className="mac-wechat-environment-header">
<strong>微信发送环境</strong>
<span
className={`mac-wechat-environment-status ${macEnvironmentReady ? 'is-ready' : 'is-neutral'}`}
>
{loading
? '正在检查环境'
: macUnavailable
? '当前版本没有微信发送能力'
: macComponentError
? '发送组件缺失或异常'
: macEnvironmentReady
? '运行环境已就绪'
: '需要完成配置'}
</span>
</header>
<div className="mac-wechat-status-grid" aria-label="环境状态">
{[
['运行时正常', Boolean(senderStatus?.runtimeReady)],
['微信已绑定', macBound],
['发送组件正常', Boolean(senderStatus?.canSend)]
].map(([label, complete]) => (
<div className="mac-wechat-status-item" key={String(label)}>
<span
className={complete ? 'is-ready' : 'is-pending'}
aria-hidden="true"
>
{complete ? '✓' : '○'}
</span>
<strong>{label}</strong>
<small>{loading ? '检测中' : complete ? '正常' : '待完成'}</small>
</div>
))}
</div>
{senderStatus && macRuntimeAvailability?.state === 'available' ? (
<div
className="mac-wechat-capability-details"
aria-label="文字、图片和语音能力"
>
{(
[
['文字', senderStatus.canSendText],
['图片', senderStatus.canSendImage],
['语音', senderStatus.canSendVoice]
] as const
).map(([label, available]) => (
<span key={label} className={available ? 'is-ready' : 'is-pending'}>
{label} {available ? '可用' : '未就绪'}
</span>
))}
</div>
) : null}
<button
type="button"
className="mac-wechat-setup-toggle"
aria-expanded={setupExpanded ?? !macEnvironmentReady}
aria-controls={setupBodyId}
onClick={() =>
setSetupExpanded((expanded) => !(expanded ?? !macEnvironmentReady))
}
>
<span>首次使用配置</span>
<span className="mac-wechat-setup-chevron" aria-hidden="true">
⌄
</span>
</button>
<div
id={setupBodyId}
className="mac-wechat-setup-content"
hidden={!(setupExpanded ?? !macEnvironmentReady)}
>
{macRuntimeAvailability?.state === 'available' ? (
<PersonalWechatSetupGuide
senderStatus={senderStatus}
binding={binding}
detecting={detecting}
sessionBound={macBound}
showBindAction={false}
showCapabilityStatus={false}
showBindingInstructionsInInitialization
showAuthorizationWarning={false}
canBind={macPrimaryAction.action === 'bind'}
onStartSending={() =>
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
}
showStartSendingAction={false}
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
/>
) : null}
</div>
<div className="mac-wechat-primary-action">
<Button
className="w-full"
disabled={macPrimaryAction.disabled}
onClick={() => {
if (macPrimaryAction.action === 'bind') {
void bindWechat()
} else if (macPrimaryAction.action === 'send') {
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
} else if (!macPrimaryAction.disabled) {
setSetupExpanded(true)
}
}}
>
{macPrimaryAction.label}
</Button>
</div>
</section>
{macUnavailable ? (
<>
<h2 className="settings-section-heading">发送能力授权</h2>
<SendCapabilityAuthorizationCard />
</>
) : null}
</>
) : null}
</>
+242
View File
@@ -249,6 +249,248 @@
background: var(--wxex-bg-elevated);
padding: 24px 26px;
}
.mac-pro-license-card,
.mac-wechat-environment-card {
display: grid;
gap: 14px;
min-width: 0;
padding: 20px 22px;
}
.mac-pro-license-header,
.mac-wechat-environment-header {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
> strong {
color: var(--wxex-text-primary);
font-size: 15px;
font-weight: 650;
}
}
.mac-pro-license-status,
.mac-wechat-environment-status {
flex: 0 0 auto;
color: var(--wxex-text-secondary);
font-size: 12px;
}
.mac-pro-license-status.is-ready,
.mac-wechat-environment-status.is-ready,
.mac-wechat-status-item .is-ready,
.mac-wechat-capability-details .is-ready {
color: var(--wxex-success);
}
.mac-pro-license-status.is-error {
color: var(--wxex-danger);
}
.mac-pro-license-status.is-neutral,
.mac-wechat-environment-status.is-neutral {
color: var(--wxex-text-muted);
}
.mac-pro-device-row {
display: flex;
min-width: 0;
align-items: center;
gap: 10px;
border-radius: var(--wxex-radius-md);
background: color-mix(in srgb, var(--wxex-text-primary) 4%, transparent);
padding: 10px 12px;
}
.mac-pro-device-value {
display: grid;
min-width: 0;
flex: 1;
gap: 4px;
> span {
color: var(--wxex-text-muted);
font-size: 11px;
}
code {
overflow: hidden;
color: var(--wxex-text-primary);
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.mac-pro-license-hint {
margin: -5px 0 0;
color: var(--wxex-text-secondary);
font-size: 12px;
}
.mac-pro-license-features {
display: flex;
flex-wrap: wrap;
gap: 6px;
> span {
border-radius: 999px;
background: color-mix(in srgb, var(--wxex-text-primary) 5%, transparent);
padding: 3px 8px;
color: var(--wxex-text-secondary);
font-size: 11px;
}
}
.mac-pro-license-meta {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
color: var(--wxex-text-muted);
font-size: 11px;
strong {
margin-left: 4px;
color: var(--wxex-text-secondary);
font-weight: 550;
}
}
.mac-pro-license-footer {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.mac-pro-identity-note {
margin: 0;
}
.mac-wechat-status-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.mac-wechat-status-item {
display: grid;
min-width: 0;
justify-items: center;
gap: 5px;
border-radius: var(--wxex-radius-md);
background: color-mix(in srgb, var(--wxex-text-primary) 3%, transparent);
padding: 12px 8px;
text-align: center;
> span {
font-size: 18px;
line-height: 1;
}
.is-pending {
color: var(--wxex-text-muted);
}
strong {
color: var(--wxex-text-primary);
font-size: 12px;
font-weight: 550;
}
small {
color: var(--wxex-text-muted);
font-size: 10px;
}
}
.mac-wechat-capability-details {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
color: var(--wxex-text-muted);
font-size: 11px;
.is-pending {
color: var(--wxex-text-muted);
}
}
.mac-wechat-setup-toggle {
display: flex;
width: 100%;
align-items: center;
justify-content: space-between;
gap: 12px;
border: 0;
border-top: 1px solid var(--wxex-border);
background: transparent;
padding: 12px 0 0;
color: var(--wxex-text-primary);
cursor: pointer;
font: inherit;
font-size: 13px;
font-weight: 600;
text-align: left;
&:focus-visible {
border-radius: 4px;
outline: 2px solid var(--wxex-brand);
outline-offset: 3px;
}
}
.mac-wechat-setup-chevron {
color: var(--wxex-text-muted);
font-size: 18px;
transition: transform 160ms ease;
}
.mac-wechat-setup-toggle[aria-expanded='true'] .mac-wechat-setup-chevron {
transform: rotate(180deg);
}
.mac-wechat-setup-content {
min-width: 0;
&[hidden] {
display: none;
}
.personal-wechat-setup {
gap: 12px;
border: 0;
padding: 2px 0 0;
}
.personal-wechat-setup-heading h2,
.personal-wechat-eyebrow {
display: none;
}
}
.mac-wechat-primary-action {
padding-top: 2px;
}
@media (prefers-reduced-motion: reduce) {
.mac-wechat-setup-chevron {
transition: none;
}
}
@media (max-width: 560px) {
.mac-pro-license-card,
.mac-wechat-environment-card {
padding: 16px;
}
.mac-pro-license-header,
.mac-wechat-environment-header {
align-items: flex-start;
flex-direction: column;
gap: 4px;
}
.mac-wechat-status-grid {
gap: 5px;
}
.mac-wechat-status-item {
padding: 10px 4px;
strong {
font-size: 10px;
}
}
.mac-pro-license-meta {
flex-direction: column;
gap: 5px;
}
}
.settings-account-overview {
display: grid;
grid-template-columns: minmax(190px, 1fr) minmax(220px, 1fr) auto;
+53 -6
View File
@@ -104,12 +104,56 @@ export interface MsgInsertSwitchStatus {
message?: string
}
/** 授权状态(与「能不能发消息」无关) */
export type EntitlementState = 'valid' | 'invalid' | 'pending' | 'unavailable' | 'unsupported'
/** 发送能力组件状态 */
export type NativeComponentState = 'ready' | 'missing' | 'invalid' | 'incompatible'
/**
* 发送能力被拒的原因。**不要用 HELPER_NOT_FOUND 表达授权问题** ——
* 那会让「没装组件」「没授权」「发不了消息」三种情况在界面上无法区分。
*/
export type CapabilityReasonCode =
| 'CAPABILITY_READY'
| 'UNSUPPORTED_PLATFORM'
| 'LICENSE_REQUIRED'
| 'LICENSE_PENDING'
| 'LICENSE_EXPIRED'
| 'LICENSE_INVALID'
| 'LICENSE_MACHINE_MISMATCH'
| 'LICENSE_REVOKED'
| 'LICENSE_UNAVAILABLE'
| 'COMPONENT_MISSING'
| 'COMPONENT_INVALID'
| 'DATABASE_UNAVAILABLE'
/** 主进程算好的发送能力视图,渲染层只读这个,不再自己判断 */
export interface CapabilityView {
entitlementState: EntitlementState
nativeComponentState: NativeComponentState
databaseReady: boolean
canEnable: boolean
canDisable: boolean
reasonCode: CapabilityReasonCode
message: string
licenseStatus?: string
checkedAt?: number
}
export interface MsgInsertSwitchesSnapshot {
success: boolean
switches: Record<MsgInsertSwitchName, MsgInsertSwitchStatus>
/** helper 是否可用(不可用时只能读不能写) */
/** 原生发送能力(授权 + 组件 + 数据库),两个开关共用 */
capability?: CapabilityView
/**
* **能力标志**:本机是否存在「微信内消息写入组件」(那个一次性 helper)。
* @deprecated 语义漂移过:曾等于「这是不是 mac native 包」,在 Windows 上恒为 true。
* 新代码请用 `capability.canEnable`;这里只留一个与它一致的值给旧调用方。
*/
sendCapabilityAvailable?: boolean
switches: Record<MsgInsertSwitchName, MsgInsertSwitchStatus>
/** 发送能力组件是否可用(不可用时只能读不能写) */
/**
* **能力标志**:本机是否存在「微信内发送能力组件」。
*
* 这是「微信内防撤回提示」和「微信内退群监控消息」的**唯一硬门槛**:
* 主进程对微信库只持只读连接,任何写入都必须 spawn 那个组件,没有它两个功能都做不了。
@@ -117,9 +161,7 @@ export interface MsgInsertSwitchesSnapshot {
* 语义上它是 **capability(能力)**,不是 error(错误)——
* 缺失时 UI 显示「暂无法使用」,而不是「请重新安装」。
*
* ⚠️ 它是**唯一**的能力判据,不要再新增第二份(曾经因为 native 与 TS 各存一份判据
* 而出现 946 里莫名少 323 的假象)。将来的授权/付费门禁应当**并列**加在它旁边
* (capability && entitlement),而不是替换它。
* 它是组件能力判据;授权状态应与其并列,不能替换它。
*/
helperAvailable: boolean
/** native code 只放这里,不往 UI 上抛 */
@@ -152,6 +194,11 @@ export type MsgInsertErrorCode =
| 'UNSUPPORTED_SWITCH'
| 'NO_TARGET_ROOMS'
| 'DATABASE_UNAVAILABLE'
| 'LICENSE_REQUIRED'
| 'LICENSE_PENDING'
| 'LICENSE_EXPIRED'
| 'COMPONENT_MISSING'
| 'CAPABILITY_UNAVAILABLE'
| 'UNKNOWN'
/** 界面上要展示的两个开关(顺序即展示顺序) */
+149
View File
@@ -0,0 +1,149 @@
/**
* macOS 设备授权接口的 wire 类型。
* 所有字段都由 `parseMacLicenseStatus` 运行时校验后才会交给上层使用。
*/
export type MacLicenseState =
| 'unlicensed' // no license for this device
| 'valid' // online check passed in this process
| 'cached' // local cache verified, not re-confirmed online
| 'expired'
| 'revoked'
| 'device_mismatch' // token belongs to a different device
| 'identity_error' // device key unusable
| 'server_unavailable' // network / 5xx; cache may still hold
| 'checking' // an online refresh is in flight
| 'unsupported' // host is running but has no /license endpoints (old build)
| 'runtime_missing' // host not reachable / runtime absent
| 'platform_unsupported' // not macOS native (Windows / OSS)
const MAC_LICENSE_STATES = new Set<MacLicenseState>([
'unlicensed',
'valid',
'cached',
'expired',
'revoked',
'device_mismatch',
'identity_error',
'server_unavailable',
'checking',
'unsupported',
'runtime_missing',
'platform_unsupported'
])
export interface MacLicenseStatus {
deviceId: string | null
state: MacLicenseState
authorized: boolean
source: 'online' | 'cache' | 'none'
features: string[]
lastCheckedAt: string | null
licenseExpiresAt: string | null
tokenExpiresAt: string | null
message: string
/** False when the running host predates the license endpoints (404). */
runtimeProtocolSupported?: boolean
/** Host-reported numeric TM_WECHAT_* code when a refresh failed. */
errorCode?: number | null
}
const DEVICE_ID_PATTERN = /^mac_[0-9a-f]{64}$/
function asOptionalString(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}
function asOptionalIsoDate(value: unknown): string | null {
if (typeof value !== 'string' || value.length === 0) return null
// Accept RFC3339 (what the native core emits); reject obvious garbage.
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) return null
return value
}
function asStringArray(value: unknown): string[] {
if (!Array.isArray(value)) return []
return value.filter((entry): entry is string => typeof entry === 'string')
}
/**
* 把任意 JSON 校验成 MacLicenseStatus;无法确认的字段一律落到安全默认值。
* `authorized` 由 state 重算,伪造的 `authorized: true` 覆盖不了已撤销状态。
*/
export function parseMacLicenseStatus(raw: unknown): MacLicenseStatus {
const base: MacLicenseStatus = {
deviceId: null,
state: 'unlicensed',
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message: '当前设备暂无发送能力授权'
}
if (raw === null || typeof raw !== 'object') return base
const record = raw as Record<string, unknown>
const deviceId = asOptionalString(record.deviceId)
if (deviceId !== null && DEVICE_ID_PATTERN.test(deviceId)) {
base.deviceId = deviceId
}
const state = asOptionalString(record.state)
if (state !== null && MAC_LICENSE_STATES.has(state as MacLicenseState)) {
base.state = state as MacLicenseState
}
const source = asOptionalString(record.source)
if (source === 'online' || source === 'cache' || source === 'none') {
base.source = source
}
base.features = asStringArray(record.features)
base.lastCheckedAt = asOptionalIsoDate(record.lastCheckedAt)
base.licenseExpiresAt = asOptionalIsoDate(record.licenseExpiresAt)
base.tokenExpiresAt = asOptionalIsoDate(record.tokenExpiresAt)
const message = asOptionalString(record.message)
if (message !== null) base.message = message
if (typeof record.runtimeProtocolSupported === 'boolean') {
base.runtimeProtocolSupported = record.runtimeProtocolSupported
}
if (typeof record.errorCode === 'number' && Number.isFinite(record.errorCode)) {
base.errorCode = record.errorCode
}
/*
* authorized is DERIVED, not copied: only a small whitelist of states may
* present as authorized, and even then the payload's own boolean must agree.
* This keeps a forged {"authorized": true} from flipping a revoked state.
*/
const trustedStates: ReadonlySet<MacLicenseState> = new Set(['valid', 'cached'])
base.authorized = trustedStates.has(base.state) && record.authorized === true
return base
}
/**
* Build the "runtime missing / old host" status without a network round-trip.
* Used when the host is down or answered 404 on /license/status.
*/
export function offlineMacLicenseStatus(
state: 'runtime_missing' | 'unsupported' | 'platform_unsupported' | 'server_unavailable',
message: string
): MacLicenseStatus {
return {
deviceId: null,
state,
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message,
runtimeProtocolSupported: state === 'unsupported' ? false : undefined
}
}
+17 -2
View File
@@ -15,6 +15,13 @@ export type MacWechatRuntimeLifecycle =
| 'crashed_unbound' // died while unbound — safe to auto-restart
| 'crashed_bound' // died while bound — WeChat keeps an orphan agent
export type MacWechatSendRuntimeAvailability = 'unavailable' | 'component_error' | 'available'
export interface MacWechatSendRuntimeAvailabilityResult {
state: MacWechatSendRuntimeAvailability
message: string
}
export type MacWechatHostRuntimeState =
| 'not_initialized'
| 'wechat_not_running'
@@ -45,6 +52,16 @@ export interface MacWechatRuntimeManifest {
addressProfileSha256: string
supportedWechatVersions: string[]
capabilities: Array<'text' | 'image' | 'voice'>
capabilitiesByVersion?: Record<
string,
{
text?: 'verified' | 'addresses-only' | 'unsupported'
image?: 'verified' | 'addresses-only' | 'unsupported'
voice?: 'verified' | 'addresses-only' | 'unsupported'
downloadImage?: 'verified' | 'addresses-only' | 'unsupported'
textMechanism?: string
}
>
}
export interface MacWechatBindingStatus {
@@ -60,7 +77,6 @@ export interface MacWechatBindingStatus {
wechatPid: number
wechatVersion?: string
supported: boolean
supportedVersions?: string
bindingState: MacWechatBindingState
bound: boolean
boundWechatPid: number
@@ -82,7 +98,6 @@ export interface MacWechatRuntimeSnapshot {
endpoint: string
port: number
runtimeDir?: string
manifest?: MacWechatRuntimeManifest
error?: string
binding?: MacWechatBindingStatus
}
@@ -0,0 +1,103 @@
import type { MacLicenseStatus } from './personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from './personal-wechat-mac-runtime'
import type { PersonalWechatSenderStatus } from './personal-wechat'
export type MacSendPrimaryActionKind = 'none' | 'bind' | 'send'
export interface MacSendPrimaryAction {
label: string
disabled: boolean
loading: boolean
action: MacSendPrimaryActionKind
reason:
| 'runtime_unavailable'
| 'runtime_error'
| 'license_pending'
| 'license_invalid'
| 'license_feature_denied'
| 'binding'
| 'unbound'
| 'initializing'
| 'ready'
}
export function hasValidWechatLicense(license: MacLicenseStatus | null): boolean {
if (
!license ||
!license.authorized ||
(license.state !== 'valid' && license.state !== 'cached') ||
!license.features.includes('wechat')
) {
return false
}
const tokenExpiresAt = license.tokenExpiresAt ? Date.parse(license.tokenExpiresAt) : Number.NaN
return Number.isFinite(tokenExpiresAt) && tokenExpiresAt > Date.now()
}
export function resolveMacSendPrimaryAction(input: {
runtime: MacWechatSendRuntimeAvailabilityResult | null
license: MacLicenseStatus | null
senderStatus: PersonalWechatSenderStatus | null
binding: boolean
detecting: boolean
}): MacSendPrimaryAction {
const { runtime, license, senderStatus, binding, detecting } = input
const result = (
label: string,
disabled: boolean,
loading: boolean,
action: MacSendPrimaryActionKind,
reason: MacSendPrimaryAction['reason']
): MacSendPrimaryAction => ({ label, disabled, loading, action, reason })
if (!runtime || (detecting && !senderStatus)) {
return result('正在检查发送组件…', true, true, 'none', 'runtime_error')
}
if (runtime.state === 'unavailable') {
return result('当前版本没有微信发送能力', true, false, 'none', 'runtime_unavailable')
}
if (runtime.state === 'component_error') {
return result('发送组件缺失或异常', true, false, 'none', 'runtime_error')
}
if (license === null) {
return result('正在检测授权…', true, true, 'none', 'license_pending')
}
if (license.state === 'valid' || license.state === 'cached') {
if (license.authorized && !license.features.includes('wechat')) {
return result('未开通微信发送', true, false, 'none', 'license_feature_denied')
}
if (hasValidWechatLicense(license)) {
if (binding) return result('正在绑定…', true, true, 'none', 'binding')
const bound = Boolean(
senderStatus &&
(senderStatus.state === 'online' ||
Boolean(
senderStatus.wechatPid &&
senderStatus.boundWechatPid === senderStatus.wechatPid &&
senderStatus.attachReady &&
senderStatus.baseAddressReady
))
)
if (!bound) return result('绑定微信', false, false, 'bind', 'unbound')
if (senderStatus?.canSend) return result('开始发送', false, false, 'send', 'ready')
return result('正在准备发送能力…', true, detecting, 'none', 'initializing')
}
}
const bound = Boolean(
senderStatus &&
(senderStatus.state === 'online' ||
Boolean(
senderStatus.wechatPid &&
senderStatus.boundWechatPid === senderStatus.wechatPid &&
senderStatus.attachReady &&
senderStatus.baseAddressReady
))
)
return result(
bound ? '授权后可开始发送' : '授权后可绑定微信',
true,
false,
'none',
'license_invalid'
)
}