diff --git a/src/main/capabilities/desktop-uia.ts b/src/main/capabilities/desktop-uia.ts index 6243560..74a6aa2 100644 --- a/src/main/capabilities/desktop-uia.ts +++ b/src/main/capabilities/desktop-uia.ts @@ -249,6 +249,29 @@ async function runScript(script: string, t: UiaTarget, timeoutMs = 60000): Promi } } +function sleepMs(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function runWithImplicitWait( + t: UiaTarget, + action: string, + script: string, + exec: (script: string, t: UiaTarget, timeoutMs?: number) => Promise | null>, + args: Record +): Promise> { + 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 | null, t: UiaTarget, action: string): Record { if (!result) { const s = t.selector; @@ -259,15 +282,13 @@ function requireFound(result: Record | 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); +