From f47af8024f345fae8bd086ca0754ad09831d045e Mon Sep 17 00:00:00 2001 From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:19:59 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84mac=E5=8F=91=E9=80=81?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/index.ts | 60 +++- src/main/report-template-service.ts | 7 +- .../services/mac-wechat-residual-cleanup.ts | 217 +++++++++++++ .../services/mac-wechat-runtime-manager.ts | 46 ++- .../services/msg-insert-capability-service.ts | 2 +- src/preload/index.d.ts | 22 +- src/preload/index.ts | 15 +- .../chat/PersonalWechatSetupGuide.tsx | 8 +- .../settings/pages/PersonalWechatSendPage.tsx | 286 +++++++++++++++++- src/shared/personal-wechat-mac-runtime.ts | 13 + .../personal-wechat-send-page.test.tsx | 189 +++++++++++- .../personal-wechat-unavailable.test.tsx | 64 +++- .../unit/mac-wechat-residual-cleanup.test.ts | 165 ++++++++++ 13 files changed, 1048 insertions(+), 46 deletions(-) create mode 100644 src/main/services/mac-wechat-residual-cleanup.ts create mode 100644 tests/unit/mac-wechat-residual-cleanup.test.ts diff --git a/src/main/index.ts b/src/main/index.ts index f8419e0..0c4027a 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -161,6 +161,10 @@ import { type MessageInsertCapability } from './services/msg-insert-capability-service' import { resolveExternalComponent } from './services/external-component-locator' +import { + cleanupMacWechatResidualProcesses, + inspectMacWechatResidualProcesses +} from './services/mac-wechat-residual-cleanup' import { isDefinitelyBlocked, isEntitlementBlocked, @@ -317,10 +321,7 @@ async function attachCapability( } } switches.recall_notice = applyPresentation('recall_notice', switches.recall_notice)! - switches.group_exit_notice = applyPresentation( - 'group_exit_notice', - switches.group_exit_notice - )! + switches.group_exit_notice = applyPresentation('group_exit_notice', switches.group_exit_notice)! return { ...snapshot, switches, @@ -1982,7 +1983,8 @@ app.whenReady().then(async () => { * 刻意不返回资源密钥、完整 XML、fileid 或任何 CDN 凭据。 */ ipcMain.handle( - 'image:getDebugInfo', async (_, request: ImageDebugInfoRequest): Promise => { + 'image:getDebugInfo', + async (_, request: ImageDebugInfoRequest): Promise => { try { const service = ensureImageDecryptService() const self = chat.getSelfAccountInfo() @@ -2003,7 +2005,9 @@ app.whenReady().then(async () => { // 复用真实选图逻辑;找不到就是 null,不根据文件名猜。 const filePath = service - ? service.findImageFile(md5 || undefined, datName || undefined, { sessionId: sessionId || undefined }) + ? service.findImageFile(md5 || undefined, datName || undefined, { + sessionId: sessionId || undefined + }) : null const quality = filePath ? toDebugQuality(imageFileQuality(filePath)) : 'unknown' const relativePath = @@ -3466,6 +3470,50 @@ app.whenReady().then(async () => { ipcMain.handle('wechat-personal:getMacSendRuntimeAvailability', () => macWechatRuntimeManager.getSendRuntimeAvailability() ) + ipcMain.handle('wechat-personal:startMacSendRuntime', () => { + if (process.platform !== 'darwin') throw new Error('仅 macOS 支持微信发送组件') + return macWechatRuntimeManager.startAfterResidualCleanup() + }) + ipcMain.handle('wechat-personal:listMacResidualProcesses', () => + inspectMacWechatResidualProcesses() + ) + ipcMain.handle('wechat-personal:cleanupMacResidualProcesses', async (_, pids: unknown) => { + if (process.platform !== 'darwin') throw new Error('仅 macOS 支持清理微信残留进程') + if (!Array.isArray(pids)) throw new Error('清理目标无效') + const requestedTargets = pids.filter( + (target): target is { pid: number; confirmationToken: string } => + Boolean(target) && + typeof target === 'object' && + Number.isSafeInteger((target as { pid?: unknown }).pid) && + typeof (target as { confirmationToken?: unknown }).confirmationToken === 'string' + ) + if (requestedTargets.length === 0) throw new Error('没有确认的清理目标') + const currentTargets = await inspectMacWechatResidualProcesses() + const confirmedTargets = requestedTargets.filter((requested) => + currentTargets.some( + (current) => + current.pid === requested.pid && current.confirmationToken === requested.confirmationToken + ) + ) + if (confirmedTargets.length === 0) { + return { stopped: [], remaining: currentTargets } + } + let runtimeStopped = false + const result = await cleanupMacWechatResidualProcesses( + confirmedTargets, + undefined, + (targets) => { + if ( + macWechatRuntimeManager.getPort() === 4290 && + targets.some((target) => target.targets.includes('port_4290')) + ) { + macWechatRuntimeManager.prepareForResidualCleanup() + runtimeStopped = true + } + } + ) + return { ...result, runtimeStopped } + }) ipcMain.handle('wechat-personal:refreshMacLicense', () => macWechatRuntimeManager.refreshMacLicense() ) diff --git a/src/main/report-template-service.ts b/src/main/report-template-service.ts index 0fb2ff2..a232da6 100644 --- a/src/main/report-template-service.ts +++ b/src/main/report-template-service.ts @@ -230,7 +230,12 @@ function builtInTemplate(template: ReportTemplateDefinition): InstalledReportTem } export class ReportTemplateService { - private readonly directory = rootPath() + /* 延迟到首次真正用到时再取 app.getPath('userData')。 + * 这个类在模块顶层被 new(见文件末尾),而 import 顺序一变,模块就可能 + * 在 electron.app 可用之前被 require —— 那时 app 是 undefined,getPath 直接抛。 */ + private get directory(): string { + return rootPath() + } async list(): Promise { await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true }) diff --git a/src/main/services/mac-wechat-residual-cleanup.ts b/src/main/services/mac-wechat-residual-cleanup.ts new file mode 100644 index 0000000..1d1a1a6 --- /dev/null +++ b/src/main/services/mac-wechat-residual-cleanup.ts @@ -0,0 +1,217 @@ +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { promisify } from 'node:util' +import type { MacWechatResidualProcess } from '../../shared/personal-wechat-mac-runtime' + +const execFileAsync = promisify(execFile) +type PidCommandRunner = ( + executable: string, + args: string[], + options: { timeout: number } +) => Promise<{ stdout: string }> + +export interface MacWechatResidualCleanupDependencies { + platform: NodeJS.Platform + listWechatPids: () => Promise + listPortPids: () => Promise + processName: (pid: number) => Promise + processIdentity: (pid: number) => Promise + signal: (pid: number, signal: NodeJS.Signals) => void + wait: (milliseconds: number) => Promise +} + +export async function readPids( + executable: string, + args: string[], + run: PidCommandRunner = async (file, commandArgs, options) => + execFileAsync(file, commandArgs, options) +): Promise { + try { + const { stdout } = await run(executable, args, { timeout: 4_000 }) + return stdout + .split(/\s+/) + .map(Number) + .filter((pid) => Number.isSafeInteger(pid) && pid > 0) + } catch (error) { + const result = error as { code?: unknown; status?: unknown } + if (result.code === 'ENOENT' || result.code === 1 || result.status === 1) return [] + throw error + } +} + +const defaultDependencies: MacWechatResidualCleanupDependencies = { + platform: process.platform, + listWechatPids: async () => { + const results = await Promise.all([ + readPids('/usr/bin/pgrep', ['-x', 'WeChat']), + readPids('/usr/bin/pgrep', ['-x', 'Weixin']) + ]) + return [...new Set(results.flat())] + }, + listPortPids: () => readPids('/usr/sbin/lsof', ['-nP', '-t', '-iTCP:4290', '-sTCP:LISTEN']), + processName: async (pid) => { + try { + const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], { + timeout: 2_000 + }) + return stdout.trim().split('/').pop() || 'unknown' + } catch { + return 'unknown' + } + }, + processIdentity: async (pid) => { + try { + const { stdout } = await execFileAsync( + '/bin/ps', + ['-p', String(pid), '-o', 'lstart=', '-o', 'comm='], + { timeout: 2_000 } + ) + return createHash('sha256').update(stdout.trim()).digest('hex') + } catch { + return '' + } + }, + signal: (pid, signal) => process.kill(pid, signal), + wait: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)) +} + +interface ObservedTarget extends MacWechatResidualProcess { + confirmationToken: string +} + +function mergeTargets( + wechatPids: number[], + portPids: number[], + processNames: Map, + processIdentities: Map +): ObservedTarget[] { + const targets = new Map>() + for (const pid of wechatPids) { + if (!Number.isSafeInteger(pid) || pid <= 0) continue + const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>() + reasons.add('wechat') + targets.set(pid, reasons) + } + for (const pid of portPids) { + if (!Number.isSafeInteger(pid) || pid <= 0) continue + const reasons = targets.get(pid) || new Set<'wechat' | 'port_4290'>() + reasons.add('port_4290') + targets.set(pid, reasons) + } + return [...targets.entries()] + .sort(([first], [second]) => first - second) + .map(([pid, reasons]) => ({ + pid, + name: processNames.get(pid) || 'unknown', + targets: [...reasons].sort(), + confirmationToken: processIdentities.get(pid) || '' + })) +} + +async function inspectObservedTargets( + dependencies: MacWechatResidualCleanupDependencies +): Promise { + if (dependencies.platform !== 'darwin') return [] + const [rawWechatPids, rawPortPids] = await Promise.all([ + dependencies.listWechatPids(), + dependencies.listPortPids() + ]) + const wechatPids = rawWechatPids.filter((pid) => pid !== process.pid) + const portPids = rawPortPids.filter((pid) => pid !== process.pid) + const pids = [...new Set([...wechatPids, ...portPids])].filter( + (pid) => Number.isSafeInteger(pid) && pid > 0 + ) + const [names, identities] = await Promise.all([ + Promise.all(pids.map(async (pid) => [pid, await dependencies.processName(pid)] as const)), + Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const)) + ]) + return mergeTargets(wechatPids, portPids, new Map(names), new Map(identities)) +} + +export async function inspectMacWechatResidualProcesses( + dependencies: MacWechatResidualCleanupDependencies = defaultDependencies +): Promise { + return inspectObservedTargets(dependencies) +} + +export async function cleanupMacWechatResidualProcesses( + confirmedTargets: Array>, + dependencies: MacWechatResidualCleanupDependencies = defaultDependencies, + onTargetsConfirmed?: (targets: MacWechatResidualProcess[]) => void +): Promise<{ stopped: MacWechatResidualProcess[]; remaining: MacWechatResidualProcess[] }> { + if (dependencies.platform !== 'darwin') return { stopped: [], remaining: [] } + const confirmed = new Map( + confirmedTargets + .filter( + (target) => + target.pid !== process.pid && + Number.isSafeInteger(target.pid) && + target.pid > 0 && + typeof target.confirmationToken === 'string' && + target.confirmationToken.length > 0 + ) + .map((target) => [target.pid, target.confirmationToken]) + ) + const current = await inspectObservedTargets(dependencies) + const selected = current.filter( + (target) => confirmed.get(target.pid) === target.confirmationToken + ) + if (selected.length === 0) { + return { + stopped: [], + remaining: current.filter((target) => confirmed.has(target.pid)) + } + } + let cleanupTargetsNotified = false + const signalMatchingTarget = async ( + target: ObservedTarget, + expectedIdentity: string, + signal: NodeJS.Signals + ): Promise => { + const identity = await dependencies.processIdentity(target.pid) + if (!expectedIdentity || identity !== expectedIdentity) return + try { + dependencies.signal(target.pid, signal) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error + } + if (target.targets.includes('port_4290') && !cleanupTargetsNotified) { + cleanupTargetsNotified = true + onTargetsConfirmed?.([target]) + } + } + + for (const target of selected.filter((item) => item.targets.includes('wechat'))) { + await signalMatchingTarget(target, confirmed.get(target.pid) || '', 'SIGTERM') + } + if (selected.some((item) => item.targets.includes('wechat'))) await dependencies.wait(1_000) + + let remaining = (await inspectObservedTargets(dependencies)).filter((target) => + confirmed.has(target.pid) + ) + for (const target of remaining) { + const selectedTarget = selected.find((item) => item.pid === target.pid) + if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue + await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGTERM') + } + if (remaining.length > 0) await dependencies.wait(1_000) + + remaining = (await inspectObservedTargets(dependencies)).filter((target) => + confirmed.has(target.pid) + ) + for (const target of remaining) { + const selectedTarget = selected.find((item) => item.pid === target.pid) + if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue + await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGKILL') + } + if (remaining.length > 0) await dependencies.wait(250) + remaining = (await inspectObservedTargets(dependencies)).filter((target) => + confirmed.has(target.pid) + ) + return { + stopped: selected + .filter((target) => !remaining.some((item) => item.pid === target.pid)) + .map((target) => target), + remaining + } +} diff --git a/src/main/services/mac-wechat-runtime-manager.ts b/src/main/services/mac-wechat-runtime-manager.ts index 70fc808..aad5bb1 100644 --- a/src/main/services/mac-wechat-runtime-manager.ts +++ b/src/main/services/mac-wechat-runtime-manager.ts @@ -48,7 +48,10 @@ import { * auto-binding, that path dead-ends in a 20s attach timeout every time. */ -const PORT = 4290 +/* 默认 4290。进程会 fork 继承监听 fd(CLOEXEC 只挡 exec), + * host 崩溃后孤儿进程仍扣着端口,新 host bind 失败会返回 1 无限重启。 + * 被占用时用 TM_WECHAT_HOST_PORT 指到备用端口。 */ +const PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290 const HOST = '127.0.0.1' const START_TIMEOUT_MS = 15_000 const REQUEST_TIMEOUT_MS = 30_000 @@ -199,6 +202,7 @@ class MacWechatRuntimeManager { private manifest: MacWechatRuntimeManifest | null = null private lastError: string | null = null private restartTimer: NodeJS.Timeout | null = null + private manuallyStopped = false getPort(): number { return PORT @@ -216,6 +220,22 @@ class MacWechatRuntimeManager { } } + prepareForResidualCleanup(): void { + if (this.restartTimer) { + clearTimeout(this.restartTimer) + this.restartTimer = null + } + this.lifecycle = 'stopped' + this.manuallyStopped = true + this.child = null + this.lastBinding = null + this.lastError = null + } + + async startAfterResidualCleanup(): Promise { + return this.ensureStarted({ allowManualRestart: true }) + } + private resolveRuntimeDir(): string | null { if (isMacNativeRuntimeUnavailable()) return null const resolved = resolveWechatRuntimeDirectory() @@ -261,7 +281,11 @@ class MacWechatRuntimeManager { * comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime * online" and "WeChat bound" stay two independent states. */ - async ensureStarted(): Promise { + async ensureStarted( + options: { allowManualRestart?: boolean } = {} + ): Promise { + if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot() + if (options.allowManualRestart) this.manuallyStopped = false if (isMacNativeRuntimeUnavailable()) { this.manifest = null this.lifecycle = 'stopped' @@ -603,6 +627,12 @@ class MacWechatRuntimeManager { if (availability.state !== 'available') { return offlineMacLicenseStatus('runtime_missing', availability.message) } + if (this.manuallyStopped) { + return 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) { @@ -637,6 +667,12 @@ class MacWechatRuntimeManager { if (availability.state !== 'available') { return offlineMacLicenseStatus('runtime_missing', availability.message) } + if (this.manuallyStopped) { + return offlineMacLicenseStatus( + 'runtime_missing', + 'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。' + ) + } if (this.lifecycle === 'stopped') await this.ensureStarted() if (this.licenseRefreshInFlight) { // A refresh is already running; answer from the local snapshot so the @@ -725,7 +761,7 @@ class MacWechatRuntimeManager { * never succeed because the check itself is what should start the host. * Starting it never touches WeChat, so doing it from a read is safe. */ - if (this.lifecycle === 'stopped') { + if (this.lifecycle === 'stopped' && !this.manuallyStopped) { await this.ensureStarted().catch(() => undefined) } /* Self-heal the status card too: if WeChat was restarted, drop the stale @@ -817,7 +853,7 @@ class MacWechatRuntimeManager { return { ok: false, attached: false, state: 'runtime_offline', message: availability.message } } if (this.lifecycle !== 'online') { - const snapshot = await this.ensureStarted() + const snapshot = await this.ensureStarted({ allowManualRestart: true }) if (snapshot.lifecycle !== 'online') { return { ok: false, @@ -902,7 +938,7 @@ class MacWechatRuntimeManager { async reload(): Promise { await this.shutdown().catch(() => undefined) await new Promise((resolve) => setTimeout(resolve, 2_000)) - return this.ensureStarted() + return this.ensureStarted({ allowManualRestart: true }) } private isProcessAlive(pid: number): boolean { diff --git a/src/main/services/msg-insert-capability-service.ts b/src/main/services/msg-insert-capability-service.ts index 1bf3880..9be1a55 100644 --- a/src/main/services/msg-insert-capability-service.ts +++ b/src/main/services/msg-insert-capability-service.ts @@ -140,7 +140,7 @@ export function probeLicenseStatus(timeoutMs = PROBE_TIMEOUT_MS): Promise { const chunks: Buffer[] = [] res.on('data', (chunk: Buffer) => chunks.push(chunk)) diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 05001a1..2cfa820 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -85,7 +85,12 @@ import type { } 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 { + MacWechatResidualCleanupResult, + MacWechatResidualProcess, + MacWechatRuntimeSnapshot, + MacWechatSendRuntimeAvailabilityResult +} from '../shared/personal-wechat-mac-runtime' import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats' import type { ScheduledReportExecution, @@ -753,9 +758,14 @@ declare global { repairImageTextIndex: () => Promise onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void getPersonalWechatSenderStatus: () => Promise - getMacLicenseStatus: () => Promise - getMacSendRuntimeAvailability: () => Promise - refreshMacLicense: () => Promise + getMacLicenseStatus: () => Promise + getMacSendRuntimeAvailability: () => Promise + startMacSendRuntime: () => Promise + listMacWechatResidualProcesses: () => Promise + cleanupMacWechatResidualProcesses: ( + targets: Array> + ) => Promise + refreshMacLicense: () => Promise getPersonalWechatSendCapability: () => Promise checkPersonalWechatSenderStatus: (port?: string) => Promise checkPersonalWechatVoiceEncodingEnvironment: () => Promise @@ -774,9 +784,7 @@ declare global { ruleId: string ) => Promise<{ success: boolean; error?: string; data?: ScheduledRuleRunOutcome }> /** 定时日报:旧执行记录**只读存档**(旧记录无法无损转换,原样展示)。 */ - listScheduledReportLegacyExecutions: ( - ruleId?: string - ) => Promise + listScheduledReportLegacyExecutions: (ruleId?: string) => Promise /** 定时日报:微信异常通知开关与能力检测。 */ getScheduledReportNotificationSettings: () => Promise getScheduledReportNotificationCapability: () => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index 8a29c52..a4c17e3 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -15,7 +15,12 @@ import type { 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 { + MacWechatResidualCleanupResult, + MacWechatResidualProcess, + MacWechatRuntimeSnapshot, + MacWechatSendRuntimeAvailabilityResult +} from '../shared/personal-wechat-mac-runtime' import type { AIChatRequestOptions, AiSearchExternalAuthorizationRequest, @@ -591,6 +596,14 @@ const api = { ipcRenderer.invoke('wechat-personal:getMacLicenseStatus'), getMacSendRuntimeAvailability: (): Promise => ipcRenderer.invoke('wechat-personal:getMacSendRuntimeAvailability'), + startMacSendRuntime: (): Promise => + ipcRenderer.invoke('wechat-personal:startMacSendRuntime'), + listMacWechatResidualProcesses: (): Promise => + ipcRenderer.invoke('wechat-personal:listMacResidualProcesses'), + cleanupMacWechatResidualProcesses: ( + targets: Array> + ): Promise => + ipcRenderer.invoke('wechat-personal:cleanupMacResidualProcesses', targets), refreshMacLicense: (): Promise => ipcRenderer.invoke('wechat-personal:refreshMacLicense'), getPersonalWechatSendCapability: (): Promise => diff --git a/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx b/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx index 24e4c14..db4d70b 100644 --- a/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx +++ b/src/renderer/src/components/chat/PersonalWechatSetupGuide.tsx @@ -76,7 +76,7 @@ export function PersonalWechatSetupGuide({
首次使用

先准备好微信消息功能

-

只需几步,TraceMemo 就能在当前会话中生成并发送语音。

+

只需几步,TraceMemo 就能具备微信消息发送能力。

{allReady && 已完成} @@ -176,7 +176,11 @@ export function PersonalWechatSetupGuide({ )} {initializing && (

- {detecting ? '正在初始化发送能力…' : '正在等待发送运行时完成初始化…'} + {detecting + ? '正在初始化发送能力…' + : runtimeReady + ? '微信已绑定,正在等待发送能力完成初始化…' + : '正在等待发送运行时完成初始化…'}

)} {senderStatus?.state === 'error' && ( diff --git a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx index 57c5a64..f818f03 100644 --- a/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx +++ b/src/renderer/src/features/settings/pages/PersonalWechatSendPage.tsx @@ -9,7 +9,19 @@ import type { } 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 { + 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' @@ -33,6 +45,15 @@ 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 boundToCurrentWechat(status: PersonalWechatSenderStatus | null): boolean { if (!status) return false return ( @@ -94,6 +115,28 @@ function licenseTone(state: MacLicenseState): string { return 'is-neutral' } +function licenseStateConflictsWithExpiry(license: MacLicenseStatus): boolean { + const expiresAt = license.licenseExpiresAt ? Date.parse(license.licenseExpiresAt) : NaN + return license.state === 'expired' && Number.isFinite(expiresAt) && expiresAt > Date.now() +} + +function macLicenseStatusLabel(license: MacLicenseStatus): string { + if (license.state === 'valid' || license.state === 'cached') return '设备已授权' + if (licenseStateConflictsWithExpiry(license)) return '授权状态需刷新' + return macLicenseStateLabel[license.state] +} + +function macLicenseStatusTone(license: MacLicenseStatus): string { + return licenseStateConflictsWithExpiry(license) ? 'is-neutral' : licenseTone(license.state) +} + +function macLicenseStatusHint(license: MacLicenseStatus): string { + if (licenseStateConflictsWithExpiry(license)) { + return '当前授权状态与到期日不一致,请点击「重新检测授权」更新状态。' + } + return '将设备 ID 提供给授权管理员,完成授权后点击「重新检测授权」。' +} + function formatMacLicenseDateTime(iso: string | null): string { if (!iso) return '—' const parsed = new Date(iso) @@ -191,10 +234,8 @@ export function MacProLicenseCard({
发送能力授权 - - {license.state === 'valid' || license.state === 'cached' - ? '设备已授权' - : macLicenseStateLabel[license.state]} + + {macLicenseStatusLabel(license)}
@@ -215,10 +256,8 @@ export function MacProLicenseCard({ {copied ? '已复制' : '复制'} - {license.deviceId && !license.authorized ? ( -

- 将设备 ID 提供给授权管理员,完成授权后点击「重新检测授权」。 -

+ {license.deviceId && (!license.authorized || licenseStateConflictsWithExpiry(license)) ? ( +

{macLicenseStatusHint(license)}

) : null} {license.authorized && license.features.length > 0 ? (
@@ -273,7 +312,33 @@ export function PersonalWechatSendPage({ 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 [macResidualRuntimeStopped, setMacResidualRuntimeStopped] = 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) @@ -351,6 +416,13 @@ export function PersonalWechatSendPage({ } }, [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 @@ -395,6 +467,9 @@ export function PersonalWechatSendPage({ 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) @@ -419,6 +494,99 @@ 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) { + onNotice('没有发现微信进程或占用 4290 端口的进程') + 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.runtimeStopped) setMacResidualRuntimeStopped(true) + if (result.stopped.some((target) => target.targets.includes('wechat'))) { + setMacWechatRebindRequired(true) + } + if (result.stopped.length === 0) { + if (result.remaining.length > 0) { + setMacResidualProcesses(result.remaining) + onNotice('进程状态已变化,请核对更新后的清理目标。') + return + } + setMacResidualDialogOpen(false) + setMacResidualProcesses([]) + await refreshMac4290PortStatus() + await refresh() + onNotice('目标进程已退出,发送环境状态已刷新。') + return + } + if (result.remaining.length > 0) { + setMacResidualProcesses(result.remaining) + onNotice( + '已结束 ' + + result.stopped.length + + ' 个进程,仍有 ' + + result.remaining.length + + ' 个;请核对后重试。' + ) + } else { + setMacResidualDialogOpen(false) + setMacResidualProcesses([]) + } + await refreshMac4290PortStatus() + await refresh() + if (result.remaining.length === 0) { + onNotice('已结束 ' + result.stopped.length + ' 个残留进程;发送环境状态已刷新。') + } + } catch (reason) { + onNotice(reason instanceof Error ? reason.message : '清理残留进程失败') + } finally { + setMacResidualBusy(false) + } + } + + const restartMacSendRuntime = async (): Promise => { + if (macResidualBusy) return + setMacResidualBusy(true) + try { + const snapshot = await window.api.startMacSendRuntime() + if (snapshot.lifecycle !== 'online') { + throw new Error(snapshot.error || '发送组件启动失败') + } + setMacResidualRuntimeStopped(false) + await refresh() + onNotice('发送组件已启动;如刚才关闭了微信,请重新打开微信并绑定。') + } catch (reason) { + onNotice(reason instanceof Error ? reason.message : '发送组件启动失败') + } finally { + setMacResidualBusy(false) + } + } + const normalizedWindowsPort = normalizeWindowsPort(windowsPortInput) const windowsCanSave = Boolean( normalizedWindowsPort && @@ -516,6 +684,7 @@ export function PersonalWechatSendPage({ 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 ) @@ -723,6 +892,50 @@ export function PersonalWechatSendPage({
))} + {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' ? (
{macPrimaryAction.label} + + {macResidualRuntimeStopped ? ( + + ) : null}
{macUnavailable ? ( @@ -810,6 +1041,43 @@ export function PersonalWechatSendPage({ + + + + 清理微信残留进程? + + 将结束下面列出的微信进程或占用 4290 + 端口的进程。若列表包含微信,微信会关闭;如曾绑定发送组件,之后需要重新打开微信并绑定。 + + +
    + {macResidualProcesses.map((item) => ( +
  • + {item.name} + + PID {item.pid} ·{' '} + {item.targets + .map((target) => (target === 'wechat' ? '微信进程' : '4290 端口')) + .join('、')} + +
  • + ))} +
+ + 取消 + { + event.preventDefault() + void cleanupMacResidualProcesses() + }} + > + {macResidualBusy ? '清理中…' : '确认结束进程'} + + +
+
) } diff --git a/src/shared/personal-wechat-mac-runtime.ts b/src/shared/personal-wechat-mac-runtime.ts index a253134..9635a62 100644 --- a/src/shared/personal-wechat-mac-runtime.ts +++ b/src/shared/personal-wechat-mac-runtime.ts @@ -22,6 +22,19 @@ export interface MacWechatSendRuntimeAvailabilityResult { message: string } +export interface MacWechatResidualProcess { + pid: number + name: string + targets: Array<'wechat' | 'port_4290'> + confirmationToken: string +} + +export interface MacWechatResidualCleanupResult { + stopped: MacWechatResidualProcess[] + remaining: MacWechatResidualProcess[] + runtimeStopped: boolean +} + export type MacWechatHostRuntimeState = | 'not_initialized' | 'wechat_not_running' diff --git a/tests/component/personal-wechat-send-page.test.tsx b/tests/component/personal-wechat-send-page.test.tsx index 8b343a6..4683d4c 100644 --- a/tests/component/personal-wechat-send-page.test.tsx +++ b/tests/component/personal-wechat-send-page.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from '@testing-library/react' +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' @@ -12,6 +12,10 @@ vi.mock('../../src/renderer/src/utils/runtime-environment', () => ({ const getCapability = vi.fn() const getSenderStatus = vi.fn() const rebindSender = vi.fn() +const listResidualProcesses = vi.fn() +const cleanupResidualProcesses = vi.fn() +const startMacRuntime = vi.fn() +const getMacLicenseStatus = vi.fn() const senderStatus = { state: 'online' as const, @@ -21,7 +25,7 @@ const senderStatus = { wechatRunning: true, wechatPid: 4668, boundWechatPid: 4668, - endpoint: '127.0.0.1:4290', + endpoint: 'http://127.0.0.1:4290', endpointReady: true, runtimeReady: true, attachReady: true, @@ -53,29 +57,54 @@ describe('PersonalWechatSendPage on macOS', () => { 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 + }) + startMacRuntime.mockReset().mockResolvedValue({ lifecycle: 'online' }) + getMacLicenseStatus.mockReset().mockResolvedValue({ + deviceId: null, + state: 'unlicensed', + authorized: false, + source: 'none', + features: [], + lastCheckedAt: null, + licenseExpiresAt: null, + tokenExpiresAt: null, + message: '当前设备暂无发送能力授权' + }) Object.defineProperty(window, 'api', { configurable: true, value: { getPersonalWechatSendCapability: getCapability, getPersonalWechatSenderStatus: getSenderStatus, rebindPersonalWechatSender: rebindSender, + listMacWechatResidualProcesses: listResidualProcesses, + cleanupMacWechatResidualProcesses: cleanupResidualProcesses, + startMacSendRuntime: startMacRuntime, // 发送能力授权卡所需的两个入口。页面在 Native 档位会调用它们, // 缺 mock 会让 refresh 抛错、整页停在错误态。 getMacSendRuntimeAvailability: vi.fn(async () => ({ state: 'available', message: '微信发送组件可用' })), - getMacLicenseStatus: vi.fn(async () => ({ - deviceId: null, - state: 'unlicensed', - authorized: false, - source: 'none', - features: [], - lastCheckedAt: null, - licenseExpiresAt: null, - tokenExpiresAt: null, - message: '当前设备暂无发送能力授权' - })), + getMacLicenseStatus, refreshMacLicense: vi.fn() } }) @@ -87,8 +116,142 @@ describe('PersonalWechatSendPage on macOS', () => { // 页面重构后「就绪」的落点从 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() }) + + 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 () => { + 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 only the process the user confirmed and refreshes the runtime state', async () => { + const onNotice = vi.fn() + render() + + await screen.findByText('运行环境已就绪') + fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' })) + fireEvent.click(await screen.findByRole('button', { name: '确认结束进程' })) + + await waitFor(() => { + expect(cleanupResidualProcesses).toHaveBeenCalledWith([ + { pid: 202, confirmationToken: 'process-identity-202' } + ]) + }) + expect(onNotice).toHaveBeenCalledWith('已结束 1 个残留进程;发送环境状态已刷新。') + expect(await screen.findByRole('button', { name: '重新启动发送组件' })).toBeVisible() + fireEvent.click(screen.getByRole('button', { name: '重新启动发送组件' })) + await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce()) + }) + + 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 + }) + 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) + 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() + + 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() + }) }) diff --git a/tests/component/personal-wechat-unavailable.test.tsx b/tests/component/personal-wechat-unavailable.test.tsx index da1a6f9..767719f 100644 --- a/tests/component/personal-wechat-unavailable.test.tsx +++ b/tests/component/personal-wechat-unavailable.test.tsx @@ -97,6 +97,63 @@ describe('personal WeChat unavailable product state', () => { expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument() }) + it('describes a ready runtime separately from pending send capability initialization', () => { + const boundStatus: PersonalWechatSenderStatus = { + ...unavailableStatus, + state: 'hook_not_ready', + wechatRunning: true, + wechatPid: 4668, + boundWechatPid: 4668, + endpointReady: true, + runtimeReady: true, + attachReady: true, + baseAddressReady: true, + message: '已绑定,等待发送 hook 就绪' + } + + render( + + ) + + expect(screen.getByText('微信已绑定,正在等待发送能力完成初始化…')).toBeVisible() + expect(screen.queryByText('正在等待发送运行时完成初始化…')).not.toBeInTheDocument() + }) + + it('does not say the runtime is still initializing when it is ready but message capabilities are pending', () => { + const boundButInitializing: PersonalWechatSenderStatus = { + ...unavailableStatus, + state: 'hook_not_ready', + wechatRunning: true, + wechatPid: 4668, + boundWechatPid: 4668, + endpointReady: true, + runtimeReady: true, + attachReady: true, + baseAddressReady: true, + message: '已绑定,等待发送 hook 就绪' + } + + render( + + ) + + expect(screen.getByText('微信已绑定,正在等待发送能力完成初始化…')).toBeVisible() + expect(screen.queryByText('正在等待发送运行时完成初始化…')).not.toBeInTheDocument() + }) + it('shows the disabled binding flow on the settings page', async () => { render() @@ -206,12 +263,17 @@ describe('personal WeChat unavailable product state', () => { const copyButton = await screen.findByRole('button', { name: '复制完整设备 ID' }) fireEvent.click(copyButton) await waitFor(() => expect(navigator.clipboard.writeText).toHaveBeenCalledWith(deviceId)) - expect(await screen.findByText('授权已过期')).toBeVisible() + expect(await screen.findByText('授权状态需刷新')).toBeVisible() + expect( + screen.getByText('当前授权状态与到期日不一致,请点击「重新检测授权」更新状态。') + ).toBeVisible() fireEvent.click(screen.getByRole('button', { name: '重新检测授权' })) expect(await screen.findByRole('button', { name: '检测中…' })).toBeDisabled() expect(copyButton).toBeEnabled() resolveRefresh?.({ ...licenseStatus, deviceId, state: 'valid', authorized: true }) + expect(await screen.findByText('设备已授权')).toBeVisible() + expect(screen.queryByText('授权状态需刷新')).not.toBeInTheDocument() }) it('does not query or render License when the send runtime is unavailable', async () => { diff --git a/tests/unit/mac-wechat-residual-cleanup.test.ts b/tests/unit/mac-wechat-residual-cleanup.test.ts new file mode 100644 index 0000000..5afd620 --- /dev/null +++ b/tests/unit/mac-wechat-residual-cleanup.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it, vi } from 'vitest' +import { + cleanupMacWechatResidualProcesses, + inspectMacWechatResidualProcesses, + readPids, + type MacWechatResidualCleanupDependencies +} from '../../src/main/services/mac-wechat-residual-cleanup' + +function createDependencies( + overrides: Partial = {} +): MacWechatResidualCleanupDependencies { + return { + platform: 'darwin', + listWechatPids: vi.fn(async () => [101]), + listPortPids: vi.fn(async () => [202]), + processName: vi.fn(async (pid) => (pid === 101 ? 'WeChat' : 'tm-wechat-host')), + processIdentity: vi.fn(async (pid) => 'identity-' + pid), + signal: vi.fn(), + wait: vi.fn(async () => undefined), + ...overrides + } +} + +describe('macOS WeChat residual cleanup', () => { + it('treats pgrep exit code 1 as no matching process', async () => { + const run = vi.fn(async () => { + throw Object.assign(new Error('Command failed: /usr/bin/pgrep -x Weixin'), { code: 1 }) + }) + + await expect(readPids('/usr/bin/pgrep', ['-x', 'Weixin'], run)).resolves.toEqual([]) + }) + + it('lists only WeChat processes and port 4290 listeners', async () => { + const dependencies = createDependencies() + + await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([ + { pid: 101, name: 'WeChat', targets: ['wechat'], confirmationToken: 'identity-101' }, + { + pid: 202, + name: 'tm-wechat-host', + targets: ['port_4290'], + confirmationToken: 'identity-202' + } + ]) + expect(dependencies.processName).toHaveBeenCalledTimes(2) + }) + + it('does not signal a PID whose process identity changed after confirmation', async () => { + const dependencies = createDependencies({ + listWechatPids: vi.fn(async () => []), + listPortPids: vi.fn(async () => [202]), + processIdentity: vi.fn(async () => 'changed-process') + }) + + const result = await cleanupMacWechatResidualProcesses( + [{ pid: 202, confirmationToken: 'old-process' }], + dependencies + ) + + expect(dependencies.signal).not.toHaveBeenCalled() + expect(result.remaining).toEqual([ + { + pid: 202, + name: 'tm-wechat-host', + targets: ['port_4290'], + confirmationToken: 'changed-process' + } + ]) + }) + + it('uses graceful termination first and only escalates confirmed targets', async () => { + const signalled: Array<[number, NodeJS.Signals]> = [] + const dependencies = createDependencies({ + listWechatPids: vi.fn(async () => []), + listPortPids: vi.fn(async () => [202]), + signal: vi.fn((pid, signal) => signalled.push([pid, signal])) + }) + + const targets = await inspectMacWechatResidualProcesses(dependencies) + const result = await cleanupMacWechatResidualProcesses( + [{ pid: 202, confirmationToken: targets[0].confirmationToken }], + dependencies + ) + + expect(signalled).toEqual([ + [202, 'SIGTERM'], + [202, 'SIGKILL'] + ]) + expect(result.remaining.map((target) => target.pid)).toEqual([202]) + }) + + it('reports only identity-matched targets before signaling so the caller can stop its own runtime safely', async () => { + const dependencies = createDependencies({ + listWechatPids: vi.fn(async () => []), + listPortPids: vi.fn(async () => [202, 303]), + processIdentity: vi.fn(async (pid) => + pid === 202 ? 'identity-202' : 'stale-confirmation-303' + ), + processName: vi.fn(async (pid) => 'process-' + pid), + signal: vi.fn() + }) + const onTargetsConfirmed = vi.fn() + + await cleanupMacWechatResidualProcesses( + [{ pid: 202, confirmationToken: 'identity-202' }], + dependencies, + onTargetsConfirmed + ) + + expect(onTargetsConfirmed).toHaveBeenCalledWith([ + { + pid: 202, + name: 'process-202', + targets: ['port_4290'], + confirmationToken: 'identity-202' + } + ]) + expect(dependencies.signal).toHaveBeenCalledWith(202, 'SIGTERM') + expect(dependencies.signal).not.toHaveBeenCalledWith(303, expect.any(String)) + }) + + it('does not signal a process after its PID identity changes', async () => { + let identityReads = 0 + const dependencies = createDependencies({ + listWechatPids: vi.fn(async () => []), + listPortPids: vi.fn(async () => [202]), + processIdentity: vi.fn(async () => { + identityReads += 1 + return identityReads === 1 ? 'confirmed-process' : 'reused-pid-process' + }), + signal: vi.fn() + }) + const onTargetsConfirmed = vi.fn() + + const result = await cleanupMacWechatResidualProcesses( + [{ pid: 202, confirmationToken: 'confirmed-process' }], + dependencies, + onTargetsConfirmed + ) + + expect(dependencies.signal).not.toHaveBeenCalled() + expect(onTargetsConfirmed).not.toHaveBeenCalled() + expect(result.stopped).toEqual([]) + expect(result.remaining[0]).toMatchObject({ + pid: 202, + confirmationToken: 'reused-pid-process' + }) + }) + + it('does nothing outside macOS', async () => { + const dependencies = createDependencies({ platform: 'win32' }) + + await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([]) + await expect( + cleanupMacWechatResidualProcesses( + [{ pid: 101, confirmationToken: 'identity-101' }], + dependencies + ) + ).resolves.toEqual({ + stopped: [], + remaining: [] + }) + expect(dependencies.signal).not.toHaveBeenCalled() + }) +})