Files
aichat/src/bridge/ai-rpc.ts
T
2026-11-18 11:07:24 +08:00

84 lines
3.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* CEF 通用 RPC(Phase 3)。
* 传输层:`window.cefApp.SyncCall(name, id, ...args)`,native 回调
* `ExecuteJavaScript('window.aiResolve(id, resultString)')`。
*
* native 响应统一包络(JSON 字符串):
* 成功:{ ok: true, ... }
* 失败:{ ok: false, message: string, ... }
* JS 侧 SyncCall 始终 resolve(解析后的对象),调用方自行判 ok。
*/
type Pending = { resolve: (value: Record<string, unknown>) => void }
const pending = new Map<string, Pending>()
let seq = 0
/**
* SyncCall 默认超时。native 不回包(卡死 / 丢回调)时 promise 永不 settle,
* await 它的调用方(getSkills / loadSkill / getPolicyContext)会永远挂起
* ⇒ 整个请求卡「思考中」。超时按失败包络 resolve —— 保持
* 「SyncCall 始终 resolve,调用方判 ok」的契约,调用方现有 catch 分支自然接管。
*
* 这个超时只对「native 内存读」类调用有效(getSkills / loadSkill /
* getPolicyContext,毫秒级返回,超时是有效的降级)。
* ⚠️ 涉及等用户操作的调用(applyStrategy)必须传 `timeoutMs = 0`(不设超时):
* native 的 applyStrategy 会在模态命名对话框里等用户改名并点确定,时长不可预期;
* 而 CEF 的模态框阻塞的是 native 的 UI 线程,**不阻塞渲染进程的定时器**
* ⇒ 计时器会在弹框期间照样到点,把 pending 里那个仍然有效的 id 摘掉并按失败 resolve
* ⇒ 用户点确定后 native 调 aiResolve 时查不到 id,结果被丢弃
* ⇒ 页面判失败 ⇒ 回灌重做 ⇒ 再发一次调用 ⇒ 又弹一个框、又落盘一次。
* 超时在这里不是兜底,是故障源:它主动制造重复弹框和重复落盘。
*/
const SYNC_CALL_TIMEOUT = 5000
declare global {
interface Window {
cefApp?: {
SyncCall: (name: string, id: string, ...args: unknown[]) => unknown
}
aiResolve: (id: string, result: string) => void
}
}
/** 全局回调:native 经 ExecuteJavaScript 调到这里。 */
window.aiResolve = (id: string, result: string) => {
const p = pending.get(id)
if (!p) return
pending.delete(id)
// console.log(result);
p.resolve(JSON.parse(result) as Record<string, unknown>)
}
/** 发一次 RPC,返回 native 回传的解析后对象(始终 resolve,调用方判 ok)。 */
export function SyncCall(
name: string,
args: unknown[] = [],
timeoutMs: number = SYNC_CALL_TIMEOUT,
): Promise<Record<string, unknown>> {
const id = String(++seq)
return new Promise<Record<string, unknown>>((resolve) => {
// timeoutMs <= 0 表示不设超时(等用户操作的调用,如 applyStrategy)。
// timer 用 0 占位;resolve 包装里的 clearTimeout(0) 是空操作,安全。
let timer = 0
if (timeoutMs > 0) {
timer = window.setTimeout(() => {
// native 未在时限内回包 ⇒ 摘掉挂起项并按失败包络 resolve。
// 迟到的 aiResolve 会因 pending 里查不到 id 而被丢弃(见 window.aiResolve)。
if (pending.delete(id)) {
console.warn(`[SyncCall] 超时 ${name}(${timeoutMs}ms)`)
resolve({ ok: false, message: `native 调用 ${name} 超时(${timeoutMs}ms 无响应)` })
}
}, timeoutMs)
}
pending.set(id, {
resolve: (value) => {
window.clearTimeout(timer)
resolve(value)
},
})
window.cefApp?.SyncCall(name, id, ...args)
})
}