/** * ============================================================ * waitFor.ts —— 语义等待(wait_for_element / text / window) * ------------------------------------------------------------ * ★ **零协议改动、零 vendor 重编。** 这三个动作本质是「轮询观测直到条件 * 成立」,而观测与 AX 树原生侧早已提供 —— 编排是 TS 的事,符合 * 「Rust 出像素,TS 做判断」总纲。 * * 它们解决的是一个真实的成本问题:在此之前模型只能 * `observe → 看 → observe` 地轮询,而每次 observe 都要组装图(约 1100 token)。 * 这里改用**元数据观测**(`includeScreenshot:false`,`list_apps` 已经在走这条 * 路径),一轮几乎不花 token,命中才返回。 * * 三条刻意的边界,缺任一条都会变成新的故障源: * * ① **超时不抛异常,而且要说清现场。** 只回一句「等了 5 秒没等到」,模型 * 只能盲试;带上「现在前台是谁、有哪些窗口、AX 里有哪些角色」,它才有 * 下一步可走。 * ② **AX 不可用时立刻返回**,不空转到超时。微信这类自绘应用的树整棵是空的, * `wait_for_element` 在那里等多久都不会成立 —— 等 5 秒再报一个含糊的超时 * 是纯粹的浪费,且会把「这个能力用不了」误导成「这次没等到」。 * ③ **条件已成立就首轮返回**,不为了「像在等」而先睡一轮。 * ============================================================ */ import { containsFold, describeNode, findByRole, flattenAx, matchesText, type AxSearchNode, } from './axSearch.js'; import type { ComputerState, ComputerUseAction } from './protocol.js'; /** 本模块接管的动作。 */ export const WAIT_ACTIONS = [ 'wait', 'wait_for_element', 'wait_for_text', 'wait_for_window', ] as const satisfies readonly ComputerUseAction[]; export type WaitAction = (typeof WAIT_ACTIONS)[number]; export function isWaitAction(action: ComputerUseAction): action is WaitAction { return (WAIT_ACTIONS as readonly string[]).includes(action); } export function isSimpleWaitAction(action: ComputerUseAction): action is 'wait' { return action === 'wait'; } /** 轮询间隔。200ms 是「人眼觉得即时」与「别把守护进程压满」之间的常用折中。 */ export const WAIT_POLL_INTERVAL_MS = 200; /** 默认等待上限。模型可用 `timeoutMs` 覆盖(schema 限 100–120000)。 */ export const WAIT_DEFAULT_TIMEOUT_MS = 5_000; export interface WaitInput { action: WaitAction; /** `wait_for_element` 必填:AX 角色,如 `AXButton`。 */ role?: string; /** 名字/文本片段。element 时可选,text/window 时必填。 */ text?: string; /** 等待时间(毫秒),仅用于简单 `wait` 动作,默认 1000ms。 */ waitMs?: number; timeoutMs?: number; } export interface WaitOutcome { ok: boolean; content: string; /** 命中的控件 id(`wait_for_element` / `wait_for_text` 命中可点控件时才有)。 */ elementId?: string; /** 实际等了多久,供遥测。 */ waitedMs: number; /** 轮询了几次。 */ polls: number; } /** 一次观测的判定结果。`unavailable` = 这条判据在此应用上根本用不了。 */ type Verdict = | { kind: 'hit'; description: string; elementId?: string } | { kind: 'miss' } | { kind: 'unavailable'; reason: string }; function axNodes(state: ComputerState): AxSearchNode[] { return flattenAx(state.accessibility?.root as AxSearchNode | undefined); } function axUsable(state: ComputerState): boolean { return state.accessibility !== undefined && state.accessibility.truncated !== true; } const AX_BLIND_HINT = '这个应用没有可用的无障碍树(自绘/Electron 应用的常态),按控件等待在这里永远不会成立。' + '改用 `settle` 判断界面稳没稳,再 `observe` 看图确认。'; function evaluate(input: WaitInput, state: ComputerState): Verdict { switch (input.action) { case 'wait': // 简单 wait 不需要评估条件,直接返回 hit(它只 sleep) return { kind: 'hit', description: '等待完成' }; case 'wait_for_window': { // 窗口列表不依赖 AX 树的完整性,自绘应用上照样可用 —— 这是三个 wait // 里唯一对微信这类应用有效的那个。 const needle = input.text ?? ''; const hit = state.windows.find((window) => containsFold(window.title, needle)); if (hit) { return { kind: 'hit', description: `窗口「${hit.title ?? '(无标题)'}」(${hit.appId})` }; } return { kind: 'miss' }; } case 'wait_for_element': { if (!axUsable(state)) return { kind: 'unavailable', reason: AX_BLIND_HINT }; const matches = findByRole(axNodes(state), input.role ?? '', input.text); const hit = matches[0]; if (!hit) return { kind: 'miss' }; return { kind: 'hit', description: describeNode(hit) + (matches.length > 1 ? `(另有 ${matches.length - 1} 个同样匹配的控件)` : ''), ...(hit.elementId ? { elementId: hit.elementId } : {}), }; } case 'wait_for_text': { if (!axUsable(state)) return { kind: 'unavailable', reason: AX_BLIND_HINT }; const hit = axNodes(state).find((node) => matchesText(node, input.text ?? '')); if (!hit) return { kind: 'miss' }; return { kind: 'hit', description: describeNode(hit), ...(hit.elementId ? { elementId: hit.elementId } : {}), }; } default: return { kind: 'miss' }; } } /** * 超时时给模型看的现场。 * * 这段是本模块最容易被写敷衍的地方,也是最要紧的:模型拿不到现场就只能重试 * 同一件事,而重试同一件事正是熔断要拦的行为。 */ function describeScene(input: WaitInput, state: ComputerState | null): string[] { if (!state) return [' 等待期间一次观测都没成功 —— 先检查权限与守护进程。']; const lines = [ ` 当前前台:${state.activeApp?.name ?? '未知'}(${state.activeApp?.id ?? '无标识'})`, ` 窗口:${state.windows.length > 0 ? state.windows.map((w) => `「${w.title ?? '(无标题)'}」`).slice(0, 6).join('、') : '(一个都没有)'}`, ]; if (input.action !== 'wait_for_window') { const nodes = axNodes(state); const roles = [...new Set(nodes.map((node) => node.role).filter(Boolean))].slice(0, 12); lines.push(` 无障碍树:${axUsable(state) ? `${nodes.length} 个节点` : '不可用'}`); if (roles.length > 0) lines.push(` 树里出现过的角色:${roles.join('、')}`); } return lines; } function requirementOf(input: WaitInput): string { switch (input.action) { case 'wait': return '等待时间结束'; case 'wait_for_element': return `控件 ${input.role}${input.text ? `(名字含「${input.text}」)` : ''}`; case 'wait_for_text': return `文本「${input.text}」`; case 'wait_for_window': return `标题含「${input.text}」的窗口`; default: return '未知条件'; } } /** 入参校验。返回非 null 表示参数本身就不成立,不必去等。 */ export function validateWaitInput(input: WaitInput): string | null { // 简单 wait 不需要任何参数,只需要可选的等待时间 if (input.action === 'wait') { if (input.waitMs !== undefined && (input.waitMs < 10 || input.waitMs > 30000)) { return 'wait 的 waitMs 参数必须在 10-30000 毫秒之间(默认 1000ms)。'; } return null; } if (input.action === 'wait_for_element' && !input.role?.trim()) { return 'wait_for_element 需要 role(AX 角色,如 AXButton);只给文本请用 wait_for_text。'; } if (input.action !== 'wait_for_element' && !input.text?.trim()) { return `${input.action} 需要 text(要等的文本/窗口标题片段)。`; } return null; } /** * 轮询直到条件成立或超时。 * * `observeOnce` 由调用方注入(生产里是一次元数据观测),便于单测用合成状态 * 驱动而不碰真实守护进程。 */ export async function waitForCondition(input: WaitInput, deps: { observeOnce: () => Promise; now?: () => number; sleep?: (ms: number) => Promise; signal?: AbortSignal; }): Promise { const invalid = validateWaitInput(input); if (invalid) return { ok: false, content: invalid, waitedMs: 0, polls: 0 }; const now = deps.now ?? (() => Date.now()); const sleep = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); // 简单 wait:纯 sleep,不截图不查 AX 树 if (input.action === 'wait') { const waitMs = input.waitMs ?? 2000; const startedAt = now(); if (deps.signal) { // 支持中断:用 Promise.race 实现可取消的 sleep await Promise.race([ sleep(waitMs), new Promise((_, reject) => { deps.signal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true }); }).catch(() => {}), ]); } else { await sleep(waitMs); } const waitedMs = now() - startedAt; if (deps.signal?.aborted) { return { ok: false, content: '等待被中断。', waitedMs, polls: 0 }; } return { ok: true, content: `已等待 ${waitMs}ms`, waitedMs, polls: 0, }; } const timeoutMs = input.timeoutMs ?? WAIT_DEFAULT_TIMEOUT_MS; const startedAt = now(); let polls = 0; let last: ComputerState | null = null; // do-while:**先判一次再睡**。条件已经成立时不该白等一个间隔。 do { if (deps.signal?.aborted) { return { ok: false, content: '等待被中断。', waitedMs: now() - startedAt, polls }; } polls += 1; last = await deps.observeOnce(); if (last) { const verdict = evaluate(input, last); if (verdict.kind === 'hit') { return { ok: true, content: `已等到${requirementOf(input)}:${verdict.description}(用时 ${now() - startedAt}ms)`, ...(verdict.elementId ? { elementId: verdict.elementId } : {}), waitedMs: now() - startedAt, polls, }; } if (verdict.kind === 'unavailable') { // 立刻返回,不空转到超时 —— 等下去也不会变成立。 return { ok: false, content: `无法等待${requirementOf(input)}:${verdict.reason}`, waitedMs: now() - startedAt, polls, }; } } if (now() - startedAt >= timeoutMs) break; await sleep(WAIT_POLL_INTERVAL_MS); } while (now() - startedAt < timeoutMs); const waitedMs = now() - startedAt; return { ok: false, content: [ `等了 ${waitedMs}ms(${polls} 次观测)仍未出现${requirementOf(input)}。当前实际看到的是:`, ...describeScene(input, last), '别用同样的参数再等一次 —— 要么条件写错了,要么这一步的前置操作没生效。', ].join('\n'), waitedMs, polls, }; }