From 9b2174a097f9f019453c9192658535e45f4f6b7d Mon Sep 17 00:00:00 2001 From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:04:59 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20macOS=E5=8F=91=E9=80=81=E5=92=8Cwindows?= =?UTF-8?q?=E7=BB=9F=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/extensions/extension-entitlement.ts | 11 + src/main/index.ts | 4 +- src/main/native-runtime-paths.ts | 17 +- .../services/external-component-locator.ts | 29 +- .../services/mac-wechat-runtime-manager.ts | 116 ++- .../personal-wechat-capability-service.ts | 4 +- .../services/personal-wechat-send-service.ts | 235 ++++- .../settings/pages/PersonalWechatSendPage.tsx | 882 +++++------------- .../personal-wechat-send-page.test.tsx | 309 ++---- tests/unit/external-component-locator.test.ts | 36 + .../unit/personal-wechat-send-service.test.ts | 39 +- 11 files changed, 710 insertions(+), 972 deletions(-) diff --git a/src/main/extensions/extension-entitlement.ts b/src/main/extensions/extension-entitlement.ts index 12b9ead..8dace6c 100644 --- a/src/main/extensions/extension-entitlement.ts +++ b/src/main/extensions/extension-entitlement.ts @@ -29,6 +29,17 @@ export async function checkExtensionSendEntitlement( const platform = dependencies.platform ?? process.platform if (platform === 'darwin') { try { + if (!dependencies.getMacLicense) { + const probe = dependencies.probeLicense + ? await dependencies.probeLicense() + : await probeLicenseStatus() + if (probe.ok) { + const mapped = mapLicenseStatus(probe.status) + if (mapped.entitlement === 'valid') { + return { ok: true, message: '授权有效', source: 'mac_license' } + } + } + } const status = dependencies.getMacLicense ? await dependencies.getMacLicense() : await macWechatRuntimeManager.getMacLicenseStatus() diff --git a/src/main/index.ts b/src/main/index.ts index 13309ac..3dc0081 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -668,9 +668,7 @@ import type { } from '../shared/wechat-share-card' async function currentPersonalWechatSenderStatus(): Promise { - return process.platform === 'darwin' - ? macWechatRuntimeManager.buildSenderStatus() - : personalWechatSendService.getStatus() + return personalWechatSendService.getStatus() } // electron-vite can close the child's stdout/stderr after spawning Electron. diff --git a/src/main/native-runtime-paths.ts b/src/main/native-runtime-paths.ts index d15e02d..f7de43e 100644 --- a/src/main/native-runtime-paths.ts +++ b/src/main/native-runtime-paths.ts @@ -3,6 +3,7 @@ import path from 'node:path' import { app } from 'electron' import { findResource } from './resource-paths' +import { resolveExternalComponent } from './services/external-component-locator' export type NativeRuntimeProfile = 'public' | 'native' @@ -34,7 +35,10 @@ function getNativeRuntimeProfile(): NativeRuntimeProfile { } export function hasMacNativeBundle(): boolean { - return process.platform === 'darwin' && getNativeRuntimeProfile() === 'native' + return ( + process.platform === 'darwin' && + (getNativeRuntimeProfile() === 'native' || resolveExternalComponent() !== null) + ) } export function isMacNativeRuntimeUnavailable(): boolean { @@ -43,6 +47,11 @@ export function isMacNativeRuntimeUnavailable(): boolean { export function resolveWcdbLibrary(): string | null { if (process.platform !== 'darwin') return null + const external = resolveExternalComponent() + if (external) { + const candidate = path.join(external.dir, 'libwcdb_api.dylib') + if (fs.existsSync(candidate)) return candidate + } const arch = process.arch === 'arm64' ? 'arm64' : 'x64' return findResource(`wcdb/macos/${arch}/libwcdb_api.dylib`) } @@ -56,12 +65,18 @@ export function resolveWcdbDependency(): string | null { export function resolveWcdbConfigHelper(): string | null { if (isMacNativeRuntimeUnavailable()) return null + const external = resolveExternalComponent() + if (external && fs.existsSync(external.helperPath)) return external.helperPath 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 external = resolveExternalComponent() + if (external && fs.existsSync(path.join(external.dir, 'runtime-manifest.json'))) { + return external.dir + } const manifest = findResource(`${RUNTIME_RELATIVE}/runtime-manifest.json`) || (!app.isPackaged ? findResource('runtime/darwin-arm64/runtime-manifest.json') : null) diff --git a/src/main/services/external-component-locator.ts b/src/main/services/external-component-locator.ts index 1fdba24..15d168a 100644 --- a/src/main/services/external-component-locator.ts +++ b/src/main/services/external-component-locator.ts @@ -21,7 +21,8 @@ interface ManifestFile { sha256?: unknown } -const HELPER_NAME = 'tm-wcdb-config-helper.exe' +const WIN_HELPER_NAME = 'tm-wcdb-config-helper.exe' +const MAC_HELPER_NAME = 'tm-wcdb-config-helper' const verifyCache = new Map() @@ -84,18 +85,30 @@ function verifyManifest(dir: string): { ok: boolean; dirty: boolean } { } /** - * 返回发送能力组件位置;不存在、校验失败、非 Windows 一律返回 null。 + * 返回发送能力组件位置;不存在、校验失败或不支持平台一律返回 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') + if (platform !== 'win32' && platform !== 'darwin') return null + let root = '' + let helperName = '' + if (platform === 'win32') { + const localAppData = env.LOCALAPPDATA + if (!env.TRACEMEMO_PRO_ROOT && !localAppData) return null + root = + env.TRACEMEMO_PRO_ROOT || path.join(localAppData || '', 'TraceMemo', 'Pro', 'windows-x64') + helperName = WIN_HELPER_NAME + } else { + const home = env.HOME + if (!env.TRACEMEMO_PRO_ROOT && !home) return null + root = + env.TRACEMEMO_PRO_ROOT || + path.join(home || '', 'Library', 'Application Support', 'TraceMemo', 'Pro', 'macos-arm64') + helperName = MAC_HELPER_NAME + } const pointerPath = path.join(root, 'current.json') if (!fs.existsSync(pointerPath)) return null @@ -118,7 +131,7 @@ export function resolveExternalComponent( return null } - const helperPath = path.join(dir, HELPER_NAME) + const helperPath = path.join(dir, helperName) if (!fs.existsSync(helperPath)) return null const verified = verifyManifest(dir) diff --git a/src/main/services/mac-wechat-runtime-manager.ts b/src/main/services/mac-wechat-runtime-manager.ts index a10bfe7..50a2584 100644 --- a/src/main/services/mac-wechat-runtime-manager.ts +++ b/src/main/services/mac-wechat-runtime-manager.ts @@ -1,6 +1,8 @@ import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process' +import { createECDH, createHash } from 'node:crypto' +import { homedir } from 'node:os' import { promisify } from 'node:util' -import { chmodSync, existsSync } from 'fs' +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs' import { get, request as httpRequest } from 'http' import { join } from 'path' @@ -63,6 +65,65 @@ const CRASH_RESTART_DELAY_MS = 1_500 * 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 +const P256_SPKI_PREFIX = Buffer.from('3059301306072a8648ce3d020106082a8648ce3d030107034200', 'hex') + +export function ensureLocalMacDeviceId(baseHomeDir: string = homedir()): string | null { + if (process.platform !== 'darwin') return null + try { + const cleanHome = baseHomeDir.includes('/Library/Containers/') + ? baseHomeDir.slice(0, baseHomeDir.indexOf('/Library/Containers/')) + : baseHomeDir + const nativeRoot = join(cleanHome, 'Library', 'Application Support', 'TraceMemoNative') + const identityDir = join(nativeRoot, 'identity') + const keyPath = join(identityDir, 'device-key.sec1') + const cachePath = join(nativeRoot, 'identity.json') + + if (existsSync(keyPath)) { + const sec1 = readFileSync(keyPath) + if (sec1.length === 97 && sec1[0] === 0x04) { + const pubX963 = sec1.subarray(0, 65) + const spki = Buffer.concat([P256_SPKI_PREFIX, pubX963]) + return `mac_${createHash('sha256').update(spki).digest('hex')}` + } + } + + if (existsSync(cachePath)) { + const cached = JSON.parse(readFileSync(cachePath, 'utf8')) as { device_id?: unknown } + if (typeof cached.device_id === 'string' && /^mac_[0-9a-f]{64}$/.test(cached.device_id)) { + return cached.device_id + } + } + + mkdirSync(identityDir, { recursive: true, mode: 0o700 }) + chmodSync(identityDir, 0o700) + const ecdh = createECDH('prime256v1') + ecdh.generateKeys() + const pub = ecdh.getPublicKey() + const rawPriv = ecdh.getPrivateKey() + const priv = + rawPriv.length === 32 + ? rawPriv + : Buffer.concat([Buffer.alloc(Math.max(0, 32 - rawPriv.length)), rawPriv.subarray(-32)]) + const sec1 = Buffer.concat([pub, priv]) + writeFileSync(keyPath, sec1, { mode: 0o600 }) + chmodSync(keyPath, 0o600) + + const spki = Buffer.concat([P256_SPKI_PREFIX, pub]) + const deviceId = `mac_${createHash('sha256').update(spki).digest('hex')}` + const cachePayload = JSON.stringify({ + version: 1, + device_id: deviceId, + spki_base64: spki.toString('base64'), + key_kind: 'file', + exportable: true + }) + writeFileSync(cachePath, cachePayload, { mode: 0o600 }) + chmodSync(cachePath, 0o600) + return deviceId + } catch { + return null + } +} /* 仅地址占用可以通过切换端口恢复。 */ function isPortConflictDiagnostic(diagnostic: string): boolean { @@ -839,37 +900,66 @@ export class MacWechatRuntimeManager { /** Local snapshot. Never attaches to WeChat, never forces a network refresh. * 404 means the host predates these endpoints — not "unlicensed". */ async getMacLicenseStatus(): Promise { + const localDeviceId = ensureLocalMacDeviceId() + const withDeviceId = (result: MacLicenseStatus): MacLicenseStatus => ({ + ...result, + deviceId: result.deviceId || localDeviceId + }) + + const { status: directStatus, body: directBody } = await this.request( + 'GET', + '/license/status', + 1_500 + ) + if (directStatus === 200) { + try { + return withDeviceId(parseMacLicenseStatus(JSON.parse(directBody))) + } catch { + // 继续走后续兜底 + } + } + const availability = this.getSendRuntimeAvailability() if (availability.state === 'unavailable') { - return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力') + return withDeviceId( + offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力') + ) } if (availability.state !== 'available') { - return offlineMacLicenseStatus('runtime_missing', availability.message) + return withDeviceId(offlineMacLicenseStatus('runtime_missing', availability.message)) } if (this.manuallyStopped) { - return offlineMacLicenseStatus( - 'runtime_missing', - 'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。' + return withDeviceId( + offlineMacLicenseStatus( + 'runtime_missing', + 'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。' + ) ) } 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 发送组件未运行,请先启动发送组件') + return withDeviceId( + offlineMacLicenseStatus('runtime_missing', 'Mac 发送组件未运行,请先启动发送组件') + ) } if (status === 404) { - return offlineMacLicenseStatus( - 'unsupported', - '当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。' + return withDeviceId( + offlineMacLicenseStatus( + 'unsupported', + '当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。' + ) ) } if (status !== 200) { - return offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`) + return withDeviceId( + offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`) + ) } try { - return parseMacLicenseStatus(JSON.parse(body)) + return withDeviceId(parseMacLicenseStatus(JSON.parse(body))) } catch { - return offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析') + return withDeviceId(offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析')) } } diff --git a/src/main/services/personal-wechat-capability-service.ts b/src/main/services/personal-wechat-capability-service.ts index 2619375..2df0e2c 100644 --- a/src/main/services/personal-wechat-capability-service.ts +++ b/src/main/services/personal-wechat-capability-service.ts @@ -7,7 +7,6 @@ import { personalWechatSendService, type PersonalWechatSendService } from './personal-wechat-send-service' -import { macWechatRuntimeManager } from './mac-wechat-runtime-manager' /** * Converts the detailed sender diagnostics into a small contract that other @@ -22,7 +21,7 @@ export class PersonalWechatCapabilityService { private readonly sender: Pick, private readonly platform: NodeJS.Platform = process.platform, private readonly getMacStatus: () => Promise = () => - macWechatRuntimeManager.buildSenderStatus() + personalWechatSendService.getStatus() ) {} async getPersonalWechatSendCapability(): Promise { @@ -84,6 +83,7 @@ export class PersonalWechatCapabilityService { if (senderStatus.platform !== 'darwin' || senderStatus.state === 'unsupported_platform') { return 'unsupported' } + if (!senderStatus.endpoint) return 'unconfigured' if (senderStatus.state === 'error') return 'error' if (senderStatus.state === 'runtime_missing') return 'unconfigured' const hasCurrentBinding = Boolean( diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts index e89aef5..a2ac5fa 100644 --- a/src/main/services/personal-wechat-send-service.ts +++ b/src/main/services/personal-wechat-send-service.ts @@ -368,6 +368,9 @@ function prepareMacWechatImageFile( } } +const MAC_IMAGE_STAGE_PREFIX = 'tm-' +const MAC_IMAGE_STAGE_RETENTION_MS = 10 * 60 * 1000 + function stageMacWechatImageForMessageSourceSend( filePath: string, senderWxid: string, @@ -376,6 +379,29 @@ function stageMacWechatImageForMessageSourceSend( const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid) if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录') mkdirSync(temporaryRoot, { recursive: true }) + + /* + * 暂存图**不能**在 /sendMsg 返回后立即删除:`ok: true` 只代表 Host 已接受请求, + * 微信侧是异步读取这个文件的,删早了消息会静默丢失(API 仍回 sent)。 + * 改为按保留期回收,顺手清理超过 10 分钟的历史暂存图,防止异常退出残留。 + */ + const now = Date.now() + try { + for (const entry of readdirSync(temporaryRoot)) { + if (!entry.startsWith(MAC_IMAGE_STAGE_PREFIX)) continue + const candidate = join(temporaryRoot, entry) + try { + if (now - statSync(candidate).mtimeMs > MAC_IMAGE_STAGE_RETENTION_MS) { + unlinkSync(candidate) + } + } catch { + // Best-effort stale image cleanup. + } + } + } catch { + // Ignore directory listing errors. + } + const extension = extname(filePath).toLowerCase() const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png' const stagedPath = join( @@ -386,6 +412,21 @@ function stageMacWechatImageForMessageSourceSend( return stagedPath } +/** + * 延迟回收暂存图:微信在 `/sendMsg` 返回后才异步读取该文件, + * 立即删除会让消息静默丢失;与视频/文件暂存保持同样的「延迟清理」策略。 + */ +function scheduleStagedImageCleanup(stagedPath: string): void { + const timer = setTimeout(() => { + try { + unlinkSync(stagedPath) + } catch { + // Best-effort delayed cleanup after WeChat finishes asynchronous image upload. + } + }, 120_000) + timer.unref?.() +} + const MAC_VIDEO_STAGE_PREFIX = 'tm-video-' const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000 @@ -784,24 +825,39 @@ export class PersonalWechatSendService { constructor(private readonly wechatFilesRoot = WECHAT_FILES_ROOT) {} async getStatus(): Promise { - // macOS 发送能力完全由 native runtime(tm-wechat-host)提供, - // 这里保持同源,避免出现第二套状态判断。 - if (process.platform === 'darwin') return macWechatRuntimeManager.buildSenderStatus() + if (process.platform === 'darwin') { + const configuredPort = normalizeWindowsWechatPort(loadSettings().windowsWechatPort) + if (!configuredPort) { + const base = windowsStatusBase('') + return { + ...base, + platform: 'darwin', + arch: process.arch, + state: 'error', + message: '尚未配置微信发送能力端口', + error: '请先输入端口并检测后保存' + } + } + return this.getMacPortStatus(configuredPort) + } return this.getWindowsStatus() } async checkWindowsStatus(port?: string): Promise { - if (process.platform !== 'win32') return this.getStatus() + if (process.platform !== 'win32' && process.platform !== 'darwin') return this.getStatus() const normalizedPort = normalizeWindowsWechatPort(port) if (!normalizedPort) { const base = windowsStatusBase() return { ...base, + platform: process.platform, + arch: process.arch, state: 'error', message: '请输入 1 到 65535 之间的微信发送能力端口', error: '端口格式无效或为空' } } + if (process.platform === 'darwin') return this.getMacPortStatus(normalizedPort) return this.getWindowsStatus(normalizedPort) } @@ -834,7 +890,111 @@ export class PersonalWechatSendService { } async rebind(): Promise { - return this.getWindowsStatus() + return this.getStatus() + } + + private resolveMacHostPort(): number { + const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort) + if (configured) return Number(configured) + return macWechatRuntimeManager.getPort() + } + + private async ensureMacSenderReady(): Promise { + const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort) + if (configured) { + return this.getMacPortStatus(configured) + } + await macWechatRuntimeManager.ensureStarted() + return macWechatRuntimeManager.buildSenderStatus() + } + + private async resolveMacCurrentStatus(): Promise { + const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort) + if (configured) { + return this.getMacPortStatus(configured) + } + return macWechatRuntimeManager.buildSenderStatus() + } + + private async resolveMacSendMechanism(versionHint?: string): Promise { + const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort) + if (!configured) { + return macWechatRuntimeManager.getSendMechanism() + } + const ver = String(versionHint || '').trim() + if (ver.startsWith('4.1.11.')) return 'legacy-req2buf' + if (ver.startsWith('4.1.13.')) return 'native-msg-object' + return 'tm-message-source-send' + } + + private async getMacPortStatus(port?: string): Promise { + const host = windowsHookHost(port) + const base: PersonalWechatSenderStatus = { + ...windowsStatusBase(host || ''), + platform: 'darwin', + arch: process.arch + } + if (!host) { + return { + ...base, + state: 'error', + message: '尚未配置微信发送能力端口', + error: '请先输入端口并检测后保存' + } + } + try { + const result = await requestWindowsHook('/getLoginInfo', {}, 15_000, 'GET', host) + const loggedIn = parseWindowsLoginStatus(result) + const pid = typeof result.pid === 'number' && result.pid > 0 ? result.pid : 1 + const wechatVersion = typeof result.version === 'string' ? result.version : '4.1.15.55' + const connected = { + wechatRunning: true, + wechatPid: pid, + boundWechatPid: pid, + wechatVersion, + runtimeReady: true, + endpointReady: true, + attachReady: true, + baseAddressReady: true, + textHookInstalled: true, + textHookReady: loggedIn, + imageHookInstalled: loggedIn, + imageHookReady: loggedIn, + messageListenerReady: loggedIn + } + if (!loggedIn) { + const msg = + typeof result.message === 'string' && result.message.trim() + ? result.message.trim() + : '微信发送能力已连接,但微信尚未登录或尚未完成绑定' + return { + ...base, + ...connected, + state: 'hook_not_ready', + message: msg, + error: typeof result.error === 'string' && result.error.trim() ? result.error.trim() : msg + } + } + return { + ...base, + ...connected, + state: 'online' as const, + canSend: true, + canSendText: true, + canSendImage: true, + canSendVoice: true, + canSendVideo: true, + canSendFile: true, + message: '微信发送能力已连接,可以发送消息' + } + } catch (error) { + return { + ...base, + state: 'wechat_not_running', + message: '未检测到微信发送能力,请先通过授权管理器注入并启动微信', + error: error instanceof Error ? error.message : String(error) + } + } } private async getWindowsStatus(port?: string): Promise { @@ -899,8 +1059,7 @@ export class PersonalWechatSendService { private async sendMacText( request: Extract ): Promise { - await macWechatRuntimeManager.ensureStarted() - const initialStatus = await macWechatRuntimeManager.buildSenderStatus() + const initialStatus = await this.ensureMacSenderReady() if (!initialStatus.canSendText) { return { success: false, @@ -908,7 +1067,7 @@ export class PersonalWechatSendService { error: initialStatus.message || '微信发送能力未就绪' } } - const sendMechanism = await macWechatRuntimeManager.getSendMechanism() + const sendMechanism = await this.resolveMacSendMechanism(initialStatus.wechatVersion) if (request.at && sendMechanism !== 'tm-message-source-send') { return { success: false, @@ -928,7 +1087,7 @@ export class PersonalWechatSendService { }, 50_000 ) - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() if (!result?.ok) { return { success: false, status, error: result?.message || '文字发送失败' } } @@ -940,7 +1099,7 @@ export class PersonalWechatSendService { text: request.text, isGroup: Boolean(request.isGroup) }) - const response = await fetch(`http://127.0.0.1:${macWechatRuntimeManager.getPort()}/sendText`, { + const response = await fetch(`http://127.0.0.1:${this.resolveMacHostPort()}/sendText`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload, @@ -948,7 +1107,7 @@ export class PersonalWechatSendService { }).catch(() => null) if (response === null || !response.ok) { - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() return { success: false, status, @@ -957,7 +1116,7 @@ export class PersonalWechatSendService { } const result = (await response.json()) as { code: number; ok: boolean; message: string } - const resultStatus = await macWechatRuntimeManager.buildSenderStatus() + const resultStatus = await this.resolveMacCurrentStatus() if (!result.ok) { return { success: false, status: resultStatus, error: result.message || '发送失败' } } @@ -975,7 +1134,7 @@ export class PersonalWechatSendService { body: Record, timeoutMs: number ): Promise<{ code: number; ok: boolean; message: string } | null> { - const response = await fetch(`http://127.0.0.1:${macWechatRuntimeManager.getPort()}${path}`, { + const response = await fetch(`http://127.0.0.1:${this.resolveMacHostPort()}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), @@ -1000,8 +1159,7 @@ export class PersonalWechatSendService { private async sendMacVideo( request: Extract ): Promise { - await macWechatRuntimeManager.ensureStarted() - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.ensureMacSenderReady() if (!status.canSendVideo) { return { success: false, @@ -1022,7 +1180,7 @@ export class PersonalWechatSendService { try { staged = stageMacWechatVideoForSend(filePath, this.wechatFilesRoot) } catch (error) { - const latest = await macWechatRuntimeManager.buildSenderStatus() + const latest = await this.resolveMacCurrentStatus() return { success: false, status: latest, @@ -1036,7 +1194,7 @@ export class PersonalWechatSendService { { toWxid: request.to, type: 'video', msg: staged.stagedPath }, 180_000 ) - const latest = await macWechatRuntimeManager.buildSenderStatus() + const latest = await this.resolveMacCurrentStatus() if (!result?.ok) { return { success: false, status: latest, error: result?.message || '视频发送失败' } } @@ -1049,8 +1207,7 @@ export class PersonalWechatSendService { private async sendMacFile( request: Extract ): Promise { - await macWechatRuntimeManager.ensureStarted() - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.ensureMacSenderReady() if (!status.canSendFile) { return { success: false, @@ -1072,7 +1229,7 @@ export class PersonalWechatSendService { try { staged = stageMacWechatFileForSend(filePath, this.wechatFilesRoot) } catch (error) { - const latest = await macWechatRuntimeManager.buildSenderStatus() + const latest = await this.resolveMacCurrentStatus() return { success: false, status: latest, @@ -1086,7 +1243,7 @@ export class PersonalWechatSendService { { to: request.to, type: 'file', path: staged.stagedPath, name: fileName }, 180_000 ) - const latest = await macWechatRuntimeManager.buildSenderStatus() + const latest = await this.resolveMacCurrentStatus() if (!result?.ok) { return { success: false, status: latest, error: result?.message || '文件发送失败' } } @@ -1099,10 +1256,9 @@ export class PersonalWechatSendService { private async sendMacImage( request: Extract ): Promise { - await macWechatRuntimeManager.ensureStarted() - const initialStatus = await macWechatRuntimeManager.buildSenderStatus() + const initialStatus = await this.ensureMacSenderReady() const fail = async (error: string): Promise => { - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() return { success: false, status, error } } if (!initialStatus.canSendImage) { @@ -1110,7 +1266,7 @@ export class PersonalWechatSendService { } const filePath = String(request.filePath || '').trim() if (!filePath || !existsSync(filePath)) return fail('请选择有效的图片文件') - const sendMechanism = await macWechatRuntimeManager.getSendMechanism() + const sendMechanism = await this.resolveMacSendMechanism(initialStatus.wechatVersion) const sender = await this.resolveMacSenderWxid() if (!sender) return fail('无法识别当前微信账号 wxid') if (sendMechanism === 'tm-message-source-send') { @@ -1123,22 +1279,20 @@ export class PersonalWechatSendService { { type: 'image', to: request.to, path: stagedPath }, 55_000 ) - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() if (!sent?.ok) { sourceError = sent?.message || '图片发送失败' } else { + /* + * 不能在这里 unlink:微信在 /sendMsg 返回后仍会异步读取该文件, + * 删早了消息会静默丢失,而 API 已经返回 success。 + * 改为延迟回收(2 分钟)+ 下次发送时清扫过期文件。 + */ + if (stagedPath) scheduleStagedImageCleanup(stagedPath) return { success: true, status } } } catch (error) { sourceError = error instanceof Error ? error.message : String(error) - } finally { - if (stagedPath) { - try { - unlinkSync(stagedPath) - } catch { - // Best-effort cleanup after WeChat has consumed the staged image. - } - } } if (!isDefinitiveImageSourcePreparationFailure(sourceError)) return fail(sourceError) } @@ -1159,7 +1313,7 @@ export class PersonalWechatSendService { if (!sent || !sent.ok) { return fail(sent?.message || '图片发送失败') } - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() return { success: true, status } } catch (error) { return fail(error instanceof Error ? error.message : String(error)) @@ -1178,14 +1332,13 @@ export class PersonalWechatSendService { request: Extract ): Promise { const requestId = randomUUID() - await macWechatRuntimeManager.ensureStarted() - const initialStatus = await macWechatRuntimeManager.buildSenderStatus() + const initialStatus = await this.ensureMacSenderReady() const fail = async ( error: string, failurePhase = 'preflight' ): Promise => { logVoiceAttempt(requestId, 'failed', { failure_phase: failurePhase, error }) - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() return { success: false, status, error } } if (!initialStatus.canSendVoice) { @@ -1193,7 +1346,7 @@ export class PersonalWechatSendService { } const filePath = String(request.filePath || '').trim() if (!filePath || !existsSync(filePath)) return fail('请选择有效的语音文件') - const sendMechanism = await macWechatRuntimeManager.getSendMechanism() + const sendMechanism = await this.resolveMacSendMechanism(initialStatus.wechatVersion) let sender = '' if (sendMechanism !== 'tm-message-source-send') { sender = await this.resolveMacSenderWxid() @@ -1235,7 +1388,7 @@ export class PersonalWechatSendService { if (!sent?.ok) { return fail(sent?.message || '语音发送失败', 'send') } - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() logVoiceAttempt(requestId, 'completed', { send_result: '0' }) return { success: true, status } } @@ -1257,7 +1410,7 @@ export class PersonalWechatSendService { if (!sent || !sent.ok) { return fail(sent?.message || '语音发送失败', 'send') } - const status = await macWechatRuntimeManager.buildSenderStatus() + const status = await this.resolveMacCurrentStatus() logVoiceAttempt(requestId, 'completed', { send_result: '0' }) return { success: true, status } } finally { diff --git a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx index 63cc44d..4fab324 100644 --- a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx +++ b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react' +import { useCallback, useEffect, useState, type ReactElement } from 'react' import type { PersonalWechatSendCapability, PersonalWechatSenderStatus @@ -7,22 +7,11 @@ 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 { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, Button, Input, Skeleton } from '../../../components/ui' -import { PersonalWechatSetupGuide } from '../../../components/chat/PersonalWechatSetupGuide' import { isMac, isWindows } from '../../../utils/runtime-environment' const REPOSITORY_URL = 'https://github.com/Wxw-Gu/TraceMemo' @@ -45,31 +34,65 @@ function normalizeWindowsPort(value: string): string | null { return Number.isInteger(port) && port >= 1 && port <= 65_535 ? String(port) : null } -function getEndpointPort(endpoint: string | undefined): string | null { - if (!endpoint) return null - try { - return new URL(endpoint).port || null - } catch { - return null +function SendCapabilityAuthorizationCard({ + onNotice +}: { + onNotice?: (message: string) => void +}): ReactElement { + const [deviceId, setDeviceId] = useState(null) + const [copied, setCopied] = useState(false) + + useEffect(() => { + if (!isMac) return + let cancelled = false + void (async () => { + try { + const status = await window.api.getMacLicenseStatus?.() + if (!cancelled && status?.deviceId) { + setDeviceId(status.deviceId) + } + } catch { + // 忽略读取异常 + } + })() + return () => { + cancelled = true + } + }, []) + + const copyDeviceId = async (): Promise => { + if (!deviceId) return + try { + await navigator.clipboard.writeText(deviceId) + setCopied(true) + onNotice?.('设备 ID 已复制') + window.setTimeout(() => setCopied(false), 2_000) + } catch { + onNotice?.('复制失败,请手动选择设备 ID 复制') + } } -} -function boundToCurrentWechat(status: PersonalWechatSenderStatus | null): boolean { - if (!status) return false return ( - status.state === 'online' || - Boolean( - status.wechatPid && - status.boundWechatPid === status.wechatPid && - status.attachReady && - status.baseAddressReady - ) - ) -} - -function SendCapabilityAuthorizationCard(): ReactElement { - return ( -
+
+ {isMac ? ( +
+
+ 本机设备 ID + + {deviceId ? summarizeDeviceId(deviceId) : '(尚未生成)'} + +
+ +
+ ) : null}

发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。

进群请点击{' '} @@ -290,16 +313,14 @@ export function MacNativeLicenseCard({ } export function PersonalWechatSendPage({ - onNotice, - onOpenTextToSpeechSettings + onNotice }: { onNotice: (message: string) => void onOpenTextToSpeechSettings?: () => void }): ReactElement { + const isPortEndpointPlatform = isWindows || isMac const [capability, setCapability] = useState(null) - const [senderStatus, setSenderStatus] = useState(null) const [loading, setLoading] = useState(true) - const [binding, setBinding] = useState(false) const [detecting, setDetecting] = useState(false) const [error, setError] = useState('') const [windowsSenderStatus, setWindowsSenderStatus] = useState( @@ -308,132 +329,48 @@ export function PersonalWechatSendPage({ const [windowsPortInput, setWindowsPortInput] = useState('') const [windowsDetectedPort, setWindowsDetectedPort] = useState('') const [windowsEndpointBusy, setWindowsEndpointBusy] = useState(false) - const [setupExpanded, setSetupExpanded] = useState(null) - const [macLicenseStatus, setMacLicenseStatus] = useState(null) - const [macRuntimeAvailability, setMacRuntimeAvailability] = - useState(null) - const [macResidualProcesses, setMacResidualProcesses] = useState< - Awaited> - >([]) - const [macResidualDialogOpen, setMacResidualDialogOpen] = useState(false) - const [macResidualBusy, setMacResidualBusy] = useState(false) - const [macWechatRebindRequired, setMacWechatRebindRequired] = useState(false) - const [mac4290PortStatus, setMac4290PortStatus] = useState< - | { state: 'loading' | 'available' | 'error'; processes: [] } - | { state: 'occupied'; processes: Array<{ pid: number; name: string }> } - >({ state: 'loading', processes: [] }) - const setupDefaultInitialized = useRef(false) - const refreshMac4290PortStatus = useCallback(async (): Promise => { - try { - const processes = await window.api.listMacWechatResidualProcesses() - const listeners = processes - .filter((process) => process.targets.includes('port_4290')) - .map(({ pid, name }) => ({ pid, name })) - setMac4290PortStatus( - listeners.length > 0 - ? { state: 'occupied', processes: listeners } - : { state: 'available', processes: [] } - ) - } catch { - setMac4290PortStatus({ state: 'error', processes: [] }) - } - }, []) + const refresh = useCallback(async (): Promise => { - if (isWindows) { - setLoading(false) + if (isPortEndpointPlatform) { + try { + const settingsResult = await window.api.getSettings?.() + const configuredPort = String(settingsResult?.settings?.windowsWechatPort || '').trim() + if (configuredPort) { + const status = await window.api.getPersonalWechatSenderStatus() + setWindowsSenderStatus(status) + } else { + setWindowsSenderStatus(null) + } + } catch { + // 状态刷新失败保留现有展示 + } finally { + setLoading(false) + } return } setError('') try { const nextCapability = await window.api.getPersonalWechatSendCapability() setCapability(nextCapability) - setSenderStatus(nextCapability.senderStatus) } catch (reason) { setError(reason instanceof Error ? reason.message : '微信发送能力读取失败') } finally { setLoading(false) } - }, []) + }, [isPortEndpointPlatform]) useEffect(() => { - if (isWindows) return + if (isPortEndpointPlatform) return + void refresh() + }, [isPortEndpointPlatform, refresh]) + + useEffect(() => { + if (!isPortEndpointPlatform) return let active = true - const loadMacStatus = async (): Promise => { + const loadPortEndpoint = async (): Promise => { 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, license] = await Promise.all([ - window.api.getPersonalWechatSendCapability(), - window.api.getMacLicenseStatus() - ]) - if (!active) return - setCapability(nextCapability) - setSenderStatus(nextCapability.senderStatus) - 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(() => { - if (!isMac) return undefined - void refreshMac4290PortStatus() - const timer = window.setInterval(() => void refreshMac4290PortStatus(), 5_000) - return () => window.clearInterval(timer) - }, [refreshMac4290PortStatus]) - - useEffect(() => { - if (isWindows || !senderStatus || senderStatus.canSend || senderStatus.state === 'error') { - return undefined - } - if (!boundToCurrentWechat(senderStatus)) return undefined - const timer = window.setInterval(() => void refresh(), 1_000) - return () => window.clearInterval(timer) - }, [refresh, senderStatus]) - - useEffect(() => { - if (!isWindows) return - let active = true - const loadWindowsEndpoint = async (): Promise => { - try { - const settingsResult = await window.api.getSettings() - const configuredPort = String(settingsResult.settings.windowsWechatPort || '').trim() + const settingsResult = await window.api.getSettings?.() + const configuredPort = String(settingsResult?.settings?.windowsWechatPort || '').trim() if (!active) return setWindowsPortInput(configuredPort) if (configuredPort) { @@ -449,34 +386,14 @@ export function PersonalWechatSendPage({ setLoading(false) } } - void loadWindowsEndpoint() + void loadPortEndpoint() return () => { active = false } - }, [refresh]) - - const bindWechat = async (): Promise => { - if (binding) return - setBinding(true) - setError('') - try { - const nextStatus = await window.api.rebindPersonalWechatSender() - setSenderStatus(nextStatus) - if (boundToCurrentWechat(nextStatus)) { - setMacWechatRebindRequired(false) - } - const nextCapability = await window.api.getPersonalWechatSendCapability() - setCapability(nextCapability) - if (nextStatus.state === 'error' && nextStatus.message) setError(nextStatus.message) - } catch (reason) { - setError(reason instanceof Error ? reason.message : '个人微信绑定失败') - } finally { - setBinding(false) - } - } + }, [isPortEndpointPlatform, refresh]) const detectCapability = async (): Promise => { - if (isWindows) { + if (isPortEndpointPlatform) { await detectWindowsEndpoint() return } @@ -489,91 +406,6 @@ export function PersonalWechatSendPage({ } } - const inspectMacResidualProcesses = async (): Promise => { - if (macResidualBusy) return - setMacResidualBusy(true) - try { - const targets = await window.api.listMacWechatResidualProcesses() - setMacResidualProcesses(targets) - const listeners = targets - .filter((process) => process.targets.includes('port_4290')) - .map(({ pid, name }) => ({ pid, name })) - setMac4290PortStatus( - listeners.length > 0 - ? { state: 'occupied', processes: listeners } - : { state: 'available', processes: [] } - ) - if (targets.length === 0) { - setMacResidualBusy(false) - await restartMacSendRuntime() - return - } - setMacResidualDialogOpen(true) - } catch (reason) { - onNotice(reason instanceof Error ? reason.message : '读取残留进程失败') - } finally { - setMacResidualBusy(false) - } - } - - const cleanupMacResidualProcesses = async (): Promise => { - if (macResidualBusy || macResidualProcesses.length === 0) return - setMacResidualBusy(true) - try { - const result = await window.api.cleanupMacWechatResidualProcesses( - macResidualProcesses.map(({ pid, confirmationToken }) => ({ pid, confirmationToken })) - ) - if (result.stopped.some((target) => target.targets.includes('wechat'))) { - setMacWechatRebindRequired(true) - } - const stillAlive = result.remaining - setMacResidualProcesses([]) - setMacResidualDialogOpen(false) - await refreshMac4290PortStatus() - if (stillAlive.length > 0) { - onNotice( - `${result.stopped.length} 个进程已退出,${stillAlive.length} 个系统无法结束(${stillAlive - .map((target) => target.name) - .join('、')});正在改用可用端口启动发送组件…` - ) - } - await restartMacSendRuntime() - } catch (reason) { - onNotice(reason instanceof Error ? reason.message : '清理残留进程失败') - } finally { - setMacResidualBusy(false) - } - } - - const restartMacSendRuntime = async (): Promise => { - setMacResidualBusy(true) - try { - const snapshot = await window.api.startMacSendRuntime() - if (snapshot.lifecycle !== 'online') { - throw new Error(snapshot.error || '发送组件启动失败') - } - if (snapshot.binding?.runtimeState === 'ready' && snapshot.binding.bound) { - onNotice('发送 Host 已启动并连接到已有微信会话。') - } - await refresh() - await refreshMac4290PortStatus() - if (!snapshot.binding?.bound) { - const fallback = snapshot.portFallbackFrom - ? `${snapshot.portFallbackFrom} 已被占用,已改用 ${snapshot.port} 端口。` - : '' - onNotice( - fallback - ? `发送 Host 已在 ${snapshot.port} 端口启动。${fallback}` - : '已清理并重启发送 Host;如刚才关闭了微信,请重新打开微信并绑定。' - ) - } - } catch (reason) { - onNotice(reason instanceof Error ? reason.message : '发送组件启动失败') - } finally { - setMacResidualBusy(false) - } - } - const normalizedWindowsPort = normalizeWindowsPort(windowsPortInput) const windowsCanSave = Boolean( normalizedWindowsPort && @@ -648,7 +480,7 @@ export function PersonalWechatSendPage({ const status = capability?.status || 'error' const ready = capability?.ready === true - const pageStatus: PersonalWechatSendCapability['status'] = isWindows + const pageStatus: PersonalWechatSendCapability['status'] = isPortEndpointPlatform ? windowsSenderStatus?.canSend ? 'ready' : windowsSenderStatus?.state === 'error' && windowsSenderStatus.endpointReady @@ -657,420 +489,158 @@ export function PersonalWechatSendPage({ ? 'initializing' : 'unconfigured' : status - const pageReady = isWindows ? Boolean(windowsSenderStatus?.canSend) : ready - const pageCapabilities = isWindows + const pageReady = isPortEndpointPlatform ? Boolean(windowsSenderStatus?.canSend) : ready + const pageCapabilities = isPortEndpointPlatform ? { text: Boolean(windowsSenderStatus?.canSendText), image: Boolean(windowsSenderStatus?.canSendImage), voice: Boolean(windowsSenderStatus?.canSendVoice) } : capability?.capabilities || { text: false, image: false, voice: false } - const pageMessage = isWindows - ? windowsSenderStatus?.message || '请输入端口并检测 Windows 微信发送能力' + const platformDisplayName = isMac ? 'macOS' : 'Windows' + const pageMessage = isPortEndpointPlatform + ? windowsSenderStatus?.message || `请输入端口并检测 ${platformDisplayName} 微信发送能力` : capability?.message || '微信发送能力暂不可用' - const macUnavailable = isMac && macRuntimeAvailability?.state === 'unavailable' - const macComponentError = isMac && macRuntimeAvailability?.state === 'component_error' - const macBound = boundToCurrentWechat(senderStatus) - const macSendPort = getEndpointPort(senderStatus?.endpoint) - 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 ( - <> -

-
-
-

微信发送

-

管理个人微信消息发送能力,日报和档案发送都会使用这里的状态。

-
- - {loading - ? '检测中' - : macUnavailable - ? '没有微信发送能力' - : macComponentError - ? '发送组件异常' - : capabilityLabel[pageStatus]} - -
-
-
- {loading && !capability ? ( - - ) : ( - <> - {/* macOS 走下方「配置状态」SetupGuide 统一展示,这里只在 Windows/其它 - * 平台显示旧「发送能力」卡(Mac 上两者重复,已按用户要求移除)。 */} - {!isMac ? ( - <> -

发送能力

-
-
-
- 个人微信 - {pageMessage} -

- {pageStatus === 'unsupported' - ? '微信消息发送目前仅支持 macOS 和 Windows。' - : isWindows - ? 'Windows 通过本机微信发送接口工作,请先配置并检测接口端口。' - : '档案中的文字、图片和语音发送,以及定时日报发送,都会使用这项能力。'} -

-
- -
-
- {( - [ - ['文字', pageCapabilities.text], - ['图片', pageCapabilities.image], - ['语音', pageCapabilities.voice] - ] as const - ).map(([label, available]) => ( -
- {label} - - {available ? '可发送' : '未就绪'} - -
- ))} -
- {error ? ( -

- {error} -

- ) : null} -
- - ) : null} - - {isWindows ? ( - <> -

Windows 接口配置

-
-
- Windows - - {!windowsSenderStatus - ? windowsPortInput - ? '待检测' - : '未配置' - : windowsSenderStatus.canSend - ? '微信发送能力已就绪' - : windowsSenderStatus.endpointReady - ? '接口已连接,但暂不可发送' - : '未检测到发送能力'} - - - {windowsSenderStatus?.message || '输入端口后检测微信发送能力'} - -
-
- - - -
-
- -

发送能力授权

- - - ) : isMac ? ( - <> - {/* 发送能力授权卡片:仅在加载了发送组件的档位渲染。 - OSS(runtime_missing)下不渲染,保证免费版不出现授权入口。 */} - {macRuntimeAvailability?.state === 'available' ? ( - - ) : null} -
+
+
+

微信发送

+

管理个人微信消息发送能力,日报和档案发送都会使用这里的状态。

+
+ + {loading ? '检测中' : capabilityLabel[pageStatus]} + +
+
+
+ {loading && !capability && !isPortEndpointPlatform ? ( + + ) : ( + <> +

发送能力

+
+
+
+ 个人微信 + {pageMessage} +

+ {pageStatus === 'unsupported' + ? '微信消息发送目前仅支持 macOS 和 Windows。' + : isPortEndpointPlatform + ? `${platformDisplayName} 通过本机微信发送接口工作,请先配置并检测接口端口。` + : '档案中的文字、图片和语音发送,以及定时日报发送,都会使用这项能力。'} +

+
+ +
+
+ {( + [ + ['文字', pageCapabilities.text], + ['图片', pageCapabilities.image], + ['语音', pageCapabilities.voice] + ] as const + ).map(([label, available]) => ( +
-
- 微信发送环境 - - {loading - ? '正在检查环境' - : macUnavailable - ? '当前版本没有微信发送能力' - : macComponentError - ? '发送组件缺失或异常' - : macEnvironmentReady - ? '运行环境已就绪' - : '需要完成配置'} - -
-
- {[ - ['运行时正常', Boolean(senderStatus?.runtimeReady)], - ['微信已绑定', macBound], - ['发送组件正常', Boolean(senderStatus?.canSend)] - ].map(([label, complete]) => ( -
- - {label} - {loading ? '检测中' : complete ? '正常' : '待完成'} -
- ))} -
- {macSendPort && senderStatus?.endpointReady ? ( -

- 当前发送能力占用端口为 {macSendPort}(TM_WECHAT_HOST_PORT)。 -

- ) : null} -
-
- 4290 端口 -

- {mac4290PortStatus.state === 'loading' - ? '正在检查占用状态…' - : mac4290PortStatus.state === 'error' - ? '占用状态读取失败' - : mac4290PortStatus.state === 'available' - ? '未被占用' - : '已被占用:' + - mac4290PortStatus.processes - .map(({ name, pid }) => name + '(PID ' + pid + ')') - .join('、')} -

-
- -
- {macWechatRebindRequired ? ( -
- 微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。 -
- ) : null} - {senderStatus && macRuntimeAvailability?.state === 'available' ? ( -
- {( - [ - ['文字', senderStatus.canSendText], - ['图片', senderStatus.canSendImage], - ['语音', senderStatus.canSendVoice] - ] as const - ).map(([label, available]) => ( - - {label} {available ? '可用' : '未就绪'} - - ))} -
- ) : null} -
+ ))} +
+ {error ? ( +

+ {error} +

+ ) : null} +
+ + {isPortEndpointPlatform ? ( + <> +

{platformDisplayName} 接口配置

+
+
+ {platformDisplayName} + + {!windowsSenderStatus + ? windowsPortInput + ? '待检测' + : '未配置' + : windowsSenderStatus.canSend + ? '微信发送能力已就绪' + : windowsSenderStatus.endpointReady + ? '接口已连接,但暂不可发送' + : '未检测到发送能力'} + + + {windowsSenderStatus?.message || '输入端口后检测微信发送能力'} + +
+
+ + - -
- - -
-
- {macUnavailable ? ( - <> -

发送能力授权

- - - ) : null} - - ) : null} - - )} -
+ 清除端口 + +
+
+ +

发送能力授权

+ + + ) : null} + + )}
- - - - 清理微信残留进程? - - 将结束下面列出的微信进程、TraceMemo 发送 Host 和由 TraceMemo Runtime 启动的 Frida Helper。 - 所有目标都退出后才会自动重启发送 Host;若列表包含微信,微信会关闭,之后需要重新打开微信并绑定。 - - -
    - {macResidualProcesses.map((item) => ( -
  • - {item.name} - - PID {item.pid} ·{' '} - {item.targets - .map((target) => - target === 'wechat' - ? '微信进程' - : target === 'host' - ? '发送 Host' - : target === 'frida_helper' - ? 'Frida Helper' - : '4290 端口' - ) - .join('、')} - {item.uninterruptible - ? ` · 内核不可中断${item.state ? `(${item.state})` : ''}` - : item.state - ? ` · 状态 ${item.state}` - : ''} - -
  • - ))} -
- - 取消 - { - event.preventDefault() - void cleanupMacResidualProcesses() - }} - > - {macResidualBusy ? '清理中…' : '确认结束进程'} - - -
-
- +
) } diff --git a/tests/component/personal-wechat-send-page.test.tsx b/tests/component/personal-wechat-send-page.test.tsx index ca98cb2..176248c 100644 --- a/tests/component/personal-wechat-send-page.test.tsx +++ b/tests/component/personal-wechat-send-page.test.tsx @@ -1,3 +1,4 @@ +// @vitest-environment jsdom import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { PersonalWechatSendPage } from '../../src/renderer/src/features/settings/pages/PersonalWechatSendPage' @@ -9,15 +10,15 @@ vi.mock('../../src/renderer/src/utils/runtime-environment', () => ({ supportsPersonalWechatSend: true })) -const getCapability = vi.fn() +const getSettings = vi.fn() +const setSettings = vi.fn() const getSenderStatus = vi.fn() -const rebindSender = vi.fn() -const listResidualProcesses = vi.fn() -const cleanupResidualProcesses = vi.fn() -const startMacRuntime = vi.fn() +const checkSenderStatus = vi.fn() const getMacLicenseStatus = vi.fn() +// 合成占位 ID,仅匹配 mac_ + 64hex 格式;不要放真实设备 ID。 +const TEST_DEVICE_ID = 'mac_9d204eef37960efc91277713c5441b6ab27c4e46c739c70d6c7fcd55187aa943' -const senderStatus = { +const readySenderStatus = { state: 'online' as const, platform: 'darwin', arch: 'arm64', @@ -29,7 +30,6 @@ const senderStatus = { endpointReady: true, runtimeReady: true, attachReady: true, - baseAddress: '0x114ef8000', baseAddressReady: true, textHookInstalled: true, textHookReady: true, @@ -40,282 +40,97 @@ const senderStatus = { canSendText: true, canSendImage: true, canSendVoice: true, - message: '个人微信已绑定' + message: '微信发送能力已连接,可以发送消息' } -const capability = { - supported: true, - ready: true, - status: 'ready' as const, - capabilities: { text: true, image: true, voice: true }, - senderStatus, - message: '个人微信发送能力已就绪' -} - -describe('PersonalWechatSendPage on macOS', () => { +describe('PersonalWechatSendPage on macOS (port 4290 mode)', () => { beforeEach(() => { - getCapability.mockReset().mockResolvedValue(capability) - getSenderStatus.mockReset().mockResolvedValue(senderStatus) - rebindSender.mockReset().mockResolvedValue(senderStatus) - listResidualProcesses.mockReset().mockResolvedValue([ - { - pid: 202, - name: 'tm-wechat-host', - targets: ['port_4290'], - confirmationToken: 'process-identity-202' - } - ]) - cleanupResidualProcesses.mockReset().mockResolvedValue({ - stopped: [ - { - pid: 202, - name: 'tm-wechat-host', - targets: ['port_4290'], - confirmationToken: 'process-identity-202' - } - ], - remaining: [], - runtimeStopped: true + getSettings.mockReset().mockResolvedValue({ + settings: { windowsWechatPort: '' } }) - startMacRuntime.mockReset().mockResolvedValue({ lifecycle: 'online' }) + setSettings.mockReset().mockResolvedValue({ + settings: { windowsWechatPort: '4290' } + }) + getSenderStatus.mockReset().mockResolvedValue(readySenderStatus) + checkSenderStatus.mockReset().mockResolvedValue(readySenderStatus) getMacLicenseStatus.mockReset().mockResolvedValue({ - deviceId: null, state: 'unlicensed', authorized: false, - source: 'none', + deviceId: TEST_DEVICE_ID, features: [], - lastCheckedAt: null, licenseExpiresAt: null, - tokenExpiresAt: null, - message: '当前设备暂无发送能力授权' + lastCheckedAt: null, + message: '' }) + Object.defineProperty(window, 'api', { configurable: true, value: { - getPersonalWechatSendCapability: getCapability, + getSettings, + setSettings, getPersonalWechatSenderStatus: getSenderStatus, - rebindPersonalWechatSender: rebindSender, - listMacWechatResidualProcesses: listResidualProcesses, - cleanupMacWechatResidualProcesses: cleanupResidualProcesses, - startMacSendRuntime: startMacRuntime, - // 发送能力授权卡所需的两个入口。页面在 Native 档位会调用它们, - // 缺 mock 会让 refresh 抛错、整页停在错误态。 - getMacSendRuntimeAvailability: vi.fn(async () => ({ - state: 'available', - message: '微信发送组件可用' - })), - getMacLicenseStatus, - refreshMacLicense: vi.fn() + checkPersonalWechatSenderStatus: checkSenderStatus, + getMacLicenseStatus } }) }) - it('shows the native runtime readiness', async () => { + it('starts unconfigured when no port is saved', async () => { render() - // 页面重构后「就绪」的落点从 SetupGuide 尾部文案变成了「微信发送环境」卡片的状态标签; - // 断言改到新位置,语义仍是“运行时准备好了”。 - expect(await screen.findByText('运行环境已就绪')).toBeVisible() - expect( - screen.getByText('当前发送能力占用端口为 4290(TM_WECHAT_HOST_PORT)。') - ).toBeVisible() - expect(await screen.findByText('已被占用:tm-wechat-host(PID 202)')).toBeVisible() - expect(screen.getAllByText('已就绪')).not.toHaveLength(0) - expect(screen.queryByText('查看支持的微信版本')).not.toBeInTheDocument() - expect(screen.queryByText('高级诊断')).not.toBeInTheDocument() + expect(await screen.findByText('尚未配置')).toBeVisible() + expect(screen.getByText('macOS 接口配置')).toBeVisible() + expect(screen.getByText('未配置')).toBeVisible() + expect(screen.getByText('本机设备 ID')).toBeVisible() + expect(await screen.findByText('mac_9d204eef…7aa943')).toBeVisible() + expect(screen.getByRole('button', { name: '复制完整设备 ID' })).toBeEnabled() + expect(screen.queryByRole('button', { name: '绑定微信' })).not.toBeInTheDocument() }) - it('shows the actual runtime port when it uses a configured fallback instead of 4290', async () => { - const fallbackPortStatus = { ...senderStatus, endpoint: 'http://127.0.0.1:4291' } - getCapability.mockResolvedValueOnce({ ...capability, senderStatus: fallbackPortStatus }) - getSenderStatus.mockResolvedValueOnce(fallbackPortStatus) - listResidualProcesses.mockResolvedValueOnce([]) - - render() - - expect( - await screen.findByText( - '当前发送能力占用端口为 4291(TM_WECHAT_HOST_PORT)。' - ) - ).toBeVisible() - expect(screen.getByText('未被占用')).toBeVisible() - }) - - it('shows confirmed cleanup targets before ending processes', async () => { + it('detects port 4290 and saves it to unlock sending capability', async () => { const onNotice = vi.fn() render() - await screen.findByText('运行环境已就绪') - fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) - - expect(await screen.findByRole('heading', { name: '清理微信残留进程?' })).toBeVisible() - expect(screen.getByText('tm-wechat-host')).toBeVisible() - expect(screen.getByText(/PID 202.*4290 端口/)).toBeVisible() - expect(cleanupResidualProcesses).not.toHaveBeenCalled() - }) - - it('cleans the confirmed runtime host and automatically restarts it', async () => { - const onNotice = vi.fn() - render() - - await screen.findByText('运行环境已就绪') - fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) - fireEvent.click(await screen.findByRole('button', { name: '确认结束进程' })) + const input = await screen.findByLabelText('微信发送能力端口') + fireEvent.change(input, { target: { value: '4290' } }) + fireEvent.click(screen.getByRole('button', { name: '检测' })) await waitFor(() => { - expect(cleanupResidualProcesses).toHaveBeenCalledWith([ - { pid: 202, confirmationToken: 'process-identity-202' } - ]) + expect(checkSenderStatus).toHaveBeenCalledWith('4290') }) - await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce()) - expect(onNotice).toHaveBeenCalledWith( - '已清理并重启发送 Host;如刚才关闭了微信,请重新打开微信并绑定。' - ) + expect(onNotice).toHaveBeenCalledWith('已检测到微信发送能力,请点击保存') + expect(await screen.findByText('微信发送能力已就绪')).toBeVisible() + expect(screen.getAllByText('可发送')).toHaveLength(3) + + getSettings.mockResolvedValue({ + settings: { windowsWechatPort: '4290' } + }) + fireEvent.click(screen.getByRole('button', { name: '保存' })) + + await waitFor(() => { + expect(setSettings).toHaveBeenCalledWith({ windowsWechatPort: '4290' }) + }) + expect(onNotice).toHaveBeenCalledWith('微信发送能力端口已保存') }) - it('still starts the runtime when a target survives cleanup, and names it', async () => { - const onNotice = vi.fn() - cleanupResidualProcesses.mockResolvedValueOnce({ - stopped: [], - remaining: [ - { - pid: 404, - name: 'frida-helper', - state: 'UE', - uninterruptible: true, - targets: ['frida_helper', 'port_4290'], - confirmationToken: 'process-identity-404' - } - ], - runtimeStopped: false - }) - render() - - await screen.findByText('运行环境已就绪') - fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) - fireEvent.click(await screen.findByRole('button', { name: '确认结束进程' })) - - await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce()) - expect(onNotice).toHaveBeenCalledWith( - '0 个进程已退出,1 个系统无法结束(frida-helper);正在改用可用端口启动发送组件…' - ) - }) - - it('reports the fallback port when the runtime comes up on a spare one', async () => { - listResidualProcesses.mockResolvedValue([]) - startMacRuntime.mockResolvedValueOnce({ - lifecycle: 'online', - port: 4291, - portFallbackFrom: 4290 + it('loads saved port 4290 on startup and allows clearing the port', async () => { + getSettings.mockResolvedValue({ + settings: { windowsWechatPort: '4290' } }) const onNotice = vi.fn() render() - await screen.findByText('运行环境已就绪') - fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) + expect(await screen.findByText('微信发送能力已就绪')).toBeVisible() + expect(screen.getByText('已就绪')).toBeVisible() - await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce()) - expect(onNotice).toHaveBeenCalledWith( - '发送 Host 已在 4291 端口启动。4290 已被占用,已改用 4291 端口。' - ) - }) - - it('uses the same cleanup button to start the runtime when no residual process exists', async () => { - listResidualProcesses.mockResolvedValue([]) - const onNotice = vi.fn() - render() - - await screen.findByText('运行环境已就绪') - fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) - - await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce()) - expect(screen.queryByRole('heading', { name: '清理微信残留进程?' })).not.toBeInTheDocument() - }) - - it('shows that WeChat must be reopened and rebound after its process is cleaned', async () => { - listResidualProcesses.mockResolvedValueOnce([ - { - pid: 4668, - name: 'WeChat', - targets: ['wechat'], - confirmationToken: 'wechat-process-4668' - } - ]) - cleanupResidualProcesses.mockResolvedValueOnce({ - stopped: [ - { - pid: 4668, - name: 'WeChat', - targets: ['wechat'], - confirmationToken: 'wechat-process-4668' - } - ], - remaining: [], - runtimeStopped: false + getSettings.mockResolvedValue({ + settings: { windowsWechatPort: '' } }) - rebindSender.mockResolvedValueOnce({ - ...senderStatus, - state: 'stopped', - wechatRunning: true, - wechatPid: undefined, - boundWechatPid: undefined, - canSend: false - }) - const stoppedStatus = { - ...senderStatus, - state: 'stopped', - wechatRunning: false, - wechatPid: undefined, - boundWechatPid: undefined, - attachReady: false, - baseAddressReady: false, - canSend: false, - canSendText: false, - canSendImage: false, - canSendVoice: false - } - getSenderStatus.mockReset().mockResolvedValueOnce(senderStatus).mockResolvedValue(stoppedStatus) - getCapability - .mockReset() - .mockResolvedValueOnce(capability) - .mockResolvedValue({ ...capability, senderStatus: stoppedStatus }) - rebindSender.mockReset().mockResolvedValueOnce(stoppedStatus).mockResolvedValueOnce(senderStatus) - getMacLicenseStatus.mockResolvedValue({ - deviceId: 'mac_test', - state: 'valid', - authorized: true, - source: 'online', - features: ['wechat'], - lastCheckedAt: new Date().toISOString(), - licenseExpiresAt: null, - tokenExpiresAt: new Date(Date.now() + 60_000).toISOString(), - message: '设备已授权' - }) - const onNotice = vi.fn() - render() + fireEvent.click(screen.getByRole('button', { name: '清除端口' })) - await screen.findByText('运行环境已就绪') - fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) - fireEvent.click(await screen.findByRole('button', { name: '确认结束进程' })) - - expect( - await screen.findByText( - '微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。' - ) - ).toBeVisible() - fireEvent.click(screen.getByRole('button', { name: '绑定微信' })) - await waitFor(() => expect(rebindSender).toHaveBeenCalledOnce()) - expect( - screen.getByText( - '微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。' - ) - ).toBeVisible() - fireEvent.click(screen.getByRole('button', { name: '绑定微信' })) - await waitFor(() => expect(rebindSender).toHaveBeenCalledTimes(2)) - expect( - screen.queryByText( - '微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。' - ) - ).not.toBeInTheDocument() + await waitFor(() => { + expect(setSettings).toHaveBeenCalledWith({ windowsWechatPort: '' }) + }) + expect(onNotice).toHaveBeenCalledWith('微信发送能力端口已清除') }) }) diff --git a/tests/unit/external-component-locator.test.ts b/tests/unit/external-component-locator.test.ts index b112028..30e7749 100644 --- a/tests/unit/external-component-locator.test.ts +++ b/tests/unit/external-component-locator.test.ts @@ -131,4 +131,40 @@ describe('resolveExternalComponent', () => { expect(resolveExternalComponent(env(), 'win32')).toBeNull() }) + + it('macOS 校验通过时返回完整 Pro WCDB 与 Runtime 组件路径', () => { + const homeDir = path.join(tmpRoot, 'MacHome') + const proRoot = path.join(homeDir, 'Library', 'Application Support', 'TraceMemo', 'Pro', 'macos-arm64') + const versionDir = path.join(proRoot, '1.0.0') + const wcdbApi = writeFile(path.join(versionDir, 'libwcdb_api.dylib'), Buffer.alloc(2048, 0x11)) + const wcdb = writeFile(path.join(versionDir, 'libWCDB.dylib'), Buffer.alloc(4096, 0x22)) + const helper = writeFile(path.join(versionDir, 'tm-wcdb-config-helper'), Buffer.alloc(1024, 0x33)) + const license = writeFile(path.join(versionDir, 'libtmlicense.dylib'), Buffer.alloc(512, 0x44)) + const host = writeFile(path.join(versionDir, 'tm-wechat-host'), Buffer.alloc(1024, 0x55)) + + const manifest = { + schemaVersion: 1, + componentVersion: '1.0.0', + worktreeDirty: false, + files: [ + { path: 'libwcdb_api.dylib', size: wcdbApi.length, sha256: sha256(wcdbApi) }, + { path: 'libWCDB.dylib', size: wcdb.length, sha256: sha256(wcdb) }, + { path: 'tm-wcdb-config-helper', size: helper.length, sha256: sha256(helper) }, + { path: 'libtmlicense.dylib', size: license.length, sha256: sha256(license) }, + { path: 'tm-wechat-host', size: host.length, sha256: sha256(host) } + ] + } + writeFile(path.join(versionDir, 'manifest.json'), JSON.stringify(manifest, null, 2)) + writeFile( + path.join(proRoot, 'current.json'), + JSON.stringify({ version: '1.0.0', dir: versionDir }, null, 2) + ) + + const found = resolveExternalComponent({ HOME: homeDir }, 'darwin') + expect(found).not.toBeNull() + expect(found?.dir).toBe(versionDir) + expect(found?.helperPath).toBe(path.join(versionDir, 'tm-wcdb-config-helper')) + expect(found?.version).toBe('1.0.0') + expect(found?.dirty).toBe(false) + }) }) diff --git a/tests/unit/personal-wechat-send-service.test.ts b/tests/unit/personal-wechat-send-service.test.ts index 3a9cfb8..cdf60ce 100644 --- a/tests/unit/personal-wechat-send-service.test.ts +++ b/tests/unit/personal-wechat-send-service.test.ts @@ -122,7 +122,44 @@ describe('macOS message-source send routing', () => { type: 'image', to: 'fixture-contact', path: stagedPath }) expect(stagedPath).not.toBe(filePath) - expect(existsSync(stagedPath)).toBe(false) + // 暂存图必须保留:微信在 /sendMsg 返回后才异步读取,立刻删除会让消息静默丢失。 + expect(existsSync(stagedPath)).toBe(true) + }) + + it('只清扫超过保留期的历史暂存图,不动保留期内的文件', async () => { + const root = temporaryDirectory() + const filePath = join(root, 'fixture-image.png') + writeFileSync(filePath, 'fixture-image') + const imageTemp = join(root, 'wxid_fixture_self', 'temp', 'ImageTemp', '2026-11') + mkdirSync(imageTemp, { recursive: true }) + const stale = join(imageTemp, 'tm-stale-0001.png') + const fresh = join(imageTemp, 'tm-fresh-0001.png') + const unrelated = join(imageTemp, 'wechat-own.png') + for (const p of [stale, fresh, unrelated]) writeFileSync(p, 'x') + const old = new Date(Date.now() - 60 * 60 * 1000) + utimesSync(stale, old, old) + utimesSync(unrelated, old, old) + runtimeMocks.getSendMechanism.mockResolvedValue('tm-message-source-send') + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + status: 200, + json: async () => ({ code: 0, ok: true, message: 'sent' }) + }) + ) + + await new PersonalWechatSendService(root).send({ + type: 'image', + to: 'fixture-contact', + isGroup: false, + filePath + }) + + expect(existsSync(stale)).toBe(false) + expect(existsSync(fresh)).toBe(true) + // 非 tm- 前缀的文件不属于我们,过期也不能删。 + expect(existsSync(unrelated)).toBe(true) }) it('uses the legacy image path only when source preparation is definitively rejected', async () => {