Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
34 changes: 21 additions & 13 deletions scripts/jev/act.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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(" ");
Expand All @@ -233,16 +228,29 @@ 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"]);
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}` });
}
Expand All @@ -256,7 +264,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);
Expand Down
2 changes: 2 additions & 0 deletions scripts/jev/act.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);
Expand Down
67 changes: 67 additions & 0 deletions scripts/jev/bin.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* 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;
Comment on lines +19 to +21

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With a local npm installation on Windows and no release build, binary lookup misses the executable beside node_modules/.bin and JEv fails to launch agent-desktop.

Fix on Vercel

}
return null;
};

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";
};

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`;
};
62 changes: 62 additions & 0 deletions scripts/jev/bin.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
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/);

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 {
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 }, 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 }, release: absent }),
join(native, "agent-desktop-win32-x64.exe"), "Windows spells the variable Path");
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 }, 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 });
}

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");
41 changes: 24 additions & 17 deletions scripts/jev/desktop.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -52,23 +46,36 @@ 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];
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");
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" });
}
Expand Down Expand Up @@ -156,7 +163,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) } };
Expand Down
71 changes: 71 additions & 0 deletions scripts/jev/flow.integration.test.mjs
Original file line number Diff line number Diff line change
@@ -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");
Loading