Skip to content

feat: add persistent CUA JS REPL (js/js_reset) and run_batch MCP tools - #505

Merged
avifenesh merged 8 commits into
agent-sh:mainfrom
bvolpato:bvolpato/cua-repl-and-batch
Nov 24, 2026
Merged

avifenesh merged 8 commits into
agent-sh:mainfrom
bvolpato:bvolpato/cua-repl-and-batch

Conversation

@bvolpato

@bvolpato bvolpato commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds two ways to run multi-step desktop UI workflows in a single MCP round-trip instead of step-by-step tool calls (inspired by Codex's persistent JS CUA REPL):

  1. run_batch (enabled by default, pure Rust, zero external runtime dependencies)

    • Runs 1 to 100 ordered desktop steps (click, type_text, press_key, set_value, perform_action, scroll, drag, activate_window, move_window, resize_window, get_app_state, get_tree_page, list_windows, focused_window, list_apps, screenshot, doctor, setup_accessibility, setup_window_targeting, plus sleep_ms) strictly sequentially.
    • Rejects invalid steps that set neither or both tool and sleep_ms, propagates the latest snapshot_id across element-targeted steps, preserves post-action include_tree accessibility snapshots in compacted step summaries, treats background retry_to_continue refusals as step failures, blocks run_shell and recursive run_batch / js calls, and enforces HTTP screenshot_file_path restrictions.
  2. js and js_reset (opt-in on stdio, always disabled over HTTP)

    • Opt-in via COMPUTER_USE_LINUX_ENABLE_REPL=1 (adds js and js_reset alongside the default tools) or COMPUTER_USE_LINUX_REPL_ONLY=1 (scripted-only mode exposing only js and js_reset while keeping every desktop and setup operation callable through the desktop / cua API). Always refused over HTTP (mcp --listen).
    • Persistent Node.js worker (src/repl_worker.mjs) communicating over line-delimited JSON RPC with the Rust MCP server, exposing a Codex-style fluent handle DSL (desktop / cua, desktop.window(query), WindowHandle, ElementHandle, desktop.getState(), win.summary(), desktop.setupAccessibility(), desktop.setupWindowTargeting(), desktop.help(), clickAll, fillForm, waitFor, sleep, viewImage).
    • Hardened worker execution: spawns Node with a cleared environment (env_clear()), passes Node 22+'s --permission flag with zero --allow-* grants when supported, blocks run_shell over RPC, enforces exact async deadlines across evals and RPCs, resets the worker on synchronous VM timeouts (reporting worker_restarted), cancels surviving timers and pending RPCs at eval end, handles unhandled rejections without crashing, scopes string-click tree cache per window and rejects ambiguous exact-name matches, honors stopOnError: false in clickAll and fillForm, reads CompactText.content in node text matching and summary(), and uses a unified syntax-aware lexer (with regex literal support) for persistent top-level const/let/var/function/async function/function*/class bindings.

Review Feedback Addressed

  • Made js/js_reset opt-in on stdio (COMPUTER_USE_LINUX_ENABLE_REPL=1 / COMPUTER_USE_LINUX_REPL_ONLY=1), always disabled over HTTP, and hardened worker startup with env_clear() and Node --permission (with honest trust-level documentation).
  • Updated MCP initialize instructions so default stdio and HTTP sessions do not advertise js when it is not registered, and added setup_accessibility / setup_window_targeting dispatch plus desktop.setupAccessibility() / desktop.setupWindowTargeting() helpers so REPL-only mode has a complete setup recovery path.
  • Scoped timers and RPCs per eval_id, cleared surviving timers and pending RPCs in finally, and handled unhandledRejection / uncaughtException cleanly without crashing the worker.
  • Enforced exact timeout_ms async deadlines and reset the worker cleanly on synchronous VM timeouts (ERR_SCRIPT_EXECUTION_TIMEOUT), returning worker_restarted.
  • Fixed normalizeText to read CompactText.content (and return "" instead of "[object Object]" for objects without string content), fixing win.find/win.waitFor text matching and summary().
  • Unified the JS lexer and declaration rewriter with regex literal support, skipped expression-first compilation for top-level declarations (function, async function, class), and persisted hoisted function declarations and rewritten depth-0 const/let/class declarations across turns.
  • Preserved include_tree fields in run_batch step compaction, rejected run_batch steps that set both tool and sleep_ms, and stopped masking background retry_to_continue refusals as successes.
  • Scoped cached exact-name string click lookups to the matching window_id, threw an explicit disambiguation error when multiple elements match, and fixed clickAll/fillForm error handling under stopOnError: false.

Validation

  • Ran cargo fmt --all -- --check, cargo check --locked --all-targets, cargo clippy --locked --all-targets -- -D warnings, and RUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --document-private-items.
  • Ran python3 scripts/check_env_forwarding.py, python3 scripts/mcp_safety_check.py, scripts/check_plugins.sh, and node scripts/zod-check/check.mjs (across default, COMPUTER_USE_LINUX_ENABLE_REPL=1, and COMPUTER_USE_LINUX_REPL_ONLY=1 modes).
  • Verified the Pi tool catalog (scripts/generate_pi_tool_catalog.py --check) and ran Pi build:check, typecheck, and vitest suites.
  • Ran cargo test --locked --no-fail-fast, cargo publish --dry-run --locked --allow-dirty, and verified the rebuilt release binary with scripts/mcp_safety_check.py.

@bvolpato
bvolpato force-pushed the bvolpato/cua-repl-and-batch branch 2 times, most recently from 170574c to 84a4bd2 Compare November 24, 2026 00:20
@bvolpato
bvolpato marked this pull request as ready for review November 24, 2026 00:45
@bvolpato
bvolpato requested a review from avifenesh as a code owner November 24, 2026 00:45
Copilot AI balanced review requested due to automatic review settings November 24, 2026 00:45

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Host-realm functions let REPL code bypass sandbox restrictions and access Node privileges, while surviving timers can trigger unrequested desktop actions during later evaluations.

11 open issues
What changed in this PR

Adds scripted desktop automation to reduce round trips for multi-step workflows, using a persistent JavaScript REPL and a sequential Rust batch runner.

Changes:

  • Adds js, js_reset, and run_batch, with desktop handles, snapshot propagation, and screenshot attachments.
  • Adds REPL-only mode, HTTP opt-in controls, and internal tool dispatch restrictions.
  • Updates host environment forwarding, the generated Pi tool catalog, and safety checks.
File Description
src/​server.rs Registers tools, internal dispatch, and mode-specific instructions.
src/​repl.rs Implements worker lifecycle, batch execution, result handling, and tests.
src/​repl_worker.mjs Implements persistent JavaScript evaluation and desktop handle helpers.
src/​lib.rs Registers the REPL module.
scripts/​mcp_safety_check.py Adds tool annotations, smoke checks, and REPL-only contract checks.
scripts/​check_env_forwarding.py Documents transport and host-specific environment exceptions.
plugins/​computer-use-linux/​codex-mcp.json Forwards Node binary and REPL-only settings.
pi/​extension/​index.ts Forwards the Node binary override.
pi/​extension/​generated-tools.ts Updates tool schemas and catalog hashes.

Review effort: Balanced

Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl.rs Resolved
Comment thread src/repl.rs Resolved
Comment thread src/repl.rs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an auto review done by revuto.


The js tool is not sandboxed: a script can reach the host process and from there child_process, so it is host code execution enabled by default over stdio. That bypasses the COMPUTER_USE_LINUX_ENABLE_SHELL=1 opt-in that guards run_shell. I'd gate js​/js_reset the same way before merging.

Other findings, inline:

  • Background notice counted as success: run_batch and js treat the one-time "Not sent … repeat the call" notice as a successful step, so the sequence continues on input that never happened.
  • One-line scripts: a single-line script with two statements and no trailing ; fails with a SyntaxError.
  • stopOnError: false: it has no effect in clickAll ​/ fillForm, because a failed call throws before the check.
  • Worker crash: an un-awaited desktop.* call that fails kills the worker, and the session state is lost with no diagnostic.
  • HTTP instructions: the default server instructions tell the model to prefer js, which is not registered over HTTP by default.

This is from reading the code; I did not build or run the repository's tests. The escape was reproduced in a standalone script using the same vm.createContext options on Node v22.22.1, without executing any command. I could not check rmcp::model::ServerConfig against rmcp 3.9.0 sources.

Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl.rs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/server.rs Resolved
@bvolpato
bvolpato force-pushed the bvolpato/cua-repl-and-batch branch from 84a4bd2 to aeeda73 Compare November 24, 2026 01:08

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an auto review done by revuto.


Four findings at this head, none of them repeats of the earlier review threads. The sandbox, timer, deadline and stopOnError points raised before look addressed or are now documented.

  • High — text matching and summary() never see node text. normalizeText reads .text ​/ .value, but the server serialises a node's text as { character_count, content, … }, so every node with text becomes "[object Object]".
  • Medium — some top-level declarations do not persist. A lone function f() {} or class A {} is compiled as an expression, class is never persisted in block mode, and a regex literal containing // or a quote stops persistence for the declarations after it.
  • Medium — run_batch skips the tool when a step also sets sleep_ms. The step is reported as ok: true, including for sleep_ms: 0.
  • Medium — REPL-only mode has no route to setup_accessibility ​/ setup_window_targeting. The tree-read error still tells the model to call them.

I read the code and did not build or run the repository. The two JS scoping claims (a class declared in try is not visible in finally; a lone function declaration compiles as an expression and leaves no binding) were checked with a standalone snippet on Node 22.22.1. The regex case is traced by hand through the scanner.

Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl.rs Resolved
Comment thread src/server.rs Resolved
@bvolpato
bvolpato force-pushed the bvolpato/cua-repl-and-batch branch from aeeda73 to 46c164c Compare November 24, 2026 01:30

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an auto review done by revuto.


Four findings at this head, none repeating the earlier threads. I read the code only; nothing was built or run.

  1. Cancelled js call (medium-high). The worker is kept and reused while the cancelled script is still alive. That script can go on sending desktop input during the next call, and its result is returned as the next call's result.
  2. Spilled trees (medium). find, waitFor, summary and string clicks only see the inline prefix of a tree that get_app_state spilled. Elements past the prefix are reported missing, and the exact-name uniqueness check can pass on a partial tree.
  3. Window coordinates (medium). win.click(x, y) takes full-capture pixels, while win.screenshot() returns a window crop that is also downscaled to 1280 px wide. Coordinates read off the image land elsewhere, and nothing in the REPL-facing text explains the conversion.
  4. Named async function expression (low). A depth-0 x = async function name() {} is treated as a declaration, so the eval throws ReferenceError before any user code runs.

run_batch dispatch, the HTTP screenshot_file_path refusal, parameter field names used by the DSL, and deadline handling against the cancellation-safe input helpers all checked out. I could not verify the rmcp 3.5.1 get_info ​/ ServerConfig API from source in this sandbox.

Comment thread src/repl.rs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
@bvolpato
bvolpato force-pushed the bvolpato/cua-repl-and-batch branch from 46c164c to 293dd19 Compare November 24, 2026 02:00
bvolpato and others added 5 commits November 24, 2026 16:08
- Start Node with --disallow-code-generation-from-strings, so the host
  Function constructor reachable through injected objects throws instead
  of returning process. Fall back to --experimental-permission on Node 20.
- Spill paging: a refused page (replaced snapshot) no longer marks a tree
  complete, and a page fills the string-click cache only while its
  snapshot is still the latest. String clicks resolve locally only
  against the snapshot they send.
- find, findAll, summary and waitFor refuse a state that still holds
  only the inline part of a spilled tree.
- Cap log lines, total logs and error text in the worker, and cap the
  protocol line Rust reads from it.
- fillForm type mode no longer reuses typed text as a click selector.
- Declaration rewriter: keep later declarators after an async, function
  or class initializer; read obj.in / 2 as division; ASI-aware
  declaration positions.
- Tests for each, plus run_batch refusing js, js_reset, run_shell and
  itself.
Document run_batch, js and js_reset in the README tool and safety
tables, the env var table and the changelog. js runs code as the
server user, like run_shell; the worker's limits are defence in depth.
- Cut logs, values and errors on a character boundary: half a surrogate
  pair made serde_json refuse the line and reset the worker.
- The class rewrite ends the statement after the class body, so a next
  line starting with ( [ or a template stays a separate statement.
- Page a spilled tree until next_offset is null instead of 64 pages.
- Persist declarations with non-ASCII identifier names.

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an auto review done by revuto.


Revuto final review (round cap reached)

Three findings at this head, none repeating the earlier threads. I read the code only; nothing from the repository was built or run. Finding 2 was confirmed with a standalone node:vm script of my own that reproduces the wrapper shape.

  1. run_batch result is not size-bounded (medium). Each step's full tree is concatenated, so a batch can exceed the 32 KB inline budget every other tool result is fitted to.
  2. Persisted functions do not share top-level let​/const​/var state with later js calls (medium). The function keeps the wrapper's local; later calls read a copy on globalThis.
  3. win.clickAll and win.fillForm send {x, y} as full-capture pixels, while win.click sends them window-relative (medium).

Minor, outside the diff: CONTRIBUTING.md:149 still lists src/server.rs as a release file holding the MCP server version. This PR replaces that literal with env!("CARGO_PKG_VERSION"), so that release step no longer applies.

Not verified: the new hand-written get_info against the rmcp 3.9 API (the crate source is not available offline), and the worker under Node's --permission flag.

Comment thread src/repl.rs Resolved
Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl_worker.mjs Resolved
@avifenesh
avifenesh force-pushed the bvolpato/cua-repl-and-batch branch from 44533b0 to c2cf202 Compare November 24, 2026 14:11
- run_batch keeps only the last step's tree (earlier trees become node
  counts, since a newer tree replaces their snapshot) and fits the
  result to the 32 KB inline budget.
- Top-level declarations become assignments to script-level vars, so a
  function persisted in one js call and later calls share one binding.
- win.clickAll and win.fillForm treat x/y as window-relative like
  win.click; click, scroll and drag round coordinates to integers.
- CONTRIBUTING: src/server.rs no longer holds a version literal.

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an auto review done by revuto.


Revuto final review (round cap reached)

Four findings at this head, none repeating the earlier threads. I read the code only; nothing was built or run.

  1. desktop.windows(), desktop.window(), desktop.focused() and desktop.getState() hide a failed window or app listing (medium). The server reports those failures inside a successful result, and the helpers keep only the lists, so the advertised REPL-only starting call returns empty data with no setup hint.
  2. run_batch does not pass the batch's snapshot_id to get_tree_page (medium). Over HTTP the page is refused, and the step is still reported ok: true with no nodes.
  3. The batch result fitter drops every tree but the last, including earlier get_tree_page pages of the same snapshot (medium-low). A batch that pages a tree returns only its final page.
  4. A lone surrogate in a string the script itself produces still resets the worker (low). The truncation fix covers only the worker's own cuts.

Checked and found sound: the js timeout drops an in-flight tool future, but pointer and keyboard sequences already run through run_cancellation_safe_input, so a press is not left without its release. The spill hydration pages the same view get_app_state returned, because get_tree_page defaults interactive_only to the snapshot's own. I could not verify the new get_info against rmcp 3.9.0, since the crate source is not available in this sandbox.

Comment thread src/repl_worker.mjs Resolved
Comment thread src/repl.rs Resolved
Comment thread src/repl.rs Resolved
Comment thread src/repl_worker.mjs Resolved
- desktop.windows(), window() and focused() throw a failed listing's
  error and permissions hint instead of returning an empty desktop;
  getState() keeps the listings' errors.
- run_batch passes the batch's snapshot_id to get_tree_page and counts a
  page with no snapshot as a failed step.
- The batch fitter drops only trees whose snapshot a later step replaced;
  trees and pages of the final snapshot stay while they fit.
- The worker replaces lone surrogates in every message with U+FFFD, so a
  script's own slice of emoji text no longer resets it.

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an auto review done by revuto.


Revuto final review (round cap reached)

The paging and listing fixes resolve the earlier findings. The lone-surrogate finding remains open for object property names.

Comment thread src/repl_worker.mjs Resolved
The replacer saw values only, so a lone surrogate in an object key still
reached serde_json and reset the worker. Objects with such keys are now
rebuilt with U+FFFD in place of the lone half.

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an auto review done by revuto.


Revuto final review (round cap reached)

Revuto completed the review and found no evidence-backed concerns.

@avifenesh

Copy link
Copy Markdown
Collaborator

I took this to a mergeable state on top of main (after #504 and #506). Changes, pushed to this branch:

  • js is documented as host code execution, at the same trust as run_shell: off by default, opt-in env var only, never registered over HTTP. README, CHANGELOG and the tool description say so. The empty environment, Node's permission flag and a new --disallow-code-generation-from-strings flag are defence in depth, not a sandbox.
  • Cancelled or timed-out js calls kill the worker; stale results and RPCs are refused.
  • Spilled trees: paging stops on a replaced snapshot, string clicks resolve only against the snapshot they send, and find, findAll, summary and waitFor refuse a partial tree.
  • Persistent bindings: top-level declarations are real script-level bindings, so a function from one call and later calls share state. Fixed multi-declarator, ASI, class and non-ASCII name cases.
  • Window handles: x/y are window-relative on click, clickAll, fillForm and scroll; coordinates are rounded to integers.
  • Output: logs, values and errors are capped and cut on character boundaries; lone surrogates become U+FFFD; Rust caps the worker's line length.
  • desktop.windows(), window(), focused() and getState() report a failed listing instead of an empty desktop.
  • run_batch: cannot reach js, js_reset, run_shell or itself (tested); passes its snapshot_id to get_tree_page and fails a page with no snapshot; keeps only the trees of the final snapshot and fits the result to the 32 KB inline budget.
  • Pi catalog regenerated after the rebase.

Gates on the head: fmt, clippy -D warnings, cargo test (907 passed), cargo doc, mcp_safety_check, check_plugins, zod check, Pi build, typecheck and tests, and the Pi catalog check all pass. Each new test fails on the code before its fix. Revuto's final review passes and all review threads are resolved.

@avifenesh
avifenesh merged commit f24f0db into agent-sh:main Nov 24, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants