feat: 桌面元素点击/填值/读值增加隐式等待重试(默认4秒)

This commit is contained in:
yu 2026-10-28 14:56:20 +08:00
parent 876e4969bd
commit 753508b500

View File

@ -249,6 +249,29 @@ async function runScript(script: string, t: UiaTarget, timeoutMs = 60000): Promi
}
}
function sleepMs(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function runWithImplicitWait(
t: UiaTarget,
action: string,
script: string,
exec: (script: string, t: UiaTarget, timeoutMs?: number) => Promise<Record<string, unknown> | null>,
args: Record<string, unknown>
): Promise<Record<string, unknown>> {
const waitMs = Number(args.waitMs ?? args.wait_ms ?? 4000) || 4000;
const deadline = Date.now() + Math.max(0, waitMs);
for (;;) {
try {
return requireFound(await exec(script, t), t, action);
} catch (error) {
const code = (error as { code?: string }).code;
if (code !== "desktop_element_not_found" || Date.now() >= deadline) throw error;
await sleepMs(400);
}
}
}
function requireFound(result: Record<string, unknown> | null, t: UiaTarget, action: string): Record<string, unknown> {
if (!result) {
const s = t.selector;
@ -259,15 +282,13 @@ function requireFound(result: Record<string, unknown> | null, t: UiaTarget, acti
const clickGround: CapabilityHandler = async (_ctx, node, args) => {
const t = target(args, node);
const result = await runScript(clickScript(t), t);
return requireFound(result, t, "click");
return runWithImplicitWait(t, "click", clickScript(t), runScript, args);
};
const setValueGround: CapabilityHandler = async (_ctx, node, args) => {
const t = target(args, node);
const value = String(args.value ?? args.text ?? "");
const result = await runScript(setValueScript(t, value), t);
return requireFound(result, t, "setValue");
return runWithImplicitWait(t, "setValue", setValueScript(t, value), runScript, args);
};
const existsGround: CapabilityHandler = async (_ctx, node, args) => {
@ -278,8 +299,8 @@ const existsGround: CapabilityHandler = async (_ctx, node, args) => {
const getValueGround: CapabilityHandler = async (_ctx, node, args) => {
const t = target(args, node);
const result = await runScript(getValueScript(t), t);
return requireFound(result, t, "getValue").value ?? "";
const result = await runWithImplicitWait(t, "getValue", getValueScript(t), runScript, args);
return result.value ?? "";
};
const waitElementGround: CapabilityHandler = async (_ctx, node, args) => {
@ -298,3 +319,4 @@ register("Element_WaitElementGround", waitElementGround);