Repository navigation
feat: add persistent CUA JS REPL (js/js_reset) and run_batch MCP tools - #505
Conversation
170574c to
84a4bd2
Compare
There was a problem hiding this comment.
🟡 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
Prevent host-realm escape from the VM sandbox · New Cancel timers and scope RPCs to each evaluation · New Enforce the deadline across async evaluation and RPCs · New Reset worker after VM timeouts · New Preserve requested post-action tree fields · New Treat skipped actions as failures · New Resolve string clicks against the requested window · New Reject ambiguous exact-name click matches · New Honor stopOnError for failed clickAll calls · New Honor stopOnError for failed fillForm fields · New Use syntax-aware top-level binding persistence · New
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, andrun_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
There was a problem hiding this comment.
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_batchandjstreat 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 aSyntaxError. stopOnError: false: it has no effect inclickAll/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.
84a4bd2 to
aeeda73
Compare
There was a problem hiding this comment.
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.normalizeTextreads.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() {}orclass A {}is compiled as an expression,classis never persisted in block mode, and a regex literal containing//or a quote stops persistence for the declarations after it. - Medium —
run_batchskips the tool when a step also setssleep_ms. The step is reported asok: true, including forsleep_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.
aeeda73 to
46c164c
Compare
There was a problem hiding this comment.
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.
- Cancelled
jscall (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. - Spilled trees (medium).
find,waitFor,summaryand string clicks only see the inline prefix of a tree thatget_app_statespilled. Elements past the prefix are reported missing, and the exact-name uniqueness check can pass on a partial tree. - Window coordinates (medium).
win.click(x, y)takes full-capture pixels, whilewin.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. - Named
async functionexpression (low). A depth-0x = async function name() {}is treated as a declaration, so the eval throwsReferenceErrorbefore 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.
46c164c to
293dd19
Compare
- 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.
There was a problem hiding this comment.
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.
run_batchresult 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.- Persisted functions do not share top-level
let/const/varstate with laterjscalls (medium). The function keeps the wrapper's local; later calls read a copy onglobalThis. win.clickAllandwin.fillFormsend{x, y}as full-capture pixels, whilewin.clicksends 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.
44533b0 to
c2cf202
Compare
- 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.
There was a problem hiding this comment.
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.
desktop.windows(),desktop.window(),desktop.focused()anddesktop.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.run_batchdoes not pass the batch'ssnapshot_idtoget_tree_page(medium). Over HTTP the page is refused, and the step is still reportedok: truewith no nodes.- The batch result fitter drops every tree but the last, including earlier
get_tree_pagepages of the same snapshot (medium-low). A batch that pages a tree returns only its final page. - 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.
- 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.
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
This is an auto review done by revuto.
Revuto final review (round cap reached)
Revuto completed the review and found no evidence-backed concerns.
|
I took this to a mergeable state on top of main (after #504 and #506). Changes, pushed to this branch:
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. |


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):
run_batch(enabled by default, pure Rust, zero external runtime dependencies)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, plussleep_ms) strictly sequentially.toolandsleep_ms, propagates the latestsnapshot_idacross element-targeted steps, preserves post-actioninclude_treeaccessibility snapshots in compacted step summaries, treats backgroundretry_to_continuerefusals as step failures, blocksrun_shelland recursiverun_batch/jscalls, and enforces HTTPscreenshot_file_pathrestrictions.jsandjs_reset(opt-in on stdio, always disabled over HTTP)COMPUTER_USE_LINUX_ENABLE_REPL=1(addsjsandjs_resetalongside the default tools) orCOMPUTER_USE_LINUX_REPL_ONLY=1(scripted-only mode exposing onlyjsandjs_resetwhile keeping every desktop and setup operation callable through thedesktop/cuaAPI). Always refused over HTTP (mcp --listen).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).env_clear()), passes Node 22+'s--permissionflag with zero--allow-*grants when supported, blocksrun_shellover RPC, enforces exact async deadlines across evals and RPCs, resets the worker on synchronous VM timeouts (reportingworker_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, honorsstopOnError: falseinclickAllandfillForm, readsCompactText.contentin node text matching andsummary(), and uses a unified syntax-aware lexer (with regex literal support) for persistent top-levelconst/let/var/function/async function/function*/classbindings.Review Feedback Addressed
js/js_resetopt-in on stdio (COMPUTER_USE_LINUX_ENABLE_REPL=1/COMPUTER_USE_LINUX_REPL_ONLY=1), always disabled over HTTP, and hardened worker startup withenv_clear()and Node--permission(with honest trust-level documentation).initializeinstructions so default stdio and HTTP sessions do not advertisejswhen it is not registered, and addedsetup_accessibility/setup_window_targetingdispatch plusdesktop.setupAccessibility()/desktop.setupWindowTargeting()helpers so REPL-only mode has a complete setup recovery path.eval_id, cleared surviving timers and pending RPCs infinally, and handledunhandledRejection/uncaughtExceptioncleanly without crashing the worker.timeout_msasync deadlines and reset the worker cleanly on synchronous VM timeouts (ERR_SCRIPT_EXECUTION_TIMEOUT), returningworker_restarted.normalizeTextto readCompactText.content(and return""instead of"[object Object]"for objects without string content), fixingwin.find/win.waitFortext matching andsummary().function,async function,class), and persisted hoisted function declarations and rewritten depth-0const/let/classdeclarations across turns.include_treefields inrun_batchstep compaction, rejectedrun_batchsteps that set bothtoolandsleep_ms, and stopped masking backgroundretry_to_continuerefusals as successes.window_id, threw an explicit disambiguation error when multiple elements match, and fixedclickAll/fillFormerror handling understopOnError: false.Validation
cargo fmt --all -- --check,cargo check --locked --all-targets,cargo clippy --locked --all-targets -- -D warnings, andRUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --document-private-items.python3 scripts/check_env_forwarding.py,python3 scripts/mcp_safety_check.py,scripts/check_plugins.sh, andnode scripts/zod-check/check.mjs(across default,COMPUTER_USE_LINUX_ENABLE_REPL=1, andCOMPUTER_USE_LINUX_REPL_ONLY=1modes).scripts/generate_pi_tool_catalog.py --check) and ran Pibuild:check,typecheck, andvitestsuites.cargo test --locked --no-fail-fast,cargo publish --dry-run --locked --allow-dirty, and verified the rebuilt release binary withscripts/mcp_safety_check.py.