From 14cb71d5408699a12564f6fc47086459a75494e3 Mon Sep 17 00:00:00 2001 From: yumi Date: Mon, 2 Nov 2026 21:02:32 +0800 Subject: [PATCH 1/5] fix(jev): run on windows and read deep electron windows On Windows the scripts could not start agent-desktop at all: npm installs a .cmd and a .ps1 shim, and execFileSync refuses to spawn either without a shell. The default binary lookup now finds the native executable the npm package ships next to the shim on PATH. The paste fallback sent cmd+v on every platform. It now sends ctrl+v outside macOS. Electron windows lost their controls: at the CLI's default depth of 10 a canvas app returned 56 elements and none of its toolbar, against 251 at depth 20, and its reads could outlast the 3 s deadline. JEV_SNAPSHOT_MAX_DEPTH and JEV_SNAPSHOT_TIMEOUT_MS pass --max-depth and --timeout-ms to every read, validated, and change nothing when unset. The skeleton first look keeps the CLI depth. A minimized window answered with a timeout or an empty tree. When every window of the app is minimized, the error now says so and names the restore command. --- scripts/jev/act.mjs | 24 +++++----- scripts/jev/bin.mjs | 66 ++++++++++++++++++++++++++++ scripts/jev/bin.test.mjs | 57 ++++++++++++++++++++++++ scripts/jev/desktop.mjs | 27 ++++++------ scripts/jev/run.integration.test.mjs | 2 +- skills/jev-desktop/SKILL.md | 12 +++-- 6 files changed, 159 insertions(+), 29 deletions(-) create mode 100644 scripts/jev/bin.mjs create mode 100644 scripts/jev/bin.test.mjs diff --git a/scripts/jev/act.mjs b/scripts/jev/act.mjs index de7a596c5a..5b915f4962 100644 --- a/scripts/jev/act.mjs +++ b/scripts/jev/act.mjs @@ -14,17 +14,14 @@ * comes from --text. */ import { execFileSync, } from "node:child_process"; -import { existsSync } from "node:fs"; -import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { collect, describe, label, offerable, outsideWindow, overlayRole } from "./screen.mjs"; import { NO_MATCH, resolveModel, typesafeApi, route } from "./policy.mjs"; +import { defaultBin, minimizedHint, snapshotFlags } from "./bin.mjs"; export { collect, describe, label, offerable, overlayRole, route }; -const REPO = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); - /** A Choice accepts 255 options. One is reserved for the no-match outcome. */ const MAX_OPTIONS = 254; /** Below this the wide pass is re-asked over its own top candidates. */ @@ -219,9 +216,7 @@ const main = async (argv) => { const windowId = flag("window-id"); const execute = argv.includes("--execute"); const values = !argv.includes("--no-values"); - const bin = flag("bin") ?? (existsSync(join(REPO, "target/release/agent-desktop")) - ? join(REPO, "target/release/agent-desktop") - : "agent-desktop"); + const bin = flag("bin") ?? defaultBin(); const intent = argv .filter((a, i) => !a.startsWith("--") && !(argv[i - 1]?.startsWith("--") && !bools.has(argv[i - 1]))) .join(" "); @@ -233,16 +228,23 @@ const main = async (argv) => { if (!process.env.TYPESAFE_API_KEY) fail("TYPESAFE_API_KEY unset"); const scope = windowId ? ["--app", app, "--window-id", windowId] : ["--app", app]; - const base = ["snapshot", ...scope, "-i", "--compact", "--include-bounds"]; + let flags; + try { + flags = snapshotFlags(); + } catch (e) { + fail(e.message); + } + const hint = () => minimizedHint((...a) => run(bin, a), app, windowId); + const base = ["snapshot", ...scope, "-i", "--compact", "--include-bounds", ...flags]; let snap = run(bin, root ? [...base, "--root", root] : base); - if (!snap.ok) fail(`snapshot failed: ${snap.error?.code}`, { detail: snap.error?.message }); + if (!snap.ok) fail(`snapshot failed: ${snap.error?.code}`, { detail: snap.error?.message, hint: hint() }); if (root && windowId && outsideWindow(snap.data, windowId)) { fail("root_outside_window", { detail: `the region is not in window ${windowId}` }); } const overlay = overlayRole(snap.data.tree); if (overlay && !root) { - const surfaceSnap = run(bin, ["snapshot", ...scope, "--surface", overlay, "-i", "--compact", "--include-bounds"]); + const surfaceSnap = run(bin, ["snapshot", ...scope, "--surface", overlay, "-i", "--compact", "--include-bounds", ...flags]); if (surfaceSnap.ok && windowId && outsideWindow(surfaceSnap.data, windowId)) { fail("surface_outside_window", { detail: `the ${overlay} is not in window ${windowId}` }); } @@ -256,7 +258,7 @@ const main = async (argv) => { overlay, }; let candidates = offerable(collect(snap.data.tree)); - if (candidates.length === 0) fail("no actionable element on screen"); + if (candidates.length === 0) fail("no actionable element on screen", { hint: hint() }); const truncated = candidates.length > MAX_OPTIONS; if (truncated) candidates = candidates.slice(0, MAX_OPTIONS); diff --git a/scripts/jev/bin.mjs b/scripts/jev/bin.mjs new file mode 100644 index 0000000000..8639110ea6 --- /dev/null +++ b/scripts/jev/bin.mjs @@ -0,0 +1,66 @@ +/** + * Which agent-desktop binary the scripts start, and the snapshot flags every + * read shares. Both entry points read the screen the same way, so both take + * these from here. + * + * On Windows a bare `agent-desktop` cannot be started by execFileSync: npm + * installs a `.cmd` and a `.ps1` shim, and Node refuses to spawn either without + * a shell. A shell would re-parse the supplied text, so the native executable + * the npm package ships is found instead, next to the shim on PATH. + */ +import { existsSync } from "node:fs"; +import { delimiter, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const REPO = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); + +const npmNative = (env, arch) => { + for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean)) { + if (!existsSync(join(dir, "agent-desktop.cmd"))) continue; + const exe = join(dir, "node_modules", "agent-desktop", "bin", `agent-desktop-win32-${arch}.exe`); + if (existsSync(exe)) return exe; + } + return null; +}; + +export const defaultBin = ({ platform = process.platform, arch = process.arch, env = process.env } = {}) => { + const release = join(REPO, "target", "release", platform === "win32" ? "agent-desktop.exe" : "agent-desktop"); + if (existsSync(release)) return release; + if (platform === "win32") return npmNative(env, arch) ?? "agent-desktop.exe"; + return "agent-desktop"; +}; + +const bounded = (name, raw, min, max) => { + if (raw === undefined || raw === "") return null; + const value = Number(raw); + if (!Number.isInteger(value) || value < min || value > max) { + throw new Error(`${name} must be a whole number from ${min} to ${max}, not ${JSON.stringify(raw)}`); + } + return String(value); +}; + +/** + * A Chromium or Electron window can take longer than the CLI's 3 s default to + * settle, and its controls often sit deeper than the default depth of 10, where + * a read returns a tree without them. Both stay at the CLI defaults unless set. + */ +export const snapshotFlags = ({ depth = true, env = process.env } = {}) => { + const timeout = bounded("JEV_SNAPSHOT_TIMEOUT_MS", env.JEV_SNAPSHOT_TIMEOUT_MS, 1, 120000); + const maxDepth = depth ? bounded("JEV_SNAPSHOT_MAX_DEPTH", env.JEV_SNAPSHOT_MAX_DEPTH, 1, 100) : null; + return [...(timeout ? ["--timeout-ms", timeout] : []), ...(maxDepth ? ["--max-depth", maxDepth] : [])]; +}; + +export const pasteCombo = (platform = process.platform) => (platform === "darwin" ? "cmd+v" : "ctrl+v"); + +/** + * A minimized window answers a snapshot with an empty tree or a timeout, which + * reads like a broken application. The window list says which it is. + */ +export const minimizedHint = (cli, app, windowId) => { + const listed = cli("list-windows", "--app", app); + if (!listed.ok || !Array.isArray(listed.data)) return null; + const windows = windowId ? listed.data.filter((w) => w.id === windowId) : listed.data; + const shut = windows.filter((w) => w.minimized); + if (!shut.length || shut.length !== windows.length) return null; + return `the window is minimized; run agent-desktop restore --window-id ${shut[0].id} and try again`; +}; diff --git a/scripts/jev/bin.test.mjs b/scripts/jev/bin.test.mjs new file mode 100644 index 0000000000..eb3fc490f7 --- /dev/null +++ b/scripts/jev/bin.test.mjs @@ -0,0 +1,57 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { defaultBin, minimizedHint, pasteCombo, snapshotFlags } from "./bin.mjs"; + +assert.equal(pasteCombo("darwin"), "cmd+v"); +assert.equal(pasteCombo("win32"), "ctrl+v"); +assert.equal(pasteCombo("linux"), "ctrl+v"); + +assert.deepEqual(snapshotFlags({ env: {} }), []); +assert.deepEqual(snapshotFlags({ env: { JEV_SNAPSHOT_TIMEOUT_MS: "15000" } }), ["--timeout-ms", "15000"]); +assert.deepEqual(snapshotFlags({ env: { JEV_SNAPSHOT_TIMEOUT_MS: "15000", JEV_SNAPSHOT_MAX_DEPTH: "30" } }), + ["--timeout-ms", "15000", "--max-depth", "30"]); +assert.deepEqual(snapshotFlags({ depth: false, env: { JEV_SNAPSHOT_MAX_DEPTH: "30" } }), [], + "a skeleton read keeps the CLI depth so the shallow first look stays shallow"); +for (const bad of ["0", "-1", "1.5", "abc", "120001"]) { + assert.throws(() => snapshotFlags({ env: { JEV_SNAPSHOT_TIMEOUT_MS: bad } }), /JEV_SNAPSHOT_TIMEOUT_MS/, bad); +} +assert.throws(() => snapshotFlags({ env: { JEV_SNAPSHOT_MAX_DEPTH: "101" } }), /JEV_SNAPSHOT_MAX_DEPTH/); + +assert.equal(defaultBin({ platform: "linux", env: {} }), "agent-desktop"); +assert.equal(defaultBin({ platform: "darwin", env: {} }), "agent-desktop"); + +const directory = mkdtempSync(join(tmpdir(), "jev-bin-test-")); +try { + const shims = join(directory, "npm"); + const native = join(shims, "node_modules", "agent-desktop", "bin"); + mkdirSync(native, { recursive: true }); + writeFileSync(join(shims, "agent-desktop.cmd"), ""); + writeFileSync(join(native, "agent-desktop-win32-x64.exe"), ""); + const empty = join(directory, "elsewhere"); + mkdirSync(empty); + const path = [empty, shims].join(process.platform === "win32" ? ";" : ":"); + + assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { PATH: path } }), + join(native, "agent-desktop-win32-x64.exe"), "the npm shim on PATH leads to the shipped executable"); + assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { Path: path } }), + join(native, "agent-desktop-win32-x64.exe"), "Windows spells the variable Path"); + assert.equal(defaultBin({ platform: "win32", arch: "arm64", env: { PATH: path } }), "agent-desktop.exe", + "an executable for another architecture is not used"); + assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { PATH: empty } }), "agent-desktop.exe"); +} finally { + rmSync(directory, { recursive: true, force: true }); +} + +const listing = (windows) => () => ({ ok: true, data: windows }); +assert.match(minimizedHint(listing([{ id: "w-1", minimized: true }]), "App", null), /restore --window-id w-1/); +assert.equal(minimizedHint(listing([{ id: "w-1", minimized: false }]), "App", null), null); +assert.equal(minimizedHint(listing([{ id: "w-1", minimized: true }, { id: "w-2", minimized: false }]), "App", null), null, + "one open window means minimizing is not why the read failed"); +assert.match(minimizedHint(listing([{ id: "w-1", minimized: true }, { id: "w-2", minimized: false }]), "App", "w-1"), + /w-1/, "a pinned window is judged on its own"); +assert.equal(minimizedHint(() => ({ ok: false, error: { code: "APP_NOT_FOUND" } }), "App", null), null); + +console.log("ok"); diff --git a/scripts/jev/desktop.mjs b/scripts/jev/desktop.mjs index bb5c9d5abe..d9ad01d50c 100644 --- a/scripts/jev/desktop.mjs +++ b/scripts/jev/desktop.mjs @@ -4,19 +4,13 @@ * never learns what a ref is. */ import { execFileSync } from "node:child_process"; -import { existsSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; import { setTimeout as sleep } from "node:timers/promises"; import { collect, offerable, outsideWindow, overlayRole } from "./screen.mjs"; import { ARGV } from "./policy.mjs"; +import { defaultBin, minimizedHint, pasteCombo, snapshotFlags } from "./bin.mjs"; -const REPO = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); - -export const bin = - process.env.AGENT_DESKTOP_BIN ?? - (existsSync(join(REPO, "target/release/agent-desktop")) ? join(REPO, "target/release/agent-desktop") : "agent-desktop"); +export const bin = process.env.AGENT_DESKTOP_BIN ?? defaultBin(); export const cli = (...argv) => { try { @@ -57,18 +51,23 @@ export const stopCursor = () => cli("cursor-overlay", "disable"); export const observe = (app, root, windowId = null) => { const scope = windowId ? ["--app", app, "--window-id", windowId] : ["--app", app]; const base = ["snapshot", ...scope, "-i", "--compact", "--include-bounds"]; - const unreadable = (what, error) => Object.assign(new Error(`${what} could not be read: ${error?.code}`), - { code: error?.code ?? null }); - let snap = root ? cli(...base, "--root", root) : cli(...base, "--skeleton"); + const deep = [...base, ...snapshotFlags()]; + const shallow = [...base, ...snapshotFlags({ depth: false })]; + const unreadable = (what, error) => { + const hint = minimizedHint(cli, app, windowId); + return Object.assign(new Error(`${what} could not be read: ${error?.code}${hint ? `; ${hint}` : ""}`), + { code: error?.code ?? null }); + }; + let snap = root ? cli(...deep, "--root", root) : cli(...shallow, "--skeleton"); if (!snap.ok && root) throw unreadable("that region", snap.error); if (snap.ok && root && windowId && outsideWindow(snap.data, windowId)) { throw Object.assign(new Error(`that region is not in window ${windowId}`), { code: "ROOT_OUTSIDE_WINDOW" }); } - if (!snap.ok && snap.error?.code !== "WINDOW_NOT_FOUND") snap = cli(...base, "--max-depth", "4"); + if (!snap.ok && snap.error?.code !== "WINDOW_NOT_FOUND") snap = cli(...shallow, "--max-depth", "4"); if (!snap.ok) throw unreadable("the screen", snap.error); const surface = root ? null : overlayRole(snap.data.tree); if (surface) { - const scoped = cli("snapshot", ...scope, "--surface", surface, "-i", "--compact", "--include-bounds"); + const scoped = cli("snapshot", ...scope, "--surface", surface, "-i", "--compact", "--include-bounds", ...snapshotFlags()); if (scoped.ok && windowId && outsideWindow(scoped.data, windowId)) { throw Object.assign(new Error(`the ${surface} is not in window ${windowId}`), { code: "SURFACE_OUTSIDE_WINDOW" }); } @@ -156,7 +155,7 @@ export const enterText = async ({ app, windowId = null }, node, text, clipboard) clipboard.borrow(); const copied = cli("clipboard-set", text); if (!copied.ok) return { route: "paste", result: copied }; - const pasted = cli("press", "cmd+v", "--app", app, ...(windowId ? ["--window-id", windowId] : [])); + const pasted = cli("press", pasteCombo(), "--app", app, ...(windowId ? ["--window-id", windowId] : [])); if (!pasted.ok) return { route: "paste", result: pasted }; const { held, observed } = await awaitFieldText(node.ref_id, text); if (!held) return { route: "paste", result: { ok: false, error: verificationFailure(observed) } }; diff --git a/scripts/jev/run.integration.test.mjs b/scripts/jev/run.integration.test.mjs index 2bf5c84b1d..8880f4e6e3 100644 --- a/scripts/jev/run.integration.test.mjs +++ b/scripts/jev/run.integration.test.mjs @@ -67,7 +67,7 @@ if (command === 'get') { } console.log(JSON.stringify(result)); `; -for (const command of ["snapshot", "click", "set-value", "focus", "clipboard-get", "clipboard-set", "press", "get"]) { +for (const command of ["snapshot", "click", "set-value", "focus", "clipboard-get", "clipboard-set", "press", "get", "list-windows"]) { writeFileSync(join(directory, command), fake); } writeFileSync(preload, ` diff --git a/skills/jev-desktop/SKILL.md b/skills/jev-desktop/SKILL.md index 45164a0c71..df627df527 100644 --- a/skills/jev-desktop/SKILL.md +++ b/skills/jev-desktop/SKILL.md @@ -64,7 +64,7 @@ one. **Text goes in by whichever route the application accepts.** A direct value write (`set-value`) is one verified call. Only when the application refuses it and the refusal says a retry is safe does the value go through the clipboard and -a `cmd+v` paste (macOS only). The clipboard is put back when the run ends, or +a paste: `cmd+v` on macOS, `ctrl+v` elsewhere. The clipboard is put back when the run ends, or emptied if it held anything but text. One key press per character is never used: it drops characters and loses capitals. @@ -156,12 +156,18 @@ node scripts/jev/act.mjs --app TextEdit --execute \ | `--execute` | `act.mjs` only. Run the command when `decision` is `act`. Without it, nothing runs. | | `--text "…"` | Text the intent needs. Jev returns choices, never strings. `run.mjs` takes it repeatedly; `act.mjs` takes one value. | | `--root @ref` | Resolve inside one container instead of the whole window. | -| `--bin ` | `act.mjs` only. agent-desktop binary. Defaults to the release build, then `PATH`. `run.mjs` reads `AGENT_DESKTOP_BIN` instead, with the same default. | +| `--bin ` | `act.mjs` only. agent-desktop binary. Defaults to the release build, then `PATH`. On Windows the `PATH` lookup finds the `.exe` the npm package ships next to its `agent-desktop.cmd` shim, because Node cannot start the shim without a shell. `run.mjs` reads `AGENT_DESKTOP_BIN` instead, with the same default. | Environment: `TYPESAFE_API_KEY` is required (both scripts fail with `TYPESAFE_API_KEY unset`). `TYPESAFE_BASE_URL` and `TYPESAFE_MODEL` are covered below. `JEV_VERIFY_MS` sets the paste read-back deadline in ms (default 2000, 0 -to 60000). +to 60000). `JEV_SNAPSHOT_TIMEOUT_MS` (1 to 120000) and `JEV_SNAPSHOT_MAX_DEPTH` +(1 to 100) pass `--timeout-ms` and `--max-depth` to every screen read; unset, +the CLI defaults of 3000 ms and depth 10 apply. A Chromium or Electron window +often needs both: its controls can sit below depth 10, where a read returns a +tree without them. The skeleton first look keeps the CLI depth. When a read +fails and every window of the app is minimized, the error says so and names the +`restore` command. `argv` is the exact agent-desktop command. `double-click` and `hover` carry `--headed`; `scroll` always goes down. From 6ce67a11d2de3bb4bd4185297be4950b9c319522 Mon Sep 17 00:00:00 2001 From: yumi Date: Mon, 2 Nov 2026 22:36:19 +0800 Subject: [PATCH 2/5] feat(jev): run several known steps per screen with flow.mjs run.mjs and act.mjs ask Jev one step at a time, so every step costs a screen read, a request and a process start, and the caller waits between them. Measured on a browser page with 120 candidates, one question took about 0.5 s and five questions in one request took the same. flow.mjs reads the screen once, asks for the target of every pending step in one request, and runs the leading steps Jev is sure of as one agent-desktop batch. The first unsure step ends the batch and the next round asks again on the new screen. After an action the screen is re-read until it changes; when Jev then finds nothing on an unchanged screen the run stops with no_effect instead of waiting. Text is written with set-value and no separate focus, because focus on Windows moves the foreground and headless delivery refuses it, which had stopped the key press after it. --- scripts/jev/flow.mjs | 272 ++++++++++++++++++++++++++++++++++++ scripts/jev/flow.test.mjs | 80 +++++++++++ skills/jev-desktop/SKILL.md | 33 +++++ 3 files changed, 385 insertions(+) create mode 100644 scripts/jev/flow.mjs create mode 100644 scripts/jev/flow.test.mjs diff --git a/scripts/jev/flow.mjs b/scripts/jev/flow.mjs new file mode 100644 index 0000000000..99d9ee18f9 --- /dev/null +++ b/scripts/jev/flow.mjs @@ -0,0 +1,272 @@ +#!/usr/bin/env node +/** + * jev-desktop flow: several steps per screen instead of one. + * + * node scripts/jev/flow.mjs --app msedge --window-id w-42 --execute \ + * "the search box at the top of the page" --text "你好" press:return + * + * Each round reads the screen once, asks Jev for the target of every pending + * step in a single request, and runs the leading steps it is sure of as one + * agent-desktop batch. A step whose element is not on this screen yet stops + * the batch there; the next round reads the new screen and asks again for + * what is left. `--text` belongs to the step written before it, and + * `press:` sends a key without asking Jev anything. + * + * Asking five steps costs about what asking one does, so the time a run takes + * is set by how many distinct screens it passes through, not by its steps. + */ +import { fileURLToPath } from "node:url"; + +import { cli } from "./desktop.mjs"; +import { snapshotFlags } from "./bin.mjs"; +import { collect, offerable, outsideWindow, overlayRole } from "./screen.mjs"; +import { NO_MATCH, fingerprint, resolveModel, route, typesafeApi } from "./policy.mjs"; +import { reconcile } from "./act.mjs"; + +const CAP = 150; +const MAX_ROUNDS = 8; +const SETTLE_READS = 4; +const SETTLE_WAIT_MS = 300; +const FLOW_DEPTH = "30"; + +export const parseSteps = (argv) => { + const steps = []; + const flags = { execute: false }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === "--text") { + if (!steps.length || steps.at(-1).press || argv[i + 1] === undefined) { + throw new Error("--text needs a value and must follow the step it belongs to"); + } + steps.at(-1).text = argv[++i]; + } else if (arg === "--app" || arg === "--window-id") { + if (argv[i + 1] === undefined) throw new Error(`${arg} needs a value`); + flags[arg === "--app" ? "app" : "windowId"] = argv[++i]; + } else if (arg === "--execute") { + flags.execute = true; + } else if (arg.startsWith("--")) { + throw new Error(`unknown flag ${arg}`); + } else { + steps.push(arg.startsWith("press:") ? { intent: arg, press: arg.slice(6) } : { intent: arg }); + } + } + return { steps: steps.map((step, index) => ({ ...step, index })), flags }; +}; + +/** Offscreen and unlabeled elements cannot be told apart in a short description, so they stay out. */ +export const candidates = (tree, cap = CAP) => + offerable(collect(tree)) + .filter((n) => !(n.states ?? []).includes("offscreen") && (n.name || n.description || n.value)) + .slice(0, cap); + +/** Every question repeats the whole list, so each element costs a role, a label and a short value. */ +const brief = (n) => ({ + what: `${n.role} "${String(n.name ?? n.description ?? "").slice(0, 60)}"`, + ...(n.value ? { holds: String(n.value).slice(0, 60) } : {}), +}); + +export const buildFlowRequest = (steps, screen, nodes) => { + const criteria = { + ...Object.fromEntries(nodes.map((n) => [n.ref_id, brief(n)])), + [NO_MATCH]: { what: "None of the above", when: "The element is not on this screen yet." }, + }; + const questions = {}; + for (const step of steps) { + questions[`target_${step.index}`] = { + type: "choice", + instructions: { + task: `Which element on screen does this step refer to: ${step.intent}`, + how: "Match the step against each element's role, label and the value it holds.", + note: "Judge identity only. Answer none when the element is not on this screen.", + }, + criteria, + }; + questions[`risk_${step.index}`] = { + type: "noul", + instructions: `Would carrying out this step be hard or impossible to undo: ${step.intent}`, + }; + } + return { state: { app: screen.app, window: screen.window, surface: screen.surface, element_count: nodes.length }, + model: resolveModel(), questions }; +}; + +export const readFlowAnswers = (body, steps) => + Object.fromEntries(steps.map((step) => { + const target = body?.answers?.[`target_${step.index}`]; + const risk = body?.answers?.[`risk_${step.index}`]; + return [step.index, target?.type === "choice" + ? { target: target.choice, targetConfidence: target.confidence ?? 0, present: null, destructive: risk?.noul ?? null } + : { target: NO_MATCH, targetConfidence: 0, present: null, destructive: null }]; + })); + +const ARGS = { + "set-value": (ref, text) => ({ ref_id: ref, value: text }), + select: (ref, text) => ({ ref_id: ref, value: text }), + type: (ref, text) => ({ ref_id: ref, text }), + scroll: (ref) => ({ ref_id: ref, direction: "down" }), +}; + +export const toEntries = (step, node, { app, windowId }) => { + if (step.press) return [{ command: "press", args: { combo: step.press, app, ...(windowId ? { window_id: windowId } : {}) } }]; + const hasText = step.text !== undefined; + const { verb } = reconcile(hasText ? "set-value" : "click", node, hasText); + return [{ command: verb, args: (ARGS[verb] ?? ((ref) => ({ ref_id: ref })))(node.ref_id, step.text) }]; +}; + +/** The leading steps Jev is sure of run together; the first one it is not sure of ends the batch. */ +export const plan = (pending, answers, nodes, target) => { + const byRef = new Map(nodes.map((n) => [n.ref_id, n])); + const entries = []; + const decisions = []; + for (const step of pending) { + if (step.press) { + entries.push(...toEntries(step, null, target).map((e) => ({ ...e, step: step.index }))); + decisions.push({ step: step.index, decision: "act", key: step.press }); + continue; + } + const answer = answers[step.index]; + const routed = route(answer); + const node = byRef.get(answer.target); + const label = node ? `${node.role} "${String(node.name ?? node.description ?? "").slice(0, 40)}"` : null; + decisions.push({ step: step.index, decision: routed.decision, why: routed.why, element: label, + confidence: answer.targetConfidence, destructive: answer.destructive }); + if (routed.decision !== "act" || !node) break; + entries.push(...toEntries(step, node, target).map((e) => ({ ...e, step: step.index }))); + } + return { entries, decisions }; +}; + +const deepFlags = () => { + const flags = snapshotFlags(); + return flags.includes("--max-depth") ? flags : [...flags, "--max-depth", FLOW_DEPTH]; +}; + +/** One deep read per screen. An open sheet, menu or Windows popover is read instead of the window behind it. */ +const readScreen = (app, windowId) => { + const scope = windowId ? ["--app", app, "--window-id", windowId] : ["--app", app]; + const flags = deepFlags(); + let snap = cli("snapshot", ...scope, "-i", "--compact", ...flags); + if (!snap.ok) throw Object.assign(new Error(`the screen could not be read: ${snap.error?.code}`), { code: snap.error?.code }); + let surface = overlayRole(snap.data.tree); + const kind = surface ?? (process.platform === "win32" ? "popover" : null); + if (kind) { + const scoped = cli("snapshot", ...scope, "--surface", kind, "-i", "--compact", ...flags); + if (scoped.ok && candidates(scoped.data.tree).length && !(windowId && outsideWindow(scoped.data, windowId))) { + snap = scoped; + surface = kind; + } else if (!surface) { + surface = null; + } + } + return { snap, screen: { app, window: snap.data.window?.title ?? null, surface: surface ?? "window" } }; +}; + +const ask = async (payload) => { + for (let attempt = 0; ; attempt++) { + const res = await fetch(typesafeApi(), { + method: "POST", + redirect: "error", + headers: { Authorization: `Bearer ${process.env.TYPESAFE_API_KEY}`, "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }).catch(() => ({ ok: false, status: 0 })); + if (res.ok) return res.json(); + if (attempt >= 2 || ![429, 503, 529].includes(res.status)) throw new Error(`decision endpoint returned HTTP ${res.status}`); + await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1))); + } +}; + +const since = (start) => Math.round(performance.now() - start); +const emit = (event) => console.log(JSON.stringify(event)); + +/** The steps whose own action ran. A step owns one entry, so a failed entry fails only its step. */ +export const completedSteps = (entries, results) => + new Set(entries.filter((entry, i) => results[i]?.ok).map((entry) => entry.step)); + +/** + * After an action the screen is read until it differs from the one acted on, so + * Jev is never asked about a page that has not reacted yet. A screen that never + * changes is returned as it is, and the caller decides what that means. + */ +const settledScreen = async (app, windowId, actedOn) => { + for (let read = 1; ; read++) { + const seen = readScreen(app, windowId); + const nodes = candidates(seen.snap.data.tree); + const print = fingerprint(nodes); + if (!actedOn || print !== actedOn || read >= SETTLE_READS) return { ...seen, nodes, print, changed: print !== actedOn }; + await new Promise((resolve) => setTimeout(resolve, SETTLE_WAIT_MS)); + } +}; + +export const flow = async (steps, { app, windowId = null, execute = false } = {}) => { + let pending = steps; + let actedOn = null; + let idleOn = null; + for (let round = 1; pending.length; round++) { + if (round > MAX_ROUNDS) return { stop: "too many rounds", pending: pending.map((s) => s.index) }; + let start = performance.now(); + const { screen, nodes, print, changed } = await settledScreen(app, windowId, actedOn); + const readMs = since(start); + const asked = pending.filter((s) => !s.press); + start = performance.now(); + const answers = asked.length && nodes.length ? readFlowAnswers(await ask(buildFlowRequest(asked, screen, nodes)), asked) : {}; + for (const step of asked) answers[step.index] ??= { target: NO_MATCH, targetConfidence: 0, present: null, destructive: null }; + const askMs = since(start); + const { entries, decisions } = plan(pending, answers, nodes, { app, windowId }); + const event = { round, surface: screen.surface, candidates: nodes.length, read_ms: readMs, ask_ms: askMs, decisions }; + if (!execute) { + emit({ ...event, planned: entries.map(({ step, ...e }) => ({ step, ...e })) }); + return { stop: "dry_run" }; + } + if (!entries.length) { + emit(event); + if (actedOn && !changed) { + return { stop: "no_effect", why: "the screen did not change after the previous step, so it may not have taken effect", + step: decisions.at(-1) }; + } + if (idleOn === print) return { stop: "blocked", step: decisions.at(-1) }; + idleOn = print; + actedOn = print; + continue; + } + idleOn = null; + start = performance.now(); + const batch = cli("batch", "--stop-on-error", JSON.stringify(entries.map(({ step, ...e }) => e))); + const results = batch.data?.results ?? []; + const done = completedSteps(entries, results); + const firstError = results.find((r) => !r.ok)?.error ?? (batch.ok ? null : batch.error); + emit({ ...event, act_ms: since(start), ran: [...done], ...(firstError ? { error: firstError.code } : {}) }); + if (firstError && firstError.code !== "STALE_REF" && !done.size) { + return { stop: "action_failed", error: firstError }; + } + pending = pending.filter((s) => !done.has(s.index)); + actedOn = print; + } + return { done: true }; +}; + +const main = async (argv) => { + let parsed; + try { + parsed = parseSteps(argv); + } catch (error) { + console.error(String(error.message)); + process.exit(2); + } + const { steps, flags } = parsed; + if (!flags.app || !steps.length) { + console.error('usage: flow.mjs --app [--window-id ] [--execute] "" [--text "…"] [press:] …'); + process.exit(2); + } + if (!process.env.TYPESAFE_API_KEY) throw new Error("TYPESAFE_API_KEY unset"); + const start = performance.now(); + const result = await flow(steps, flags); + emit({ ...result, total_ms: since(start) }); + process.exitCode = result.done || result.stop === "dry_run" ? 0 : 1; +}; + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + await main(process.argv.slice(2)).catch((error) => { + console.log(JSON.stringify({ ok: false, error: String(error.message ?? error) })); + process.exitCode = 1; + }); +} diff --git a/scripts/jev/flow.test.mjs b/scripts/jev/flow.test.mjs new file mode 100644 index 0000000000..f70505ced7 --- /dev/null +++ b/scripts/jev/flow.test.mjs @@ -0,0 +1,80 @@ +import assert from "node:assert/strict"; + +import { buildFlowRequest, candidates, completedSteps, parseSteps, plan, readFlowAnswers, toEntries } from "./flow.mjs"; + +const parsed = parseSteps(["--app", "msedge", "--window-id", "w-1", "--execute", + "the search box", "--text", "你好", "press:return", "the first result"]); +assert.equal(parsed.flags.app, "msedge"); +assert.equal(parsed.flags.windowId, "w-1"); +assert.equal(parsed.flags.execute, true); +assert.deepEqual(parsed.steps.map((s) => [s.index, s.intent, s.text ?? null, s.press ?? null]), [ + [0, "the search box", "你好", null], + [1, "press:return", null, "return"], + [2, "the first result", null, null], +]); +assert.throws(() => parseSteps(["--text", "x"]), /must follow/, "text with no step before it"); +assert.throws(() => parseSteps(["press:return", "--text", "x"]), /must follow/, "a key press takes no text"); +assert.throws(() => parseSteps(["--bogus"]), /unknown flag/); + +const S = "s1"; +const tree = { + role: "window", + children: [ + { ref_id: `@${S}:e1`, role: "textfield", name: "搜索", available_actions: ["SetValue", "Click"] }, + { ref_id: `@${S}:e2`, role: "button", name: "搜索", available_actions: ["Click"] }, + { ref_id: `@${S}:e3`, role: "link", name: "Below", states: ["offscreen"], available_actions: ["Click"] }, + { ref_id: `@${S}:e4`, role: "group", available_actions: ["Click"] }, + { ref_id: `@${S}:e5`, role: "button", name: "Gone", states: ["disabled"], available_actions: ["Click"] }, + ], +}; +const nodes = candidates(tree); +assert.deepEqual(nodes.map((n) => n.ref_id), [`@${S}:e1`, `@${S}:e2`], + "offscreen, unlabeled and disabled elements are never offered"); +assert.equal(candidates(tree, 1).length, 1, "the cap bounds the request"); + +const asked = parsed.steps.filter((s) => !s.press); +const request = buildFlowRequest(asked, { app: "msedge", window: "B", surface: "window" }, nodes); +assert.deepEqual(Object.keys(request.questions), ["target_0", "risk_0", "target_2", "risk_2"], + "one request carries a target and a risk question for every step that needs an element"); +assert.deepEqual(Object.keys(request.questions.target_0.criteria), [`@${S}:e1`, `@${S}:e2`, "none"]); +assert.deepEqual(request.questions.target_0.criteria[`@${S}:e1`], { what: 'textfield "搜索"' }); + +const answers = readFlowAnswers({ answers: { + target_0: { type: "choice", choice: `@${S}:e1`, confidence: 0.95 }, + risk_0: { type: "noul", noul: 0.1 }, + target_2: { type: "choice", choice: "none", confidence: 0.9 }, +} }, asked); +assert.equal(answers[0].target, `@${S}:e1`); +assert.equal(answers[0].destructive, 0.1); +assert.equal(answers[2].target, "none"); +assert.deepEqual(readFlowAnswers({}, asked)[0].target, "none", "a missing answer is no match, never a guess"); + +const target = { app: "msedge", windowId: "w-1" }; +const planned = plan(parsed.steps, answers, nodes, target); +assert.deepEqual(planned.entries.map((e) => [e.step, e.command]), [[0, "set-value"], [1, "press"]], + "the steps Jev is sure of run together and the first unsure one ends the batch"); +assert.deepEqual(planned.entries[0].args, { ref_id: `@${S}:e1`, value: "你好" }); +assert.deepEqual(planned.entries[1].args, { combo: "return", app: "msedge", window_id: "w-1" }); +assert.ok(!planned.entries.some((e) => e.command === "focus"), + "no separate focus: on Windows it moves the foreground and headless delivery refuses it"); +assert.deepEqual(planned.decisions.map((d) => [d.step, d.decision]), [[0, "act"], [1, "act"], [2, "abstain"]]); + +const unsure = plan(parsed.steps, { ...answers, 0: { ...answers[0], targetConfidence: 0.6 } }, nodes, target); +assert.equal(unsure.entries.length, 0, "a step under the bar runs nothing after it either"); +assert.equal(unsure.decisions[0].decision, "confirm"); + +const risky = plan(parsed.steps, { ...answers, 0: { ...answers[0], targetConfidence: 0.8, destructive: 0.9 } }, nodes, target); +assert.equal(risky.entries.length, 0, "a hard-to-undo step needs the higher bar"); + +assert.deepEqual(toEntries({ intent: "press the search button" }, nodes[1], target), + [{ command: "click", args: { ref_id: `@${S}:e2` } }]); +assert.deepEqual(toEntries({ intent: "x", text: "y" }, { ref_id: "@s1:e9", available_actions: ["TypeText"] }, target), + [{ command: "type", args: { ref_id: "@s1:e9", text: "y" } }], "a field without SetValue is typed into"); + +const twoSteps = [{ step: 0, command: "set-value" }, { step: 1, command: "press" }]; +assert.deepEqual([...completedSteps(twoSteps, [{ ok: true }, { ok: true }])], [0, 1]); +assert.deepEqual([...completedSteps(twoSteps, [{ ok: true }, { ok: false }])], [0], + "a failed key press fails only its own step; the value already written stays done"); +assert.deepEqual([...completedSteps(twoSteps, [{ ok: true }])], [0], "an entry the batch never started is not done"); + +console.log("ok"); diff --git a/skills/jev-desktop/SKILL.md b/skills/jev-desktop/SKILL.md index df627df527..962bbdfd1a 100644 --- a/skills/jev-desktop/SKILL.md +++ b/skills/jev-desktop/SKILL.md @@ -146,6 +146,35 @@ node scripts/jev/act.mjs --app TextEdit --execute \ } ``` +## Several steps per screen + +You know the steps; you want them run without a round trip after each one. + +```sh +node scripts/jev/flow.mjs --app msedge --window-id w-42 --execute \ + "the search box in the page header" --text "hello" press:return +``` + +Each round reads the screen once, asks Jev for the target of every pending +step in one request, and runs the leading steps it is sure of as one +`agent-desktop batch`. The first step it is not sure of ends the batch; the +next round reads the screen again and asks for what is left. `--text` belongs +to the step written before it, and `press:` sends a key without asking +Jev. Without `--execute` the first round is printed and nothing runs. + +Measured on a browser page with 120 candidates: one question took about 0.5 s +and five questions in one request took the same, so a run's time is set by +how many screens it passes through, not by its steps. Each question repeats +the candidate list, so elements are described by role, label and up to sixty +characters of value, and at most 150 visible, labelled elements are offered. + +After an action the screen is read until it differs from the one acted on. If +Jev then finds nothing and the screen never changed, the run stops with +`no_effect` instead of waiting. The confidence bars are the same as `act.mjs`. +Text is written with `set-value` and no separate `focus`: on Windows `focus` +moves the foreground, which headless delivery refuses. Each round prints one +JSON line with `read_ms`, `ask_ms` and `act_ms`. + ## Calling it | Flag | Meaning | @@ -272,6 +301,8 @@ change shape. | `scripts/jev/desktop.mjs` | The only code that speaks to agent-desktop. | | `scripts/jev/run.mjs` | The loop and its command line. | | `scripts/jev/act.mjs` | The single-step resolver. | +| `scripts/jev/flow.mjs` | Several known steps per screen: one read, one request, one batch. | +| `scripts/jev/bin.mjs` | Which binary runs and the snapshot flags every read shares. | ## Checks @@ -283,6 +314,8 @@ After a paste the field is read back. If it does not hold the requested text the ```sh node scripts/jev/act.test.mjs +node scripts/jev/flow.test.mjs +node scripts/jev/bin.test.mjs node scripts/jev/run.test.mjs node scripts/jev/run.integration.test.mjs node scripts/jev/evidence.test.mjs From 5fb8092a453c3226cdabc27d03cbcd94d7be934d Mon Sep 17 00:00:00 2001 From: yumi Date: Tue, 3 Nov 2026 16:39:56 +0800 Subject: [PATCH 3/5] test(jev): isolate binary lookup from local builds --- scripts/jev/bin.mjs | 5 +++-- scripts/jev/bin.test.mjs | 17 +++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/scripts/jev/bin.mjs b/scripts/jev/bin.mjs index 8639110ea6..18ce411160 100644 --- a/scripts/jev/bin.mjs +++ b/scripts/jev/bin.mjs @@ -23,8 +23,9 @@ const npmNative = (env, arch) => { return null; }; -export const defaultBin = ({ platform = process.platform, arch = process.arch, env = process.env } = {}) => { - const release = join(REPO, "target", "release", platform === "win32" ? "agent-desktop.exe" : "agent-desktop"); +const releaseBuild = (platform) => join(REPO, "target", "release", platform === "win32" ? "agent-desktop.exe" : "agent-desktop"); + +export const defaultBin = ({ platform = process.platform, arch = process.arch, env = process.env, release = releaseBuild(platform) } = {}) => { if (existsSync(release)) return release; if (platform === "win32") return npmNative(env, arch) ?? "agent-desktop.exe"; return "agent-desktop"; diff --git a/scripts/jev/bin.test.mjs b/scripts/jev/bin.test.mjs index eb3fc490f7..e8586a5bf7 100644 --- a/scripts/jev/bin.test.mjs +++ b/scripts/jev/bin.test.mjs @@ -20,8 +20,9 @@ for (const bad of ["0", "-1", "1.5", "abc", "120001"]) { } assert.throws(() => snapshotFlags({ env: { JEV_SNAPSHOT_MAX_DEPTH: "101" } }), /JEV_SNAPSHOT_MAX_DEPTH/); -assert.equal(defaultBin({ platform: "linux", env: {} }), "agent-desktop"); -assert.equal(defaultBin({ platform: "darwin", env: {} }), "agent-desktop"); +const absent = join(tmpdir(), "jev-no-release-build"); +assert.equal(defaultBin({ platform: "linux", env: {}, release: absent }), "agent-desktop"); +assert.equal(defaultBin({ platform: "darwin", env: {}, release: absent }), "agent-desktop"); const directory = mkdtempSync(join(tmpdir(), "jev-bin-test-")); try { @@ -34,13 +35,17 @@ try { mkdirSync(empty); const path = [empty, shims].join(process.platform === "win32" ? ";" : ":"); - assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { PATH: path } }), + assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { PATH: path }, release: absent }), join(native, "agent-desktop-win32-x64.exe"), "the npm shim on PATH leads to the shipped executable"); - assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { Path: path } }), + assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { Path: path }, release: absent }), join(native, "agent-desktop-win32-x64.exe"), "Windows spells the variable Path"); - assert.equal(defaultBin({ platform: "win32", arch: "arm64", env: { PATH: path } }), "agent-desktop.exe", + assert.equal(defaultBin({ platform: "win32", arch: "arm64", env: { PATH: path }, release: absent }), "agent-desktop.exe", "an executable for another architecture is not used"); - assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { PATH: empty } }), "agent-desktop.exe"); + assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { PATH: empty }, release: absent }), "agent-desktop.exe"); + const release = join(directory, "agent-desktop.exe"); + writeFileSync(release, ""); + assert.equal(defaultBin({ platform: "win32", arch: "x64", env: { PATH: path }, release }), release, + "a release build in the clone wins over the installed package"); } finally { rmSync(directory, { recursive: true, force: true }); } From 6d902fa8a9b286b951905e05831556da7e01ee88 Mon Sep 17 00:00:00 2001 From: yumi Date: Tue, 3 Nov 2026 16:53:42 +0800 Subject: [PATCH 4/5] fix(jev): preserve retry policy across partial batches Stop on unsafe delivery after any partial batch success, read optional Windows popovers, and run the JEv suite on all three platforms. --- .github/workflows/ci.yml | 24 ++++++--- scripts/jev/act.mjs | 10 +++- scripts/jev/desktop.mjs | 14 ++++-- scripts/jev/flow.integration.test.mjs | 71 +++++++++++++++++++++++++++ scripts/jev/flow.mjs | 9 ++-- scripts/jev/run.integration.test.mjs | 20 +++++++- skills/jev-desktop/SKILL.md | 14 ++++-- 7 files changed, 140 insertions(+), 22 deletions(-) create mode 100644 scripts/jev/flow.integration.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc8e9fb906..7a102b7e3b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,23 @@ env: RUST_BACKTRACE: 1 jobs: + jev: + name: JEv (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '24' + - run: node --test scripts/jev/*.test.mjs + fmt: name: Format runs-on: ubuntu-latest @@ -189,13 +206,6 @@ jobs: with: node-version: '24' - - name: jev-desktop tests - run: | - node scripts/jev/run.test.mjs - node scripts/jev/act.test.mjs - node scripts/jev/run.integration.test.mjs - node scripts/jev/evidence.test.mjs - - name: NPM package contents run: | node --test tests/npm/*.test.js tests/release/*.test.js diff --git a/scripts/jev/act.mjs b/scripts/jev/act.mjs index 5b915f4962..bcb16cf910 100644 --- a/scripts/jev/act.mjs +++ b/scripts/jev/act.mjs @@ -242,8 +242,14 @@ const main = async (argv) => { fail("root_outside_window", { detail: `the region is not in window ${windowId}` }); } - const overlay = overlayRole(snap.data.tree); - if (overlay && !root) { + let overlay = overlayRole(snap.data.tree); + if (!overlay && !root && process.platform === "win32") { + const popover = run(bin, ["snapshot", ...scope, "--surface", "popover", "-i", "--compact", "--include-bounds", ...flags]); + if (popover.ok && offerable(collect(popover.data.tree)).length && !(windowId && outsideWindow(popover.data, windowId))) { + snap = popover; + overlay = "popover"; + } + } else if (overlay && !root) { const surfaceSnap = run(bin, ["snapshot", ...scope, "--surface", overlay, "-i", "--compact", "--include-bounds", ...flags]); if (surfaceSnap.ok && windowId && outsideWindow(surfaceSnap.data, windowId)) { fail("surface_outside_window", { detail: `the ${overlay} is not in window ${windowId}` }); diff --git a/scripts/jev/desktop.mjs b/scripts/jev/desktop.mjs index d9ad01d50c..afe8ebddd2 100644 --- a/scripts/jev/desktop.mjs +++ b/scripts/jev/desktop.mjs @@ -46,7 +46,9 @@ export const stopCursor = () => cli("cursor-overlay", "disable"); * holding thousands of elements costs the same first look as a panel holding * thirty. A region cut off by that shallow read still reports how much it holds, * which is what makes it worth drilling into. A sheet or menu owns the screen - * while it is up, so it is read instead of the window behind it. + * while it is up, so it is read instead of the window behind it. On Windows a + * Chromium toolbar bubble is a separate popup window the frame's tree does not + * contain, so when the tree shows no overlay the popover surface is read too. */ export const observe = (app, root, windowId = null) => { const scope = windowId ? ["--app", app, "--window-id", windowId] : ["--app", app]; @@ -65,8 +67,14 @@ export const observe = (app, root, windowId = null) => { } if (!snap.ok && snap.error?.code !== "WINDOW_NOT_FOUND") snap = cli(...shallow, "--max-depth", "4"); if (!snap.ok) throw unreadable("the screen", snap.error); - const surface = root ? null : overlayRole(snap.data.tree); - if (surface) { + let surface = root ? null : overlayRole(snap.data.tree); + if (!surface && !root && process.platform === "win32") { + const popover = cli("snapshot", ...scope, "--surface", "popover", "-i", "--compact", "--include-bounds", ...snapshotFlags()); + if (popover.ok && offerable(collect(popover.data.tree)).length && !(windowId && outsideWindow(popover.data, windowId))) { + snap = popover; + surface = "popover"; + } + } else if (surface) { const scoped = cli("snapshot", ...scope, "--surface", surface, "-i", "--compact", "--include-bounds", ...snapshotFlags()); if (scoped.ok && windowId && outsideWindow(scoped.data, windowId)) { throw Object.assign(new Error(`the ${surface} is not in window ${windowId}`), { code: "SURFACE_OUTSIDE_WINDOW" }); diff --git a/scripts/jev/flow.integration.test.mjs b/scripts/jev/flow.integration.test.mjs new file mode 100644 index 0000000000..ae2d80925e --- /dev/null +++ b/scripts/jev/flow.integration.test.mjs @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const directory = mkdtempSync(join(tmpdir(), "jev-flow-test-")); +const log = join(directory, "batches.jsonl"); +const preload = join(directory, "fetch.mjs"); +const entry = new URL("./flow.mjs", import.meta.url); + +writeFileSync(join(directory, "snapshot"), ` +const nodes = [1, 2].map(i => ({ref_id:'@s1:e'+i,role:'button',name:'Button '+i,available_actions:['Click']})); +const result = process.argv.includes('--surface') + ? {ok:false,error:{code:'INVALID_ARGS'}} + : {ok:true,data:{window:{id:'w-1',title:'Fixture'},tree:{role:'window',children:nodes}}}; +console.log(JSON.stringify(result)); +`); +writeFileSync(join(directory, "batch"), ` +const fs = require('node:fs'); +const entries = JSON.parse(process.argv.at(-1)); +const before = fs.readFileSync(process.env.JEV_TEST_LOG, 'utf8'); +fs.appendFileSync(process.env.JEV_TEST_LOG, JSON.stringify(entries)+'\\n'); +const safe = process.env.JEV_TEST_MODE === 'stale_safe'; +const error = {code:process.env.JEV_TEST_MODE === 'timeout' ? 'TIMEOUT' : 'STALE_REF', + disposition:{retry:safe?'safe':'unsafe',delivery:safe?'not_delivered':'delivery_uncertain'}}; +console.log(JSON.stringify({ok:true,data:{results:before ? [{ok:true}] : [{ok:true},{ok:false,error}]}})); +`); +writeFileSync(preload, ` +globalThis.fetch = async (_url, options) => { + const request = JSON.parse(options.body); + const answers = Object.fromEntries(Object.keys(request.questions).map(key => [key, + key.startsWith('target_') + ? {type:'choice',choice:'@s1:e'+(Number(key.split('_')[1])+1),confidence:0.99} + : {type:'noul',noul:0.1}])); + return {ok:true,json:async()=>({answers})}; +}; +`); + +try { + for (const mode of ["timeout", "stale_unsafe", "stale_safe"]) { + writeFileSync(log, ""); + const result = spawnSync(process.execPath, ["--import", pathToFileURL(preload).href, + fileURLToPath(entry), "--app", "Fixture", "--window-id", "w-1", + "--execute", "Button 1", "Button 2"], { + cwd: directory, encoding: "utf8", timeout: 10000, + env: { ...process.env, TYPESAFE_API_KEY: "fixture", AGENT_DESKTOP_BIN: process.execPath, + JEV_TEST_LOG: log, JEV_TEST_MODE: mode }, + }); + assert.ifError(result.error); + const events = result.stdout.trim().split("\n").map(JSON.parse); + const batches = readFileSync(log, "utf8").trim().split("\n").map(JSON.parse); + const last = events.at(-1); + if (mode === "stale_safe") { + assert.equal(result.status, 0, result.stderr); + assert.equal(last.done, true); + assert.equal(batches.length, 2); + assert.equal(batches[1].length, 1, "a completed step is never replayed"); + assert.equal(batches[1][0].args.ref_id, "@s1:e2"); + } else { + assert.equal(result.status, 1, mode); + assert.equal(last.stop, "action_failed", mode); + assert.equal(batches.length, 1, "partial success does not permit retrying an unsafe error"); + } + } +} finally { + rmSync(directory, { recursive: true, force: true }); +} + +console.log("ok"); diff --git a/scripts/jev/flow.mjs b/scripts/jev/flow.mjs index 99d9ee18f9..ff31db84d3 100644 --- a/scripts/jev/flow.mjs +++ b/scripts/jev/flow.mjs @@ -12,8 +12,8 @@ * what is left. `--text` belongs to the step written before it, and * `press:` sends a key without asking Jev anything. * - * Asking five steps costs about what asking one does, so the time a run takes - * is set by how many distinct screens it passes through, not by its steps. + * Grouping decisions reduces the number of model requests. Total latency + * still depends on the application, the request size, and the model service. */ import { fileURLToPath } from "node:url"; @@ -235,7 +235,10 @@ export const flow = async (steps, { app, windowId = null, execute = false } = {} const done = completedSteps(entries, results); const firstError = results.find((r) => !r.ok)?.error ?? (batch.ok ? null : batch.error); emit({ ...event, act_ms: since(start), ran: [...done], ...(firstError ? { error: firstError.code } : {}) }); - if (firstError && firstError.code !== "STALE_REF" && !done.size) { + const refreshable = firstError?.code === "STALE_REF" + && firstError.disposition?.retry === "safe" + && firstError.disposition?.delivery === "not_delivered"; + if (firstError && !refreshable) { return { stop: "action_failed", error: firstError }; } pending = pending.filter((s) => !done.has(s.index)); diff --git a/scripts/jev/run.integration.test.mjs b/scripts/jev/run.integration.test.mjs index 8880f4e6e3..0895ab1447 100644 --- a/scripts/jev/run.integration.test.mjs +++ b/scripts/jev/run.integration.test.mjs @@ -26,6 +26,8 @@ if (command === 'snapshot' && mode === 'window_closed' && clicked()) result = er else if (command === 'snapshot' && mode === 'closed_top' && require('node:fs').readFileSync(process.env.JEV_TEST_LOG,'utf8').split('\\n').filter(l=>l.includes('"command":"snapshot"')).length >= 3) result = error('WINDOW_NOT_FOUND','safe','not_delivered'); +else if (command === 'snapshot' && args.includes('popover') && !['popover_open','popover_other'].includes(mode)) + result = error(mode === 'popover_unsupported' ? 'INVALID_ARGS' : 'ELEMENT_NOT_FOUND','safe','not_delivered'); else if (command === 'snapshot') { const at = args.indexOf('--window-id'); const actions = require('node:fs').readFileSync(process.env.JEV_TEST_LOG,'utf8').split('\\n').filter(Boolean) @@ -36,7 +38,7 @@ else if (command === 'snapshot') { const surfaced = args.includes('--surface'); const rooted = args.includes('--root'); let id = pinned; - if (surfaced && mode === 'surface_other') id = 'w-other'; + if (surfaced && ['surface_other','popover_other'].includes(mode)) id = 'w-other'; if (rooted && mode === 'root_other') id = 'w-other'; const window = surfaced && mode === 'surface_noid' ? {title:'試験'} : {title:'試験',id}; const sheet = mode.startsWith('surface') && !surfaced ? [{role:'sheet',children:[]}] : []; @@ -83,7 +85,7 @@ globalThis.fetch=async (_url,options)=>{ if (['destructive','risk_safe'].includes(mode)) { appendFileSync(process.env.JEV_TEST_LOG,JSON.stringify({command:'goal',args:[body.state.goal]})+'\\n'); } - const operation=['destructive','risk_safe'].includes(mode)?(calls===1?'CLICK':'DONE'):mode==='direct_type'?(calls===1?'TYPE_TEXT':'DONE'):mode==='sequence'?({1:'TYPE_TEXT',2:'CLICK',3:'TYPE_TEXT',4:'CLICK'}[calls]??'DONE'):mode==='wait'?(calls<=3?'WAIT':'DONE'):mode==='closed_top'?'WAIT':(mode==='done'||mode.startsWith('surface')||mode.endsWith('_other'))?'DONE': + const operation=['destructive','risk_safe'].includes(mode)?(calls===1?'CLICK':'DONE'):mode==='direct_type'?(calls===1?'TYPE_TEXT':'DONE'):mode==='sequence'?({1:'TYPE_TEXT',2:'CLICK',3:'TYPE_TEXT',4:'CLICK'}[calls]??'DONE'):mode==='wait'?(calls<=3?'WAIT':'DONE'):mode==='closed_top'?'WAIT':(mode==='done'||mode.startsWith('surface')||mode.startsWith('popover')||mode.endsWith('_other'))?'DONE': mode==='blocked'?'BLOCKED':mode==='click_error'||mode==='window_closed'?'CLICK':(mode==='paste_correct'||mode==='paste_late')&&calls>1?'DONE':'TYPE_TEXT'; if (mode==='sequence') appendFileSync(process.env.JEV_TEST_LOG,JSON.stringify({command:'request',body})+'\\n'); const answers={}; @@ -145,6 +147,20 @@ const run = (mode, extra = [], input = "試験") => { }; try { + if (process.platform === "win32") { + for (const [mode, expected] of [["popover_open", "popover"], ["popover_other", "window"], ["popover_unsupported", "window"]]) { + const observed = run(mode, ["--window-id", "w-42"]); + assert.equal(observed.status, 0, mode); + assert.equal(observed.stop.screen.surface, expected, mode); + const resolved = act(mode, ["--window-id", "w-42"]); + assert.equal(resolved.status, 0, mode); + assert.equal(resolved.out.surface, expected, mode); + for (const commands of [observed.commands, resolved.commands]) { + assert.ok(commands.some(c => c.command === "snapshot" && c.args.includes("popover")), mode); + assert.equal(commands.some(c => ["click", "set-value", "press"].includes(c.command)), false, mode); + } + } + } const confirmed = run("destructive", ["--confirm-destructive"]); assert.equal(confirmed.status, 1); assert.match(confirmed.stop.stop, /^confirm: hard to undo/); diff --git a/skills/jev-desktop/SKILL.md b/skills/jev-desktop/SKILL.md index 962bbdfd1a..cb6f668e9c 100644 --- a/skills/jev-desktop/SKILL.md +++ b/skills/jev-desktop/SKILL.md @@ -162,11 +162,10 @@ next round reads the screen again and asks for what is left. `--text` belongs to the step written before it, and `press:` sends a key without asking Jev. Without `--execute` the first round is printed and nothing runs. -Measured on a browser page with 120 candidates: one question took about 0.5 s -and five questions in one request took the same, so a run's time is set by -how many screens it passes through, not by its steps. Each question repeats -the candidate list, so elements are described by role, label and up to sixty -characters of value, and at most 150 visible, labelled elements are offered. +Grouping decisions reduces the number of model requests. Total latency still +depends on the application, request size, and model service. Each question +repeats the candidate list, so elements are described by role, label and up to +sixty characters of value, and at most 150 visible, labelled elements are offered. After an action the screen is read until it differs from the one acted on. If Jev then finds nothing and the screen never changed, the run stops with @@ -175,6 +174,11 @@ Text is written with `set-value` and no separate `focus`: on Windows `focus` moves the foreground, which headless delivery refuses. Each round prints one JSON line with `read_ms`, `ask_ms` and `act_ms`. +If a batch fails, completed steps stay completed. The runner refreshes the +screen and retries a stale ref only when the error says delivery did not +occur and retry is safe. Other errors stop the flow, including failures +after earlier steps in the batch succeeded. + ## Calling it | Flag | Meaning | From 24dd146697eabe3fc089100581e1cc9592c9d8ae Mon Sep 17 00:00:00 2001 From: yumi Date: Tue, 3 Nov 2026 17:17:20 +0800 Subject: [PATCH 5/5] fix(jev): ignore the windows title bar menu --- scripts/jev/act.test.mjs | 2 ++ scripts/jev/screen.mjs | 1 + 2 files changed, 3 insertions(+) diff --git a/scripts/jev/act.test.mjs b/scripts/jev/act.test.mjs index 15e2c45c4f..21cadc13ec 100644 --- a/scripts/jev/act.test.mjs +++ b/scripts/jev/act.test.mjs @@ -34,6 +34,8 @@ assert.equal(label(screen[2]), 'button "Save"'); assert.equal(overlayRole({ role: "window", children: [{ role: "group" }] }), null); assert.equal(overlayRole({ role: "window", children: [{ role: "group", children: [{ role: "sheet" }] }] }), "sheet"); +assert.equal(overlayRole({ role: "window", children: [{ role: "menu", native_id: { value: "TitleBar" } }] }), null); +assert.equal(overlayRole({ role: "window", children: [{ role: "menu", children: [{ role: "menuitem" }] }] }), "menu"); const req = buildRequest("save the file", { app: "TextEdit", window: "Untitled" }, offerable(screen)); assert.deepEqual(Object.keys(req.questions), ["target", "command", "present", "destructive", "needs_text"]); diff --git a/scripts/jev/screen.mjs b/scripts/jev/screen.mjs index dccafd76ce..744b3c8cc2 100644 --- a/scripts/jev/screen.mjs +++ b/scripts/jev/screen.mjs @@ -28,6 +28,7 @@ export const outsideWindow = (data, windowId) => { export const overlayRole = (tree) => { let found = null; const walk = (n) => { + if (n.role === "menu" && n.native_id?.value === "TitleBar") return; if (!found && ["sheet", "alert", "menu", "popover"].includes(n.role)) found = n.role; for (const c of n.children ?? []) walk(c); };