feat: mac发送完整支持4.1.13以上版本, 完善授权

This commit is contained in:
Wxw-Gu committed 2026-11-04 15:49:15 +08:00
1 parent 9db08dba1a
commit 8c162969ff
18 files changed
+1841 -238

No files matched your search

+13 -3
View File
@@ -1557,15 +1557,16 @@ app.whenReady().then(async () => {
/**
* 正式 MessageListener(Observation Mode 接入)。
*
* 本轮**只监听、回读、规范化、去重、统计**,不触发任何业务:
* 只监听、回读、规范化、去重、统计,不触发任何业务:
* 不匹配关键词、不判断 @我、不出日报、不回复、不调 AI / Agent、不发送。
* 下一层的 Trigger 由后续任务接入。
* 业务响应由上层消费者自行订阅,不在监听层实现。
*/
const messageListener = new MessageListenerService(wcdb4Client)
/**
* Automation v1(@我生成日报)。
*
* `isListening` 要等下面 `startMonitor` 有结果才知道,所以先用闭包变量占位。
* `isListening` 反映 `startMonitor` 的实际结果,因此通过闭包读取,
* 而不是在初始化时传入快照。
*/
let automationListening = false
initAutomationService(wcdb4Client, { isListening: () => automationListening })
@@ -3442,6 +3443,15 @@ app.whenReady().then(async () => {
return { success: true }
})
ipcMain.handle('wechat-personal:getStatus', () => currentPersonalWechatSenderStatus())
ipcMain.handle('wechat-personal:getMacLicenseStatus', () =>
macWechatRuntimeManager.getMacLicenseStatus()
)
ipcMain.handle('wechat-personal:getMacSendRuntimeAvailability', () =>
macWechatRuntimeManager.getSendRuntimeAvailability()
)
ipcMain.handle('wechat-personal:refreshMacLicense', () =>
macWechatRuntimeManager.refreshMacLicense()
)
ipcMain.handle('wechat-personal:checkStatus', (_, port?: string) =>
personalWechatSendService.checkWindowsStatus(port)
)
+197 -17
View File
@@ -1,20 +1,30 @@
import { spawn, type ChildProcess } from 'child_process'
import { chmodSync, existsSync } from 'fs'
import { get } from 'http'
import { get, request as httpRequest } from 'http'
import { join } from 'path'
import { app } from 'electron'
import { appLogger } from '../app-logger'
import { isMacNativeRuntimeUnavailable, resolveWechatRuntimeDirectory } from '../native-runtime-paths'
import {
isMacNativeRuntimeUnavailable,
resolveWechatRuntimeDirectory
} from '../native-runtime-paths'
import type { MacLicenseStatus } from '../../shared/personal-wechat-mac-license'
import {
offlineMacLicenseStatus,
parseMacLicenseStatus
} from '../../shared/personal-wechat-mac-license'
import type {
MacWechatBindResult,
MacWechatBindingStatus,
MacWechatRuntimeManifest,
MacWechatRuntimeLifecycle,
MacWechatRuntimeSnapshot
MacWechatRuntimeSnapshot,
MacWechatSendRuntimeAvailabilityResult
} from '../../shared/personal-wechat-mac-runtime'
import type { PersonalWechatSenderStatus } from '../../shared/personal-wechat'
import { hasValidWechatLicense } from '../../shared/personal-wechat-mac-send-action'
import {
bindingMatchesRuntimeManifest,
readMacWechatRuntimeManifest
@@ -43,6 +53,10 @@ const HOST = '127.0.0.1'
const START_TIMEOUT_MS = 15_000
const REQUEST_TIMEOUT_MS = 30_000
const CRASH_RESTART_DELAY_MS = 1_500
/* /license/status is a local cache read; keep it snappy. /license/refresh runs a
* real challenge->sign->check cycle inside the host, which is bounded at 15s. */
const LICENSE_STATUS_TIMEOUT_MS = 8_000
const LICENSE_REFRESH_TIMEOUT_MS = 20_000
interface MacWechatSenderStatusInput {
snapshot: MacWechatRuntimeSnapshot
@@ -119,12 +133,9 @@ export function deriveMacWechatSenderStatus({
identityMatches &&
state === 'online' &&
(binding?.sendContextReady === true || nativeBindingReady)
const canSendText =
bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage =
bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice =
bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -157,6 +168,25 @@ export function deriveMacWechatSenderStatus({
}
}
/**
* 在线刷新失败时的返回策略:
* 缓存里还有可用授权就保留它(只把失败写进 message),否则明确报告网络故障。
* 单独抽出来是因为这两条分支都必须可测 —— 把网络故障错报成「已撤销」会让
* 用户去找客服,错报成「有效」又会掩盖真实故障。
*/
export function resolveLicenseRefreshFailure(
snapshot: MacLicenseStatus | null,
diagnostic: string
): MacLicenseStatus {
if (snapshot?.authorized) {
return {
...snapshot,
message: `本次刷新失败:${diagnostic}(仍使用本地缓存授权)`
}
}
return offlineMacLicenseStatus('server_unavailable', diagnostic)
}
class MacWechatRuntimeManager {
private child: ChildProcess | null = null
private lifecycle: MacWechatRuntimeLifecycle = 'stopped'
@@ -211,6 +241,21 @@ class MacWechatRuntimeManager {
}
}
getSendRuntimeAvailability(): MacWechatSendRuntimeAvailabilityResult {
if (isMacNativeRuntimeUnavailable()) {
return { state: 'unavailable', message: '当前版本没有微信发送能力' }
}
try {
const runtimeDir = this.resolveRuntimeDir()
if (!runtimeDir) throw new Error('发送 Runtime 目录缺失')
this.manifest = readMacWechatRuntimeManifest(runtimeDir)
return { state: 'available', message: '微信发送组件可用' }
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
return { state: 'component_error', message: `发送组件缺失或异常:${detail}` }
}
}
/**
* Start the host if it is not already running. Deliberately lazy: the host
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
@@ -423,11 +468,28 @@ class MacWechatRuntimeManager {
private request(
method: string,
path: string,
timeoutMs = REQUEST_TIMEOUT_MS
timeoutMs = REQUEST_TIMEOUT_MS,
body?: string
): Promise<{ status: number | null; body: string }> {
return new Promise((resolve) => {
const request = get(
{ host: HOST, port: PORT, path, method, timeout: timeoutMs },
const payload = body !== undefined ? Buffer.from(body, 'utf8') : undefined
// GET keeps using `get()` (auto-end); POST goes through `request()` so we
// can attach a JSON body. Both funnel into the same resolve contract.
const transport = method === 'GET' || method === 'HEAD' ? get : httpRequest
const req = transport(
{
host: HOST,
port: PORT,
path,
method,
timeout: timeoutMs,
headers: payload
? {
'Content-Type': 'application/json',
'Content-Length': payload.length
}
: undefined
},
(response) => {
let body = ''
response.on('data', (chunk) => {
@@ -438,14 +500,15 @@ class MacWechatRuntimeManager {
})
}
)
request.on('timeout', () => {
request.destroy()
req.on('timeout', () => {
req.destroy()
resolve({ status: null, body: '' })
})
request.on('error', () => {
req.on('error', () => {
resolve({ status: null, body: '' })
})
request.end()
if (payload) req.write(payload)
req.end()
})
}
@@ -527,6 +590,97 @@ class MacWechatRuntimeManager {
return this.lastBinding
}
// GET reads the local snapshot; POST runs one real online check.
// Neither touches the WeChat binding.
/** Local snapshot. Never attaches to WeChat, never forces a network refresh.
* 404 means the host predates these endpoints — not "unlicensed". */
async getMacLicenseStatus(): Promise<MacLicenseStatus> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
}
if (availability.state !== 'available') {
return offlineMacLicenseStatus('runtime_missing', availability.message)
}
if (this.lifecycle === 'stopped') await this.ensureStarted()
const { status, body } = await this.request('GET', '/license/status', LICENSE_STATUS_TIMEOUT_MS)
if (status === null) {
return offlineMacLicenseStatus('runtime_missing', 'Mac 发送组件未运行,请先启动发送组件')
}
if (status === 404) {
return offlineMacLicenseStatus(
'unsupported',
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
)
}
if (status !== 200) {
return offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`)
}
try {
return parseMacLicenseStatus(JSON.parse(body))
} catch {
return offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析')
}
}
/**
* One real online check; re-entrant calls return the current snapshot instead
* of minting a duplicate challenge. Network failure maps to server_unavailable,
* never to revoked.
*/
async refreshMacLicense(): Promise<MacLicenseStatus> {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
}
if (availability.state !== 'available') {
return offlineMacLicenseStatus('runtime_missing', availability.message)
}
if (this.lifecycle === 'stopped') await this.ensureStarted()
if (this.licenseRefreshInFlight) {
// A refresh is already running; answer from the local snapshot so the
// button click is a no-op instead of stacking a second online check.
return this.getMacLicenseStatus()
}
this.licenseRefreshInFlight = true
try {
const { status, body } = await this.request(
'POST',
'/license/refresh',
LICENSE_REFRESH_TIMEOUT_MS,
'{}'
)
if (status === null) {
const snapshot = await this.getMacLicenseStatus().catch(() => null)
return resolveLicenseRefreshFailure(snapshot, '无法连接授权服务器,请检查网络后重试')
}
if (status === 404) {
return offlineMacLicenseStatus(
'unsupported',
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
)
}
let envelope: Record<string, unknown>
try {
envelope = JSON.parse(body) as Record<string, unknown>
} catch {
return offlineMacLicenseStatus('runtime_missing', '授权刷新响应无法解析')
}
// The host wraps the result: { ok, code, message, status: MacLicenseStatus }
const nested = envelope.status ?? envelope
const parsed = parseMacLicenseStatus(nested)
if (typeof envelope.errorCode === 'number' && parsed.errorCode == null) {
parsed.errorCode = envelope.errorCode
}
return parsed
} finally {
this.licenseRefreshInFlight = false
}
}
private licenseRefreshInFlight = false
/*
* Build the legacy PersonalWechatSenderStatus contract from the live mac
* runtime state. Lives here (not in the capability service) so BOTH the
@@ -650,7 +804,8 @@ class MacWechatRuntimeManager {
* live WeChat pid again returns attached=false and never double-attaches.
*/
async bind(): Promise<MacWechatBindResult> {
if (isMacNativeRuntimeUnavailable()) {
const availability = this.getSendRuntimeAvailability()
if (availability.state === 'unavailable') {
return {
ok: false,
attached: false,
@@ -658,6 +813,9 @@ class MacWechatRuntimeManager {
message: '当前环境不包含微信发送能力'
}
}
if (availability.state !== 'available') {
return { ok: false, attached: false, state: 'runtime_offline', message: availability.message }
}
if (this.lifecycle !== 'online') {
const snapshot = await this.ensureStarted()
if (snapshot.lifecycle !== 'online') {
@@ -684,6 +842,28 @@ class MacWechatRuntimeManager {
}
}
const license = await this.getMacLicenseStatus()
const licenseAllowed = hasValidWechatLicense(license)
if (!licenseAllowed) {
const tokenExpiresAt = license.tokenExpiresAt
? Date.parse(license.tokenExpiresAt)
: Number.NaN
const message =
license.state === 'revoked'
? 'LICENSE_REVOKED: 微信发送授权已撤销'
: license.state === 'expired' ||
(Number.isFinite(tokenExpiresAt) && tokenExpiresAt <= Date.now())
? 'LICENSE_EXPIRED: 微信发送授权已过期'
: license.state === 'device_mismatch'
? 'LICENSE_DEVICE_MISMATCH: 授权与当前设备不匹配'
: license.state === 'identity_error'
? 'LICENSE_IDENTITY_ERROR: 设备身份异常'
: license.authorized && !license.features.includes('wechat')
? 'LICENSE_FEATURE_DENIED: 未开通微信发送'
: 'LICENSE_REQUIRED: 需要有效的微信发送授权'
return { ok: false, attached: false, state: 'host_error', message }
}
const { status, body } = await this.request('POST', '/bindWeChat')
await this.refreshBinding().catch(() => null)
+5
View File
@@ -84,6 +84,8 @@ import type {
PersonalWechatVoiceDiagnostic
} from '../shared/personal-wechat'
import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from '../shared/personal-wechat-mac-runtime'
import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../shared/group-stats'
import type {
ScheduledReportExecution,
@@ -751,6 +753,9 @@ declare global {
repairImageTextIndex: () => Promise<ImageTextIndexRepairResult>
onImageTextIndexStatus: (callback: (status: ImageTextIndexStatus) => void) => () => void
getPersonalWechatSenderStatus: () => Promise<PersonalWechatSenderStatus>
getMacLicenseStatus: () => Promise<MacLicenseStatus>
getMacSendRuntimeAvailability: () => Promise<MacWechatSendRuntimeAvailabilityResult>
refreshMacLicense: () => Promise<MacLicenseStatus>
getPersonalWechatSendCapability: () => Promise<PersonalWechatSendCapability>
checkPersonalWechatSenderStatus: (port?: string) => Promise<PersonalWechatSenderStatus>
checkPersonalWechatVoiceEncodingEnvironment: () => Promise<PersonalWechatVoiceEncodingEnvironment>
+8
View File
@@ -14,6 +14,8 @@ import type {
SaveGeneratedReportRequest,
UpdateGeneratedReportTemplateRequest
} from '../shared/report-history'
import type { MacLicenseStatus } from '../shared/personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from '../shared/personal-wechat-mac-runtime'
import type {
AIChatRequestOptions,
AiSearchExternalAuthorizationRequest,
@@ -585,6 +587,12 @@ const api = {
},
getPersonalWechatSenderStatus: (): Promise<PersonalWechatSenderStatus> =>
ipcRenderer.invoke('wechat-personal:getStatus'),
getMacLicenseStatus: (): Promise<MacLicenseStatus> =>
ipcRenderer.invoke('wechat-personal:getMacLicenseStatus'),
getMacSendRuntimeAvailability: (): Promise<MacWechatSendRuntimeAvailabilityResult> =>
ipcRenderer.invoke('wechat-personal:getMacSendRuntimeAvailability'),
refreshMacLicense: (): Promise<MacLicenseStatus> =>
ipcRenderer.invoke('wechat-personal:refreshMacLicense'),
getPersonalWechatSendCapability: (): Promise<PersonalWechatSendCapability> =>
ipcRenderer.invoke('wechat-personal:getSendCapability'),
checkPersonalWechatSenderStatus: (port?: string): Promise<PersonalWechatSenderStatus> =>
@@ -8,19 +8,20 @@ interface PersonalWechatSetupGuideProps {
binding: boolean
detecting: boolean
sessionBound: boolean
onBind: () => void
onStartSending: () => void
onBind?: () => void
onStartSending?: () => void
onOpenTextToSpeechSettings?: () => void
}
function capabilityLabel(ready: boolean, initializing: boolean): string {
if (ready) return '已就绪'
return initializing ? '初始化中' : '未就绪'
showBindAction?: boolean
showStartSendingAction?: boolean
showCapabilityStatus?: boolean
showBindingInstructionsInInitialization?: boolean
showAuthorizationWarning?: boolean
canBind?: boolean
}
function bindingHint(status: PersonalWechatSenderStatus): string {
if (status.state === 'wechat_not_running') {
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
}
if (status.state === 'unsupported_platform') return '当前系统暂不支持个人微信发送。'
if (status.state === 'unsupported_version')
@@ -29,7 +30,7 @@ function bindingHint(status: PersonalWechatSenderStatus): string {
return '请先完成发送运行时准备。'
}
if (status.state === 'error') return '连接微信时遇到问题,请稍后重试。'
return '请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。'
return '4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。4.1.13以上登录状态微信直接点击“绑定微信”'
}
function isWechatBound(status: PersonalWechatSenderStatus): boolean {
@@ -41,6 +42,11 @@ function isWechatBound(status: PersonalWechatSenderStatus): boolean {
)
}
function capabilityLabel(ready: boolean, initializing: boolean): string {
if (ready) return '已就绪'
return initializing ? '初始化中' : '未就绪'
}
export function PersonalWechatSetupGuide({
senderStatus,
binding,
@@ -48,7 +54,13 @@ export function PersonalWechatSetupGuide({
sessionBound,
onBind,
onStartSending,
onOpenTextToSpeechSettings
onOpenTextToSpeechSettings,
showBindAction = true,
showStartSendingAction = true,
showCapabilityStatus = true,
showBindingInstructionsInInitialization = false,
showAuthorizationWarning = true,
canBind = true
}: PersonalWechatSetupGuideProps): React.ReactElement {
const runtimeUnavailable = senderStatus?.state === 'runtime_missing'
const runtimeLabel = '发送运行时'
@@ -76,7 +88,7 @@ export function PersonalWechatSetupGuide({
<strong>准备 {runtimeLabel}</strong>
<p>
{runtimeUnavailable
? `个人微信发送需要${runtimeLabel},授权后即可使用。`
? '当前版本没有微信发送能力。'
: `${runtimeLabel}随 TraceMemo 一起提供,无需额外安装。`}
</p>
{runtimeReady ? (
@@ -89,65 +101,79 @@ export function PersonalWechatSetupGuide({
</div>
</li>
<li
className={
connected
? 'is-complete'
: binding
? 'is-active'
: runtimeReady
? 'is-current'
: 'is-pending'
}
>
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
<div className="personal-wechat-step-content">
<strong>绑定个人微信</strong>
<p>请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
{connected ? (
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
) : (
<Button
size="sm"
variant="outline"
onClick={onBind}
disabled={runtimeUnavailable || !runtimeReady || binding}
>
{binding ? '正在绑定…' : '绑定微信'}
</Button>
)}
{!connected && senderStatus && !runtimeUnavailable && (
<p className="personal-wechat-step-hint">{bindingHint(senderStatus)}</p>
)}
{!connected && runtimeUnavailable && (
<div className="personal-wechat-authorization-warning" role="alert">
<span aria-hidden>!</span>
<p>
发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。
进群请点击{' '}
<a href={GROUP_README_URL} target="_blank" rel="noreferrer">
这里
</a>{' '}
跳转。
</p>
</div>
)}
{!connected && !runtimeUnavailable && (
<p className="personal-wechat-step-warning" role="note">
绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。
{showBindAction ? (
<li
className={
connected
? 'is-complete'
: binding
? 'is-active'
: runtimeReady
? 'is-current'
: 'is-pending'
}
>
<span className="personal-wechat-step-number">{connected ? '✓' : '2'}</span>
<div className="personal-wechat-step-content">
<strong>绑定个人微信</strong>
<p>
4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。
<br />
微信总是自动更新?请在微信左下角打开“设置 →
通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。
4.1.13以上登录状态微信直接点击“绑定微信”
</p>
)}
</div>
</li>
{connected ? (
<span className="personal-wechat-step-status">✓ 微信已绑定</span>
) : (
<Button
size="sm"
variant="outline"
onClick={() => onBind?.()}
disabled={!canBind || runtimeUnavailable || !runtimeReady || binding}
>
{binding ? '正在绑定…' : '绑定微信'}
</Button>
)}
{!connected && senderStatus && !runtimeUnavailable ? (
<p className="personal-wechat-step-hint">{bindingHint(senderStatus)}</p>
) : null}
{!connected && runtimeUnavailable && showAuthorizationWarning ? (
<div className="personal-wechat-authorization-warning" role="alert">
<span aria-hidden>!</span>
<p>
发送能力属授权制,需要联系群主。请先加入交流群,然后在群内添加群主申请授权。
进群请点击{' '}
<a href={GROUP_README_URL} target="_blank" rel="noreferrer">
这里
</a>{' '}
跳转。
</p>
</div>
) : null}
{!connected && !runtimeUnavailable ? (
<p className="personal-wechat-step-warning" role="note">
绑定微信可能导致当前微信异常闪退,这是正常现象。若微信退出,请重新启动微信后,再回到这里重新检测/绑定。
<br />
微信总是自动更新?请在微信左下角打开“设置 →
通用”,取消勾选“有更新时自动升级微信”,否则版本变化后可能无法绑定。
</p>
) : null}
</div>
</li>
) : null}
<li className={allReady ? 'is-complete' : connected ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">{allReady ? '✓' : '3'}</span>
<span className="personal-wechat-step-number">
{allReady ? '✓' : showBindAction ? '3' : '2'}
</span>
<div className="personal-wechat-step-content">
<strong>初始化发送能力</strong>
<p>绑定微信后,TraceMemo 会自动完成文字、图片和语音发送所需的初始化。</p>
<p>每个微信进程只能绑定一次</p>
{showBindingInstructionsInInitialization && (
<>
<p>4.1.13以下请保持微信未登录窗口状态,点击“绑定微信”后,再点击微信窗口登录。</p>
<p>4.1.13以上登录状态微信直接点击“绑定微信”</p>
</>
)}
{initializing && (
<p className="personal-wechat-step-hint" role="status">
{detecting ? '正在初始化发送能力…' : '正在等待发送运行时完成初始化…'}
@@ -161,37 +187,43 @@ export function PersonalWechatSetupGuide({
</div>
</li>
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">{allReady ? '✓' : '4'}</span>
<div className="personal-wechat-step-content">
<strong>能力检测</strong>
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
{[
['文字消息', Boolean(senderStatus?.canSendText)],
['图片消息', Boolean(senderStatus?.canSendImage)],
['语音消息', canSendVoice]
].map(([label, ready]) => (
<span key={String(label)} className={ready ? 'is-ready' : ''}>
<b aria-hidden>{ready ? '✓' : '−'}</b>
{label}
<small>{capabilityLabel(Boolean(ready), initializing)}</small>
</span>
))}
{showCapabilityStatus ? (
<li className={allReady ? 'is-complete' : initializing ? 'is-current' : 'is-pending'}>
<span className="personal-wechat-step-number">
{allReady ? '✓' : showBindAction ? '4' : '3'}
</span>
<div className="personal-wechat-step-content">
<strong>能力检测</strong>
<div className="personal-wechat-capabilities" aria-label="微信消息能力">
{[
['文字消息', Boolean(senderStatus?.canSendText)],
['图片消息', Boolean(senderStatus?.canSendImage)],
['语音消息', canSendVoice]
].map(([label, ready]) => (
<span key={String(label)} className={ready ? 'is-ready' : ''}>
<b aria-hidden>{ready ? '✓' : '−'}</b>
{label}
<small>{capabilityLabel(Boolean(ready), initializing)}</small>
</span>
))}
</div>
{allReady ? (
<>
<span className="personal-wechat-step-status">微信消息发送已配置完成</span>
{showStartSendingAction && (
<Button size="sm" onClick={() => onStartSending?.()}>
开始发送
</Button>
)}
</>
) : initializing ? (
<p className="personal-wechat-step-hint" role="status">
发送能力准备完成后会自动进入已就绪状态。
</p>
) : null}
</div>
{allReady ? (
<>
<span className="personal-wechat-step-status">微信消息发送已配置完成</span>
<Button size="sm" onClick={onStartSending}>
开始发送
</Button>
</>
) : initializing ? (
<p className="personal-wechat-step-hint" role="status">
发送能力准备完成后会自动进入已就绪状态。
</p>
) : null}
</div>
</li>
</li>
) : null}
</ol>
{!runtimeReady && runtimeUnavailable && onOpenTextToSpeechSettings && (
@@ -1,8 +1,14 @@
import { useCallback, useEffect, useState, type ReactElement } from 'react'
import { useCallback, useEffect, useRef, useState, type ReactElement } from 'react'
import type {
PersonalWechatSendCapability,
PersonalWechatSenderStatus
} from '../../../../../shared/personal-wechat'
import type {
MacLicenseState,
MacLicenseStatus
} from '../../../../../shared/personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from '../../../../../shared/personal-wechat-mac-runtime'
import { resolveMacSendPrimaryAction } from '../../../../../shared/personal-wechat-mac-send-action'
import { Button, Input, Skeleton } from '../../../components/ui'
import { PersonalWechatSetupGuide } from '../../../components/chat/PersonalWechatSetupGuide'
import { isMac, isWindows } from '../../../utils/runtime-environment'
@@ -60,6 +66,190 @@ function SendCapabilityAuthorizationCard(): ReactElement {
)
}
const macLicenseStateLabel: Record<MacLicenseState, string> = {
unlicensed: '当前设备暂无发送能力授权',
valid: '已授权',
cached: '授权有效(本地缓存)',
expired: '授权已过期',
revoked: '授权已撤销',
device_mismatch: '授权与当前设备不匹配',
identity_error: '设备身份异常',
server_unavailable: '授权服务器不可用',
checking: '检测中…',
unsupported: '发送组件版本较旧',
runtime_missing: '发送组件未运行',
platform_unsupported: '当前构建不支持'
}
const macLicenseFeatureLabel: Record<string, string> = {
basic: '基础功能',
wechat: '微信发送',
advanced: '高级功能',
api: 'API 接口'
}
function licenseTone(state: MacLicenseState): string {
if (state === 'valid' || state === 'cached') return 'is-ready'
if (state === 'revoked' || state === 'expired' || state === 'identity_error') return 'is-error'
return 'is-neutral'
}
function formatMacLicenseDateTime(iso: string | null): string {
if (!iso) return '—'
const parsed = new Date(iso)
if (Number.isNaN(parsed.getTime())) return iso
return parsed.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
}
function formatMacLicenseDate(iso: string | null): string {
if (!iso) return '—'
const parsed = new Date(iso)
if (Number.isNaN(parsed.getTime())) return iso
return parsed.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
function summarizeDeviceId(deviceId: string): string {
return deviceId.length === 68 ? `${deviceId.slice(0, 12)}…${deviceId.slice(-6)}` : deviceId
}
/** 展示当前设备的授权状态,并提供刷新与复制设备 ID 的操作。 */
export function MacProLicenseCard({
onNotice,
onStatusChange
}: {
onNotice: (message: string) => void
onStatusChange: (status: MacLicenseStatus) => void
}): ReactElement {
const [license, setLicense] = useState<MacLicenseStatus | null>(null)
const [refreshing, setRefreshing] = useState(false)
const [copied, setCopied] = useState(false)
const load = useCallback(async (): Promise<void> => {
try {
const next = await window.api.getMacLicenseStatus()
setLicense(next)
onStatusChange(next)
} catch {
setLicense(null)
}
}, [onStatusChange])
useEffect(() => {
void load()
}, [load])
const refresh = async (): Promise<void> => {
if (refreshing) return
setRefreshing(true)
try {
const next = await window.api.refreshMacLicense()
setLicense(next)
onStatusChange(next)
if (next.authorized) {
onNotice('授权检测完成:已授权')
} else {
onNotice(next.message || '授权检测完成')
}
} catch (reason) {
onNotice(reason instanceof Error ? reason.message : '授权检测失败')
} finally {
setRefreshing(false)
}
}
const copyDeviceId = async (): Promise<void> => {
if (!license?.deviceId) return
try {
await navigator.clipboard.writeText(license.deviceId)
setCopied(true)
onNotice('设备 ID 已复制')
window.setTimeout(() => setCopied(false), 2_000)
} catch {
onNotice('复制失败,请手动选择设备 ID 复制')
}
}
if (!license) {
return <Skeleton className="h-24 w-full" />
}
// OSS 构建走到这里(platform_unsupported)时不渲染卡片,保证免费版不出现授权入口。
if (license.state === 'platform_unsupported') {
return <></>
}
return (
<section className="settings-card mac-pro-license-card" aria-label="发送能力授权">
<header className="mac-pro-license-header">
<strong>发送能力授权</strong>
<span className={`mac-pro-license-status ${licenseTone(license.state)}`}>
{license.state === 'valid' || license.state === 'cached'
? '设备已授权'
: macLicenseStateLabel[license.state]}
</span>
</header>
<div className="mac-pro-device-row">
<div className="mac-pro-device-value">
<span>本机设备 ID</span>
<code title={license.deviceId || undefined}>
{license.deviceId ? summarizeDeviceId(license.deviceId) : '(尚未生成)'}
</code>
</div>
<Button
variant="ghost"
size="sm"
disabled={!license.deviceId}
aria-label="复制完整设备 ID"
onClick={() => void copyDeviceId()}
>
{copied ? '已复制' : '复制'}
</Button>
</div>
{license.deviceId && !license.authorized ? (
<p className="mac-pro-license-hint">
将设备 ID 提供给授权管理员,完成授权后点击「重新检测授权」。
</p>
) : null}
{license.authorized && license.features.length > 0 ? (
<div className="mac-pro-license-features" aria-label="已开通功能">
{license.features.map((feature) => (
<span key={feature}>{macLicenseFeatureLabel[feature] || feature}</span>
))}
</div>
) : null}
<div className="mac-pro-license-meta">
<span>
授权到期 <strong>{formatMacLicenseDate(license.licenseExpiresAt)}</strong>
</span>
<span>
最近检测 <strong>{formatMacLicenseDateTime(license.lastCheckedAt)}</strong>
</span>
</div>
<div className="mac-pro-license-footer">
<span />
<Button
variant="outline"
size="sm"
disabled={refreshing || license.state === 'unsupported'}
onClick={() => void refresh()}
>
{refreshing ? '检测中…' : '重新检测授权'}
</Button>
</div>
</section>
)
}
export function PersonalWechatSendPage({
onNotice,
onOpenTextToSpeechSettings
@@ -79,6 +269,11 @@ export function PersonalWechatSendPage({
const [windowsPortInput, setWindowsPortInput] = useState('')
const [windowsDetectedPort, setWindowsDetectedPort] = useState('')
const [windowsEndpointBusy, setWindowsEndpointBusy] = useState(false)
const [setupExpanded, setSetupExpanded] = useState<boolean | null>(null)
const [macLicenseStatus, setMacLicenseStatus] = useState<MacLicenseStatus | null>(null)
const [macRuntimeAvailability, setMacRuntimeAvailability] =
useState<MacWechatSendRuntimeAvailabilityResult | null>(null)
const setupDefaultInitialized = useRef(false)
const refresh = useCallback(async (): Promise<void> => {
if (isWindows) {
setLoading(false)
@@ -101,7 +296,59 @@ export function PersonalWechatSendPage({
useEffect(() => {
if (isWindows) return
void refresh()
let active = true
const loadMacStatus = async (): Promise<void> => {
try {
const availability = await window.api.getMacSendRuntimeAvailability()
if (!active) return
setMacRuntimeAvailability(availability)
if (availability.state !== 'available') {
setSenderStatus({
state: 'runtime_missing',
platform: 'darwin',
arch: 'arm64',
sipDisabled: true,
wechatRunning: false,
endpoint: '',
endpointReady: false,
runtimeReady: false,
attachReady: false,
baseAddressReady: false,
textHookInstalled: false,
textHookReady: false,
imageHookInstalled: false,
imageHookReady: false,
messageListenerReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false,
message: availability.message,
error: availability.message
})
setLoading(false)
return
}
const [nextCapability, nextSender, license] = await Promise.all([
window.api.getPersonalWechatSendCapability(),
window.api.getPersonalWechatSenderStatus(),
window.api.getMacLicenseStatus()
])
if (!active) return
setCapability(nextCapability)
setSenderStatus(nextSender)
setMacLicenseStatus(license)
} catch (reason) {
if (!active) return
setError(reason instanceof Error ? reason.message : '微信发送能力读取失败')
} finally {
if (active) setLoading(false)
}
}
void loadMacStatus()
return () => {
active = false
}
}, [refresh])
useEffect(() => {
@@ -266,7 +513,27 @@ export function PersonalWechatSendPage({
const pageMessage = isWindows
? windowsSenderStatus?.message || '请输入端口并检测 Windows 微信发送能力'
: capability?.message || '微信发送能力暂不可用'
const macUnavailable = isMac && senderStatus?.state === 'runtime_missing'
const macUnavailable = isMac && macRuntimeAvailability?.state === 'unavailable'
const macComponentError = isMac && macRuntimeAvailability?.state === 'component_error'
const macBound = boundToCurrentWechat(senderStatus)
const macEnvironmentReady = Boolean(
senderStatus?.runtimeReady && macBound && senderStatus.canSend
)
useEffect(() => {
if (isMac && senderStatus && !setupDefaultInitialized.current) {
setSetupExpanded(!macEnvironmentReady)
setupDefaultInitialized.current = true
}
}, [macEnvironmentReady, senderStatus])
const setupBodyId = 'personal-wechat-first-use-setup'
const macPrimaryAction = resolveMacSendPrimaryAction({
runtime: macRuntimeAvailability,
license: macLicenseStatus,
senderStatus,
binding,
detecting: loading || detecting
})
return (
<>
@@ -279,7 +546,13 @@ export function PersonalWechatSendPage({
<span
className={`settings-status-badge ${loading ? 'checking' : pageReady ? '' : pageStatus === 'unsupported' ? 'unavailable' : 'warning'}`}
>
{loading ? '检测中' : macUnavailable ? '暂不可用' : capabilityLabel[pageStatus]}
{loading
? '检测中'
: macUnavailable
? '没有微信发送能力'
: macComponentError
? '发送组件异常'
: capabilityLabel[pageStatus]}
</span>
</header>
<div className="settings-page-scroll">
@@ -407,18 +680,129 @@ export function PersonalWechatSendPage({
</>
) : isMac ? (
<>
<h2 className="settings-section-heading">配置状态</h2>
<PersonalWechatSetupGuide
senderStatus={senderStatus}
binding={binding}
detecting={detecting}
sessionBound={boundToCurrentWechat(senderStatus)}
onBind={() => void bindWechat()}
onStartSending={() =>
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
}
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
/>
{/* 发送能力授权卡片:仅在加载了发送组件的档位渲染。
OSS(runtime_missing)下不渲染,保证免费版不出现授权入口。 */}
{macRuntimeAvailability?.state === 'available' ? (
<MacProLicenseCard onNotice={onNotice} onStatusChange={setMacLicenseStatus} />
) : null}
<section
className="settings-card mac-wechat-environment-card"
aria-label="微信发送环境"
>
<header className="mac-wechat-environment-header">
<strong>微信发送环境</strong>
<span
className={`mac-wechat-environment-status ${macEnvironmentReady ? 'is-ready' : 'is-neutral'}`}
>
{loading
? '正在检查环境'
: macUnavailable
? '当前版本没有微信发送能力'
: macComponentError
? '发送组件缺失或异常'
: macEnvironmentReady
? '运行环境已就绪'
: '需要完成配置'}
</span>
</header>
<div className="mac-wechat-status-grid" aria-label="环境状态">
{[
['运行时正常', Boolean(senderStatus?.runtimeReady)],
['微信已绑定', macBound],
['发送组件正常', Boolean(senderStatus?.canSend)]
].map(([label, complete]) => (
<div className="mac-wechat-status-item" key={String(label)}>
<span
className={complete ? 'is-ready' : 'is-pending'}
aria-hidden="true"
>
{complete ? '✓' : '○'}
</span>
<strong>{label}</strong>
<small>{loading ? '检测中' : complete ? '正常' : '待完成'}</small>
</div>
))}
</div>
{senderStatus && macRuntimeAvailability?.state === 'available' ? (
<div
className="mac-wechat-capability-details"
aria-label="文字、图片和语音能力"
>
{(
[
['文字', senderStatus.canSendText],
['图片', senderStatus.canSendImage],
['语音', senderStatus.canSendVoice]
] as const
).map(([label, available]) => (
<span key={label} className={available ? 'is-ready' : 'is-pending'}>
{label} {available ? '可用' : '未就绪'}
</span>
))}
</div>
) : null}
<button
type="button"
className="mac-wechat-setup-toggle"
aria-expanded={setupExpanded ?? !macEnvironmentReady}
aria-controls={setupBodyId}
onClick={() =>
setSetupExpanded((expanded) => !(expanded ?? !macEnvironmentReady))
}
>
<span>首次使用配置</span>
<span className="mac-wechat-setup-chevron" aria-hidden="true">
⌄
</span>
</button>
<div
id={setupBodyId}
className="mac-wechat-setup-content"
hidden={!(setupExpanded ?? !macEnvironmentReady)}
>
{macRuntimeAvailability?.state === 'available' ? (
<PersonalWechatSetupGuide
senderStatus={senderStatus}
binding={binding}
detecting={detecting}
sessionBound={macBound}
showBindAction={false}
showCapabilityStatus={false}
showBindingInstructionsInInitialization
showAuthorizationWarning={false}
canBind={macPrimaryAction.action === 'bind'}
onStartSending={() =>
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
}
showStartSendingAction={false}
onOpenTextToSpeechSettings={onOpenTextToSpeechSettings}
/>
) : null}
</div>
<div className="mac-wechat-primary-action">
<Button
className="w-full"
disabled={macPrimaryAction.disabled}
onClick={() => {
if (macPrimaryAction.action === 'bind') {
void bindWechat()
} else if (macPrimaryAction.action === 'send') {
onNotice('微信消息发送能力已就绪,请在档案中选择会话开始发送。')
} else if (!macPrimaryAction.disabled) {
setSetupExpanded(true)
}
}}
>
{macPrimaryAction.label}
</Button>
</div>
</section>
{macUnavailable ? (
<>
<h2 className="settings-section-heading">发送能力授权</h2>
<SendCapabilityAuthorizationCard />
</>
) : null}
</>
) : null}
</>
+242
View File
@@ -249,6 +249,248 @@
background: var(--wxex-bg-elevated);
padding: 24px 26px;
}
.mac-pro-license-card,
.mac-wechat-environment-card {
display: grid;
gap: 14px;
min-width: 0;
padding: 20px 22px;
}
.mac-pro-license-header,
.mac-wechat-environment-header {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
> strong {
color: var(--wxex-text-primary);
font-size: 15px;
font-weight: 650;
}
}
.mac-pro-license-status,
.mac-wechat-environment-status {
flex: 0 0 auto;
color: var(--wxex-text-secondary);
font-size: 12px;
}
.mac-pro-license-status.is-ready,
.mac-wechat-environment-status.is-ready,
.mac-wechat-status-item .is-ready,
.mac-wechat-capability-details .is-ready {
color: var(--wxex-success);
}
.mac-pro-license-status.is-error {
color: var(--wxex-danger);
}
.mac-pro-license-status.is-neutral,
.mac-wechat-environment-status.is-neutral {
color: var(--wxex-text-muted);
}
.mac-pro-device-row {
display: flex;
min-width: 0;
align-items: center;
gap: 10px;
border-radius: var(--wxex-radius-md);
background: color-mix(in srgb, var(--wxex-text-primary) 4%, transparent);
padding: 10px 12px;
}
.mac-pro-device-value {
display: grid;
min-width: 0;
flex: 1;
gap: 4px;
> span {
color: var(--wxex-text-muted);
font-size: 11px;
}
code {
overflow: hidden;
color: var(--wxex-text-primary);
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.mac-pro-license-hint {
margin: -5px 0 0;
color: var(--wxex-text-secondary);
font-size: 12px;
}
.mac-pro-license-features {
display: flex;
flex-wrap: wrap;
gap: 6px;
> span {
border-radius: 999px;
background: color-mix(in srgb, var(--wxex-text-primary) 5%, transparent);
padding: 3px 8px;
color: var(--wxex-text-secondary);
font-size: 11px;
}
}
.mac-pro-license-meta {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
color: var(--wxex-text-muted);
font-size: 11px;
strong {
margin-left: 4px;
color: var(--wxex-text-secondary);
font-weight: 550;
}
}
.mac-pro-license-footer {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.mac-pro-identity-note {
margin: 0;
}
.mac-wechat-status-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.mac-wechat-status-item {
display: grid;
min-width: 0;
justify-items: center;
gap: 5px;
border-radius: var(--wxex-radius-md);
background: color-mix(in srgb, var(--wxex-text-primary) 3%, transparent);
padding: 12px 8px;
text-align: center;
> span {
font-size: 18px;
line-height: 1;
}
.is-pending {
color: var(--wxex-text-muted);
}
strong {
color: var(--wxex-text-primary);
font-size: 12px;
font-weight: 550;
}
small {
color: var(--wxex-text-muted);
font-size: 10px;
}
}
.mac-wechat-capability-details {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
color: var(--wxex-text-muted);
font-size: 11px;
.is-pending {
color: var(--wxex-text-muted);
}
}
.mac-wechat-setup-toggle {
display: flex;
width: 100%;
align-items: center;
justify-content: space-between;
gap: 12px;
border: 0;
border-top: 1px solid var(--wxex-border);
background: transparent;
padding: 12px 0 0;
color: var(--wxex-text-primary);
cursor: pointer;
font: inherit;
font-size: 13px;
font-weight: 600;
text-align: left;
&:focus-visible {
border-radius: 4px;
outline: 2px solid var(--wxex-brand);
outline-offset: 3px;
}
}
.mac-wechat-setup-chevron {
color: var(--wxex-text-muted);
font-size: 18px;
transition: transform 160ms ease;
}
.mac-wechat-setup-toggle[aria-expanded='true'] .mac-wechat-setup-chevron {
transform: rotate(180deg);
}
.mac-wechat-setup-content {
min-width: 0;
&[hidden] {
display: none;
}
.personal-wechat-setup {
gap: 12px;
border: 0;
padding: 2px 0 0;
}
.personal-wechat-setup-heading h2,
.personal-wechat-eyebrow {
display: none;
}
}
.mac-wechat-primary-action {
padding-top: 2px;
}
@media (prefers-reduced-motion: reduce) {
.mac-wechat-setup-chevron {
transition: none;
}
}
@media (max-width: 560px) {
.mac-pro-license-card,
.mac-wechat-environment-card {
padding: 16px;
}
.mac-pro-license-header,
.mac-wechat-environment-header {
align-items: flex-start;
flex-direction: column;
gap: 4px;
}
.mac-wechat-status-grid {
gap: 5px;
}
.mac-wechat-status-item {
padding: 10px 4px;
strong {
font-size: 10px;
}
}
.mac-pro-license-meta {
flex-direction: column;
gap: 5px;
}
}
.settings-account-overview {
display: grid;
grid-template-columns: minmax(190px, 1fr) minmax(220px, 1fr) auto;
+149
View File
@@ -0,0 +1,149 @@
/**
* macOS 设备授权接口的 wire 类型。
* 所有字段都由 `parseMacLicenseStatus` 运行时校验后才会交给上层使用。
*/
export type MacLicenseState =
| 'unlicensed' // no license for this device
| 'valid' // online check passed in this process
| 'cached' // local cache verified, not re-confirmed online
| 'expired'
| 'revoked'
| 'device_mismatch' // token belongs to a different device
| 'identity_error' // device key unusable
| 'server_unavailable' // network / 5xx; cache may still hold
| 'checking' // an online refresh is in flight
| 'unsupported' // host is running but has no /license endpoints (old build)
| 'runtime_missing' // host not reachable / runtime absent
| 'platform_unsupported' // not macOS native (Windows / OSS)
const MAC_LICENSE_STATES = new Set<MacLicenseState>([
'unlicensed',
'valid',
'cached',
'expired',
'revoked',
'device_mismatch',
'identity_error',
'server_unavailable',
'checking',
'unsupported',
'runtime_missing',
'platform_unsupported'
])
export interface MacLicenseStatus {
deviceId: string | null
state: MacLicenseState
authorized: boolean
source: 'online' | 'cache' | 'none'
features: string[]
lastCheckedAt: string | null
licenseExpiresAt: string | null
tokenExpiresAt: string | null
message: string
/** False when the running host predates the license endpoints (404). */
runtimeProtocolSupported?: boolean
/** Host-reported numeric TM_WECHAT_* code when a refresh failed. */
errorCode?: number | null
}
const DEVICE_ID_PATTERN = /^mac_[0-9a-f]{64}$/
function asOptionalString(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}
function asOptionalIsoDate(value: unknown): string | null {
if (typeof value !== 'string' || value.length === 0) return null
// Accept RFC3339 (what the native core emits); reject obvious garbage.
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value)) return null
return value
}
function asStringArray(value: unknown): string[] {
if (!Array.isArray(value)) return []
return value.filter((entry): entry is string => typeof entry === 'string')
}
/**
* 把任意 JSON 校验成 MacLicenseStatus;无法确认的字段一律落到安全默认值。
* `authorized` 由 state 重算,伪造的 `authorized: true` 覆盖不了已撤销状态。
*/
export function parseMacLicenseStatus(raw: unknown): MacLicenseStatus {
const base: MacLicenseStatus = {
deviceId: null,
state: 'unlicensed',
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message: '当前设备暂无发送能力授权'
}
if (raw === null || typeof raw !== 'object') return base
const record = raw as Record<string, unknown>
const deviceId = asOptionalString(record.deviceId)
if (deviceId !== null && DEVICE_ID_PATTERN.test(deviceId)) {
base.deviceId = deviceId
}
const state = asOptionalString(record.state)
if (state !== null && MAC_LICENSE_STATES.has(state as MacLicenseState)) {
base.state = state as MacLicenseState
}
const source = asOptionalString(record.source)
if (source === 'online' || source === 'cache' || source === 'none') {
base.source = source
}
base.features = asStringArray(record.features)
base.lastCheckedAt = asOptionalIsoDate(record.lastCheckedAt)
base.licenseExpiresAt = asOptionalIsoDate(record.licenseExpiresAt)
base.tokenExpiresAt = asOptionalIsoDate(record.tokenExpiresAt)
const message = asOptionalString(record.message)
if (message !== null) base.message = message
if (typeof record.runtimeProtocolSupported === 'boolean') {
base.runtimeProtocolSupported = record.runtimeProtocolSupported
}
if (typeof record.errorCode === 'number' && Number.isFinite(record.errorCode)) {
base.errorCode = record.errorCode
}
/*
* authorized is DERIVED, not copied: only a small whitelist of states may
* present as authorized, and even then the payload's own boolean must agree.
* This keeps a forged {"authorized": true} from flipping a revoked state.
*/
const trustedStates: ReadonlySet<MacLicenseState> = new Set(['valid', 'cached'])
base.authorized = trustedStates.has(base.state) && record.authorized === true
return base
}
/**
* Build the "runtime missing / old host" status without a network round-trip.
* Used when the host is down or answered 404 on /license/status.
*/
export function offlineMacLicenseStatus(
state: 'runtime_missing' | 'unsupported' | 'platform_unsupported' | 'server_unavailable',
message: string
): MacLicenseStatus {
return {
deviceId: null,
state,
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message,
runtimeProtocolSupported: state === 'unsupported' ? false : undefined
}
}
@@ -15,6 +15,13 @@ export type MacWechatRuntimeLifecycle =
| 'crashed_unbound' // died while unbound — safe to auto-restart
| 'crashed_bound' // died while bound — WeChat keeps an orphan agent
export type MacWechatSendRuntimeAvailability = 'unavailable' | 'component_error' | 'available'
export interface MacWechatSendRuntimeAvailabilityResult {
state: MacWechatSendRuntimeAvailability
message: string
}
export type MacWechatHostRuntimeState =
| 'not_initialized'
| 'wechat_not_running'
@@ -0,0 +1,103 @@
import type { MacLicenseStatus } from './personal-wechat-mac-license'
import type { MacWechatSendRuntimeAvailabilityResult } from './personal-wechat-mac-runtime'
import type { PersonalWechatSenderStatus } from './personal-wechat'
export type MacSendPrimaryActionKind = 'none' | 'bind' | 'send'
export interface MacSendPrimaryAction {
label: string
disabled: boolean
loading: boolean
action: MacSendPrimaryActionKind
reason:
| 'runtime_unavailable'
| 'runtime_error'
| 'license_pending'
| 'license_invalid'
| 'license_feature_denied'
| 'binding'
| 'unbound'
| 'initializing'
| 'ready'
}
export function hasValidWechatLicense(license: MacLicenseStatus | null): boolean {
if (
!license ||
!license.authorized ||
(license.state !== 'valid' && license.state !== 'cached') ||
!license.features.includes('wechat')
) {
return false
}
const tokenExpiresAt = license.tokenExpiresAt ? Date.parse(license.tokenExpiresAt) : Number.NaN
return Number.isFinite(tokenExpiresAt) && tokenExpiresAt > Date.now()
}
export function resolveMacSendPrimaryAction(input: {
runtime: MacWechatSendRuntimeAvailabilityResult | null
license: MacLicenseStatus | null
senderStatus: PersonalWechatSenderStatus | null
binding: boolean
detecting: boolean
}): MacSendPrimaryAction {
const { runtime, license, senderStatus, binding, detecting } = input
const result = (
label: string,
disabled: boolean,
loading: boolean,
action: MacSendPrimaryActionKind,
reason: MacSendPrimaryAction['reason']
): MacSendPrimaryAction => ({ label, disabled, loading, action, reason })
if (!runtime || (detecting && !senderStatus)) {
return result('正在检查发送组件…', true, true, 'none', 'runtime_error')
}
if (runtime.state === 'unavailable') {
return result('当前版本没有微信发送能力', true, false, 'none', 'runtime_unavailable')
}
if (runtime.state === 'component_error') {
return result('发送组件缺失或异常', true, false, 'none', 'runtime_error')
}
if (license === null) {
return result('正在检测授权…', true, true, 'none', 'license_pending')
}
if (license.state === 'valid' || license.state === 'cached') {
if (license.authorized && !license.features.includes('wechat')) {
return result('未开通微信发送', true, false, 'none', 'license_feature_denied')
}
if (hasValidWechatLicense(license)) {
if (binding) return result('正在绑定…', true, true, 'none', 'binding')
const bound = Boolean(
senderStatus &&
(senderStatus.state === 'online' ||
Boolean(
senderStatus.wechatPid &&
senderStatus.boundWechatPid === senderStatus.wechatPid &&
senderStatus.attachReady &&
senderStatus.baseAddressReady
))
)
if (!bound) return result('绑定微信', false, false, 'bind', 'unbound')
if (senderStatus?.canSend) return result('开始发送', false, false, 'send', 'ready')
return result('正在准备发送能力…', true, detecting, 'none', 'initializing')
}
}
const bound = Boolean(
senderStatus &&
(senderStatus.state === 'online' ||
Boolean(
senderStatus.wechatPid &&
senderStatus.boundWechatPid === senderStatus.wechatPid &&
senderStatus.attachReady &&
senderStatus.baseAddressReady
))
)
return result(
bound ? '授权后可开始发送' : '授权后可绑定微信',
true,
false,
'none',
'license_invalid'
)
}