diff --git a/resources/wcdb/macos/arm64/libwcdb_api.dylib b/resources/wcdb/macos/arm64/libwcdb_api.dylib index 242725f..c68dc8c 100755 Binary files a/resources/wcdb/macos/arm64/libwcdb_api.dylib and b/resources/wcdb/macos/arm64/libwcdb_api.dylib differ diff --git a/resources/wcdb/macos/x64/libwcdb_api.dylib b/resources/wcdb/macos/x64/libwcdb_api.dylib index fcdf6ba..b2527a2 100755 Binary files a/resources/wcdb/macos/x64/libwcdb_api.dylib and b/resources/wcdb/macos/x64/libwcdb_api.dylib differ diff --git a/resources/wcdb/win32/x64/WCDB.dll b/resources/wcdb/win32/x64/WCDB.dll index 75308fd..70d4877 100644 Binary files a/resources/wcdb/win32/x64/WCDB.dll and b/resources/wcdb/win32/x64/WCDB.dll differ diff --git a/resources/wcdb/win32/x64/wcdb_api.dll b/resources/wcdb/win32/x64/wcdb_api.dll index 1c1b888..259bcbe 100644 Binary files a/resources/wcdb/win32/x64/wcdb_api.dll and b/resources/wcdb/win32/x64/wcdb_api.dll differ diff --git a/src/main/index.ts b/src/main/index.ts index ae9a9b3..c420059 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,4 +1,5 @@ import path from 'node:path' +import { isWcdbDebugEnabled } from './wcdb-debug' import { isLegacyMigrationHelper, isUserDataIsolated, @@ -530,7 +531,10 @@ async function cleanupLegacyRecallResidueOnStart(): Promise { }) } 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', @@ -1722,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, diff --git a/src/main/services/chat-service.ts b/src/main/services/chat-service.ts index c2ed545..286d24a 100644 --- a/src/main/services/chat-service.ts +++ b/src/main/services/chat-service.ts @@ -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' diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts index 4041522..c56562d 100644 --- a/src/main/wcdb4-client.ts +++ b/src/main/wcdb4-client.ts @@ -6,7 +6,7 @@ import { createRequire } from 'module' import { createConnection, Socket } from 'net' import { getResourceRoots } from './resource-paths' import { resolveWcdbLibrary } from './native-runtime-paths' -import { wcdbDebugLog } from './wcdb-debug' +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' @@ -148,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 | null = null export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string): KoffiLibrary { @@ -206,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 未成功,继续尝试打开数据库' + ) } } @@ -262,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 } @@ -272,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((resolve, reject) => { @@ -780,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' ) } @@ -813,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] @@ -921,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 @@ -936,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 } @@ -3617,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 { @@ -3639,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 {