mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 完善mac发送逻辑
This commit is contained in:
1 parent
05b881d79e
commit
f47af8024f
13 files changed
+1048
-46
No files matched your search
+54
-6
@@ -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<ImageDebugInfoResult> => {
|
||||
'image:getDebugInfo',
|
||||
async (_, request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> => {
|
||||
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()
|
||||
)
|
||||
|
||||
@@ -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<InstalledReportTemplate[]> {
|
||||
await fs.mkdir(path.join(this.directory, INSTALLED_DIR), { recursive: true })
|
||||
|
||||
@@ -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<number[]>
|
||||
listPortPids: () => Promise<number[]>
|
||||
processName: (pid: number) => Promise<string>
|
||||
processIdentity: (pid: number) => Promise<string>
|
||||
signal: (pid: number, signal: NodeJS.Signals) => void
|
||||
wait: (milliseconds: number) => Promise<void>
|
||||
}
|
||||
|
||||
export async function readPids(
|
||||
executable: string,
|
||||
args: string[],
|
||||
run: PidCommandRunner = async (file, commandArgs, options) =>
|
||||
execFileAsync(file, commandArgs, options)
|
||||
): Promise<number[]> {
|
||||
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<number, string>,
|
||||
processIdentities: Map<number, string>
|
||||
): ObservedTarget[] {
|
||||
const targets = new Map<number, Set<'wechat' | 'port_4290'>>()
|
||||
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<ObservedTarget[]> {
|
||||
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<MacWechatResidualProcess[]> {
|
||||
return inspectObservedTargets(dependencies)
|
||||
}
|
||||
|
||||
export async function cleanupMacWechatResidualProcesses(
|
||||
confirmedTargets: Array<Pick<MacWechatResidualProcess, 'pid' | 'confirmationToken'>>,
|
||||
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<void> => {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<MacWechatRuntimeSnapshot> {
|
||||
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<MacWechatRuntimeSnapshot> {
|
||||
async ensureStarted(
|
||||
options: { allowManualRestart?: boolean } = {}
|
||||
): Promise<MacWechatRuntimeSnapshot> {
|
||||
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<MacWechatRuntimeSnapshot> {
|
||||
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 {
|
||||
|
||||
@@ -140,7 +140,7 @@ export function probeLicenseStatus(timeoutMs = PROBE_TIMEOUT_MS): Promise<Licens
|
||||
let req: http.ClientRequest
|
||||
try {
|
||||
req = http.get(
|
||||
{ host: '127.0.0.1', port: 4290, path: '/license/status', timeout: timeoutMs },
|
||||
{ host: '127.0.0.1', port: Number(process.env.TM_WECHAT_HOST_PORT) || 4290, path: '/license/status', timeout: timeoutMs },
|
||||
(res) => {
|
||||
const chunks: Buffer[] = []
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||
|
||||
Vendored
+15
-7
@@ -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<ImageTextIndexRepairResult>
|
||||
onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void
|
||||
getPersonalWechatSenderStatus: () => Promise<PersonalWechatSenderStatus>
|
||||
getMacLicenseStatus: () => Promise<MacLicenseStatus>
|
||||
getMacSendRuntimeAvailability: () => Promise<MacWechatSendRuntimeAvailabilityResult>
|
||||
refreshMacLicense: () => Promise<MacLicenseStatus>
|
||||
getMacLicenseStatus: () => Promise<MacLicenseStatus>
|
||||
getMacSendRuntimeAvailability: () => Promise<MacWechatSendRuntimeAvailabilityResult>
|
||||
startMacSendRuntime: () => Promise<MacWechatRuntimeSnapshot>
|
||||
listMacWechatResidualProcesses: () => Promise<MacWechatResidualProcess[]>
|
||||
cleanupMacWechatResidualProcesses: (
|
||||
targets: Array<Pick<MacWechatResidualProcess, 'pid' | 'confirmationToken'>>
|
||||
) => Promise<MacWechatResidualCleanupResult>
|
||||
refreshMacLicense: () => Promise<MacLicenseStatus>
|
||||
getPersonalWechatSendCapability: () => Promise<PersonalWechatSendCapability>
|
||||
checkPersonalWechatSenderStatus: (port?: string) => Promise<PersonalWechatSenderStatus>
|
||||
checkPersonalWechatVoiceEncodingEnvironment: () => Promise<PersonalWechatVoiceEncodingEnvironment>
|
||||
@@ -774,9 +784,7 @@ declare global {
|
||||
ruleId: string
|
||||
) => Promise<{ success: boolean; error?: string; data?: ScheduledRuleRunOutcome }>
|
||||
/** 定时日报:旧执行记录**只读存档**(旧记录无法无损转换,原样展示)。 */
|
||||
listScheduledReportLegacyExecutions: (
|
||||
ruleId?: string
|
||||
) => Promise<ScheduledReportExecution[]>
|
||||
listScheduledReportLegacyExecutions: (ruleId?: string) => Promise<ScheduledReportExecution[]>
|
||||
/** 定时日报:微信异常通知开关与能力检测。 */
|
||||
getScheduledReportNotificationSettings: () => Promise<ScheduledReportNotificationSettings>
|
||||
getScheduledReportNotificationCapability: () => Promise<ScheduledReportNotificationCapability>
|
||||
|
||||
+14
-1
@@ -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<MacWechatSendRuntimeAvailabilityResult> =>
|
||||
ipcRenderer.invoke('wechat-personal:getMacSendRuntimeAvailability'),
|
||||
startMacSendRuntime: (): Promise<MacWechatRuntimeSnapshot> =>
|
||||
ipcRenderer.invoke('wechat-personal:startMacSendRuntime'),
|
||||
listMacWechatResidualProcesses: (): Promise<MacWechatResidualProcess[]> =>
|
||||
ipcRenderer.invoke('wechat-personal:listMacResidualProcesses'),
|
||||
cleanupMacWechatResidualProcesses: (
|
||||
targets: Array<Pick<MacWechatResidualProcess, 'pid' | 'confirmationToken'>>
|
||||
): Promise<MacWechatResidualCleanupResult> =>
|
||||
ipcRenderer.invoke('wechat-personal:cleanupMacResidualProcesses', targets),
|
||||
refreshMacLicense: (): Promise<MacLicenseStatus> =>
|
||||
ipcRenderer.invoke('wechat-personal:refreshMacLicense'),
|
||||
getPersonalWechatSendCapability: (): Promise<PersonalWechatSendCapability> =>
|
||||
|
||||
@@ -76,7 +76,7 @@ export function PersonalWechatSetupGuide({
|
||||
<div>
|
||||
<span className="personal-wechat-eyebrow">首次使用</span>
|
||||
<h2>先准备好微信消息功能</h2>
|
||||
<p>只需几步,TraceMemo 就能在当前会话中生成并发送语音。</p>
|
||||
<p>只需几步,TraceMemo 就能具备微信消息发送能力。</p>
|
||||
</div>
|
||||
{allReady && <span className="personal-wechat-setup-complete">已完成</span>}
|
||||
</div>
|
||||
@@ -176,7 +176,11 @@ export function PersonalWechatSetupGuide({
|
||||
)}
|
||||
{initializing && (
|
||||
<p className="personal-wechat-step-hint" role="status">
|
||||
{detecting ? '正在初始化发送能力…' : '正在等待发送运行时完成初始化…'}
|
||||
{detecting
|
||||
? '正在初始化发送能力…'
|
||||
: runtimeReady
|
||||
? '微信已绑定,正在等待发送能力完成初始化…'
|
||||
: '正在等待发送运行时完成初始化…'}
|
||||
</p>
|
||||
)}
|
||||
{senderStatus?.state === 'error' && (
|
||||
|
||||
@@ -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({
|
||||
<section className="settings-card mac-pro-license-card" aria-label="发送能力授权">
|
||||
<header className="mac-pro-license-header">
|
||||
<strong>发送能力授权</strong>
|
||||
<span className={`mac-pro-license-status ${licenseTone(license.state)}`}>
|
||||
{license.state === 'valid' || license.state === 'cached'
|
||||
? '设备已授权'
|
||||
: macLicenseStateLabel[license.state]}
|
||||
<span className={`mac-pro-license-status ${macLicenseStatusTone(license)}`}>
|
||||
{macLicenseStatusLabel(license)}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
@@ -215,10 +256,8 @@ export function MacProLicenseCard({
|
||||
{copied ? '已复制' : '复制'}
|
||||
</Button>
|
||||
</div>
|
||||
{license.deviceId && !license.authorized ? (
|
||||
<p className="mac-pro-license-hint">
|
||||
将设备 ID 提供给授权管理员,完成授权后点击「重新检测授权」。
|
||||
</p>
|
||||
{license.deviceId && (!license.authorized || licenseStateConflictsWithExpiry(license)) ? (
|
||||
<p className="mac-pro-license-hint">{macLicenseStatusHint(license)}</p>
|
||||
) : null}
|
||||
{license.authorized && license.features.length > 0 ? (
|
||||
<div className="mac-pro-license-features" aria-label="已开通功能">
|
||||
@@ -273,7 +312,33 @@ export function PersonalWechatSendPage({
|
||||
const [macLicenseStatus, setMacLicenseStatus] = useState<MacLicenseStatus | null>(null)
|
||||
const [macRuntimeAvailability, setMacRuntimeAvailability] =
|
||||
useState<MacWechatSendRuntimeAvailabilityResult | null>(null)
|
||||
const [macResidualProcesses, setMacResidualProcesses] = useState<
|
||||
Awaited<ReturnType<typeof window.api.listMacWechatResidualProcesses>>
|
||||
>([])
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
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({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{macSendPort && senderStatus?.endpointReady ? (
|
||||
<p
|
||||
className="mt-3 rounded-md border border-border-subtle p-3 text-sm"
|
||||
role="status"
|
||||
>
|
||||
当前发送能力占用端口为 {macSendPort}(TM_WECHAT_HOST_PORT)。
|
||||
</p>
|
||||
) : null}
|
||||
<section
|
||||
className="mt-4 flex flex-wrap items-center justify-between gap-2 rounded-md border border-border-subtle p-3"
|
||||
aria-label="4290 端口状态"
|
||||
>
|
||||
<div>
|
||||
<strong className="text-sm">4290 端口</strong>
|
||||
<p className="mt-1 text-sm text-muted-foreground" role="status">
|
||||
{mac4290PortStatus.state === 'loading'
|
||||
? '正在检查占用状态…'
|
||||
: mac4290PortStatus.state === 'error'
|
||||
? '占用状态读取失败'
|
||||
: mac4290PortStatus.state === 'available'
|
||||
? '未被占用'
|
||||
: '已被占用:' +
|
||||
mac4290PortStatus.processes
|
||||
.map(({ name, pid }) => name + '(PID ' + pid + ')')
|
||||
.join('、')}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={macResidualBusy}
|
||||
onClick={() => void refreshMac4290PortStatus()}
|
||||
>
|
||||
刷新端口状态
|
||||
</Button>
|
||||
</section>
|
||||
{macWechatRebindRequired ? (
|
||||
<div
|
||||
className="mt-3 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm"
|
||||
role="status"
|
||||
>
|
||||
微信进程已清理。请重新打开微信,然后点击“绑定微信”;绑定完成后此提示会自动消失。
|
||||
</div>
|
||||
) : null}
|
||||
{senderStatus && macRuntimeAvailability?.state === 'available' ? (
|
||||
<div
|
||||
className="mac-wechat-capability-details"
|
||||
@@ -795,6 +1008,24 @@ export function PersonalWechatSendPage({
|
||||
>
|
||||
{macPrimaryAction.label}
|
||||
</Button>
|
||||
<Button
|
||||
className="mt-2 w-full"
|
||||
variant="outline"
|
||||
disabled={macResidualBusy}
|
||||
onClick={() => void inspectMacResidualProcesses()}
|
||||
>
|
||||
{macResidualBusy ? '检查中…' : '清理残留以及微信进程'}
|
||||
</Button>
|
||||
{macResidualRuntimeStopped ? (
|
||||
<Button
|
||||
className="mt-2 w-full"
|
||||
variant="outline"
|
||||
disabled={macResidualBusy}
|
||||
onClick={() => void restartMacSendRuntime()}
|
||||
>
|
||||
{macResidualBusy ? '启动中…' : '重新启动发送组件'}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
{macUnavailable ? (
|
||||
@@ -810,6 +1041,43 @@ export function PersonalWechatSendPage({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AlertDialog open={macResidualDialogOpen} onOpenChange={setMacResidualDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>清理微信残留进程?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
将结束下面列出的微信进程或占用 4290
|
||||
端口的进程。若列表包含微信,微信会关闭;如曾绑定发送组件,之后需要重新打开微信并绑定。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<ul className="grid gap-2 rounded-md border border-border-subtle p-3 text-sm">
|
||||
{macResidualProcesses.map((item) => (
|
||||
<li key={item.pid} className="flex justify-between gap-4">
|
||||
<span className="break-all">{item.name}</span>
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
PID {item.pid} ·{' '}
|
||||
{item.targets
|
||||
.map((target) => (target === 'wechat' ? '微信进程' : '4290 端口'))
|
||||
.join('、')}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={macResidualBusy}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
disabled={macResidualBusy}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
void cleanupMacResidualProcesses()
|
||||
}}
|
||||
>
|
||||
{macResidualBusy ? '清理中…' : '确认结束进程'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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(<PersonalWechatSendPage onNotice={vi.fn()} />)
|
||||
|
||||
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(<PersonalWechatSendPage onNotice={onNotice} />)
|
||||
|
||||
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(<PersonalWechatSendPage onNotice={onNotice} />)
|
||||
|
||||
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(<PersonalWechatSendPage onNotice={onNotice} />)
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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(
|
||||
<PersonalWechatSetupGuide
|
||||
senderStatus={boundStatus}
|
||||
binding={false}
|
||||
detecting={false}
|
||||
sessionBound
|
||||
showBindAction={false}
|
||||
/>
|
||||
)
|
||||
|
||||
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(
|
||||
<PersonalWechatSetupGuide
|
||||
senderStatus={boundButInitializing}
|
||||
binding={false}
|
||||
detecting={false}
|
||||
sessionBound
|
||||
showBindAction={false}
|
||||
showBindingInstructionsInInitialization
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('微信已绑定,正在等待发送能力完成初始化…')).toBeVisible()
|
||||
expect(screen.queryByText('正在等待发送运行时完成初始化…')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the disabled binding flow on the settings page', async () => {
|
||||
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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> = {}
|
||||
): 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()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user