Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(computer): run UI actions in an isolated script
jeffreyedc7c782ffdf
diff --git a/.github/actions/check/action.yml b/.github/actions/check/action.ymlindex f69b9fbe..5f98409d 100644--- a/.github/actions/check/action.yml+++ b/.github/actions/check/action.yml@@ -22,8 +22,8 @@ runs:run: |echo "::error::The changes job did not succeed (${CHANGES_RESULT:-not passed}); no check can be skipped."exit 1- # teamhub runs only Go. computer-go's tests run the managed-tools scripts,- # which need the pinned Node but no workspace packages.+ # TeamHub runs only Go. Computer Go tests exercise the workspace's pinned+ # QuickJS engine through the managed Node runtime.# Each Go check keeps its own build and module cache, so one job's save# never replaces another's. Pull requests and merge-queue builds restore# main's latest entry; only pushes to main save, and a successful push@@ -37,8 +37,7 @@ runs:set -euo pipefailcase "$APP" inteamhub) is_go=true node=false install=false ;;- computer-go) is_go=true node=true install=false ;;- desktop | contracts) is_go=true node=true install=true ;;+ computer-go | desktop | contracts) is_go=true node=true install=true ;;packages | teamhub-cli | installer) is_go=false node=true install=true ;;*)echo "::error::Unknown app: $APP"diff --git a/Makefile b/Makefileindex d490636c..35c3f26b 100644--- a/Makefile+++ b/Makefile@@ -145,7 +145,7 @@ check-computer-go:cd apps/computer/local-daemon && go test ./... -run '^$$'cd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./internal/platform/...cd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./cmd/linger-computer-daemon ./cmd/linger-computer-launcher ./internal/computercli ./internal/computerconfig ./internal/daemon ./internal/linger/context ./internal/linger/assignment ./internal/linger/control ./internal/linger/registration ./internal/linger/localskills ./internal/linger/mcpproxy ./internal/linger/transport ./internal/linger/runtimehistory ./internal/linger/localtools ./internal/process ./internal/workspace ./internal/provider ./internal/provider/redact ./internal/permission ./internal/localmodels- cd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./internal/provider/native+ cd apps/computer/local-daemon && $(COMPUTER_TEST_RUNNER) go test ./internal/provider/native ./internal/uiruntimecheck-computer-release:pnpm vitest run --no-file-parallelism $(SCRIPT_COMPUTER_RELEASE_TEST)diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex 409b8e63..f2e6f633 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -317,15 +317,45 @@ through the standard-input protocol.## Controlled desktop and browser tools-On macOS the Computer gives each Operation two MCP tool entries (MCP is the Model-Context Protocol). `computer` provides desktop screenshots and input. `browser`-uses a pinned Playwright MCP. After actions such as click and type, Playwright+Each Operation with installed drivers exposes two Model Context Protocol (MCP)+tools, `computer.ui_exec` and `computer.ui_reset`. The Daemon keeps the native+desktop service and the Playwright browser service private. Only the public+entry appears in the model's tool catalog. Each nested action keeps its original+permission check, arguments, evidence collector, operation lease and receipt.++`ui_exec` runs an async JavaScript function body. The bundled Node child hosts+QuickJS compiled to WebAssembly. A separate engine compiles the script. The+execution engine has no filesystem, network, process or module loader, and it+rejects dynamic code evaluation. The Daemon limits memory, runtime, call count+and output. Only the explicit `state` object is intended to persist between+calls within one Operation. `ui_reset` discards this state and image handles.+Applications and action records survive a reset. An unknown write outcome+blocks further writes to its driver in this Operation.++Use `await ui.page(url)` for a managed browser and `ui.window(pid, window_id)`+for a macOS window. Use `ui.computer.list_windows({app: appName})` to discover+a named window and check its title. `await target.observe()` returns the visible+text and actions. Call `view.click(role, name)` on that observation and use its+returned view for the next step. A newer driver call in the same namespace+expires the previous observation. In a browser, `view.fill(fields)` resolves+all named fields against one observation before sending the driver call. If an+action has no browser snapshot, the helper obtains one. Use `ui.help("browser")`+or `ui.help("computer")` for the underlying methods. `ui.emit(result)` selects+text or native images for the model; the script receives opaque image handles.++The public tool allows ten minutes. The default script budget is 165 seconds,+with up to nine minutes per call. Nested calls reserve time to return their+receipts. Cancellation stops scheduling actions; an already dispatched action+can still complete within its hard deadline. After a script error, inspect the+returned receipts and current state before taking another action.++After actions such as click and type, Playwrightwrites the page snapshot to a file and returns only a link; the Daemon reads thefile, puts the snapshot back into the result and deletes the file, so the modelneed not call `browser_snapshot` again. Only links under `.linger/browser-output/`are replaced.-A Codex Context home receives these entries as URL servers in its projected+A Codex Context home receives the public entry as a URL server in its projected`config.toml`, together with `mcp_oauth_credentials_store = "file"`. Codexotherwise reads the OAuth credentials of every URL server from the OS keyring,and on Linux a session bus whose Secret Service never answers blocks the turn@@ -462,26 +492,20 @@ macOS also offers `run_script`: Cua runs one JavaScript program in a single callThe Daemon admits only background, output-file-free scripts, fits the time limit into the call's remaining time, and cuts the result to its text: the first and last call-log lines and 40000 characters, with no screenshots.On macOS, `click` takes `delivery_mode: "foreground"` and `action`: the first for web controls that react only to a real pointer, the second for accessibility actions such as `show_alternate_ui`.-Every Operation's developer instructions carry a list of the Computer tools, so-the model need not search the tool catalog before its first call; macOS uses-`MacToolGuide`, with the call shapes of the browser tools. For Codex the Runtime-sets the Daemon's own `computer` and `browser` servers to-`omit_tools_from = ["code_mode", "deferred"]`, only on Codex 0.163.0 and later;-earlier Codex does not know the field and keeps the tools in code mode. The two-tool groups are therefore ordinary function tools, neither in code mode nor-deferred, like Codex's own `cua_repl` plugin: one model call is one JSON function-call, not a `text(await tools.mcp__computer__…)` script.+The macOS and Linux developer instructions identify the public entry. Codex+0.163.0 and later calls the public tools directly, outside code mode and+deferred tool search. Earlier versions use their standard tool discovery.Claude Code defers its own `WebSearch` and `WebFetch` behind `ToolSearch`, soevery Claude Operation's developer instructions also name them and how to loadthem; Codex's `web_search` is not deferred and gets no such line.On macOS these tools show only the fields the Computer routes. They hide Cua's `scope` and `capture_id`; only `click` takes `delivery_mode`, as described above.-Codex does not see the single macOS input tools: the `computer` server hides them-with `disabled_tools`. All input goes through `run_actions`, with as many steps as-possible in one call, like consecutive operations in one Codex script.+Within `ui_exec`, scripts can call individual input methods. An input to a+specified macOS window includes its next observation. Browser actions return+a snapshot without Playwright's generated code transcript.`run_actions` sends each step as its own driver call, in order and without pauses, and stops at the first failed step.-On macOS it always reads the window once after the last step and returns only the-changes in the same result. By default it reads the last step's window, or the+On macOS it reads the window after the last step and returns the full tree+when available. By default it reads the last step's window, or theapplication's focused window when that step gave no `window_id`; pass `read` toread another window or add a `query`. When a step is refused or its result isunknown, the result lists the completed, unsent and possibly applied steps.@@ -723,7 +747,10 @@ an unrelated part of its cleanup fails. The `computer` tool names are Cua 0.35.4`move_cursor`, `press_key`, `launch_app` and `bring_to_front`. `doctor` reportsChrome and the extension.-The release bundle pins Playwright MCP 0.0.83. Pi's MCP extension uses the+The release bundle pins Playwright MCP 0.0.83 and QuickJS-WASI 3.6.2.+CLI and Desktop ship the same engine in `cli/computer-tools/node_modules/quickjs-wasi/`.+The release manifest covers its JavaScript files and WebAssembly binary.+Pi's MCP extension uses theofficial 1.2.0 API. Cua is pinned to the official 0.35.4 release assets: thesigned macOS application and `cua-driver.exe` for Windows x64 and ARM64. Thebundle includes every dependency resource and a per-file SHA-256 manifest; thediff --git a/apps/computer/local-daemon/internal/daemon/local_tools_test.go b/apps/computer/local-daemon/internal/daemon/local_tools_test.goindex fb78ee80..8d20d667 100644--- a/apps/computer/local-daemon/internal/daemon/local_tools_test.go+++ b/apps/computer/local-daemon/internal/daemon/local_tools_test.go@@ -3,13 +3,18 @@ package daemonimport ("context""encoding/json"+ "os/exec"+ "path/filepath"+ "slices""strings""sync/atomic""testing""time"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/localtools""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/mcpproxy""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/protocol""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider")@@ -102,3 +107,92 @@ func TestWelcomePrewarmsLocalToolsOncePerProcess(t *testing.T) {t.Fatalf("prewarm ran %d times across reconnect, want once", got)}}++// The real Manager builds the public entry; the fixture supplies the private browser.+type fixtureUIBinder struct {+ *localtools.Manager+ browser mcpproxy.LocalBinding+}++func (b fixtureUIBinder) Bind(_ context.Context, _ provider.OperationSpec, _ mcpproxy.OperationIdentity, set *mcpproxy.Set) error {+ return set.AddLocal(b.browser)+}++type recordedUIReview struct{ payload map[string]any }++func (r *recordedUIReview) Request(_ string, payload map[string]any, respond func(json.RawMessage) error) error {+ r.payload = payload+ return respond(json.RawMessage(`{"decision":"deny","message":"confirmation required"}`))+}+func (*recordedUIReview) Forget(string) {}++func TestOperationMCPPublishesScriptEntryAndKeepsBrowserReview(t *testing.T) {+ node, err := exec.LookPath("node")+ if err != nil {+ t.Fatal(err)+ }+ entry, err := filepath.Abs("../../../node_modules/@playwright/mcp/cli.js")+ if err != nil {+ t.Fatal(err)+ }+ manager, err := localtools.New(localtools.Options{NodePath: node, PlaywrightEntry: entry, StateDirectory: t.TempDir()})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := manager.Close(); err != nil {+ t.Error(err)+ }+ })+ driver := mcpproxy.LocalBinding{+ Name: "browser", URL: "http://127.0.0.1:1/mcp/browser", ToolNames: []string{"browser_click"},+ WaitReady: func(context.Context) error { return nil }, Close: func() error { return nil },+ Allowed: func(name string, input json.RawMessage) bool {+ return name == "browser_click" && string(input) == `{"target":"known"}`+ },+ Evidence: func(_ context.Context, name string, _ json.RawMessage) *permission.Evidence {+ if name != "browser_click" {+ t.Fatalf("unexpected evidence request for %s", name)+ }+ return &permission.Evidence{Browser: &permission.Browser{Title: "Test form", TargetName: "Submit"}}+ },+ }+ d := &Daemon{openMCPProxies: mcpproxy.Open, localTools: fixtureUIBinder{manager, driver}}+ spec := provider.OperationSpec{OperationKind: "run.start", PermissionReview: true}+ id := mcpproxy.OperationIdentity{OperationID: t.Name(), ExecutionLeaseID: "lease", RuntimeType: "codex"}+ set, err := d.openOperationMCP(t.Context(), spec, id)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := set.Close(); err != nil {+ t.Error(err)+ }+ })+ if tools := set.LocalToolNames(); !slices.Equal(tools, []string{"mcp__computer__ui_exec", "mcp__computer__ui_reset"}) || strings.Contains(string(set.Config()), driver.URL) {+ t.Fatalf("unexpected public bindings: %v %s", tools, set.Config())+ }+ sink := &recordedUIReview{}+ release, err := set.RegisterToolReviewer(&permission.Reviewer{Requester: sink, LocalAllowed: set.LocalAllowed, LocalEvidence: set.LocalEvidence})+ if err != nil {+ t.Fatal(err)+ }+ defer release()+ if err := set.ReviewTool(t.Context(), "browser", "browser_click", json.RawMessage(`{"target":"known"}`)); err != nil || sink.payload != nil {+ t.Fatalf("an allowed driver action requested approval: %v %+v", err, sink.payload)+ }+ if err := set.ReviewTool(t.Context(), "browser", "browser_click", json.RawMessage(`{"target":"confirm"}`)); err == nil {+ t.Fatal("expected the review denial")+ }+ data, err := json.Marshal(sink.payload)+ if err != nil {+ t.Fatal(err)+ }+ var request permission.Request+ if err := json.Unmarshal(data, &request); err != nil {+ t.Fatal(err)+ }+ if request.Action.Tool != "mcp__browser__browser_click" || request.Evidence == nil || request.Evidence.Browser == nil || request.Evidence.Browser.TargetName != "Submit" {+ t.Fatalf("driver permissions lost their original target: %+v", request)+ }+}diff --git a/apps/computer/local-daemon/internal/daemon/operation_start_prepare.go b/apps/computer/local-daemon/internal/daemon/operation_start_prepare.goindex 08a84c09..938dac7f 100644--- a/apps/computer/local-daemon/internal/daemon/operation_start_prepare.go+++ b/apps/computer/local-daemon/internal/daemon/operation_start_prepare.go@@ -40,6 +40,13 @@ func (d *Daemon) openOperationMCP(ctx context.Context, spec provider.OperationSpif err := d.localTools.Bind(ctx, spec, identity, proxies); err != nil {return nil, errors.Join(err, proxies.Close())}+ if unified, ok := d.localTools.(interface {+ BindUI(context.Context, provider.OperationSpec, mcpproxy.OperationIdentity, *mcpproxy.Set) error+ }); ok {+ if err := unified.BindUI(ctx, spec, identity, proxies); err != nil {+ return nil, errors.Join(err, proxies.Close())+ }+ }}return proxies, nil}@@ -117,6 +124,7 @@ func (d *Daemon) startAcceptedOperation(ctx context.Context, command protocol.Cospec.TrustedLocalMCPTools = proxies.LocalToolNames()spec.LocalEvidence = proxies.LocalEvidencespec.LocalAllowed = proxies.LocalAllowed+ spec.RegisterToolReviewer = proxies.RegisterToolReviewerstartedAt := time.Now()execution, err = d.executor.Start(ctx, spec, emit)startMs = time.Since(startedAt).Milliseconds()diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua.go b/apps/computer/local-daemon/internal/linger/localtools/cua.goindex e1da5c94..9b9f2767 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua.go@@ -118,7 +118,7 @@ func (m *Manager) openCua(ctx context.Context, op *operation) (*cuaSession, []toclient, err := startClientWith(ctx, run, m.options.CuaPath, arguments, op.spec.WorkingDirectory, environment)var session *cuaSessionif client != nil {- session = &cuaSession{op: op, client: client, label: "linger-" + rand.Text(), servicePID: servicePID, snapshots: newSnapshotRows()}+ session = &cuaSession{op: op, client: client, label: "linger-" + rand.Text(), servicePID: servicePID, snapshots: newSnapshotRows(&m.cuaInputGeneration)}client.observe = session.snapshots.observe}if err != nil {@@ -205,29 +205,10 @@ var macKeyDescriptions = map[string]string{"type_text": "Type text. It does not press Return, Escape or arrows; use press_key for those.",}-// MacToolGuide lists the macOS computer tools' call shapes for every-// Operation, which always has both tool servers. The model then plans a whole-// batch without reading each tool's schema first.-const MacToolGuide = `Computer tools on this Mac (MCP server "computer"):-- launch_app({bundle_id, urls?}) opens an app in the background and returns its pid and windows. list_windows({pid}) lists an app's windows.-- get_window_state({pid, window_id?, since?: "latest", query?, max_depth?}) reads a window as text; without window_id it reads the app's focused window, such as a sheet or panel just opened. Row [N] is element_token "<snapshot_id>:N". Read a Save or Open sheet with max_depth: 3: its name field, Where and buttons are within that depth, and its file list is slow to walk.-- run_actions({actions: [...], read?: {pid, window_id, query?}}) sends inputs in order in one call, then reads the window and returns what changed. The read follows the last step's window, or the app's focused window when that step names none; pass read to choose another. Steps:- {tool: "click" | "double_click" | "right_click", pid, window_id, element_token, modifier?: ["cmd"]} on a row of the latest read; cmd-clicks add rows to a selection, so one cmd+c copies several files;- {tool: "hotkey", pid, keys: ["cmd", "s"]}, {tool: "press_key", pid, key: "return"}, {tool: "type_text", pid, text} go to the app's focused field, such as a sheet, panel or rename field; a new Save sheet's name field already has focus with its text selected, so type the name without clicking, and text fields refuse click;- {tool: "scroll", pid, window_id, direction}.- A click, scroll or type_text, in a step or alone, can name its target with role and name instead of element_token: the one element with that role whose label or value is exactly name, apart from white space, or nth (from 0) when several match. It is found when it runs, so one batch can cross pages; finding it reads the window, which stales the tokens of your earlier read, so later steps name their targets the same way.-- run_script({script}) runs JavaScript that loops, waits and reads between inputs and returns only what you extract. Use it to repeat a flow over several items, such as open each result, read it and close it, in one call instead of a turn per item.-- bring_to_front({pid, window_id}) raises one window.-- report_blocker({kind, url}) as soon as a page in the Computer's own browser shows a check only the user may pass (captcha, verification, login_required, rate_limited) or one item that cannot be viewed (content_unavailable). Never try to pass the check.-The Computer's own browser takes input at a person's pace, within a budget per task and per day, and a script there sends at most 20 inputs: return what you have and look at the window before the next script. A tab that a link in the script opens is the task's and is in front afterwards. The browser tools stay off every site a task opened in that browser.-Plan as many steps as you can in one run_actions call, as in one script; its read shows their effect, so do not read again before the next input unless you need another window. Keys are often shorter than clicks: in Finder, cmd+shift+g then a path and Return opens a folder, cmd+down opens the selected item, and in the Trash cmd+delete puts the selected item back.-In Chrome, launch_app({bundle_id: "com.google.Chrome", urls: [url]}) opens a URL in a new tab without bringing Chrome forward; its pages read as empty while the window is covered or on another Space. Add agent_browser: true to use the Computer's own browser window instead: it keeps working while covered, but not on another desktop (Space). Chrome's own toolbar, such as Back and the address bar, refuses background input. The user's everyday Chrome takes no key in any window, not even Return in a search box. Fill fields with set_value, press the page's buttons, and go back through its links. In Safari, Edge or Firefox press escape to close a page overlay, or hotkey cmd+[ to go back. A web control that ignores a background click, such as an option in a menu that opens on hover, takes one click with delivery_mode "foreground" at x,y of a screenshot.-A menu item in the read, such as File > Put Back, can be clicked directly; do not click a menu bar title first, because an open menu holds the app until it closes. A right_click menu does not show in the read, so select the row with click and use the menu bar item or its keyboard shortcut.-Before the first shell screenshot, or when one fails or comes back blank, run ` + "`teamhub computer permissions status`" + `; if Screen Recording is missing for Linger, run ` + "`teamhub computer permissions request --permissions screen_recording`" + ` and end your turn — the card wakes you. Never operate System Settings or privacy prompts yourself.-` + browserToolGuide--// browserToolGuide lists the Playwright browser tools, which Codex also defers.-const browserToolGuide = `Browser tools (MCP server "browser", when present): browser_navigate({url}), browser_snapshot() reads the page with element refs, browser_click({target}) and browser_type({target, text, submit?}) act on a ref from the latest snapshot, browser_tabs({action: "list" | "new" | "select" | "close"}). Each action returns the page snapshot after it, so call browser_snapshot only to read a page you have not changed.`+// MacToolGuide describes macOS targeting and permission requirements to the Runtime.+const MacToolGuide = `Use computer.ui_exec for desktop and browser interaction. Within the script use ui.window for a specific macOS window, ui.page for the managed browser, and ui.computer for native methods. Window actions use the latest observation and return the updated window. Use the full app name and the requested window title to discover the target.+When a site opened in the Computer's own browser asks for a CAPTCHA, verification or login, reports a rate limit, or makes the requested item unavailable, call ui.computer.report_blocker({kind,url}) and stop. Keep the task on that browser; respect its input pacing and limits. The user's everyday Chrome accepts no synthetic keys. For Save or Open sheets, read the app's focused window and use max_depth: 3.+Before the first shell screenshot, or when one fails or comes back blank, run ` + "`teamhub computer permissions status`" + `. If Linger lacks Screen Recording permission, run ` + "`teamhub computer permissions request --permissions screen_recording`" + ` and end the turn for the owner's permission card. Never operate System Settings or privacy prompts yourself.`// macCompactTool is the macOS shape of one Cua tool: the fields the Computer// routes, without Cua's delivery modes, scopes and capture ids.@@ -285,9 +266,8 @@ const macWindowStateDescription = "Read a window as text: its accessibility tree// macKeyRouting describes how the Computer delivers macOS keys.const macKeyRouting = " The input goes to the focused field of the app with this pid, as a person's keys do: a sheet, panel or rename field that has focus receives it. Pass only pid to follow the app's focus; also pass window_id to require that this window holds the focus. The Computer first brings the app to the front and leaves it there; if the user has since brought another app forward, nothing is sent."-// macInputResult says what a macOS input returns. As in Codex, an input does-// not read the window: a chain of inputs reads once, when the Agent asks.-const macInputResult = " The result reports only whether the input was sent; read the window with get_window_state after the inputs whose effect you need."+// macInputResult describes the readback for explicitly targeted input.+const macInputResult = " With pid and window_id, the result includes the changed window state and fresh element tokens. Without a window_id, read the focused window when you need the effect."// cuaQuietEnvironment keeps the pinned driver offline: no telemetry and no// update check. Computer upgrades replace it with a reviewed release.@@ -376,6 +356,12 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessageif err != nil {return nil, err}+ namedWindow := arguments["window_id"] != nil+ if inputTools[name] && ctx.Value(cuaInternalInput{}) == nil {+ if err := c.checkWindowToken(arguments); err != nil {+ return nil, err+ }+ }if own, _ := arguments["agent_browser"].(bool); own && name == "launch_app" {// Refused before the launch takes the browser, the pace or the journal.urls, _ := arguments["urls"].([]any)@@ -508,6 +494,9 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessagereturn nil, err}if name == "launch_app" && runtime.GOOS == "darwin" {+ if c.snapshots != nil {+ c.snapshots.sent(name)+ }result, err := c.launchApp(ctx, arguments)confirmed = !errors.Is(err, errOutcomeUnknown)return result, err@@ -570,7 +559,7 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessageresult = withNote(result, note)}}- return c.finishInput(ctx, name, arguments, appKeys, result, err)+ return c.finishInput(ctx, name, arguments, appKeys, namedWindow, result, err)}// cuaReadTools send no input.@@ -928,7 +917,7 @@ func (c *cuaSession) rereadWindow(ctx context.Context, name string, arguments ma// finishInput records what the call changed and shapes its result for the// Agent.-func (c *cuaSession) finishInput(ctx context.Context, name string, arguments map[string]any, appKeys bool, result json.RawMessage, err error) (json.RawMessage, error) {+func (c *cuaSession) finishInput(ctx context.Context, name string, arguments map[string]any, appKeys, namedWindow bool, result json.RawMessage, err error) (json.RawMessage, error) {if (inputTools[name] || appKeys) && runtime.GOOS == "darwin" {c.stampInput(arguments["pid"])}@@ -948,7 +937,7 @@ func (c *cuaSession) finishInput(ctx context.Context, name string, arguments mapc.op.reads.observe(result)c.readAgentChromeWindow(arguments["pid"], arguments["window_id"])}- if err == nil && inputTools[name] && ctx.Value(cuaInternalInput{}) == nil && runtime.GOOS != "darwin" {+ if err == nil && inputTools[name] && ctx.Value(cuaInternalInput{}) == nil && (runtime.GOOS != "darwin" || namedWindow) {result = c.withWindowState(ctx, arguments, result)}if err == nil && name == "run_script" {@@ -1047,6 +1036,13 @@ func (c *cuaSession) startSession(ctx context.Context, scope string) error {// themselves.type cuaInternalInput struct{}+func (c *cuaSession) checkWindowToken(arguments map[string]any) error {+ if runtime.GOOS == "darwin" && arguments["window_id"] != nil && c.snapshots != nil && c.snapshots.staleWindowToken(arguments) {+ return fmt.Errorf("COMPUTER_STALE_SNAPSHOT: read the target window again before sending input: %w", errNotSent)+ }+ return nil+}+// runActions sends inputs planned on one snapshot in order and reads the last// window once. Each step is its own driver call: an input does not replace the// snapshot, so later steps keep their tokens, and a token from an older read@@ -1072,6 +1068,10 @@ func (c *cuaSession) runActions(ctx context.Context, args json.RawMessage) (jsonreturn nil, fmt.Errorf("step %d: %s is owned by the Computer", i+1, key)}}+ // All tokens in the batch were chosen before its first input.+ if err := c.checkWindowToken(step); err != nil {+ return nil, fmt.Errorf("step %d: batch was not sent: %w", i+1, err)+ }}internal := context.WithValue(ctx, cuaInternalInput{}, true)var reports []json.RawMessage@@ -1239,7 +1239,12 @@ func (c *cuaSession) withWindowState(ctx context.Context, arguments map[string]a}return view.Content}- added := read(map[string]any{"since": "latest", "include_screenshot": false})+ // A macOS action returns a complete tree. A delta can omit unchanged+ // buttons that the next decision still needs to address by name.+ var added []json.RawMessage+ if runtime.GOOS != "darwin" {+ added = read(map[string]any{"since": "latest", "include_screenshot": false})+ }if added == nil {// Cua 0.35.4 can reject its own delta tree; a full read is still text.added = read(map[string]any{"include_screenshot": false})diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.go b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.goindex 8901a527..7bbf6b81 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.go@@ -6,13 +6,14 @@ import ("regexp""strings""sync"+ "sync/atomic")// snapshotRowsKept bounds how many reads the Computer remembers, across// windows. Each input to the Computer's own browser adds about three reads// (the tab check, the read after it and the tab count), and an Agent acts on// its latest read; a full browser tree is a few hundred kilobytes, so the-// bound also caps memory. A token whose read was dropped stays as it is.+// bound also caps memory. The current snapshot ID survives row eviction.const snapshotRowsKept = 16// snapshotRows remembers the rows of the window reads that pass through one@@ -28,21 +29,24 @@ type snapshotRows struct {order []string// current is, per window, the snapshot_id of its latest read, or empty// when a script may have read it since.- current map[string]string- // seq numbers the reads; fence is the last read before the latest input.- // An input can change the page, so a read from before it is never- // carried over, even where a row reads the same.- seq, fence int+ current map[string]windowSnapshot+ // All connections to the same desktop share this counter, not their rows.+ generation *atomic.Uint64}type snapshotRead struct {- window string- rows map[string]string- seq int+ window string+ rows map[string]string+ generation uint64}-func newSnapshotRows() *snapshotRows {- return &snapshotRows{reads: map[string]snapshotRead{}, current: map[string]string{}}+type windowSnapshot struct {+ id string+ generation uint64+}++func newSnapshotRows(generation *atomic.Uint64) *snapshotRows {+ return &snapshotRows{reads: map[string]snapshotRead{}, current: map[string]windowSnapshot{}, generation: generation}}// observe records the rows of a read, or forgets the current snapshots after@@ -116,9 +120,9 @@ func (s *snapshotRows) record(read windowRead) {if _, known := s.reads[read.Snapshot]; !known {s.order = append(s.order, read.Snapshot)}- s.seq++- s.reads[read.Snapshot] = snapshotRead{window: window, rows: rows, seq: s.seq}- s.current[window] = read.Snapshot+ generation := s.generation.Load()+ s.reads[read.Snapshot] = snapshotRead{window: window, rows: rows, generation: generation}+ s.current[window] = windowSnapshot{id: read.Snapshot, generation: generation}for len(s.order) > snapshotRowsKept {delete(s.reads, s.order[0])s.order = s.order[1:]@@ -146,6 +150,25 @@ func snapshotRow(line string) (index, row string, ok bool) {// scriptToken finds an element token written into a script or its args.var scriptToken = regexp.MustCompile(`\bs[0-9a-f]{8}:[0-9]+\b`)+// staleWindowToken requires evidence from this connection for the named+// window, observed after the last input to the shared desktop.+func (s *snapshotRows) staleWindowToken(arguments map[string]any) bool {+ token, _ := arguments["element_token"].(string)+ id, _, ok := strings.Cut(token, ":")+ if !ok {+ return false+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ window := fmt.Sprintf("%v:%v", arguments["pid"], arguments["window_id"])+ generation := s.generation.Load()+ if read, known := s.reads[id]; known {+ return read.window != window || read.generation != generation+ }+ current, known := s.current[window]+ return !known || current.id != id || current.generation != generation+}+// remap points element_token, and each token written into a script, at the// window's current snapshot when the token names an older read whose row// reads the same there. A row that changed, or a read the Computer does not@@ -169,9 +192,7 @@ func (s *snapshotRows) sent(name string) {if cuaReadTools[name] {return}- s.mu.Lock()- s.fence = s.seq- s.mu.Unlock()+ s.generation.Add(1)}// unpressable reports whether token names a remembered row that lists no@@ -200,10 +221,10 @@ func (s *snapshotRows) carry(token string) string {return token}read, known := s.reads[snapshot]- if !known || read.seq <= s.fence {+ if !known || read.generation != s.generation.Load() {return token}- current := s.current[read.window]+ current := s.current[read.window].idif current == "" || current == snapshot {return token}diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.go b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.goindex 618066f1..a2e1711a 100644--- a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.go@@ -2,7 +2,11 @@ package localtoolsimport ("encoding/json"+ "errors"+ "fmt"+ "runtime""strings"+ "sync/atomic""testing")@@ -20,7 +24,7 @@ func readCall(arguments map[string]any) map[string]any {}func TestSnapshotRowsCarriesTokensOverTheComputersOwnReads(t *testing.T) {- s := newSnapshotRows()+ s := newSnapshotRows(new(atomic.Uint64))agentTree := "- [0] AXWindow \"Shop\"\n - [4] AXLink \"Kettle\" [actions=[press]]\n - [5] AXButton \"Add to cart\" [actions=[press]]"s.observe(readCall(nil), readResult(t, map[string]any{"snapshot_id": "s00000001", "pid": 7, "window_id": 9, "tree_markdown": agentTree}))// The Computer's tab check reads the whole window: the link is unchanged,@@ -128,7 +132,7 @@ func TestSnapshotRowsCarriesAScriptsTokensIntoTheNextScript(t *testing.T) {t.Fatalf("structured value = %s", reply.Structured.Value)}- s := newSnapshotRows()+ s := newSnapshotRows(new(atomic.Uint64))s.observe(map[string]any{"name": "run_script"}, unwrapped)s.sent("run_script")for _, read := range reads {@@ -161,7 +165,7 @@ func mustJSON(t *testing.T, value any) []byte {// A row that lists no press, such as a page's static text, is told apart// from a link that lists one; a token the Computer does not remember is not.func TestSnapshotRowsTellsTextFromAPressableRow(t *testing.T) {- rows := newSnapshotRows()+ rows := newSnapshotRows(new(atomic.Uint64))rows.record(windowRead{Snapshot: "s00000001", PID: 42, Window: 9, Tree: "- [2] AXWebArea \"Shop\"\n - [3] AXStaticText = \"Sort by time\"\n - [4] AXLink \"Kettle\" [actions=[press]]\n - [5] AXGroup [actions=[show_menu]]"})for token, want := range map[string]bool{"s00000001:3": true, "s00000001:5": true, "s00000001:4": false, "s00000001:9": false, "s00000002:3": false, "bad": false} {if got := rows.unpressable(token); got != want {@@ -169,3 +173,70 @@ func TestSnapshotRowsTellsTextFromAPressableRow(t *testing.T) {}}}++func TestSingleWindowInputRejectsKnownStaleTokens(t *testing.T) {+ s := newSnapshotRows(new(atomic.Uint64))+ s.record(windowRead{Snapshot: "s00000001", PID: 2, Window: 3})+ args := map[string]any{"element_token": "s00000001:1", "pid": 2, "window_id": 4}+ if !s.staleWindowToken(args) {+ t.Fatal("another window accepted the token")+ }+ args["window_id"] = 3+ if s.staleWindowToken(args) {+ t.Fatal("current window token refused")+ }+ s.sent("click")+ if !s.staleWindowToken(args) {+ t.Fatal("token survived intervening input")+ }+}++func TestWindowTokenOnSharedDesktopAfterRowEviction(t *testing.T) {+ var desktop atomic.Uint64+ first, second := newSnapshotRows(&desktop), newSnapshotRows(&desktop)+ first.record(windowRead{Snapshot: "s00000001", PID: 2, Window: 3})+ args := map[string]any{"element_token": "s00000001:1", "pid": 2, "window_id": 3}+ if !second.staleWindowToken(args) {+ t.Fatal("another connection accepted a snapshot it never observed")+ }+ for i := 0; i < snapshotRowsKept; i++ {+ first.record(windowRead{Snapshot: fmt.Sprintf("s%08x", i+2), PID: 2, Window: float64(i + 4)})+ }+ second.sent("get_window_state")+ if first.staleWindowToken(args) {+ t.Fatal("reads of other windows expired the current token")+ }+ args["window_id"] = 4+ if !first.staleWindowToken(args) {+ t.Fatal("evicted token was accepted for another window")+ }+ args["window_id"] = 3+ second.sent("press_key")+ if !first.staleWindowToken(args) {+ t.Fatal("evicted token survived input on the shared desktop")+ }+ args["element_token"] = "s00000002:1"+ args["window_id"] = 4+ if !first.staleWindowToken(args) {+ t.Fatal("retained token survived input on the shared desktop")+ }+ first.record(windowRead{Snapshot: "s11111111", PID: 2, Window: 4})+ args["element_token"] = "s11111111:1"+ if first.staleWindowToken(args) {+ t.Fatal("new read did not restore input to its window")+ }+}++func TestWindowBatchChecksEveryTokenBeforeSending(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("macOS window tokens")+ }+ c := &cuaSession{snapshots: newSnapshotRows(new(atomic.Uint64))}+ c.snapshots.record(windowRead{Snapshot: "s00000001", PID: 2, Window: 3})+ _, err := c.runActions(t.Context(), json.RawMessage(`{"actions":[+ {"tool":"click","pid":2,"window_id":3,"element_token":"s00000001:1"},+ {"tool":"click","pid":2,"window_id":4,"element_token":"s00000001:1"}]}`))+ if !errors.Is(err, errNotSent) || !strings.Contains(err.Error(), "step 2") {+ t.Fatalf("expected refusal before the first step, got %v", err)+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/installation.go b/apps/computer/local-daemon/internal/linger/localtools/installation.goindex c699d14c..0f0e9307 100644--- a/apps/computer/local-daemon/internal/linger/localtools/installation.go+++ b/apps/computer/local-daemon/internal/linger/localtools/installation.go@@ -10,6 +10,15 @@ import ("strings")+var quickJSAssets = []string{+ "node_modules/quickjs-wasi/package.json",+ "node_modules/quickjs-wasi/quickjs.wasm",+ "node_modules/quickjs-wasi/dist/index.js",+ "node_modules/quickjs-wasi/dist/extensions.js",+ "node_modules/quickjs-wasi/dist/version.js",+ "node_modules/quickjs-wasi/dist/wasi-shim.js",+}+type Installation struct{ NodePath, PlaywrightEntry, PiExtension, CuaPath string }func cuaEntry(executable string) string {@@ -53,17 +62,17 @@ func Installed(executable string) (*Installation, error) {return nil, err}var manifest struct {- Version int `json:"schema_version"`- Versions struct{ Playwright, Pi, Cua string } `json:"versions"`- Playwright string `json:"playwright_entry"`- Pi string `json:"pi_extension"`- Cua string `json:"cua_entry"`+ Version int `json:"schema_version"`+ Versions struct{ Playwright, Pi, Cua, QuickJS string } `json:"versions"`+ Playwright string `json:"playwright_entry"`+ Pi string `json:"pi_extension"`+ Cua string `json:"cua_entry"`Assets []struct {Path string `json:"path"`Size int64 `json:"size_bytes"`} `json:"assets"`}- if json.Unmarshal(data, &manifest) != nil || manifest.Version != 1 || manifest.Versions.Playwright != "0.0.83" || manifest.Versions.Pi != "1.2.0" || manifest.Versions.Cua != "0.35.4" || manifest.Playwright != "node_modules/@playwright/mcp/cli.js" || manifest.Pi != "extensions/pi-mcp.mjs" || (manifest.Cua != "" && manifest.Cua != cuaEntry(executable)) {+ if json.Unmarshal(data, &manifest) != nil || manifest.Version != 1 || manifest.Versions.Playwright != "0.0.83" || manifest.Versions.Pi != "1.2.0" || manifest.Versions.Cua != "0.35.4" || manifest.Versions.QuickJS != "3.6.2" || manifest.Playwright != "node_modules/@playwright/mcp/cli.js" || manifest.Pi != "extensions/pi-mcp.mjs" || (manifest.Cua != "" && manifest.Cua != cuaEntry(executable)) {return nil, errors.New("managed Computer tool manifest is invalid")}seen := map[string]bool{}@@ -88,7 +97,7 @@ func Installed(executable string) (*Installation, error) {return nil, errors.New("managed Computer tool asset size mismatch")}}- for _, entry := range []string{manifest.Playwright, manifest.Pi} {+ for _, entry := range append([]string{manifest.Playwright, manifest.Pi}, quickJSAssets...) {if !seen[entry] {return nil, errors.New("managed Computer tool entrypoint is missing")}diff --git a/apps/computer/local-daemon/internal/linger/localtools/installation_test.go b/apps/computer/local-daemon/internal/linger/localtools/installation_test.goindex d92cdf77..b3f8204c 100644--- a/apps/computer/local-daemon/internal/linger/localtools/installation_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/installation_test.go@@ -14,7 +14,7 @@ import (func TestInstalledToolsRejectCorruptOrRedirectedAssets(t *testing.T) {root := t.TempDir()toolRoot := filepath.Join(root, "cli", "computer-tools")- entries := []string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}+ entries := append([]string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}, quickJSAssets...)assets := []map[string]any{}for _, name := range entries {p := filepath.Join(toolRoot, name)@@ -31,7 +31,7 @@ func TestInstalledToolsRejectCorruptOrRedirectedAssets(t *testing.T) {node := filepath.Join(root, "runtime", "bin", "node")_ = os.MkdirAll(filepath.Dir(node), 0o700)_ = os.WriteFile(node, []byte("fixture"), 0o700)- manifest := map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets}+ manifest := map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4", "quickjs": "3.6.2"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets}write := func() {t.Helper()data, _ := json.Marshal(manifest)@@ -75,7 +75,7 @@ func TestInstalledToolsRejectCorruptOrRedirectedAssets(t *testing.T) {func TestInstalledToolsIgnoreFileManagerMetadata(t *testing.T) {root := t.TempDir()tools := filepath.Join(root, "cli", "computer-tools")- entries := []string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}+ entries := append([]string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}, quickJSAssets...)assets := make([]map[string]any, 0, len(entries))for _, name := range entries {file := filepath.Join(tools, filepath.FromSlash(name))@@ -87,7 +87,7 @@ func TestInstalledToolsIgnoreFileManagerMetadata(t *testing.T) {}assets = append(assets, map[string]any{"path": name, "size_bytes": 7})}- manifest, err := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})+ manifest, err := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4", "quickjs": "3.6.2"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})if err != nil {t.Fatal(err)}@@ -142,7 +142,7 @@ func TestInstalledToolsFollowTheBundleDepsLinks(t *testing.T) {root := t.TempDir()deps := filepath.Join(root, "deps-0123456789abcdef")bundle := filepath.Join(root, "lib-fedcba9876543210-1")- entries := []string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}+ entries := append([]string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}, quickJSAssets...)assets := []map[string]any{}for _, name := range entries {p := filepath.Join(deps, "computer-tools", name)@@ -155,7 +155,7 @@ func TestInstalledToolsFollowTheBundleDepsLinks(t *testing.T) {sum := sha256.Sum256([]byte("fixture"))assets = append(assets, map[string]any{"path": name, "size_bytes": 7, "sha256": hex.EncodeToString(sum[:])})}- data, _ := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})+ data, _ := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4", "quickjs": "3.6.2"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})if err := os.WriteFile(filepath.Join(deps, "computer-tools", "manifest.json"), data, 0o600); err != nil {t.Fatal(err)}@@ -187,7 +187,7 @@ func TestWindowsInstalledToolsUseExtractedBundle(t *testing.T) {}root := t.TempDir()tools := filepath.Join(root, "cli", "computer-tools")- entries := []string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}+ entries := append([]string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}, quickJSAssets...)assets := make([]map[string]any, 0, len(entries))for _, name := range entries {file := filepath.Join(tools, filepath.FromSlash(name))@@ -199,7 +199,7 @@ func TestWindowsInstalledToolsUseExtractedBundle(t *testing.T) {}assets = append(assets, map[string]any{"path": name, "size_bytes": 7})}- manifest, err := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})+ manifest, err := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4", "quickjs": "3.6.2"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})if err != nil {t.Fatal(err)}@@ -243,7 +243,7 @@ func TestInstalledToolsInTheDesktopLayout(t *testing.T) {t.Fatalf("desktop without tools: %+v %v", result, err)}tools := ToolsDirectory(executable)- entries := []string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}+ entries := append([]string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}, quickJSAssets...)assets := make([]map[string]any, 0, len(entries))for _, name := range entries {file := filepath.Join(tools, filepath.FromSlash(name))@@ -255,7 +255,7 @@ func TestInstalledToolsInTheDesktopLayout(t *testing.T) {}assets = append(assets, map[string]any{"path": name, "size_bytes": 7})}- manifest, err := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})+ manifest, err := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4", "quickjs": "3.6.2"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})if err != nil {t.Fatal(err)}diff --git a/apps/computer/local-daemon/internal/linger/localtools/linux_native.go b/apps/computer/local-daemon/internal/linger/localtools/linux_native.goindex 0d3af44c..a81ba5ca 100644--- a/apps/computer/local-daemon/internal/linger/localtools/linux_native.go+++ b/apps/computer/local-daemon/internal/linger/localtools/linux_native.go@@ -178,4 +178,4 @@ func (op *operation) closeLinux() error {return nil}-const NativeLinuxToolGuide = `Computer tools control this signed-in user's Linux X11 desktop. get_window_state() reads AT-SPI elements; screenshot() captures the actual screen. click_element and set_value use numbers from the latest state. click({x,y}), drag({x,y,to_x,to_y}), type_text({text}), press_key({key:"ctrl+s"}), scroll({direction:"down"}) send native input. open_application supports Firefox, LibreOffice Writer/Calc/Impress, GNOME Terminal/Text Editor/Files and installed Xfce apps. open_url uses the user's default browser and existing profile. For an existing Firefox session, use computer tools; browser tools use a separate Chrome profile. Coordinates are screenshot pixels. `+const NativeLinuxToolGuide = `Use computer.ui_exec. Within the script, use ui.page for the managed browser or await ui.computer.get_window_state({}) for the signed-in user's Linux X11 desktop. Native click_element and set_value use numbers from the latest state. Use ui.emit(await ui.computer.screenshot({})) for a screenshot. Coordinates are screenshot pixels. ui.computer.open_url uses the user's default browser and existing profile. Use desktop tools for an existing Firefox session; browser tools use a separate Chrome profile. `diff --git a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.goindex ba7e4405..e2c2ecdd 100644--- a/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go+++ b/apps/computer/local-daemon/internal/linger/localtools/localtools_test.go@@ -376,6 +376,8 @@ func runToolFixture(mode string) {result = map[string]any{"content": []any{}, "structuredContent": map[string]string{"degraded_reason": "ax_window_unresolved"}}case a["since"] == "latest" && a["include_screenshot"] == false && (mode == "window-view" || mode == "window-view-sheet" || mode == "window-view-closed" || mode == "window-view-closed-text"):result = map[string]any{"content": []any{map[string]string{"type": "text", "text": "+ [3] AXButton Save"}}, "structuredContent": map[string]string{"snapshot_id": "s00000002"}}+ case a["since"] == nil && a["include_screenshot"] == false && mode == "window-view":+ result = map[string]any{"content": []any{map[string]string{"type": "text", "text": "[3] AXButton Save"}}, "structuredContent": map[string]string{"snapshot_id": "s00000002"}}case a["since"] == "latest", a["include_screenshot"] == false:result = map[string]any{"content": []any{}, "structuredContent": map[string]string{"degraded_reason": "ax_window_unresolved"}}case a["display_only"] == true && a["include_accessibility_tree"] == false:@@ -769,7 +771,7 @@ func TestLocalToolCuaMacKeysFollowTheFrontAppFocus(t *testing.T) {t.Fatal(err)}calls = fixtureCalls(t, marker)- if len(calls) != 1 || calls[0].Name != "press_key" || calls[0].Arguments["window_id"] != float64(9) || calls[0].Arguments["delivery_mode"] != "foreground" || calls[0].Arguments["session"] != "owned-session" {+ if len(calls) != 2 || calls[1].Name != "get_window_state" || calls[1].Arguments["window_id"] != float64(9) || calls[0].Name != "press_key" || calls[0].Arguments["window_id"] != float64(9) || calls[0].Arguments["delivery_mode"] != "foreground" || calls[0].Arguments["session"] != "owned-session" {t.Fatalf("driver calls=%v", calls)}if err := c.drain(); err != nil {@@ -1142,8 +1144,7 @@ func TestLocalToolCuaMacAgentChromeKeepsTabsItsOwnInputChangesLate(t *testing.T)c.op.manager.agentChromeOwner = c.opc.holdAgentChromeWindow(42, 9, 1, "")// The click below presses a row of page text, which lists no press.- c.snapshots = newSnapshotRows()- c.snapshots.record(windowRead{Snapshot: "s1", PID: 42, Window: 9, Tree: `- [1] AXStaticText = "Sort by time"`})+ c.snapshots = newSnapshotRows(&c.op.manager.cuaInputGeneration)// A tab the task's own input opens or closes may show only after the// input returns; the task keeps the count the strip settles on.// The input's result says what it changed in the window, and nothing@@ -1162,6 +1163,7 @@ func TestLocalToolCuaMacAgentChromeKeepsTabsItsOwnInputChangesLate(t *testing.T)if !strings.Contains(string(result), step.note) {t.Fatalf("result after the task's own %s=%s, want note %s", step.keys, result, step.note)}+ c.snapshots.record(windowRead{Snapshot: "s1", PID: 42, Window: 9, Tree: `- [1] AXStaticText = "Sort by time"`})result, err = c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":9,"element_token":"s1:1"}`))if err != nil {t.Fatalf("input after the task's own %s: %v", step.keys, err)@@ -1208,8 +1210,8 @@ func TestLocalToolCuaMacAgentChromeReadsTheTabStripOnlyAsFarAsItNeeds(t *testingif _, err := c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":9,"element_token":"s1:1"}`)); err != nil {t.Fatal(err)}- if got, want := reads(), []string{"click", "6", "6"}; !slices.Equal(got, want) {- t.Fatalf("calls=%v, want the click alone, then two bounded reads", got)+ if got, want := reads(), []string{"click", "6", "6", "0"}; !slices.Equal(got, want) {+ t.Fatalf("calls=%v, want click, two bounded tab checks and window readback", got)}// After a script that returned reads, the reads after it are whole.if note := c.recordAgentChromeTabs(t.Context(), float64(42), float64(9), true); note != "" {@@ -1244,7 +1246,7 @@ func TestLocalToolCuaMacAgentChromeReadsTheTabStripOnlyAsFarAsItNeeds(t *testingif err != nil {t.Fatal(err)}- if got := reads()[before:]; !slices.Equal(got, []string{"click", "6", "0", "0"}) {+ if got := reads()[before:]; !slices.Equal(got, []string{"click", "6", "0", "0", "0"}) {t.Fatalf("calls for fewer tabs=%v, want a bounded read, then whole reads", got)}if note := `The window now has 1 tab(s), 2 before this input; the tab in front still shows \"Tab 0\".`; !strings.Contains(string(result), note) || strings.Contains(string(result), "This input closed") {@@ -1255,7 +1257,7 @@ func TestLocalToolCuaMacAgentChromeReadsTheTabStripOnlyAsFarAsItNeeds(t *testingif _, err := c.call(t.Context(), "click", json.RawMessage(`{"pid":42,"window_id":9,"element_token":"s1:1"}`)); err != nil {t.Fatal(err)}- if got := reads(); !slices.Equal(got[len(got)-4:], []string{"0", "click", "6", "6"}) {+ if got := reads(); !slices.Equal(got[len(got)-5:], []string{"0", "click", "6", "6", "0"}) {t.Fatalf("calls=%v, want a whole read before the click", got)}if err := c.drain(); err != nil {@@ -1396,7 +1398,7 @@ func TestLocalToolCuaMacKeysFollowAWindowRaisedInsideTheApp(t *testing.T) {for _, call := range fixtureCalls(t, marker) {got = append(got, fmt.Sprint(call.Name, " ", call.Arguments["window_id"]))}- if want := []string{"bring_to_front 7", "hotkey 7", "press_key <nil>", "get_window_state 7"}; !slices.Equal(got, want) {+ if want := []string{"bring_to_front 7", "hotkey 7", "get_window_state 7", "press_key <nil>", "get_window_state 7"}; !slices.Equal(got, want) {t.Fatalf("driver calls=%v, want %v", got, want)}if err := c.drain(); err != nil {@@ -1469,13 +1471,14 @@ func TestLocalToolCuaMacKeysNeverReachAnotherWindow(t *testing.T) {}func TestLocalToolCuaInputReturnsWindowChangesAsText(t *testing.T) {- if runtime.GOOS == "darwin" {- t.Skip("macOS inputs report delivery only")- }windowViewDelay = 0t.Cleanup(func() { windowViewDelay = 100 * time.Millisecond })+ expectedTree := "+ [3] AXButton Save"+ if runtime.GOOS == "darwin" {+ expectedTree = "[3] AXButton Save"+ }for _, test := range []struct{ mode, args, want string }{- {"window-view", `{"pid":42,"window_id":7,"direction":"down"}`, "+ [3] AXButton Save"},+ {"window-view", `{"pid":42,"window_id":7,"direction":"down"}`, expectedTree},{"window-view-degraded", `{"pid":42,"window_id":7,"direction":"down"}`, "after"},{"window-view", `{"pid":42,"direction":"down"}`, ""},} {diff --git a/apps/computer/local-daemon/internal/linger/localtools/manager.go b/apps/computer/local-daemon/internal/linger/localtools/manager.goindex 0048f82f..ccf6d19f 100644--- a/apps/computer/local-daemon/internal/linger/localtools/manager.go+++ b/apps/computer/local-daemon/internal/linger/localtools/manager.go@@ -42,13 +42,14 @@ type Options struct {type Manager struct {// liveSlot admits one Live browser call at a time; see lockLive.- liveSlot chan struct{}- liveSessions map[string]*liveBrowserSession- options Options- env []string- journal *actionJournal- mu sync.Mutex- cuaLaunch sync.Mutex+ liveSlot chan struct{}+ liveSessions map[string]*liveBrowserSession+ options Options+ env []string+ journal *actionJournal+ mu sync.Mutex+ cuaLaunch sync.Mutex+ cuaInputGeneration atomic.Uint64// cuaGrant is the running `cua-driver permissions grant`, at most one.cuaGrantMu sync.MutexcuaGrant *exec.Cmd@@ -686,6 +687,7 @@ func (m *Manager) startPlaywright(ctx context.Context, launch playwrightLaunch)if err := privatefs.EnsureDir(launch.output); err != nil {return nil, err}+ launch.config["codegen"] = "none"launch.config["outputDir"] = launch.outputdata, _ := json.Marshal(launch.config)if err := privatefs.WriteFile(launch.configPath, data, false); err != nil {diff --git a/apps/computer/local-daemon/internal/linger/localtools/server.go b/apps/computer/local-daemon/internal/linger/localtools/server.goindex d706d161..46d8c735 100644--- a/apps/computer/local-daemon/internal/linger/localtools/server.go+++ b/apps/computer/local-daemon/internal/linger/localtools/server.go@@ -1,6 +1,7 @@package localtoolsimport (+ "bytes""context""crypto/rand""encoding/json"@@ -8,6 +9,7 @@ import ("io""net""net/http"+ "strconv""sync""time"@@ -26,14 +28,21 @@ type toolServer struct {ready chan struct{}readyOnce sync.Onceslots chan struct{}+ callsMu sync.Mutex+ calls map[string]context.CancelFunc+ timeout time.Duration}-func openToolServer(ctx context.Context, identity mcpproxy.OperationIdentity, tools []tool, call func(context.Context, string, json.RawMessage) (json.RawMessage, error)) (*toolServer, error) {+func openToolServer(ctx context.Context, identity mcpproxy.OperationIdentity, tools []tool, call func(context.Context, string, json.RawMessage) (json.RawMessage, error), timeouts ...time.Duration) (*toolServer, error) {listener, err := net.Listen("tcp", "127.0.0.1:0")if err != nil {return nil, err}- s := &toolServer{path: "/mcp/" + rand.Text(), tools: tools, identity: identity, ctx: ctx, call: call, ready: make(chan struct{}), slots: make(chan struct{}, 16)}+ s := &toolServer{path: "/mcp/" + rand.Text(), tools: tools, identity: identity, ctx: ctx, call: call, ready: make(chan struct{}), slots: make(chan struct{}, 16), calls: make(map[string]context.CancelFunc)}+ s.timeout = mcpproxy.LocalToolTimeout+ if len(timeouts) == 1 && timeouts[0] > 0 {+ s.timeout = timeouts[0]+ }s.url = "http://" + listener.Addr().String() + s.paths.server = &http.Server{Handler: http.HandlerFunc(s.handle), ReadHeaderTimeout: 5 * time.Second}go func() { _ = s.server.Serve(listener) }()@@ -52,6 +61,7 @@ func (s *toolServer) waitReady(ctx context.Context) error {}func (s *toolServer) handle(w http.ResponseWriter, r *http.Request) {+ started := time.Now()if r.URL.EscapedPath() != s.path || r.Header.Get("Origin") != "" {http.Error(w, "Invalid local tool authority", http.StatusForbidden)return@@ -64,13 +74,6 @@ func (s *toolServer) handle(w http.ResponseWriter, r *http.Request) {http.Error(w, "Operation is no longer active", http.StatusGone)return}- select {- case s.slots <- struct{}{}:- defer func() { <-s.slots }()- default:- http.Error(w, "Too many local tool requests", http.StatusTooManyRequests)- return- }body, err := io.ReadAll(io.LimitReader(r.Body, 1024*1024+1))if err != nil || len(body) > 1024*1024 {http.Error(w, "Invalid local tool request", http.StatusBadRequest)@@ -87,10 +90,31 @@ func (s *toolServer) handle(w http.ResponseWriter, r *http.Request) {return}if len(request.ID) == 0 {+ if request.Method == "notifications/cancelled" {+ var params struct {+ RequestID json.RawMessage `json:"requestId"`+ }+ if json.Unmarshal(request.Params, ¶ms) == nil {+ s.callsMu.Lock()+ cancel := s.calls[string(bytes.TrimSpace(params.RequestID))]+ s.callsMu.Unlock()+ if cancel != nil {+ cancel()+ }+ }+ }w.WriteHeader(http.StatusAccepted)return}+ select {+ case s.slots <- struct{}{}:+ defer func() { <-s.slots }()+ default:+ http.Error(w, "Too many local tool requests", http.StatusTooManyRequests)+ return+ }var result any+ startedTool := falseswitch request.Method {case "initialize":result = map[string]any{"protocolVersion": "2025-03-26", "capabilities": map[string]any{"tools": map[string]any{"listChanged": false}}, "serverInfo": map[string]string{"name": "linger-local-tools", "version": transport.ReleaseVersion}}@@ -132,20 +156,47 @@ func (s *toolServer) handle(w http.ResponseWriter, r *http.Request) {break}}- ctx, cancel := context.WithTimeout(s.ctx, 2*time.Minute)+ budget, budgetErr := toolCallBudget(r, s.timeout)+ if budgetErr != nil {+ err = budgetErr+ break+ }+ ctx, cancel := context.WithDeadline(s.ctx, started.Add(budget))defer cancel()+ scheduling, stopScheduling := context.WithCancel(ctx)+ defer stopScheduling()+ stopRequest := context.AfterFunc(r.Context(), stopScheduling)+ defer stopRequest()+ if r.Context().Err() != nil {+ stopScheduling()+ }+ key := string(bytes.TrimSpace(request.ID))+ s.callsMu.Lock()+ if _, duplicate := s.calls[key]; duplicate {+ s.callsMu.Unlock()+ err = errors.New("Local tool request ID is already active")+ break+ }+ s.calls[key] = stopScheduling+ s.callsMu.Unlock()+ defer func() { s.callsMu.Lock(); delete(s.calls, key); s.callsMu.Unlock() }()+ ctx = context.WithValue(ctx, toolSchedulingKey{}, scheduling)if s.identity.BeforeRequest != nil {- err = s.identity.BeforeRequest(ctx)+ err = s.identity.BeforeRequest(scheduling)if err != nil {break}}+ if err = schedulingError(ctx); err != nil {+ break+ }+ startedTool = trueresult, err = s.call(ctx, params.Name, params.Arguments)default:err = errors.New("MCP method is unavailable")}if err != nil {- result = toolError(err.Error())+ result = toolError(err, startedTool)}encoded, encodeErr := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": request.ID, "result": result})if encodeErr != nil || len(encoded) > maxMCPBytes {@@ -158,7 +209,70 @@ func (s *toolServer) handle(w http.ResponseWriter, r *http.Request) {}}-func toolError(message string) json.RawMessage {- data, _ := json.Marshal(map[string]any{"isError": true, "content": []any{map[string]string{"type": "text", "text": message}}})+func toolError(err error, startedTool bool) json.RawMessage {+ outcome := "failed"+ switch {+ case !startedTool:+ outcome = "not_dispatched"+ case errors.Is(err, errOutcomeUnknown), errors.Is(err, errDriverStopped), errors.Is(err, mcpproxy.ErrCleanupUnconfirmed):+ outcome = "unknown"+ case errors.Is(err, errNotSent):+ outcome = "not_dispatched"+ }+ data, _ := json.Marshal(map[string]any{+ "isError": true,+ "content": []any{map[string]string{"type": "text", "text": err.Error()}},+ "structuredContent": map[string]string{"outcome": outcome},+ })return data}++// Leave time for result serialization and transport before the Runtime gives up.+const toolResponseMargin = 5 * time.Second++type toolSchedulingKey struct{}++// schedulingContext stops new work on a caller cancellation. The supplied+// context still bounds already dispatched work by the Operation and deadline.+func schedulingContext(ctx context.Context) (context.Context, context.CancelFunc) {+ wait, cancel := context.WithCancel(ctx)+ if signal, ok := ctx.Value(toolSchedulingKey{}).(context.Context); ok {+ stop := context.AfterFunc(signal, cancel)+ if signal.Err() != nil {+ cancel()+ }+ return wait, func() { stop(); cancel() }+ }+ return wait, cancel+}++func schedulingError(ctx context.Context) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ if signal, ok := ctx.Value(toolSchedulingKey{}).(context.Context); ok {+ return signal.Err()+ }+ return nil+}++func toolCallBudget(request *http.Request, maximum ...time.Duration) (time.Duration, error) {+ budget := mcpproxy.LocalToolTimeout+ if len(maximum) == 1 && maximum[0] > 0 {+ budget = maximum[0]+ }+ if values := request.Header.Values("X-Linger-Tool-Budget-Ms"); len(values) > 0 {+ if len(values) != 1 {+ return 0, errors.New("Invalid local tool time budget")+ }+ milliseconds, err := strconv.ParseInt(values[0], 10, 64)+ if err != nil || milliseconds <= 0 {+ return 0, errors.New("Invalid local tool time budget")+ }+ budget = time.Duration(min(milliseconds, budget.Milliseconds())) * time.Millisecond+ }+ if budget <= toolResponseMargin {+ return 0, errors.New("Insufficient local tool response budget")+ }+ return budget - toolResponseMargin, nil+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/server_cancellation_test.go b/apps/computer/local-daemon/internal/linger/localtools/server_cancellation_test.gonew file mode 100644index 00000000..ef47738e--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/server_cancellation_test.go@@ -0,0 +1,176 @@+package localtools++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/mcpproxy"+)++func cancellationServer(t *testing.T, ctx context.Context, identity mcpproxy.OperationIdentity, call func(context.Context, string, json.RawMessage) (json.RawMessage, error)) *toolServer {+ t.Helper()+ s, err := openToolServer(ctx, identity, []tool{{Name: "test", InputSchema: json.RawMessage(`{"type":"object"}`)}}, call)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = s.server.Close() })+ return s+}++func toolCallRequest(s *toolServer) *http.Request {+ return httptest.NewRequest(http.MethodPost, s.url, strings.NewReader(`{"jsonrpc":"2.0","id":"call","method":"tools/call","params":{"name":"test","arguments":{}}}`))+}++func cancelToolRequest(t *testing.T, s *toolServer) {+ t.Helper()+ request := httptest.NewRequest(http.MethodPost, s.url, strings.NewReader(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"call"}}`))+ response := httptest.NewRecorder()+ s.handle(response, request)+ if response.Code != http.StatusAccepted {+ t.Fatalf("cancellation status: %d", response.Code)+ }+}++func TestToolServerNotificationCancelsBeforeDispatch(t *testing.T) {+ entered := make(chan struct{})+ called := false+ s := cancellationServer(t, t.Context(), mcpproxy.OperationIdentity{BeforeRequest: func(ctx context.Context) error {+ close(entered)+ <-ctx.Done()+ return ctx.Err()+ }}, func(context.Context, string, json.RawMessage) (json.RawMessage, error) {+ called = true+ return json.RawMessage(`{}`), nil+ })+ done := make(chan struct{})+ response := httptest.NewRecorder()+ go func() { defer close(done); s.handle(response, toolCallRequest(s)) }()+ <-entered+ cancelToolRequest(t, s)+ <-done+ if called || !strings.Contains(response.Body.String(), "context canceled") {+ t.Fatalf("cancel dispatched: called=%v response=%s", called, response.Body.String())+ }+}++func TestToolServerRequestCancellationPreservesDispatchedResult(t *testing.T) {+ for _, notification := range []bool{false, true} {+ t.Run(map[bool]string{false: "http", true: "notification"}[notification], func(t *testing.T) {+ entered := make(chan struct{})+ var actionErr error+ s := cancellationServer(t, t.Context(), mcpproxy.OperationIdentity{}, func(ctx context.Context, _ string, _ json.RawMessage) (json.RawMessage, error) {+ wait, stop := schedulingContext(ctx)+ defer stop()+ close(entered)+ <-wait.Done()+ actionErr = ctx.Err()+ return json.RawMessage(`{"content":[{"type":"text","text":"confirmed receipt"}]}`), nil+ })+ requestCtx, cancel := context.WithCancel(t.Context())+ defer cancel()+ done := make(chan struct{})+ response := httptest.NewRecorder()+ go func() { defer close(done); s.handle(response, toolCallRequest(s).WithContext(requestCtx)) }()+ <-entered+ if notification {+ cancelToolRequest(t, s)+ } else {+ cancel()+ }+ <-done+ if actionErr != nil || !strings.Contains(response.Body.String(), "confirmed receipt") {+ t.Fatalf("dispatched action canceled: %v, %s", actionErr, response.Body.String())+ }+ })+ }+}++func TestToolServerOperationRevocationStillCancelsDispatchedAction(t *testing.T) {+ operation, cancel := context.WithCancel(t.Context())+ defer cancel()+ entered := make(chan struct{})+ var actionErr error+ s := cancellationServer(t, operation, mcpproxy.OperationIdentity{}, func(ctx context.Context, _ string, _ json.RawMessage) (json.RawMessage, error) {+ close(entered)+ <-ctx.Done()+ actionErr = ctx.Err()+ return nil, errOutcomeUnknown+ })+ response := httptest.NewRecorder()+ done := make(chan struct{})+ go func() { defer close(done); s.handle(response, toolCallRequest(s)) }()+ <-entered+ cancel()+ <-done+ if !errors.Is(actionErr, context.Canceled) || !strings.Contains(response.Body.String(), errOutcomeUnknown.Error()) {+ t.Fatalf("revocation: %v, %s", actionErr, response.Body.String())+ }+}++func TestToolServerLeavesRuntimeResponseMargin(t *testing.T) {+ var remaining time.Duration+ s := cancellationServer(t, t.Context(), mcpproxy.OperationIdentity{}, func(ctx context.Context, _ string, _ json.RawMessage) (json.RawMessage, error) {+ deadline, ok := ctx.Deadline()+ if !ok {+ t.Error("missing deadline")+ }+ remaining = time.Until(deadline)+ return json.RawMessage(`{}`), nil+ })+ s.handle(httptest.NewRecorder(), toolCallRequest(s))+ if remaining > mcpproxy.LocalToolTimeout-toolResponseMargin || remaining < mcpproxy.LocalToolTimeout-toolResponseMargin-time.Second {+ t.Fatalf("remaining budget: %s", remaining)+ }+}++func TestToolServerCancellationDoesNotNeedARequestSlot(t *testing.T) {+ s := cancellationServer(t, t.Context(), mcpproxy.OperationIdentity{}, nil)+ for range cap(s.slots) {+ s.slots <- struct{}{}+ }+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ s.calls[`"call"`] = cancel+ cancelToolRequest(t, s)+ if ctx.Err() == nil {+ t.Fatal("saturated server lost cancellation")+ }+}++func TestToolServerCallerBudgetOnlyShortensDeadline(t *testing.T) {+ for _, test := range []struct {+ header string+ want time.Duration+ refused bool+ }{+ {"120000", 120*time.Second - toolResponseMargin, false},+ {"999999999999999999", mcpproxy.LocalToolTimeout - toolResponseMargin, false},+ {"", 0, true}, {"bad", 0, true}, {"-1", 0, true}, {"5000", 0, true},+ } {+ t.Run(test.header, func(t *testing.T) {+ called := false+ s := cancellationServer(t, t.Context(), mcpproxy.OperationIdentity{}, func(ctx context.Context, _ string, _ json.RawMessage) (json.RawMessage, error) {+ called = true+ deadline, _ := ctx.Deadline()+ remaining := time.Until(deadline)+ if remaining > test.want || remaining < test.want-time.Second {+ t.Errorf("remaining=%s, want=%s", remaining, test.want)+ }+ return json.RawMessage(`{}`), nil+ })+ request := toolCallRequest(s)+ request.Header.Set("X-Linger-Tool-Budget-Ms", test.header)+ response := httptest.NewRecorder()+ s.handle(response, request)+ if called == test.refused {+ t.Fatalf("called=%v refused=%v response=%s", called, test.refused, response.Body.String())+ }+ })+ }+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime.go b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime.gonew file mode 100644index 00000000..1ac8507c--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime.go@@ -0,0 +1,544 @@+package localtools++import (+ "bytes"+ "context"+ "crypto/rand"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "path/filepath"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/mcpproxy"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/uiruntime"+)++const unifiedToolTimeout = 10 * time.Minute+const uiImageBudget = 12 * 1024 * 1024++// Leave enough time for a driver to act and return its receipt.+const minUIExecutionBudget = 3 * toolResponseMargin++type uiDispatchReceipt struct {+ Server string `json:"server"`+ Method string `json:"method"`+ Status string `json:"status"`+}++// uiExecution keeps script state for one Operation and execution lease.+type uiExecution struct {+ cancel context.CancelFunc+ set *mcpproxy.Set+ endpoints map[string]mcpproxy.ToolEndpoint+ catalogs map[string][]tool+ engine *uiruntime.Runtime+ server *toolServer+ slot chan struct{}+ closeOnce sync.Once+ closeErr error+ sequence uint64+ blocked map[string]bool+ receipts []uiDispatchReceipt+ lastResults map[string]json.RawMessage+ images map[string]json.RawMessage+ imageBytes int+ generation uint64+}++// BindUI runs after the local driver bindings have been installed.+// Those bindings remain privately owned by Set for authorization and cleanup.+func (m *Manager) BindUI(ctx context.Context, spec provider.OperationSpec, identity mcpproxy.OperationIdentity, set *mcpproxy.Set) error {+ endpoints := set.ComputerEndpoints()+ if len(endpoints) == 0 {+ return nil+ }+ if !filepath.IsAbs(m.options.NodePath) {+ return errors.New("managed UI JavaScript runtime is unavailable")+ }+ ctx, cancel := context.WithCancel(ctx)+ u := &uiExecution{cancel: cancel, set: set, endpoints: map[string]mcpproxy.ToolEndpoint{}, catalogs: map[string][]tool{}, slot: make(chan struct{}, 1), blocked: map[string]bool{}, images: map[string]json.RawMessage{}}+ for _, endpoint := range endpoints {+ if endpoint.Name != "computer" && endpoint.Name != "browser" {+ cancel()+ return errors.New("unexpected UI driver namespace")+ }+ u.endpoints[endpoint.Name] = endpoint+ }+ modules := filepath.Dir(filepath.Dir(filepath.Dir(m.options.PlaywrightEntry)))+ engine, err := uiruntime.New(ctx, uiruntime.Options{NodePath: m.options.NodePath, QuickJSDirectory: filepath.Join(modules, "quickjs-wasi"), Dispatch: u.dispatch, Limits: uiruntime.Limits{MaxWallTime: 9 * time.Minute}})+ if err != nil {+ cancel()+ return err+ }+ u.engine = engine+ server, err := openToolServer(ctx, identity, unifiedUITools(), u.call, unifiedToolTimeout)+ if err != nil {+ return errors.Join(err, u.close())+ }+ u.server = server+ if err = set.PrivatizeComputerTools(identity, spec.PermissionReview); err != nil {+ return errors.Join(err, u.close())+ }+ if err = set.AddLocal(mcpproxy.LocalBinding{Name: "computer", URL: server.url, ToolNames: []string{"ui_exec", "ui_reset"}, WaitReady: server.waitReady, Close: u.close, Timeout: unifiedToolTimeout}); err != nil {+ return errors.Join(err, u.close())+ }+ return nil+}++func unifiedUITools() []tool {+ return []tool{+ {+ Name: "ui_exec",+ Description: "Execute one async JavaScript body for the longest sequence you can determine from current UI evidence. Await each action, inspect its result, branch or loop in this same body, then return the verified outcome. " ++ "Return to the model for ambiguous choices, visual interpretation or missing information. Only state persists across executions. When the user specifies the next control, resolve it from the fresh observation and act immediately in this script. " ++ "For repeated stages, read changing values from each observation in JavaScript and continue in a bounded loop. Never paste a value from the last model turn when the current UI supplies it. On an unrecognized stage return its observation before writing. " ++ "Browser: const page=await ui.page(url); let v=await page.observe(); on resume omit the URL. Read v.text. Use v=await v.click(role,name), v=await v.type(role,name,text) or v=await v.select(role,name,[value]). " ++ "Fill several named controls from one observation with v=await v.fill([{type,name,value},...]); type is the control role, e.g. textbox or combobox. " ++ "macOS: when the user names an app and window, discover and read it in one call: const r=await ui.computer.list_windows({app:appName}); const matches=r.structuredContent.windows.filter(w=>w.title===windowTitle); if(matches.length!==1)return r.structuredContent.windows; const w=matches[0]; let v=await ui.window(w.pid,w.window_id).observe(); use v.text for reads. " ++ "To act, v=await v.click('AXButton',name). Each named action returns the next observation. Use it for the next decision. Observe again for missing or changing state. " ++ "On recovery inspect existing field values first. Raw ui.browser and ui.computer methods return driver results. Use ui.emit(result) for images and ui.help(namespace) for unfamiliar methods. Never replay an unknown write. Each action retains its permission review.",+ InputSchema: schema(map[string]any{+ "code": map[string]any{"type": "string", "minLength": 1, "maxLength": 65536, "description": "Async JavaScript body. Put repeated decisions in a for loop: inspect v.text, stop on completion or ambiguity, derive values from that view, then assign each awaited action back to v. " ++ "Return the final observed state. Do not yield between known stages. Single-step tasks need no loop."},+ "timeout_ms": map[string]any{"type": "integer", "minimum": minUIExecutionBudget.Milliseconds(), "maximum": 540000},+ }, "code"),+ },+ {Name: "ui_reset", Description: "Discard this Operation's persistent JavaScript state and image handles. Does not close user apps, clear unknown action records, or replay actions. Re-read target state after resetting.", InputSchema: schema(map[string]any{})},+ }+}++func (u *uiExecution) call(ctx context.Context, name string, args json.RawMessage) (json.RawMessage, error) {+ if !u.set.ToolReviewerReady() {+ return nil, errors.New("UI action reviewer is not ready for this Operation")+ }+ select {+ case u.slot <- struct{}{}:+ defer func() { <-u.slot }()+ default:+ return nil, errors.New("UI execution is busy; await the current call")+ }+ if err := schedulingError(ctx); err != nil {+ return nil, err+ }+ if name == "ui_reset" {+ var empty struct{}+ if err := decodeUI(args, &empty); err != nil {+ return nil, err+ }+ if err := u.engine.Reset(ctx); err != nil {+ return nil, err+ }+ u.images = map[string]json.RawMessage{}+ u.imageBytes = 0+ return uiTextResult(map[string]any{"reset": true, "generation": u.engine.Generation(), "unknown_actions_preserved": true}), nil+ }+ if name != "ui_exec" {+ return nil, errors.New("unknown UI entry")+ }+ var input struct {+ Code string `json:"code"`+ TimeoutMS *int64 `json:"timeout_ms"`+ }+ if err := decodeUI(args, &input); err != nil {+ return nil, err+ }+ if len(input.Code) == 0 || len(input.Code) > 65536 {+ return nil, errors.New("UI code must contain 1 to 65536 bytes")+ }+ budget := 165 * time.Second+ if input.TimeoutMS != nil {+ if *input.TimeoutMS < minUIExecutionBudget.Milliseconds() || *input.TimeoutMS > (9*time.Minute).Milliseconds() {+ return nil, errors.New("UI execution budget is outside the allowed range")+ }+ budget = time.Duration(*input.TimeoutMS) * time.Millisecond+ }+ ctx, cancel := context.WithTimeout(ctx, budget)+ defer cancel()+ scheduling, stop := schedulingContext(ctx)+ defer stop()+ u.receipts = nil+ u.lastResults = map[string]json.RawMessage{}+ u.syncImageGeneration(u.engine.Generation())+ result, err := u.engine.Exec(ctx, scheduling, input.Code)+ defer func() { u.syncImageGeneration(u.engine.Generation()) }()+ summary := map[string]any{"generation": result.Generation, "value": result.Value, "receipts": u.receipts}+ if current := u.engine.Generation(); current != result.Generation {+ summary["state_reset"] = true+ summary["current_generation"] = current+ }+ if err != nil {+ summary["error"] = err.Error()+ summary["last_results"] = u.lastResults+ }+ content := []json.RawMessage{}+ expandedBytes := 0+ for _, output := range result.Output {+ parts, expandErr := u.expandOutput(output)+ for _, part := range parts {+ expandedBytes += len(part)+ }+ if expandedBytes > maxMCPBytes/2 {+ expandErr = errors.New("UI expanded output exceeds its byte limit")+ }+ if expandErr != nil {+ err = errors.Join(err, expandErr)+ summary["error"] = err.Error()+ break+ }+ content = append(content, parts...)+ }+ encoded, _ := json.Marshal(summary)+ text, _ := json.Marshal(map[string]string{"type": "text", "text": string(encoded)})+ content = append(content, text)+ return json.Marshal(map[string]any{"isError": err != nil, "content": content, "structuredContent": summary})+}++func decodeUI[T any](data []byte, result *T) error {+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(result); err != nil {+ return err+ }+ if decoder.Decode(new(any)) != io.EOF {+ return errors.New("trailing UI protocol data")+ }+ return nil+}++func uiTextResult(value any) json.RawMessage {+ encoded, _ := json.Marshal(value)+ result, _ := json.Marshal(map[string]any{"content": []any{map[string]string{"type": "text", "text": string(encoded)}}, "structuredContent": value})+ return result+}++func (u *uiExecution) dispatch(ctx context.Context, call uiruntime.Call) (json.RawMessage, error) {+ u.syncImageGeneration(call.Generation)+ if err := schedulingError(ctx); err != nil {+ return nil, err+ }+ if call.Namespace == "help" {+ return u.help(ctx, call.Method)+ }+ endpoint, ok := u.endpoints[call.Namespace]+ if !ok {+ return nil, errors.New("UI namespace is unavailable; call ui.help()")+ }+ methods, err := u.catalog(ctx, endpoint)+ if err != nil {+ return nil, err+ }+ name := call.Method+ if call.Namespace == "browser" {+ name = "browser_" + name+ }+ found := false+ for _, method := range methods {+ if method.Name == name {+ found = true+ break+ }+ }+ if !found {+ return nil, errors.New("UI method is unavailable; read this namespace's help")+ }+ var object map[string]json.RawMessage+ if json.Unmarshal(call.Arguments, &object) != nil || object == nil {+ return nil, errors.New("UI method arguments must be an object")+ }+ fullName := "mcp__" + endpoint.Name + "__" + name+ write := !permission.ReadOnlyLocalTool(fullName, string(call.Arguments))+ if write && u.blocked[endpoint.Name] {+ return nil, errors.New("UI action outcome is unknown; this Operation cannot send further writes to this server")+ }+ if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) <= 2*toolResponseMargin {+ return nil, errors.New("UI action was not dispatched: insufficient response budget")+ }+ receipt := uiDispatchReceipt{Server: endpoint.Name, Method: name, Status: "not_dispatched"}+ u.receipts = append(u.receipts, receipt)+ index := len(u.receipts) - 1+ wait, stop := schedulingContext(ctx)+ err = u.set.ReviewTool(wait, endpoint.Name, name, call.Arguments)+ stop()+ if err != nil {+ return nil, err+ }+ if err = schedulingError(ctx); err != nil {+ return nil, err+ }+ if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) <= 2*toolResponseMargin {+ return nil, errors.New("UI action was not dispatched: permission review exhausted the response budget")+ }+ u.receipts[index].Status = "dispatched"+ result, err := u.rpc(ctx, endpoint, "tools/call", map[string]any{"name": name, "arguments": call.Arguments})+ if err != nil {+ if errors.Is(err, errNotSent) {+ u.receipts[index].Status = "not_dispatched"+ return nil, err+ }+ u.receipts[index].Status = "unknown"+ if write {+ u.blocked[endpoint.Name] = true+ }+ return nil, fmt.Errorf("UI tool outcome is unknown; do not replay: %w", err)+ }+ var envelope struct {+ IsError bool `json:"isError"`+ Content []struct {+ Text string `json:"text"`+ } `json:"content"`+ Structured json.RawMessage `json:"structuredContent"`+ }+ if json.Unmarshal(result, &envelope) != nil || envelope.Content == nil {+ u.receipts[index].Status = "unknown"+ if write {+ u.blocked[endpoint.Name] = true+ }+ return nil, errors.New("UI tool returned an invalid result; outcome unknown")+ }+ var structured struct {+ Outcome string `json:"outcome"`+ }+ _ = json.Unmarshal(envelope.Structured, &structured)+ if structured.Outcome == "unknown" {+ u.receipts[index].Status = "unknown"+ if write {+ u.blocked[endpoint.Name] = true+ }+ return nil, errors.New("UI tool outcome is unknown; inspect the current state")+ }+ if envelope.IsError {+ u.receipts[index].Status = "failed"+ if structured.Outcome == "not_dispatched" {+ u.receipts[index].Status = "not_dispatched"+ }+ var message strings.Builder+ for _, c := range envelope.Content {+ message.WriteString(c.Text)+ message.WriteByte('\n')+ }+ text := message.String()+ if len(text) > 4000 {+ text = text[:4000]+ }+ return nil, fmt.Errorf("UI tool failed: %s", text)+ }+ u.receipts[index].Status = "confirmed"+ delete(u.lastResults, endpoint.Name)+ retained, err := u.retainImages(result)+ if err == nil && len(retained) <= 262144 {+ u.lastResults[endpoint.Name] = retained+ }+ return retained, err+}++func (u *uiExecution) syncImageGeneration(generation uint64) {+ if generation == u.generation {+ return+ }+ u.generation = generation+ u.images = map[string]json.RawMessage{}+ u.imageBytes = 0+}++func (u *uiExecution) help(ctx context.Context, topic string) (json.RawMessage, error) {+ if topic == "" {+ var namespaces []string+ for _, name := range []string{"computer", "browser"} {+ if _, ok := u.endpoints[name]; ok {+ namespaces = append(namespaces, name)+ }+ }+ return json.Marshal(map[string]any{"namespaces": namespaces, "state": "Only state persists. Await each method. Use ui.emit(result) for native images and selected output. Read namespace help for unfamiliar methods. Methods return original MCP content and optional structuredContent. Errors throw; unknown effects cannot be retried.", "scope": "This Operation and execution lease only; resets invalidate state and image handles."})+ }+ endpoint, ok := u.endpoints[topic]+ if !ok {+ return nil, errors.New("help topic must be computer or browser")+ }+ methods, err := u.catalog(ctx, endpoint)+ if err != nil {+ return nil, err+ }+ listed := append([]tool(nil), methods...)+ for i := range listed {+ if topic == "browser" {+ listed[i].Name = strings.TrimPrefix(listed[i].Name, "browser_")+ }+ }+ return json.Marshal(map[string]any{"namespace": topic, "methods": listed})+}++func (u *uiExecution) catalog(ctx context.Context, endpoint mcpproxy.ToolEndpoint) ([]tool, error) {+ if methods, ok := u.catalogs[endpoint.Name]; ok {+ return methods, nil+ }+ wait, stop := schedulingContext(ctx)+ defer stop()+ wait, cancel := context.WithTimeout(wait, 10*time.Second)+ defer cancel()+ raw, err := u.rpc(wait, endpoint, "tools/list", map[string]any{})+ if err != nil {+ return nil, err+ }+ var result struct {+ Tools []tool `json:"tools"`+ }+ if json.Unmarshal(raw, &result) != nil || result.Tools == nil {+ return nil, errors.New("UI driver catalog is unavailable")+ }+ for _, method := range result.Tools {+ if method.Name == "browser_run_code_unsafe" || method.Name == "ui_exec" || method.Name == "ui_reset" {+ return nil, errors.New("unexpected UI driver capability")+ }+ }+ u.catalogs[endpoint.Name] = result.Tools+ return result.Tools, nil+}++func (u *uiExecution) rpc(ctx context.Context, endpoint mcpproxy.ToolEndpoint, method string, params any) (json.RawMessage, error) {+ u.sequence+++ body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": u.sequence, "method": method, "params": params})+ if err != nil {+ return nil, err+ }+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.URL, bytes.NewReader(body))+ if err != nil {+ return nil, err+ }+ request.Header.Set("Content-Type", "application/json")+ if deadline, ok := ctx.Deadline(); ok {+ budget := time.Until(deadline) - time.Second+ if budget <= toolResponseMargin {+ return nil, fmt.Errorf("%w: response budget exhausted", errNotSent)+ }+ request.Header.Set("X-Linger-Tool-Budget-Ms", strconv.FormatInt(budget.Milliseconds(), 10))+ }+ response, err := http.DefaultClient.Do(request)+ if err != nil {+ return nil, err+ }+ defer response.Body.Close()+ if response.StatusCode == http.StatusTooManyRequests || response.StatusCode == http.StatusGone {+ return nil, fmt.Errorf("local UI server refused admission (%d): %w", response.StatusCode, errNotSent)+ }+ data, err := io.ReadAll(io.LimitReader(response.Body, maxMCPBytes+1))+ if err != nil {+ return nil, err+ }+ if len(data) > maxMCPBytes || response.StatusCode != http.StatusOK {+ return nil, errors.New("UI driver response is unavailable or exceeds its limit")+ }+ var envelope struct {+ JSONRPC string `json:"jsonrpc"`+ ID uint64 `json:"id"`+ Result json.RawMessage `json:"result"`+ Error json.RawMessage `json:"error"`+ }+ if json.Unmarshal(data, &envelope) != nil || envelope.JSONRPC != "2.0" || envelope.ID != u.sequence || len(envelope.Error) > 0 || len(envelope.Result) == 0 {+ return nil, errors.New("invalid UI driver response")+ }+ return envelope.Result, nil+}++func (u *uiExecution) retainImages(raw json.RawMessage) (json.RawMessage, error) {+ var result map[string]json.RawMessage+ if json.Unmarshal(raw, &result) != nil {+ return nil, errors.New("invalid UI result")+ }+ var content []json.RawMessage+ if len(result["content"]) == 0 {+ return raw, nil+ }+ if err := json.Unmarshal(result["content"], &content); err != nil {+ return nil, err+ }+ for i, part := range content {+ var kind struct {+ Type string `json:"type"`+ }+ if json.Unmarshal(part, &kind) != nil {+ return nil, errors.New("invalid UI content")+ }+ if kind.Type != "image" {+ continue+ }+ if u.imageBytes+len(part) > uiImageBudget {+ return nil, errors.New("UI image budget exhausted; emit required images and reset state")+ }+ id := rand.Text()+ u.images[id] = part+ u.imageBytes += len(part)+ content[i], _ = json.Marshal(map[string]string{"type": "image", "image_id": id})+ }+ result["content"], _ = json.Marshal(content)+ return json.Marshal(result)+}++func (u *uiExecution) expandOutput(raw json.RawMessage) ([]json.RawMessage, error) {+ return u.expandContent(raw, 0)+}++func (u *uiExecution) expandContent(raw json.RawMessage, depth int) ([]json.RawMessage, error) {+ if depth > 1 {+ return nil, errors.New("UI content envelopes cannot be nested")+ }+ var text string+ if json.Unmarshal(raw, &text) == nil {+ part, _ := json.Marshal(map[string]string{"type": "text", "text": text})+ return []json.RawMessage{part}, nil+ }+ var object struct {+ Type string `json:"type"`+ ImageID string `json:"image_id"`+ Content []json.RawMessage `json:"content"`+ }+ if json.Unmarshal(raw, &object) != nil {+ part, _ := json.Marshal(map[string]string{"type": "text", "text": string(raw)})+ return []json.RawMessage{part}, nil //nolint:nilerr // Non-object values are represented as text.+ }+ if object.Type == "image" {+ part, ok := u.images[object.ImageID]+ if !ok {+ return nil, errors.New("UI image handle is stale or unavailable")+ }+ return []json.RawMessage{part}, nil+ }+ if object.Content != nil {+ var out []json.RawMessage+ for _, c := range object.Content {+ parts, err := u.expandContent(c, depth+1)+ if err != nil {+ return nil, err+ }+ out = append(out, parts...)+ }+ return out, nil+ }+ if object.Type == "text" || object.Type == "resource_link" || object.Type == "resource" {+ return []json.RawMessage{raw}, nil+ }+ part, _ := json.Marshal(map[string]string{"type": "text", "text": string(raw)})+ return []json.RawMessage{part}, nil+}++func (u *uiExecution) close() error {+ u.closeOnce.Do(func() {+ u.cancel()+ if u.server != nil {+ _ = u.server.server.Close()+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ if err := u.engine.Close(ctx); err != nil {+ u.closeErr = errors.Join(mcpproxy.ErrCleanupUnconfirmed, err)+ }+ })+ return u.closeErr+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_cancellation_test.go b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_cancellation_test.gonew file mode 100644index 00000000..2dd17ce0--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_cancellation_test.go@@ -0,0 +1,182 @@+package localtools++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++func TestUnifiedUICancellationDrainsDispatchedAction(t *testing.T) {+ for _, notification := range []bool{false, true} {+ name := "HTTP"+ if notification {+ name = "MCPNotification"+ }+ t.Run(name, func(t *testing.T) {+ entered := make(chan context.Context, 1)+ release := make(chan struct{})+ completed := make(chan error, 1)+ var releaseOnce sync.Once+ unblock := func() { releaseOnce.Do(func() { close(release) }) }+ defer unblock()+ var calls atomic.Int32+ f := newUIRuntimeFixture(t, false, func(ctx context.Context, name string, _ json.RawMessage) (json.RawMessage, error) {+ if name != "browser_click" {+ return uiTextResult("read"), nil+ }+ if calls.Add(1) != 1 {+ return uiTextResult("unexpected second dispatch"), nil+ }+ entered <- ctx+ select {+ case <-release:+ completed <- ctx.Err()+ return uiTextResult("confirmed first click"), nil+ case <-ctx.Done():+ completed <- ctx.Err()+ return nil, ctx.Err()+ }+ })+ clear, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ defer clear()+ before := cancellationSummary(t, f.execute(t, `state.marker="old"; return 1;`))+ requestCtx, cancel := context.WithCancel(t.Context())+ defer cancel()+ id := f.sequence.Add(1)+ body, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": map[string]any{"name": "ui_exec", "arguments": map[string]any{"code": `await ui.browser.click({}); await ui.browser.click({});`, "timeout_ms": 30000}}})+ type response struct {+ data []byte+ err error+ }+ responseCh := make(chan response, 1)+ go func() { data, _, err := cancellationPost(requestCtx, f.url, body); responseCh <- response{data, err} }()+ var actionCtx context.Context+ select {+ case actionCtx = <-entered:+ case result := <-responseCh:+ t.Fatalf("execution ended before callback: err=%v body=%s", result.err, result.data)+ case <-time.After(10 * time.Second):+ t.Fatal("first callback did not start")+ }+ if notification {+ notice, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/cancelled", "params": map[string]any{"requestId": id}})+ data, status, err := cancellationPost(t.Context(), f.url, notice)+ if err != nil || status != http.StatusAccepted {+ t.Fatalf("notification: status=%d err=%v body=%s", status, err, data)+ }+ } else {+ cancel()+ select {+ case result := <-responseCh:+ if !errors.Is(result.err, context.Canceled) {+ t.Fatalf("HTTP cancellation error=%v body=%s", result.err, result.data)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("HTTP request did not cancel")+ }+ }+ // The in-flight callback must retain its hard deadline while the scheduler stops.+ select {+ case <-actionCtx.Done():+ t.Fatalf("soft cancellation reached callback: %v", actionCtx.Err())+ case <-time.After(150 * time.Millisecond):+ }+ if calls.Load() != 1 {+ t.Fatalf("second action dispatched before release: %d", calls.Load())+ }+ unblock()+ select {+ case err := <-completed:+ if err != nil {+ t.Fatalf("callback did not finish normally: %v", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("callback did not finish")+ }+ if notification {+ select {+ case result := <-responseCh:+ if result.err != nil {+ t.Fatal(result.err)+ }+ var envelope struct {+ Result json.RawMessage `json:"result"`+ }+ if err := json.Unmarshal(result.data, &envelope); err != nil {+ t.Fatal(err)+ }+ summary := cancellationSummary(t, envelope.Result)+ if !summary.IsError || !summary.Structured.StateReset || summary.Structured.Error == "" || len(summary.Structured.Receipts) != 1 || summary.Structured.Receipts[0].Status != "confirmed" || !strings.Contains(string(result.data), "confirmed first click") {+ t.Fatalf("completion receipt lost: %s", result.data)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("cancelled execution did not return its receipt")+ }+ }+ // HTTP cancellation has no response to await. A pure read may see busy until+ // callback transport and process cleanup finish; it must never run old state.+ deadline := time.Now().Add(5 * time.Second)+ for {+ result := f.execute(t, `return typeof state.marker;`)+ if strings.Contains(string(result), "busy") && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ continue+ }+ after := cancellationSummary(t, result)+ if after.IsError || after.Structured.Generation <= before.Structured.Generation || string(after.Structured.Value) != `"undefined"` {+ t.Fatalf("runtime did not recover without stale state: %s", result)+ }+ break+ }+ if calls.Load() != 1 {+ t.Fatalf("cancelled second action dispatched: %d", calls.Load())+ }+ })+ }+}++type uiCancellationSummary struct {+ IsError bool `json:"isError"`+ Structured struct {+ Generation uint64 `json:"generation"`+ Value json.RawMessage `json:"value"`+ StateReset bool `json:"state_reset"`+ Error string `json:"error"`+ Receipts []struct {+ Status string `json:"status"`+ } `json:"receipts"`+ } `json:"structuredContent"`+}++func cancellationSummary(t *testing.T, data json.RawMessage) uiCancellationSummary {+ t.Helper()+ var result uiCancellationSummary+ if err := json.Unmarshal(data, &result); err != nil {+ t.Fatalf("invalid UI response: %s (%v)", data, err)+ }+ return result+}+func cancellationPost(ctx context.Context, url string, body []byte) ([]byte, int, error) {+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return nil, 0, err+ }+ response, err := http.DefaultClient.Do(request)+ if err != nil {+ return nil, 0, err+ }+ defer response.Body.Close()+ data, err := io.ReadAll(response.Body)+ return data, response.StatusCode, err+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_live_test.go b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_live_test.gonew file mode 100644index 00000000..ac970411--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_live_test.go@@ -0,0 +1,150 @@+//go:build darwin || linux++package localtools++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/mcpproxy"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider"+)++// Exercises the public unified HTTP surface against the pinned MCP and an+// isolated Chrome. No user's profile or extension participates.+func TestUnifiedUIBrowserLive(t *testing.T) {+ if os.Getenv("LINGER_UI_BROWSER_PROBE") != "1" {+ t.Skip("opt-in real unified browser probe")+ }+ node, entry, chrome := os.Getenv("LINGER_PLAYWRIGHT_COMPAT_NODE"), os.Getenv("LINGER_PLAYWRIGHT_COMPAT_ENTRY"), os.Getenv("LINGER_UI_BROWSER_CHROME")+ if node == "" || entry == "" || chrome == "" {+ t.Fatal("set browser probe paths")+ }+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)+ defer cancel()+ profile := t.TempDir()+ process := exec.CommandContext(ctx, chrome, "--headless=new", "--remote-debugging-port=0", "--user-data-dir="+profile, "--no-first-run", "--no-default-browser-check", "about:blank")+ if err := process.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = process.Process.Kill(); _ = process.Wait() })+ var port string+ for deadline := time.Now().Add(30 * time.Second); port == "" && time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {+ if data, err := os.ReadFile(filepath.Join(profile, "DevToolsActivePort")); err == nil {+ port, _, _ = strings.Cut(string(data), "\n")+ }+ }+ if port == "" {+ t.Fatal("Chrome did not open debugging port")+ }+ var submits atomic.Int32+ fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "text/html")+ switch r.URL.Path {+ case "/next":+ _, _ = fmt.Fprint(w, `<h1>Second page</h1><form id="f"><label>Note: Jo's order<input name="note"></label><button>Save #42</button></form><script>f.onsubmit=async e=>{e.preventDefault();await fetch('/saved',{method:'POST'});setTimeout(()=>document.body.innerHTML='<h1>Saved</h1>',150)}</script>`)+ case "/saved":+ submits.Add(1)+ _, _ = fmt.Fprint(w, "ok")+ default:+ _, _ = fmt.Fprint(w, `<h1>First page</h1><a href="/next">Next</a>`)+ }+ }))+ defer fixture.Close()+ m := laneManager(t, t.TempDir())+ m.options = Options{NodePath: node, PlaywrightEntry: entry, StateDirectory: t.TempDir()}+ m.env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir()}+ // Supply only the test's existing Chrome. Bind discovers its own tool+ // catalog and applies the same Operation policy as a normal Agent run.+ m.noEverydayChrome = true+ spec := provider.OperationSpec{AgentID: "unified-live", WorkingDirectory: t.TempDir()}+ m.browsers[spec.AgentID] = &nativeBrowser{endpoint: "http://127.0.0.1:" + port, done: make(chan struct{})}+ identity := mcpproxy.OperationIdentity{OperationID: t.Name(), ExecutionLeaseID: "lease", RuntimeType: "codex"}+ set, err := mcpproxy.Open(ctx, nil, identity)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := set.Close(); err != nil {+ t.Error(err)+ }+ })+ if err = m.Bind(ctx, spec, identity, set); err != nil {+ t.Fatal(err)+ }+ if err = m.BindUI(ctx, spec, identity, set); err != nil {+ t.Fatal(err)+ }+ release, err := set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ defer release()+ var config struct {+ Servers map[string]struct {+ URL string `json:"url"`+ } `json:"mcpServers"`+ }+ if err = json.Unmarshal(set.Config(), &config); err != nil {+ t.Fatal(err)+ }+ if len(config.Servers) != 1 || config.Servers["computer"].URL == "" {+ t.Fatalf("private drivers exposed: %s", set.Config())+ }+ f := &uiRuntimeFixture{set: set, url: config.Servers["computer"].URL}+ listed := f.rpc(t, ctx, "tools/list", nil)+ var catalog struct {+ Tools []tool `json:"tools"`+ }+ if err = json.Unmarshal(listed, &catalog); err != nil {+ t.Fatal(err)+ }+ if len(catalog.Tools) != 2 || catalog.Tools[0].Name != "ui_exec" || catalog.Tools[1].Name != "ui_reset" {+ t.Fatalf("public catalog: %s", listed)+ }+ check := func(code string) json.RawMessage {+ t.Helper()+ got := f.execute(t, code)+ if strings.Contains(string(got), `"isError":true`) {+ t.Fatalf("exec failed: %s", got)+ }+ return got+ }+ url, _ := json.Marshal(fixture.URL)+ check(`const help=await ui.help('browser');+if(help.methods.some(x=>x.name==='run_code_unsafe')) throw Error('unsafe capability exposed');+const page=await ui.page(` + string(url) + `), first=await page.observe();+await first.click('link','Next');+state.note='retained across calls'; return 'second page';`)+ got := check(`const page=await ui.page(), second=await page.observe();+const filled=await second.type('textbox',"Note: Jo's order",state.note);+if(!filled.text.includes(state.note)) throw Error('state lost');+await filled.click('button','Save #42');+await ui.browser.wait_for({text:'Saved'});+ui.emit(await ui.browser.snapshot({})); ui.emit(await ui.browser.take_screenshot({})); return state.note;`)+ if submits.Load() != 1 || !strings.Contains(string(got), "Saved") || !strings.Contains(string(got), `"type":"image"`) || !strings.Contains(string(got), `"mimeType":"image/png"`) {+ t.Fatalf("completion or native image missing; submits=%d result=%s", submits.Load(), got)+ }+ reset := f.rpc(t, ctx, "tools/call", map[string]any{"name": "ui_reset", "arguments": map[string]any{}})+ if !strings.Contains(string(reset), `"reset":true`) {+ t.Fatal(string(reset))+ }+ after := check(`if(Object.keys(state).length)throw Error('state not reset');const snapshot=await ui.browser.snapshot({});ui.emit(snapshot);return 'reset retained page';`)+ if !strings.Contains(string(after), "Saved") || submits.Load() != 1 {+ t.Fatalf("reset changed page: %s", after)+ }+ if _, err = os.Stat(profile); err != nil {+ t.Fatal("reset removed profile", err)+ }+ t.Log("public ui_exec/ui_reset; actual MCP two-page async form; state retained; one submit; native image; reset retained page/profile")+}diff --git a/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_test.go b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_test.gonew file mode 100644index 00000000..23b92779--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/localtools/ui_runtime_test.go@@ -0,0 +1,371 @@+package localtools++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "os/exec"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/mcpproxy"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission"+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider"+)++type uiRuntimeFixture struct {+ set *mcpproxy.Set+ url string+ sequence atomic.Uint64+}++func newUIRuntimeFixture(t *testing.T, required bool, callback func(context.Context, string, json.RawMessage) (json.RawMessage, error)) *uiRuntimeFixture {+ t.Helper()+ node, err := exec.LookPath("node")+ if err != nil {+ t.Fatal(err)+ }+ identity := mcpproxy.OperationIdentity{OperationID: t.Name(), ExecutionLeaseID: "lease", RuntimeType: "codex"}+ set, err := mcpproxy.Open(t.Context(), nil, identity)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := set.Close(); err != nil {+ t.Error(err)+ }+ })+ methods := []tool{+ {Name: "browser_type", InputSchema: schema(map[string]any{})},+ {Name: "browser_snapshot", InputSchema: schema(map[string]any{})},+ {Name: "browser_click", InputSchema: schema(map[string]any{})},+ {Name: "browser_take_screenshot", InputSchema: schema(map[string]any{})},+ }+ original, err := openToolServer(t.Context(), identity, methods, callback)+ if err != nil {+ t.Fatal(err)+ }+ err = set.AddLocal(mcpproxy.LocalBinding{Name: "browser", URL: original.url, ToolNames: []string{"browser_type", "browser_snapshot", "browser_click", "browser_take_screenshot"}, WaitReady: original.waitReady, Close: original.server.Close})+ if err != nil {+ t.Fatal(err)+ }+ entry, err := filepath.Abs("../../../../node_modules/@playwright/mcp/cli.js")+ if err != nil {+ t.Fatal(err)+ }+ m := &Manager{options: Options{NodePath: node, PlaywrightEntry: entry}}+ if err = m.BindUI(t.Context(), provider.OperationSpec{PermissionReview: required}, identity, set); err != nil {+ t.Fatal(err)+ }+ var config struct {+ Servers map[string]struct {+ URL string `json:"url"`+ } `json:"mcpServers"`+ }+ if err = json.Unmarshal(set.Config(), &config); err != nil {+ t.Fatal(err)+ }+ if len(config.Servers) != 1 || config.Servers["computer"].URL == "" {+ t.Fatalf("public tools were not unified: %s", set.Config())+ }+ if got := strings.Join(set.LocalToolNames(), ","); got != "mcp__computer__ui_exec,mcp__computer__ui_reset" {+ t.Fatal(got)+ }+ f := &uiRuntimeFixture{set: set, url: config.Servers["computer"].URL}+ f.rpc(t, t.Context(), "tools/list", nil)+ ready, cancel := context.WithTimeout(t.Context(), time.Second)+ defer cancel()+ if err = set.WaitReady(ready); err != nil {+ t.Fatalf("private drivers incorrectly block readiness: %v", err)+ }+ return f+}++func (f *uiRuntimeFixture) rpc(t *testing.T, ctx context.Context, method string, params any) json.RawMessage {+ t.Helper()+ body, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": f.sequence.Add(1), "method": method, "params": params})+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, f.url, bytes.NewReader(body))+ if err != nil {+ t.Fatal(err)+ }+ response, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer response.Body.Close()+ data, err := io.ReadAll(response.Body)+ if err != nil {+ t.Fatal(err)+ }+ var envelope struct {+ Result json.RawMessage `json:"result"`+ }+ if json.Unmarshal(data, &envelope) != nil || len(envelope.Result) == 0 {+ t.Fatalf("invalid response: %s", data)+ }+ return envelope.Result+}++func (f *uiRuntimeFixture) execute(t *testing.T, code string) json.RawMessage {+ t.Helper()+ return f.rpc(t, t.Context(), "tools/call", map[string]any{"name": "ui_exec", "arguments": map[string]any{"code": code, "timeout_ms": 30000}})+}++func TestUnifiedUIStateImagesAndPrivateCapabilities(t *testing.T) {+ var calls atomic.Int32+ f := newUIRuntimeFixture(t, false, func(_ context.Context, name string, _ json.RawMessage) (json.RawMessage, error) {+ calls.Add(1)+ if name == "browser_take_screenshot" {+ return json.RawMessage(`{"content":[{"type":"image","mimeType":"image/png","data":"aW1hZ2U="}]}`), nil+ }+ return uiTextResult(map[string]any{"page": "Ready"}), nil+ })+ if got := f.execute(t, `return 1`); !strings.Contains(string(got), "not ready") {+ t.Fatalf("unregistered reviewer accepted: %s", got)+ }+ clear, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ defer clear()+ got := f.execute(t, `const help=await ui.help('browser'); state.count=1; const picture=await ui.browser.take_screenshot({}); if(picture.content[0].data!==undefined) throw new Error('image data entered guest'); state.picture=picture; ui.emit(picture); return help.methods.map(m=>m.name);`)+ if strings.Contains(string(got), `"isError":true`) || !strings.Contains(string(got), `"type":"image"`) || !strings.Contains(string(got), "take_screenshot") || !strings.Contains(string(got), "aW1hZ2U=") {+ t.Fatalf("image/capability result: %s", got)+ }+ got = f.execute(t, `state.count++; ui.emit(state.picture); ui.emit([1,2]); ui.emit(3); return state.count;`)+ if strings.Contains(string(got), `"isError":true`) || !strings.Contains(string(got), `"value":2`) {+ t.Fatalf("state did not persist: %s", got)+ }+ reset := f.rpc(t, t.Context(), "tools/call", map[string]any{"name": "ui_reset", "arguments": map[string]any{}})+ if !strings.Contains(string(reset), `"reset":true`) {+ t.Fatal(string(reset))+ }+ got = f.execute(t, `return Object.keys(state);`)+ if strings.Contains(string(got), `"isError":true`) || !strings.Contains(string(got), `"value":[]`) {+ t.Fatalf("state survived reset: %s", got)+ }+ if calls.Load() != 1 {+ t.Fatalf("reset or state reads called driver: %d", calls.Load())+ }+}++type denyUIRequester struct {+ tool string+ calls int+}++func (d *denyUIRequester) Request(_ string, request map[string]any, respond func(json.RawMessage) error) error {+ d.calls+++ action := request["action"].(map[string]any)+ d.tool, _ = action["tool"].(string)+ return respond(json.RawMessage(`{"decision":"deny","message":"fixture denied"}`))+}+func (*denyUIRequester) Forget(string) {}++func TestUnifiedUIReviewsOriginalActionBeforeDispatch(t *testing.T) {+ var dispatched atomic.Int32+ f := newUIRuntimeFixture(t, true, func(context.Context, string, json.RawMessage) (json.RawMessage, error) {+ dispatched.Add(1)+ return uiTextResult("ready"), nil+ })+ if _, err := f.set.RegisterToolReviewer(nil); err == nil {+ t.Fatal("required reviewer accepted nil")+ }+ requester := &denyUIRequester{}+ clear, err := f.set.RegisterToolReviewer(&permission.Reviewer{Requester: requester, LocalAllowed: f.set.LocalAllowed, LocalEvidence: f.set.LocalEvidence})+ if err != nil {+ t.Fatal(err)+ }+ defer clear()+ got := f.execute(t, `await ui.browser.click({});`)+ if !strings.Contains(string(got), "fixture denied") || dispatched.Load() != 0 || requester.tool != "mcp__browser__browser_click" {+ t.Fatalf("review bypass: %s %+v %d", got, requester, dispatched.Load())+ }+ got = f.execute(t, `return await ui.browser.snapshot({});`)+ if strings.Contains(string(got), `"isError":true`) || dispatched.Load() != 1 || requester.calls != 1 {+ t.Fatalf("read review changed: %s", got)+ }+ clear()+ if got = f.execute(t, `return await ui.browser.snapshot({});`); !strings.Contains(string(got), "not ready") {+ t.Fatalf("closed authority remained usable: %s", got)+ }+}++func TestUnifiedUIResetDoesNotClearUnknownWrites(t *testing.T) {+ var writes atomic.Int32+ f := newUIRuntimeFixture(t, false, func(_ context.Context, name string, _ json.RawMessage) (json.RawMessage, error) {+ if name == "browser_click" {+ writes.Add(1)+ return nil, errOutcomeUnknown+ }+ return uiTextResult("visible"), nil+ })+ clear, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ defer clear()+ first := f.execute(t, `await ui.browser.click({});`)+ if !strings.Contains(string(first), `"status":"unknown"`) {+ t.Fatalf("unknown not retained: %s", first)+ }+ f.rpc(t, t.Context(), "tools/call", map[string]any{"name": "ui_reset", "arguments": map[string]any{}})+ second := f.execute(t, `await ui.browser.click({});`)+ if !strings.Contains(string(second), "cannot send further writes") || writes.Load() != 1 {+ t.Fatalf("unknown replayed: %s %d", second, writes.Load())+ }+ read := f.execute(t, `return await ui.browser.snapshot({});`)+ if strings.Contains(string(read), `"isError":true`) {+ t.Fatalf("unknown blocked observation: %s", read)+ }+}++func TestUnifiedUILocalOutcomeReceipts(t *testing.T) {+ var writes atomic.Int32+ f := newUIRuntimeFixture(t, false, func(_ context.Context, name string, _ json.RawMessage) (json.RawMessage, error) {+ switch name {+ case "browser_snapshot":+ return nil, errOutcomeUnknown+ case "browser_click":+ switch writes.Add(1) {+ case 1:+ return nil, errNotSent+ case 2:+ return nil, errors.New(errOutcomeUnknown.Error()) // Same display text, different outcome.+ default:+ return uiTextResult("clicked"), nil+ }+ case "browser_type":+ return uiTextResult(map[string]string{"outcome": "unknown"}), nil+ default:+ t.Fatalf("unexpected tool %s", name)+ return nil, nil+ }+ })+ _, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, step := range []struct {+ script string+ status string+ }{+ {"await ui.browser.snapshot({})", "unknown"},+ {"await ui.browser.click({})", "not_dispatched"},+ {"await ui.browser.click({})", "failed"},+ {"await ui.browser.click({})", "confirmed"},+ {"await ui.browser.type({})", "unknown"},+ } {+ result := cancellationSummary(t, f.execute(t, step.script))+ receipts := result.Structured.Receipts+ if len(receipts) != 1 || receipts[0].Status != step.status {+ t.Fatalf("%s: receipts=%v, want %s", step.script, receipts, step.status)+ }+ }+ if final := f.execute(t, "await ui.browser.click({})"); !strings.Contains(string(final), "cannot send further writes") || writes.Load() != 3 {+ t.Fatalf("write after unknown write outcome: %s", final)+ }+}++func TestUnifiedUIAdvertisedMinimumBudgetCanRead(t *testing.T) {+ f := newUIRuntimeFixture(t, false, func(context.Context, string, json.RawMessage) (json.RawMessage, error) {+ return uiTextResult("page"), nil+ })+ _, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ var spec struct {+ Properties struct {+ Timeout struct {+ Minimum int64 `json:"minimum"`+ } `json:"timeout_ms"`+ } `json:"properties"`+ }+ if err = json.Unmarshal(unifiedUITools()[0].InputSchema, &spec); err != nil {+ t.Fatal(err)+ }+ for _, duration := range []int64{0, spec.Properties.Timeout.Minimum - 1, spec.Properties.Timeout.Minimum} {+ result := f.rpc(t, t.Context(), "tools/call", map[string]any{"name": "ui_exec", "arguments": map[string]any{"code": "return await ui.browser.snapshot({})", "timeout_ms": duration}})+ if duration == spec.Properties.Timeout.Minimum {+ summary := cancellationSummary(t, result)+ if summary.IsError || len(summary.Structured.Receipts) != 1 || summary.Structured.Receipts[0].Status != "confirmed" {+ t.Fatalf("minimum budget rejected read: %s", result)+ }+ } else if !strings.Contains(string(result), `"isError":true`) {+ t.Fatalf("accepted duration %d: %s", duration, result)+ }+ }+}++func TestUnifiedUIOperationStateIsolation(t *testing.T) {+ callback := func(context.Context, string, json.RawMessage) (json.RawMessage, error) {+ return uiTextResult("ok"), nil+ }+ first, second := newUIRuntimeFixture(t, false, callback), newUIRuntimeFixture(t, false, callback)+ for _, f := range []*uiRuntimeFixture{first, second} {+ clear, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ defer clear()+ }+ if got := first.execute(t, `state.secret='first'; return state.secret;`); strings.Contains(string(got), `"isError":true`) {+ t.Fatal(string(got))+ }+ if got := second.execute(t, `return Object.keys(state);`); !strings.Contains(string(got), `"value":[]`) {+ t.Fatalf("state crossed Operation boundary: %s", got)+ }+}++func TestUnifiedUIImageHandleExpiresAfterScriptFailure(t *testing.T) {+ f := newUIRuntimeFixture(t, false, func(context.Context, string, json.RawMessage) (json.RawMessage, error) {+ return json.RawMessage(`{"content":[{"type":"image","mimeType":"image/png","data":"aW1hZ2U="}]}`), nil+ })+ clear, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ defer clear()+ first := f.execute(t, `return (await ui.browser.take_screenshot({})).content[0];`)+ var reply struct {+ Structured struct {+ Value json.RawMessage `json:"value"`+ } `json:"structuredContent"`+ }+ if json.Unmarshal(first, &reply) != nil || len(reply.Structured.Value) == 0 {+ t.Fatal(string(first))+ }+ failure := f.execute(t, `throw new Error('discard this state');`)+ if !strings.Contains(string(failure), `"state_reset":true`) {+ t.Fatal(string(failure))+ }+ reused := f.execute(t, `ui.emit(`+string(reply.Structured.Value)+`);`)+ if !strings.Contains(string(reused), "image handle is stale") {+ t.Fatalf("prior generation image escaped invalidation: %s", reused)+ }+}++func TestUnifiedUIExpandedImagesStayBounded(t *testing.T) {+ picture, _ := json.Marshal(map[string]any{"content": []any{map[string]string{"type": "image", "mimeType": "image/png", "data": strings.Repeat("a", 4*1024*1024)}}})+ f := newUIRuntimeFixture(t, false, func(context.Context, string, json.RawMessage) (json.RawMessage, error) { return picture, nil })+ clear, err := f.set.RegisterToolReviewer(nil)+ if err != nil {+ t.Fatal(err)+ }+ defer clear()+ got := f.execute(t, `const picture=await ui.browser.take_screenshot({}); for(let i=0;i<8;i++) ui.emit(picture);`)+ if len(got) >= maxMCPBytes || !bytes.Contains(got, []byte("expanded output exceeds")) {+ t.Fatalf("image amplification was not bounded: bytes=%d", len(got))+ }+ nested := f.execute(t, `ui.emit({content:[{content:[{type:'text',text:'nested'}]}]});`)+ if !strings.Contains(string(nested), "cannot be nested") {+ t.Fatal(string(nested))+ }+}diff --git a/apps/computer/local-daemon/internal/linger/mcpproxy/catalog.go b/apps/computer/local-daemon/internal/linger/mcpproxy/catalog.goindex 1b57a8a5..256060d4 100644--- a/apps/computer/local-daemon/internal/linger/mcpproxy/catalog.go+++ b/apps/computer/local-daemon/internal/linger/mcpproxy/catalog.go@@ -36,13 +36,19 @@ func (s *Set) WaitReady(ctx context.Context) error {return nil}listed := s.proxies- if len(listed)+len(s.local) == 0 {+ var local []LocalBinding+ for _, binding := range s.local {+ if !s.hidden[binding.URL] {+ local = append(local, binding)+ }+ }+ if len(listed)+len(local) == 0 {return nil}ctx, cancel := context.WithCancel(ctx)defer cancel()- results := make(chan error, len(listed)+len(s.local))- for _, binding := range s.local {+ results := make(chan error, len(listed)+len(local))+ for _, binding := range local {go func() { results <- binding.WaitReady(ctx) }()}for _, item := range listed {@@ -59,7 +65,7 @@ func (s *Set) WaitReady(ctx context.Context) error {}}()}- for range len(listed) + len(s.local) {+ for range len(listed) + len(local) {if err := <-results; err != nil {return err}diff --git a/apps/computer/local-daemon/internal/linger/mcpproxy/local.go b/apps/computer/local-daemon/internal/linger/mcpproxy/local.goindex ea4defe8..94d9491f 100644--- a/apps/computer/local-daemon/internal/linger/mcpproxy/local.go+++ b/apps/computer/local-daemon/internal/linger/mcpproxy/local.go@@ -6,10 +6,14 @@ import ("errors""fmt""strings"+ "time""github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission")+// LocalToolTimeout is the Runtime budget for one local tool response.+const LocalToolTimeout = 180 * time.Second+var ErrCleanupUnconfirmed = errors.New("local tool cleanup is unconfirmed")// LocalBinding is installed by the trusted daemon composition, never decoded@@ -27,6 +31,8 @@ type LocalBinding struct {// Allowed reports whether one of the binding's tool calls follows from// what the Agent has already seen and runs without review.Allowed func(tool string, input json.RawMessage) bool+ // Timeout bounds an orchestration call; zero uses the ordinary tool limit.+ Timeout time.Duration}func (s *Set) AddLocal(binding LocalBinding) error {@@ -45,7 +51,11 @@ func (s *Set) AddLocal(binding LocalBinding) error {if _, exists := config.Servers[binding.Name]; exists {return fmt.Errorf("MCP name is duplicated: %s", binding.Name)}- server, err := json.Marshal(map[string]any{"type": "http", "url": binding.URL, "tool_timeout_sec": 180})+ timeout := binding.Timeout+ if timeout == 0 {+ timeout = LocalToolTimeout+ }+ server, err := json.Marshal(map[string]any{"type": "http", "url": binding.URL, "tool_timeout_sec": int(timeout / time.Second)})if err != nil {return err}@@ -65,6 +75,9 @@ func (s *Set) LocalToolNames() []string {}var names []stringfor _, binding := range s.local {+ if s.hidden[binding.URL] {+ continue+ }for _, name := range binding.ToolNames {names = append(names, "mcp__"+binding.Name+"__"+name)}@@ -78,6 +91,10 @@ func (s *Set) LocalAllowed(tool, input string) bool {if s == nil {return false}+ if s.ui != nil && (tool == "mcp__computer__ui_exec" || tool == "mcp__computer__ui_reset") {+ // Only orchestration is allowed here. Every nested action is reviewed.+ return true+ }server, name, ok := strings.Cut(strings.TrimPrefix(tool, "mcp__"), "__")if !ok {return falsediff --git a/apps/computer/local-daemon/internal/linger/mcpproxy/orchestrator.go b/apps/computer/local-daemon/internal/linger/mcpproxy/orchestrator.gonew file mode 100644index 00000000..2f309410--- /dev/null+++ b/apps/computer/local-daemon/internal/linger/mcpproxy/orchestrator.go@@ -0,0 +1,144 @@+package mcpproxy++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "sync"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission"+)++// ToolEndpoint identifies an Operation-local driver kept outside the JavaScript context.+type ToolEndpoint struct {+ Name string+ URL string+}++type toolOrchestrator struct {+ mu sync.Mutex+ required, ready, closed bool+ reviewer *permission.Reviewer+ identity OperationIdentity+}++// ComputerEndpoints returns the original drivers, not the orchestration tool.+func (s *Set) ComputerEndpoints() []ToolEndpoint {+ if s == nil {+ return nil+ }+ var endpoints []ToolEndpoint+ for _, b := range s.local {+ if (b.Name == "computer" || b.Name == "browser") && !s.hidden[b.URL] {+ endpoints = append(endpoints, ToolEndpoint{Name: b.Name, URL: b.URL})+ }+ }+ return endpoints+}++// PrivatizeComputerTools retains driver lifecycle and evidence collection, but+// removes their public decision surface. Only trusted composition calls this.+func (s *Set) PrivatizeComputerTools(identity OperationIdentity, required bool) error {+ if s == nil || s.ui != nil || identity.OperationID == "" || identity.ExecutionLeaseID == "" {+ return errors.New("invalid UI orchestration identity")+ }+ var config struct {+ Servers map[string]json.RawMessage `json:"mcpServers"`+ }+ if err := json.Unmarshal(s.config, &config); err != nil {+ return err+ }+ s.hidden = map[string]bool{}+ for _, endpoint := range s.ComputerEndpoints() {+ s.hidden[endpoint.URL] = true+ delete(config.Servers, endpoint.Name)+ }+ encoded, err := json.Marshal(config)+ if err != nil {+ return err+ }+ s.config = encoded+ s.ui = &toolOrchestrator{required: required, identity: identity}+ return nil+}++// RegisterToolReviewer binds the Run's reviewer to this exact Operation and+// lease. The closure cannot be supplied by a wire request or another Set.+func (s *Set) RegisterToolReviewer(reviewer *permission.Reviewer) (func(), error) {+ if s == nil || s.ui == nil {+ return func() {}, nil+ }+ u := s.ui+ u.mu.Lock()+ defer u.mu.Unlock()+ if u.closed || u.ready || u.required && reviewer == nil {+ return nil, errors.New("UI action reviewer is unavailable for this Operation")+ }+ u.reviewer, u.ready = reviewer, true+ return func() { s.closeToolReviewer() }, nil+}++func (s *Set) closeToolReviewer() {+ if s == nil || s.ui == nil {+ return+ }+ s.ui.mu.Lock()+ s.ui.closed, s.ui.ready, s.ui.reviewer = true, false, nil+ s.ui.mu.Unlock()+}++// ToolReviewerReady reports whether this operation can review nested UI calls.+func (s *Set) ToolReviewerReady() bool {+ if s == nil || s.ui == nil {+ return false+ }+ s.ui.mu.Lock()+ defer s.ui.mu.Unlock()+ return s.ui.ready && !s.ui.closed+}++// ReviewTool runs before dispatch, using the original method and real values.+// The original HTTP driver checks lease authority again at dispatch.+func (s *Set) ReviewTool(ctx context.Context, server, name string, args json.RawMessage) error {+ if s == nil || s.ui == nil {+ return errors.New("UI action reviewer is unavailable")+ }+ u := s.ui+ u.mu.Lock()+ ready, reviewer, identity := u.ready && !u.closed, u.reviewer, u.identity+ u.mu.Unlock()+ if !ready {+ return errors.New("UI action reviewer is not ready")+ }+ if err := ctx.Err(); err != nil {+ return err+ }+ if identity.BeforeToolCall != nil {+ if err := identity.BeforeToolCall(); err != nil {+ return err+ }+ }+ if identity.BeforeRequest != nil {+ if err := identity.BeforeRequest(ctx); err != nil {+ return err+ }+ }+ if reviewer == nil {+ return nil+ }+ tool := "mcp__" + server + "__" + name+ var input map[string]any+ if json.Unmarshal(args, &input) != nil || input == nil {+ return errors.New("invalid UI action arguments")+ }+ request := permission.Request{Action: permission.Action{Runtime: identity.RuntimeType, Surface: permission.Surface(tool, ""), Tool: tool, Input: string(args)}, Evidence: permission.RunScriptEvidence(tool, input)}+ verdict := reviewer.Review(ctx, request)+ if verdict.Decision != permission.Allow {+ return fmt.Errorf("UI action was not dispatched: %s", verdict.Message)+ }+ if !s.ToolReviewerReady() {+ return errors.New("UI action authority ended during review")+ }+ return ctx.Err()+}diff --git a/apps/computer/local-daemon/internal/linger/mcpproxy/proxy.go b/apps/computer/local-daemon/internal/linger/mcpproxy/proxy.goindex ce3a7f72..eb48eccc 100644--- a/apps/computer/local-daemon/internal/linger/mcpproxy/proxy.go+++ b/apps/computer/local-daemon/internal/linger/mcpproxy/proxy.go@@ -42,6 +42,8 @@ type Set struct {proxies []*proxylocal []LocalBindingconfig json.RawMessage+ hidden map[string]bool+ ui *toolOrchestratoronce sync.Onceerr error}@@ -100,8 +102,11 @@ func (s *Set) Close() error {return nil}s.once.Do(func() {+ s.closeToolReviewer()var closeErrors []error- for _, binding := range s.local {+ // The public tool owns callers of the drivers bound before it.+ for i := len(s.local) - 1; i >= 0; i-- {+ binding := s.local[i]if err := binding.Close(); err != nil {closeErrors = append(closeErrors, err)}diff --git a/apps/computer/local-daemon/internal/provider/executor.go b/apps/computer/local-daemon/internal/provider/executor.goindex 8d7876ea..f5ff37e0 100644--- a/apps/computer/local-daemon/internal/provider/executor.go+++ b/apps/computer/local-daemon/internal/provider/executor.go@@ -61,8 +61,9 @@ type OperationSpec struct {LocalEvidence func(ctx context.Context, tool, input string) *permission.Evidence// LocalAllowed reports whether a local browser or desktop call runs// without review.- LocalAllowed func(tool, input string) bool- ClaudeSkillNames []string+ LocalAllowed func(tool, input string) bool+ RegisterToolReviewer func(*permission.Reviewer) (func(), error)+ ClaudeSkillNames []string// ContextSkillDigest identifies the Skill packages of the Context View// the Daemon published into the workspace.ContextSkillDigest string@@ -166,6 +167,7 @@ func (e Executor) PrepareProvider(ctx context.Context, spec OperationSpec) (Resuspec.TrustedLocalMCPTools = nilspec.LocalEvidence = nilspec.LocalAllowed = nil+ spec.RegisterToolReviewer = nilexecution, err := e.Start(ctx, spec, func(context.Context, protocol.Event) error { return nil })if err != nil {return Result{}, err@@ -531,6 +533,14 @@ func (e Executor) Start(ctx context.Context, spec OperationSpec, emit EmitFunc)RuntimeVersion: spec.CodexVersion, Platform: runtime.GOOS, Workspace: spec.WorkingDirectory,}}}+ if spec.RegisterToolReviewer != nil {+ release, err := spec.RegisterToolReviewer(reviewer)+ if err != nil {+ finish(Result{Status: "failed", Error: err.Error()})+ return+ }+ defer release()+ }runtimeHomePath := ""if runtimeHome != nil {runtimeHomePath = runtimeHome.Path@@ -795,8 +805,7 @@ var codexBatchedInputs = []any{"click", "double_click", "right_click", "drag", "// tools as plain function tools, as Codex's computer-use plugin does with its// REPL: outside code mode and never deferred. A call is then a JSON function// call, not a script that wraps each tool in text(await tools.mcp__...).-// Desktop inputs go only through run_actions, Codex's one-script-per-call-// shape, so the model plans several steps in one call.+// An older binding with direct desktop inputs uses run_actions for batches.func codexDirectLocalTools(mcpConfig json.RawMessage, localTools []string) (json.RawMessage, error) {if len(mcpConfig) == 0 || len(localTools) == 0 {return mcpConfig, nil@@ -806,12 +815,15 @@ func codexDirectLocalTools(mcpConfig json.RawMessage, localTools []string) (jsonreturn nil, fmt.Errorf("Codex MCP configuration is invalid: %w", err)}servers, _ := parsed["mcpServers"].(map[string]any)+ unified := slices.Contains(localTools, "mcp__computer__ui_exec")for _, tool := range localTools {name, _, ok := strings.Cut(strings.TrimPrefix(tool, "mcp__"), "__")if settings, found := servers[name].(map[string]any); ok && found {settings["omit_tools_from"] = []any{"code_mode", "deferred"}- if name == "computer" {+ if name == "computer" && !unified {settings["disabled_tools"] = codexBatchedInputs+ } else if name == "computer" {+ delete(settings, "disabled_tools")}}}diff --git a/apps/computer/local-daemon/internal/uiruntime/runtime.go b/apps/computer/local-daemon/internal/uiruntime/runtime.gonew file mode 100644index 00000000..596ac24e--- /dev/null+++ b/apps/computer/local-daemon/internal/uiruntime/runtime.go@@ -0,0 +1,512 @@+// Package uiruntime owns a restricted, persistent JavaScript child. Tool+// authorization, images, and uncertain action journals belong to its caller.+package uiruntime++import (+ "bufio"+ "context"+ _ "embed"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os/exec"+ "path/filepath"+ "strconv"+ "sync"+ "syscall"+ "time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/process"+)++//go:embed runtime.mjs+var script string++var (+ // ErrBusy means an execution or its dispatched callback is still running.+ ErrBusy = errors.New("UI runtime is busy")+ // ErrClosed means the owning lifetime has ended.+ ErrClosed = errors.New("UI runtime is closed")+ // ErrCleanupUnconfirmed prevents replacing a child whose cleanup is unknown.+ ErrCleanupUnconfirmed = errors.New("UI runtime child cleanup is unconfirmed")+)++// Limits bound execution and protocol resources. RSSMiB is a supervised+// threshold, not an operating-system hard memory limit.+type Limits struct {+ MaxCodeBytes int+ MaxProtocolBytes int+ MaxOutputBytes int+ MaxCalls int+ MaxWallTime time.Duration+ HeapMiB int+ RSSMiB int+ PumpTimeout time.Duration+}++// Call is an untrusted guest request. Dispatch must validate the method and+// arguments and perform the original operation's authorization before acting.+type Call struct {+ Generation uint64+ ExecutionID uint64+ ID uint64+ Namespace string+ Method string+ Arguments json.RawMessage+}++// Options contains only locally resolved executable configuration and an+// in-process dispatcher. No environment or executable is accepted from a guest.+type Options struct {+ // QuickJSDirectory belongs to the verified Computer tool bundle.+ QuickJSDirectory string+ NodePath string+ Dispatch func(context.Context, Call) (json.RawMessage, error)+ Limits Limits+}++// Result contains opaque JSON values. Image handles are resolved by the caller.+// Generation identifies this execution even when Exec returns an error.+type Result struct {+ Generation uint64+ Value json.RawMessage+ Output []json.RawMessage+}++// Runtime serializes executions within one caller-owned lifetime.+type Runtime struct {+ life context.Context+ cancel context.CancelFunc+ opts Options+ slot chan struct{}+ mu sync.Mutex+ child *child+ generation uint64+ execution uint64+ closed bool+ poisoned error+}++// New validates configuration. The child starts lazily on the first Exec.+func New(lifetime context.Context, opts Options) (*Runtime, error) {+ if lifetime == nil || !filepath.IsAbs(opts.NodePath) || !filepath.IsAbs(opts.QuickJSDirectory) || opts.Dispatch == nil {+ return nil, errors.New("UI runtime requires a lifetime, absolute engine paths, and dispatcher")+ }+ if err := defaultLimits(&opts.Limits); err != nil {+ return nil, err+ }+ life, cancel := context.WithCancel(lifetime)+ return &Runtime{life: life, cancel: cancel, opts: opts, slot: make(chan struct{}, 1), generation: 1}, nil+}++func defaultLimits(l *Limits) error {+ if l.MaxCodeBytes == 0 {+ l.MaxCodeBytes = 64 * 1024+ }+ if l.MaxProtocolBytes == 0 {+ l.MaxProtocolBytes = 2 * 1024 * 1024+ }+ if l.MaxOutputBytes == 0 {+ l.MaxOutputBytes = 1024 * 1024+ }+ if l.MaxCalls == 0 {+ l.MaxCalls = 64+ }+ if l.MaxWallTime == 0 {+ l.MaxWallTime = 120 * time.Second+ }+ if l.HeapMiB == 0 {+ l.HeapMiB = 128+ }+ if l.RSSMiB == 0 {+ l.RSSMiB = 256+ }+ if l.PumpTimeout == 0 {+ l.PumpTimeout = 100 * time.Millisecond+ }+ if l.MaxCodeBytes < 1 || l.MaxCodeBytes > 1024*1024 || l.MaxProtocolBytes < 1024 || l.MaxProtocolBytes > 24*1024*1024 || l.MaxOutputBytes < 1 || l.MaxOutputBytes > l.MaxProtocolBytes/2 || l.MaxCalls < 1 || l.MaxCalls > 1024 || l.MaxWallTime < time.Millisecond || l.MaxWallTime > 10*time.Minute || l.HeapMiB < 16 || l.HeapMiB > 1024 || l.RSSMiB < 32 || l.RSSMiB > 2048 || l.PumpTimeout < time.Millisecond || l.PumpTimeout > time.Second {+ return errors.New("invalid UI runtime limits")+ }+ return nil+}++// Generation changes when guest state is discarded. It never resets journals+// or other resources owned by the caller.+func (r *Runtime) Generation() uint64 { r.mu.Lock(); defer r.mu.Unlock(); return r.generation }++func (r *Runtime) enter() error {+ select {+ case r.slot <- struct{}{}:+ default:+ return ErrBusy+ }+ r.mu.Lock()+ defer r.mu.Unlock()+ if r.closed || r.life.Err() != nil {+ <-r.slot+ return ErrClosed+ }+ if r.poisoned != nil {+ <-r.slot+ return r.poisoned+ }+ return nil+}++// Exec executes an async function body. Only state persists; lexical declarations+// belong to this call. UI closures saved in state retain their execution scope+// and cannot dispatch during a later execution. Scheduling cancellation stops the guest immediately, but+// an already-dispatched callback finishes under hardCtx before Exec returns.+// hardCtx must be honored by Dispatch; Go cannot forcibly terminate a callback.+func (r *Runtime) Exec(hardCtx, schedulingCtx context.Context, code string) (result Result, err error) {+ if hardCtx == nil || schedulingCtx == nil {+ return result, errors.New("UI execution requires both contexts")+ }+ if err = r.enter(); err != nil {+ return result, err+ }+ defer func() { <-r.slot }()+ result.Generation = r.Generation()+ if len(code) > r.opts.Limits.MaxCodeBytes {+ return result, errors.New("UI code exceeds byte limit")+ }+ hard, cancel := context.WithTimeout(hardCtx, r.opts.Limits.MaxWallTime)+ defer cancel()+ stopLife := context.AfterFunc(r.life, cancel)+ defer stopLife()+ if err = executionCause(hard, schedulingCtx); err != nil {+ return result, err+ }+ c, startErr := r.ensureChild(hard, schedulingCtx)+ if startErr != nil {+ return result, startErr+ }+ result.Generation = r.Generation()+ r.mu.Lock()+ r.execution+++ execution := r.execution+ r.mu.Unlock()+ // Kill the guest even while Dispatch is blocked. The callback deliberately+ // receives hard rather than schedulingCtx, retaining its completion receipt.+ stopHard := context.AfterFunc(hard, func() { r.invalidate(c) })+ stopScheduling := context.AfterFunc(schedulingCtx, func() { r.invalidate(c) })+ defer stopHard()+ defer stopScheduling()+ defer func() {+ if err != nil {+ r.invalidate(c)+ if closeErr := r.reap(c); closeErr != nil {+ err = errors.Join(err, closeErr)+ }+ }+ }()+ if err = executionCause(hard, schedulingCtx); err != nil {+ return result, err+ }+ if err = c.send(hard, map[string]any{"type": "exec", "execution": execution, "code": code}, r.opts.Limits.MaxProtocolBytes); err != nil {+ return result, err+ }+ var lastID uint64+ for {+ if err = executionCause(hard, schedulingCtx); err != nil {+ return result, err+ }+ var msg message+ select {+ case <-hard.Done():+ return result, context.Cause(hard)+ case <-schedulingCtx.Done():+ return result, context.Cause(schedulingCtx)+ case msg = <-c.messages:+ case readErr := <-c.readError:+ return result, readErr+ case <-c.exited:+ return result, errors.New("UI child exited before completion")+ }+ if err = executionCause(hard, schedulingCtx); err != nil {+ return result, err+ }+ if msg.Type == "fatal" {+ return result, fmt.Errorf("UI child failed: %s", msg.Error)+ }+ if msg.Execution != execution {+ return result, errors.New("UI protocol execution mismatch")+ }+ switch msg.Type {+ case "call":+ if msg.ID != lastID+1 || msg.ID > uint64(r.opts.Limits.MaxCalls) || (msg.Namespace != "computer" && msg.Namespace != "browser" && msg.Namespace != "help") || (msg.Method == "" && msg.Namespace != "help") || len(msg.Method) > 256 || len(msg.Arguments) == 0 || !json.Valid(msg.Arguments) {+ return result, errors.New("invalid UI callback request")+ }+ lastID = msg.ID+ value, callErr := r.opts.Dispatch(hard, Call{Generation: result.Generation, ExecutionID: execution, ID: msg.ID, Namespace: msg.Namespace, Method: msg.Method, Arguments: msg.Arguments})+ if err = executionCause(hard, schedulingCtx); err != nil {+ return result, err+ }+ if callErr != nil {+ err = c.send(hard, map[string]any{"type": "reply", "execution": execution, "id": msg.ID, "error": callErr.Error()}, r.opts.Limits.MaxProtocolBytes)+ } else {+ if len(value) == 0 {+ value = json.RawMessage("null")+ }+ if !json.Valid(value) {+ return result, errors.New("UI dispatcher returned invalid JSON")+ }+ err = c.send(hard, map[string]any{"type": "reply", "execution": execution, "id": msg.ID, "value": value}, r.opts.Limits.MaxProtocolBytes)+ }+ if err != nil {+ return result, err+ }+ case "done":+ if msg.Error != "" {+ return result, fmt.Errorf("UI script failed: %s", msg.Error)+ }+ if len(msg.Value) == 0 || !json.Valid(msg.Value) {+ return result, errors.New("invalid UI return value")+ }+ size := len(msg.Value)+ for _, v := range msg.Output {+ if !json.Valid(v) {+ return result, errors.New("invalid UI output")+ }+ size += len(v)+ }+ if size > r.opts.Limits.MaxOutputBytes {+ return result, errors.New("UI output exceeds byte limit")+ }+ result.Value, result.Output = msg.Value, msg.Output+ return result, nil+ default:+ return result, errors.New("unexpected UI protocol message")+ }+ }+}++func executionCause(hard, scheduling context.Context) error {+ if hard.Err() != nil {+ return context.Cause(hard)+ }+ if scheduling.Err() != nil {+ return context.Cause(scheduling)+ }+ return nil+}++// Reset discards only guest state. An active or draining Exec returns ErrBusy.+func (r *Runtime) Reset(ctx context.Context) error {+ if err := ctx.Err(); err != nil {+ return context.Cause(ctx)+ }+ if err := r.enter(); err != nil {+ return err+ }+ defer func() { <-r.slot }()+ r.mu.Lock()+ c := r.child+ r.mu.Unlock()+ if c == nil {+ r.mu.Lock()+ r.generation+++ r.mu.Unlock()+ return nil+ }+ r.invalidate(c)+ return r.reapContext(ctx, c)+}++// Close revokes the lifetime, stops the guest, and waits for the execution and+// owned process cleanup. Repeated Close calls may retry an incomplete wait.+func (r *Runtime) Close(ctx context.Context) error {+ r.mu.Lock()+ r.closed = true+ c := r.child+ r.mu.Unlock()+ r.cancel()+ if c != nil {+ r.invalidate(c)+ }+ select {+ case r.slot <- struct{}{}:+ defer func() { <-r.slot }()+ case <-ctx.Done():+ return errors.Join(ErrCleanupUnconfirmed, context.Cause(ctx))+ }+ if c != nil {+ return r.reapContext(ctx, c)+ }+ r.mu.Lock()+ defer r.mu.Unlock()+ return r.poisoned+}++func (r *Runtime) invalidate(c *child) {+ r.mu.Lock()+ if r.child == c && !c.invalid {+ c.invalid = true+ r.generation+++ }+ r.mu.Unlock()+ c.stop()+}+func (r *Runtime) reap(c *child) error {+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)+ defer cancel()+ return r.reapContext(ctx, c)+}+func (r *Runtime) reapContext(ctx context.Context, c *child) error {+ var err error+ select {+ case <-c.exited:+ // process.Run joins cleanup failures. Only a direct exit error from an+ // intentionally stopped child is benign; a joined error remains unknown.+ if c.err != nil && c.err != context.Cause(c.ctx) { //nolint:errorlint // A wrapped cause may also contain a cleanup failure.+ if _, ok := c.err.(*exec.ExitError); !ok { //nolint:errorlint // Only a bare exit error confirms cleanup.+ err = errors.Join(ErrCleanupUnconfirmed, c.err)+ }+ }+ case <-ctx.Done():+ err = errors.Join(ErrCleanupUnconfirmed, context.Cause(ctx))+ }+ r.mu.Lock()+ defer r.mu.Unlock()+ if err != nil {+ r.poisoned = err+ return err+ }+ if r.child == c {+ r.child = nil+ }+ return nil+}++type message struct {+ Type string `json:"type"`+ Execution uint64 `json:"execution"`+ ID uint64 `json:"id"`+ Namespace string `json:"namespace"`+ Method string `json:"method"`+ Arguments json.RawMessage `json:"arguments"`+ Value json.RawMessage `json:"value"`+ Output []json.RawMessage `json:"output"`+ Error string `json:"error"`+}+type child struct {+ cmd *exec.Cmd+ stdin io.WriteCloser+ stdout io.ReadCloser+ messages chan message+ readError chan error+ exited chan struct{}+ cancel context.CancelFunc+ ctx context.Context+ stopOnce sync.Once+ invalid bool // guarded by Runtime.mu+ err error // published by exited+}++func (c *child) stop() {+ c.stopOnce.Do(func() { _ = process.Signal(c.cmd, syscall.SIGKILL); c.cancel(); _ = c.stdin.Close() })+}++func (r *Runtime) ensureChild(hard, scheduling context.Context) (*child, error) {+ r.mu.Lock()+ c := r.child+ r.mu.Unlock()+ if c != nil {+ select {+ case <-c.exited:+ r.invalidate(c)+ if err := r.reap(c); err != nil {+ return nil, err+ }+ default:+ return c, nil+ }+ }+ engineDir, err := filepath.EvalSymlinks(r.opts.QuickJSDirectory)+ if err != nil {+ return nil, fmt.Errorf("open bundled UI engine: %w", err)+ }+ cfg, _ := json.Marshal(map[string]any{"engineDirectory": engineDir, "heapBytes": r.opts.Limits.HeapMiB * 1024 * 1024, "maxProtocolBytes": r.opts.Limits.MaxProtocolBytes, "maxOutputBytes": r.opts.Limits.MaxOutputBytes, "maxCalls": r.opts.Limits.MaxCalls, "rssBytes": r.opts.Limits.RSSMiB * 1024 * 1024, "pumpMs": r.opts.Limits.PumpTimeout.Milliseconds()})+ cmd := exec.Command(r.opts.NodePath, "--permission", "--allow-fs-read="+engineDir, "--no-addons", "--max-old-space-size="+strconv.Itoa(r.opts.Limits.HeapMiB), "--input-type=module", "-e", script, string(cfg))+ cmd.Env = []string{}+ cmd.Stderr = io.Discard+ stdin, err := cmd.StdinPipe()+ if err != nil {+ return nil, err+ }+ stdout, err := cmd.StdoutPipe()+ if err != nil {+ _ = stdin.Close()+ return nil, err+ }+ childCtx, cancel := context.WithCancel(r.life)+ c = &child{cmd: cmd, stdin: stdin, stdout: stdout, messages: make(chan message, 2), readError: make(chan error, 1), exited: make(chan struct{}), cancel: cancel, ctx: childCtx}+ r.mu.Lock()+ r.child = c+ r.mu.Unlock()+ go c.read(r.opts.Limits.MaxProtocolBytes)+ go func() {+ c.err = process.Run(childCtx, cmd, time.Second)+ _ = stdin.Close()+ _ = stdout.Close()+ close(c.exited)+ }()+ select {+ case msg := <-c.messages:+ if msg.Type == "ready" {+ return c, nil+ }+ err = errors.New("invalid UI child handshake")+ case err = <-c.readError:+ case <-c.exited:+ err = errors.New("UI child exited during startup")+ case <-hard.Done():+ err = context.Cause(hard)+ case <-scheduling.Done():+ err = context.Cause(scheduling)+ }+ r.invalidate(c)+ return nil, errors.Join(err, r.reap(c))+}+func (c *child) read(limit int) {+ scanner := bufio.NewScanner(c.stdout)+ scanner.Buffer(make([]byte, 4096), limit)+ for scanner.Scan() {+ var msg message+ if err := json.Unmarshal(scanner.Bytes(), &msg); err != nil {+ c.readError <- errors.New("invalid UI child JSON")+ return+ }+ select {+ case c.messages <- msg:+ case <-c.exited:+ return+ }+ }+ err := scanner.Err()+ if err == nil {+ err = io.ErrUnexpectedEOF+ }+ c.readError <- err+}+func (c *child) send(ctx context.Context, value any, limit int) error {+ data, err := json.Marshal(value)+ if err != nil {+ return err+ }+ if len(data) >= limit {+ return errors.New("UI protocol frame exceeds byte limit")+ }+ done := make(chan error, 1)+ go func() { _, err := c.stdin.Write(append(data, '\n')); done <- err }()+ select {+ case err := <-done:+ return err+ case <-ctx.Done():+ c.stop()+ return context.Cause(ctx)+ case <-c.exited:+ return io.ErrClosedPipe+ }+}diff --git a/apps/computer/local-daemon/internal/uiruntime/runtime.mjs b/apps/computer/local-daemon/internal/uiruntime/runtime.mjsnew file mode 100644index 00000000..926c15b7--- /dev/null+++ b/apps/computer/local-daemon/internal/uiruntime/runtime.mjs@@ -0,0 +1,338 @@+"use strict";+// The trusted wrapper only exchanges JSON strings with the guest realm.+const version = process.versions.node.split(".").map(Number);+if (version[0] < 26 || (version[0] === 26 && version[1] < 5)) {+ throw new Error("UI runtime requires Node 26.5 or newer");+}+import { readFile } from "node:fs/promises";+import path from "node:path";+import { pathToFileURL } from "node:url";+const limits = JSON.parse(process.argv[1]);+const engineBase = pathToFileURL(limits.engineDirectory + path.sep);+const { QuickJS, Intrinsics } = await import(+ new URL("dist/index.js", engineBase)+);+const wasm = await WebAssembly.compile(+ await readFile(new URL("quickjs.wasm", engineBase)),+);+// Only this wrapper owns the protocol pipes. Neither VM receives host I/O,+// module loaders, native extensions, callbacks, or a shared memory object.+const wasi = () => ({ fd_write: () => 8, fd_fdstat_get: () => 8 });+let deadline = Infinity;+const options = {+ wasm,+ wasi,+ memoryLimit: limits.heapBytes,+ interruptHandler: () => performance.now() >= deadline,+};+const compiler = await QuickJS.create(options);+const unhandled = new Set();+const guest = await QuickJS.create({+ ...options,+ intrinsics: Intrinsics.ALL & ~Intrinsics.EVAL,+ onUnhandledRejection(promise, _reason, handled) {+ if (handled) unhandled.delete(promise.ptr);+ else unhandled.add(promise.ptr);+ },+});+const drain = compiler.compile("__uiBridge.drain()");+let execution = 0,+ waiting = 0,+ active = false,+ dead = false;+function send(message) {+ const text = JSON.stringify(message);+ if (Buffer.byteLength(text) >= limits.maxProtocolBytes)+ throw new Error("UI protocol frame exceeds byte limit");+ process.stdout.write(text + "\n");+}+function fail(message) {+ if (dead) return;+ dead = true;+ try {+ send({ type: "fatal", error: message.slice(0, 4096) });+ } finally {+ process.exitCode = 1;+ process.stdin.destroy();+ }+}+function evaluate(source) {+ deadline = performance.now() + limits.pumpMs;+ try {+ // Only bytecode produced by our own compiler enters the guest.+ using value = guest.evalBytecode(+ source === drain ? drain : compiler.compile(source),+ );+ guest.executePendingJobs();+ if (unhandled.size) throw new Error("UI unhandled asynchronous rejection");+ return value.typeof === "string" ? value.toString() : undefined;+ } finally {+ deadline = Infinity;+ }+}+// Functions, Promises and errors below originate inside the context. Go treats+// every bridge request as untrusted and applies its own limits and validation.+evaluate(`(() => {+ 'use strict';+ const stringify = JSON.stringify, parse = JSON.parse;+ const pending = new Map();+ let queue = [], outputs = [], outputSize = 0, next = 0;+ let active = false, completed = false, finalValue = null, failure = '', epoch = 0;+ const maxCalls = ${limits.maxCalls}, maxOutput = ${limits.maxOutputBytes}, maxFrame = ${limits.maxProtocolBytes};+ const clone = value => {+ const text = stringify(value);+ if (text === undefined) return null;+ if (text.length > maxFrame) throw new Error('UI value exceeds byte limit');+ return parse(text);+ };+ const errorText = error => {+ try { return String(error && error.message || error).slice(0, 4096); }+ catch { return 'UI script failed'; }+ };+ const revisions = {browser:0, computer:0};+ const call = (owner, namespace, method, args) => {+ if (owner !== epoch || !active || completed) return Promise.reject(new Error('UI execution is not active'));+ if (++next > maxCalls) {+ failure = 'UI call limit exceeded';+ return Promise.reject(new Error(failure));+ }+ if (namespace === 'browser' || namespace === 'computer') ++revisions[namespace];+ const argumentsValue = clone(args === undefined ? {} : args), id = next;+ const promise = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));+ queue.push({ type: 'call', id, namespace, method, arguments: argumentsValue });+ return promise;+ };+ const namespace = (owner, name) => new Proxy(Object.create(null), {+ get(_, key) {+ if (typeof key !== 'string' || key === 'then') return undefined;+ return args => call(owner, name, key, args);+ }+ });+ const makeUI = owner => Object.freeze({+ computer: namespace(owner, 'computer'), browser: namespace(owner, 'browser'),+ text(result) {+ return result.content.filter(part => part.type === 'text').map(part => part.text).join('\\n');+ },+ ref(snapshot, role, name) {+ const prefix = '- ' + role + ' ' + stringify(name) + ' ';+ const refs = [];+ for (const line of this.text(snapshot).split('\\n')) {+ let row = line.trimStart();+ // Playwright quotes an entire YAML key when a name contains e.g. ": " or " #".+ if (row.startsWith("- '")) {+ const quoted = /^- '((?:[^']|'')*)'(?=:|$)/.exec(row);+ if (!quoted) continue;+ row = '- ' + quoted[1].replace(/''/g, "'");+ }+ if (!row.startsWith(prefix)) continue;+ const match = /^((?:\\[[^\\]\\n]*\\] )*)\\[ref=([a-zA-Z0-9_-]+)\\](?=[: \\t]|$)/.exec(row.slice(prefix.length));+ if (match) refs.push(match[2]);+ }+ if (refs.length !== 1) throw new Error('Expected one matching control; inspect the current snapshot');+ return refs[0];+ },+ async page(url) {+ const ui = this;+ const b = ui.browser;+ if (url !== undefined) await b.navigate({url});+ const read = async () => {+ const pending = b.snapshot({});+ const revision = revisions.browser;+ return view(await pending, revision);+ };+ const view = (snapshot, revision) => {+ const act = async (method, argumentsForView) => {+ if (revision !== revisions.browser) throw new Error('Page observation expired; observe again');+ const pending = b[method](argumentsForView());+ const nextRevision = revisions.browser;+ const result = await pending;+ if (nextRevision !== revisions.browser) throw new Error('Page changed during action; observe again');+ // Some Playwright actions return delivery only. Read once, without replaying the input.+ const next = result.content?.some(p => p.type === 'text' && /^### Snapshot\\n\`\`\`yaml\\n/m.test(p.text))+ ? view(result, nextRevision) : await read();+ return Object.freeze({...result, ...next});+ };+ return Object.freeze({+ text: ui.text(snapshot),+ click: (role, name) => act('click', () => ({target: ui.ref(snapshot, role, name)})),+ type: (role, name, text) => act('type', () => ({target: ui.ref(snapshot, role, name), text})),+ select: (role, name, values) => act('select_option', () => ({target: ui.ref(snapshot, role, name), values})),+ fill: fields => act('fill_form', () => {+ if (!Array.isArray(fields) || !fields.length) throw new Error('Expected at least one form field');+ const targets = new Set();+ return {fields: fields.map(({type, name, value}) => {+ const target = ui.ref(snapshot, type, name);+ if (targets.has(target)) throw new Error('Form field appears more than once');+ targets.add(target);+ return {target, type, name, value};+ })};+ }),+ });+ };+ return Object.freeze({observe: read});+ },+ window(pid, window_id) {+ const c = this.computer;+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(window_id) || window_id <= 0)+ throw new Error('A window requires positive numeric process and window identifiers');+ const view = (result, revision) => {+ const prefix = 'window_id=' + window_id + ' pid=' + pid + ' ';+ const state = result.content?.find(part => part.type === 'text' && part.text.startsWith(prefix));+ const text = state?.text ?? 'Window tree unavailable; inspect the result or observe again.';+ return Object.freeze({+ ...result, text,+ async click(role, name) {+ if (revision !== revisions.computer) throw new Error('Window observation expired; observe again');+ const stamp = /^.*?\\bsnapshot_id=(s[0-9a-f]+)\\b/.exec(text);+ const rows = [];+ for (const line of text.split('\\n')) {+ const match = /^\\s*(?:-\\s+)?\\[(\\d+)\\]\\s+(AX\\w+)\\s+("(?:[^"\\\\]|\\\\.)*")(?=\\s|$)/.exec(line);+ if (match && match[2] === role && match[3] === stringify(name)) rows.push(match[1]);+ }+ if (!stamp || rows.length !== 1) throw new Error('Expected one named window control with a snapshot token');+ const pending = c.click({pid, window_id, element_token: stamp[1] + ':' + rows[0]});+ const nextRevision = revisions.computer;+ return view(await pending, nextRevision);+ }+ });+ };+ const observe = async () => {+ const pending = c.get_window_state({pid, window_id});+ const revision = revisions.computer;+ return view(await pending, revision);+ };+ return Object.freeze({observe});+ },+ help(topic = "") {+ if (typeof topic !== 'string' || topic.length > 256) throw new Error('UI help requires a topic');+ return call(owner, 'help', topic, {});+ },+ emit(value) {+ if (owner !== epoch || !active || completed) throw new Error('UI execution is not active');+ const copy = clone(value), size = stringify(copy).length;+ if (outputSize + size > maxOutput) {+ failure = 'UI output exceeds byte limit'; throw new Error(failure);+ }+ outputSize += size; outputs.push(copy);+ }+ });+ Object.defineProperty(globalThis, 'state', { value: Object.create(null) });+ Object.defineProperty(globalThis, '__uiBridge', { value: Object.freeze({+ start(fn) {+ if (active || pending.size) throw new Error('UI runtime is busy');+ queue = []; outputs = []; outputSize = 0; next = 0;+ completed = false; failure = ''; finalValue = null; active = true;+ fn(makeUI(++epoch)).then(value => { finalValue = value; completed = true; }, error => {+ failure = errorText(error); completed = true;+ });+ },+ reply(text) {+ const message = parse(text), item = pending.get(message.id);+ if (!item) throw new Error('Unknown UI reply');+ pending.delete(message.id);+ if (typeof message.error === 'string') item.reject(new Error(message.error));+ else item.resolve(message.value);+ },+ drain() {+ if (failure) return stringify({ type: 'done', error: failure });+ if (completed) {+ if (pending.size) return stringify({ type: 'done', error: 'UI calls must be awaited before execution completes' });+ const value = clone(finalValue);+ if (outputSize + stringify(value).length > maxOutput) throw new Error('UI output exceeds byte limit');+ active = false;+ return stringify({ type: 'done', value, output: outputs });+ }+ if (queue.length) return stringify(queue.shift());+ return '';+ }+ }) });+})()`);+function pump() {+ if (dead || !active || waiting) return;+ if (process.memoryUsage().rss > limits.rssBytes)+ return fail("UI RSS supervision limit exceeded");+ const text = evaluate(drain);+ if (typeof text !== "string") throw new Error("Invalid UI bridge result");+ if (!text) return;+ if (Buffer.byteLength(text) >= limits.maxProtocolBytes)+ throw new Error("UI protocol frame exceeds byte limit");+ const message = JSON.parse(text);+ if (message.type === "call") waiting = message.id;+ else if (message.type === "done") active = false;+ else throw new Error("Invalid UI bridge message");+ send({ ...message, execution });+}+function receive(message) {+ if (dead) return;+ if (message.type === "exec") {+ if (+ active ||+ waiting ||+ typeof message.code !== "string" ||+ !Number.isSafeInteger(message.execution)+ )+ throw new Error("Invalid UI execution");+ execution = message.execution;+ active = true;+ evaluate(+ '__uiBridge.start(async function(ui) {\n"use strict";\n' ++ message.code ++ "\n})",+ );+ } else if (message.type === "reply") {+ if (+ !active ||+ !waiting ||+ message.execution !== execution ||+ message.id !== waiting+ )+ throw new Error("Invalid UI reply");+ waiting = 0;+ evaluate(+ "__uiBridge.reply(" + JSON.stringify(JSON.stringify(message)) + ")",+ );+ } else throw new Error("Invalid UI request");+ pump();+}+let input = Buffer.alloc(0);+process.stdin.on("data", (chunk) => {+ if (dead) return;+ try {+ input = Buffer.concat([input, chunk]);+ for (;;) {+ const end = input.indexOf(10);+ if (end === -1) break;+ if (end >= limits.maxProtocolBytes)+ throw new Error("UI protocol frame exceeds byte limit");+ const line = input.subarray(0, end).toString("utf8");+ input = input.subarray(end + 1);+ receive(JSON.parse(line));+ }+ if (input.length >= limits.maxProtocolBytes)+ throw new Error("UI protocol frame exceeds byte limit");+ } catch {+ fail("UI protocol or execution failed");+ }+});+process.stdin.on("end", () => {+ dead = true;+ process.exitCode = 0;+});+process.on("unhandledRejection", () =>+ fail("UI unhandled asynchronous rejection"),+);+const supervision = setInterval(() => {+ if (dead) {+ clearInterval(supervision);+ return;+ }+ try {+ if (process.memoryUsage().rss > limits.rssBytes)+ return fail("UI RSS supervision limit exceeded");+ pump();+ } catch {+ fail("UI execution exceeded its CPU or serialization budget");+ }+}, 10);+supervision.unref();+send({ type: "ready" });diff --git a/apps/computer/local-daemon/internal/uiruntime/runtime_test.go b/apps/computer/local-daemon/internal/uiruntime/runtime_test.gonew file mode 100644index 00000000..da70d5f5--- /dev/null+++ b/apps/computer/local-daemon/internal/uiruntime/runtime_test.go@@ -0,0 +1,513 @@+package uiruntime++import (+ "context"+ "encoding/json"+ "errors"+ "os/exec"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++func nodeRuntime(t *testing.T, dispatch func(context.Context, Call) (json.RawMessage, error), limits Limits) *Runtime {+ t.Helper()+ node, err := exec.LookPath("node")+ if err != nil {+ t.Skip("bundled-compatible Node is unavailable")+ }+ node, err = filepath.Abs(node)+ if err != nil {+ t.Fatal(err)+ }+ engineDir, err := filepath.Abs("../../../node_modules/quickjs-wasi")+ if err != nil {+ t.Fatal(err)+ }+ r, err := New(t.Context(), Options{NodePath: node, QuickJSDirectory: engineDir, Dispatch: dispatch, Limits: limits})+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := r.Close(ctx); err != nil {+ t.Error(err)+ }+ })+ return r+}+func noCalls(t *testing.T) func(context.Context, Call) (json.RawMessage, error) {+ return func(context.Context, Call) (json.RawMessage, error) {+ t.Error("unexpected dispatch")+ return nil, errors.New("unexpected dispatch")+ }+}+func execute(t *testing.T, r *Runtime, code string) Result {+ t.Helper()+ result, err := r.Exec(t.Context(), t.Context(), code)+ if err != nil {+ t.Fatal(err)+ }+ return result+}+func TestPersistentStateOpaqueOutputAndMethodDispatch(t *testing.T) {+ var calls []Call+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ calls = append(calls, c)+ return json.RawMessage(`{"image":{"handle":"opaque"},"answer":7}`), nil+ }, Limits{})+ first := execute(t, r, `const local = 9; state.answer = await ui.computer.inspect({app:"test"}); ui.emit(state.answer.image); return local;`)+ if string(first.Value) != "9" || len(first.Output) != 1 || string(first.Output[0]) != `{"handle":"opaque"}` {+ t.Fatalf("result=%+v", first)+ }+ second := execute(t, r, `return [state.answer.answer, typeof local];`)+ if string(second.Value) != `[7,"undefined"]` || second.Generation != first.Generation {+ t.Fatalf("result=%+v", second)+ }+ execute(t, r, `await ui.browser.click({ref:"node"}); await ui.help("browser");`)+ if len(calls) != 3 || calls[0].Namespace != "computer" || calls[1].Namespace != "browser" || calls[2].Namespace != "help" || calls[2].Method != "browser" || calls[0].Generation != first.Generation || calls[0].ExecutionID == calls[1].ExecutionID {+ t.Fatalf("calls=%+v", calls)+ }+ if err := r.Reset(t.Context()); err != nil {+ t.Fatal(err)+ }+ reset := execute(t, r, `return typeof state.answer;`)+ if string(reset.Value) != `"undefined"` || reset.Generation <= first.Generation {+ t.Fatalf("reset=%+v", reset)+ }+}+func TestSerialAwaitedCallsAndGuestErrorHandling(t *testing.T) {+ var calls atomic.Int32+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ calls.Add(1)+ if c.Method == "fail" {+ return nil, errors.New("fixture rejected")+ }+ return c.Arguments, nil+ }, Limits{})+ result := execute(t, r, `const a = await Promise.all([ui.browser.read({id:1}), ui.browser.read({id:2})]); let message; try {await ui.computer.fail({});} catch (error) {message = error.message;} return {a,message};`)+ if calls.Load() != 3 || !strings.Contains(string(result.Value), "fixture rejected") {+ t.Fatalf("result=%s calls=%d", result.Value, calls.Load())+ }+}+func TestGuestHasNoHostAuthorityOrDynamicCode(t *testing.T) {+ t.Setenv("NODE_OPTIONS", "--invalid-option-must-not-be-inherited")+ t.Setenv("UI_SECRET_FIXTURE", "not-for-the-child")+ r := nodeRuntime(t, noCalls(t), Limits{})+ result := execute(t, r, `const results = [typeof process, typeof require, typeof Buffer, typeof fetch, typeof setTimeout];+ for (const fn of [() => Function("return 1")(), () => ui.emit.constructor("return process")(), () => state.constructor.constructor("return process")()]) {+ try {fn(); results.push("escaped");} catch {results.push("denied");}+ }+ try {await import("node:fs"); results.push("imported");} catch {results.push("denied");}+ return results;`)+ if strings.Contains(string(result.Value), "escaped") || strings.Contains(string(result.Value), "imported") || string(result.Value) != `["undefined","undefined","undefined","undefined","undefined","denied","denied","denied","denied"]` {+ t.Fatal(string(result.Value))+ }+}+func TestUnawaitedCallsCannotReachAnotherExecution(t *testing.T) {+ var calls atomic.Int32+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ calls.Add(1)+ return json.RawMessage(`{}`), nil+ }, Limits{})+ generation := r.Generation()+ _, err := r.Exec(t.Context(), t.Context(), `ui.browser.write({}); return "done";`)+ if err == nil || !strings.Contains(err.Error(), "awaited") || calls.Load() != 0 || r.Generation() <= generation {+ t.Fatalf("err=%v calls=%d", err, calls.Load())+ }+ execute(t, r, `return "fresh";`)+ if calls.Load() != 0 {+ t.Fatal("detached call leaked")+ }+ _, err = r.Exec(t.Context(), t.Context(), `await ui.browser.read({}); ui.browser.write({});`)+ if err == nil || calls.Load() != 1 {+ t.Fatalf("err=%v calls=%d", err, calls.Load())+ }+}+func TestSchedulingCancellationDrainsOneDispatch(t *testing.T) {+ entered, release := make(chan struct{}), make(chan struct{})+ var calls atomic.Int32+ r := nodeRuntime(t, func(ctx context.Context, c Call) (json.RawMessage, error) {+ calls.Add(1)+ close(entered)+ select {+ case <-ctx.Done():+ return nil, errors.New("scheduling cancellation reached dispatch")+ case <-release:+ }+ return json.RawMessage(`{"completed":true}`), nil+ }, Limits{})+ scheduling, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() {+ _, err := r.Exec(t.Context(), scheduling, `await ui.browser.write({}); await ui.browser.write({});`)+ done <- err+ }()+ select {+ case <-entered:+ case <-time.After(10 * time.Second):+ t.Fatal("no callback")+ }+ before := r.Generation()+ cancel()+ deadline := time.After(3 * time.Second)+ for r.Generation() == before {+ select {+ case <-deadline:+ t.Fatal("guest not invalidated while dispatch drained")+ default:+ time.Sleep(time.Millisecond)+ }+ }+ if _, err := r.Exec(t.Context(), t.Context(), `return 1;`); !errors.Is(err, ErrBusy) {+ t.Fatalf("exec while draining: %v", err)+ }+ if err := r.Reset(t.Context()); !errors.Is(err, ErrBusy) {+ t.Fatalf("reset while draining: %v", err)+ }+ select {+ case err := <-done:+ t.Fatalf("returned before dispatch receipt: %v", err)+ default:+ }+ close(release)+ select {+ case err := <-done:+ if !errors.Is(err, context.Canceled) {+ t.Fatal(err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("did not finish")+ }+ if calls.Load() != 1 {+ t.Fatal("scheduled after cancellation")+ }+ execute(t, r, `return 2;`)+}+func TestHardCancellationReachesDispatchedCallback(t *testing.T) {+ entered := make(chan struct{})+ r := nodeRuntime(t, func(ctx context.Context, c Call) (json.RawMessage, error) {+ close(entered)+ <-ctx.Done()+ return nil, context.Cause(ctx)+ }, Limits{})+ hard, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() { _, err := r.Exec(hard, t.Context(), `await ui.computer.write({});`); done <- err }()+ select {+ case <-entered:+ case <-time.After(10 * time.Second):+ t.Fatal("no dispatch")+ }+ cancel()+ select {+ case err := <-done:+ if !errors.Is(err, context.Canceled) {+ t.Fatal(err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("hard cancellation hung")+ }+}+func TestResourceFailuresInvalidateAndRecover(t *testing.T) {+ cases := []struct {+ name, code string+ limits Limits+ }{+ {"sync-loop", `for (;;) {}`, Limits{PumpTimeout: 20 * time.Millisecond}},+ {"microtask-loop", `await Promise.resolve(); for (;;) {}`, Limits{PumpTimeout: 20 * time.Millisecond}},+ {"pending-promise", `await new Promise(() => {});`, Limits{MaxWallTime: 200 * time.Millisecond}},+ {"output", `ui.emit("x".repeat(300));`, Limits{MaxOutputBytes: 128}},+ {"unicode-output", `ui.emit("\u2603".repeat(60));`, Limits{MaxOutputBytes: 128}},+ {"calls", `await ui.browser.read({}); await ui.browser.read({});`, Limits{MaxCalls: 1}},+ {"serialization-getter", `return { get value() { for (;;) {} } };`, Limits{PumpTimeout: 20 * time.Millisecond}},+ {"protocol-frame", `await ui.browser.read({text:"x".repeat(2000)});`, Limits{MaxProtocolBytes: 1024, MaxOutputBytes: 128}},+ {"cyclic-output", `const value = {}; value.self = value; ui.emit(value);`, Limits{}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ r := nodeRuntime(t, func(context.Context, Call) (json.RawMessage, error) { return json.RawMessage(`{}`), nil }, tc.limits)+ generation := r.Generation()+ _, err := r.Exec(t.Context(), t.Context(), tc.code)+ if err == nil || r.Generation() <= generation {+ t.Fatalf("error=%v generation=%d", err, r.Generation())+ }+ execute(t, r, `return 1;`)+ })+ }+}+func TestCodeBoundAndPrecancelDoNotDispatch(t *testing.T) {+ r := nodeRuntime(t, noCalls(t), Limits{MaxCodeBytes: 16})+ if _, err := r.Exec(t.Context(), t.Context(), strings.Repeat(" ", 17)); err == nil {+ t.Fatal("large code accepted")+ }+ cancelled, cancel := context.WithCancel(t.Context())+ cancel()+ if _, err := r.Exec(t.Context(), cancelled, `return 1;`); !errors.Is(err, context.Canceled) {+ t.Fatal(err)+ }+ execute(t, r, `return 1;`)+}+func TestConfigurationValidation(t *testing.T) {+ for _, opts := range []Options{+ {NodePath: "node", QuickJSDirectory: "/engine", Dispatch: noCalls(t)},+ {NodePath: "/node", QuickJSDirectory: "engine", Dispatch: noCalls(t)},+ {NodePath: "/node", QuickJSDirectory: "/engine"},+ {NodePath: "/node", QuickJSDirectory: "/engine", Dispatch: noCalls(t), Limits: Limits{MaxCalls: -1}},+ } {+ if _, err := New(t.Context(), opts); err == nil {+ t.Fatal("invalid configuration accepted")+ }+ }+}++func TestOldContinuationCannotDispatchInNewExecution(t *testing.T) {+ r := nodeRuntime(t, noCalls(t), Limits{})+ execute(t, r, `state.later = new Promise(resolve => {state.resolve = resolve;}); state.task = (async () => {await state.later; try {await ui.browser.click({});} catch {state.staleDenied = true;}})();`)+ result := execute(t, r, `state.resolve(); await state.task; return state.staleDenied;`)+ if string(result.Value) != "true" {+ t.Fatalf("stale continuation not denied: %s", result.Value)+ }+}++func TestHelpOverviewAndStaleHelper(t *testing.T) {+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ if c.Namespace != "help" || c.Method != "" {+ t.Errorf("unexpected call: %+v", c)+ }+ return json.RawMessage(`"overview"`), nil+ }, Limits{})+ execute(t, r, `state.data = 7; state.helper = () => ui.browser.click({}); return await ui.help();`)+ result := execute(t, r, `try {await state.helper(); return "bad";} catch {return state.data;}`)+ if string(result.Value) != "7" {+ t.Fatalf("result=%s", result.Value)+ }+}++func TestCloseRevokesActiveCallbackAndPreventsReuse(t *testing.T) {+ entered := make(chan struct{})+ r := nodeRuntime(t, func(ctx context.Context, _ Call) (json.RawMessage, error) {+ close(entered)+ <-ctx.Done()+ return nil, context.Cause(ctx)+ }, Limits{})+ done := make(chan error, 1)+ go func() { _, err := r.Exec(t.Context(), t.Context(), `await ui.browser.click({});`); done <- err }()+ select {+ case <-entered:+ case <-time.After(10 * time.Second):+ t.Fatal("no callback")+ }+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ if err := r.Close(ctx); err != nil {+ t.Fatal(err)+ }+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("execution error=%v", err)+ }+ if _, err := r.Exec(t.Context(), t.Context(), `return 1;`); !errors.Is(err, ErrClosed) {+ t.Fatalf("reuse error=%v", err)+ }+}++func TestUnconfirmedCleanupPreventsReplacement(t *testing.T) {+ r, err := New(t.Context(), Options{NodePath: "/fixture/node", QuickJSDirectory: "/fixture/quickjs", Dispatch: noCalls(t)})+ if err != nil {+ t.Fatal(err)+ }+ defer r.cancel()+ c := &child{exited: make(chan struct{}), ctx: context.Background()}+ ctx, cancel := context.WithCancel(t.Context())+ cancel()+ if err := r.reapContext(ctx, c); !errors.Is(err, ErrCleanupUnconfirmed) {+ t.Fatal(err)+ }+ if _, err := r.Exec(t.Context(), t.Context(), `return 1;`); !errors.Is(err, ErrCleanupUnconfirmed) {+ t.Fatalf("reopened after unknown cleanup: %v", err)+ }+ close(c.exited)+ if err := r.reapContext(t.Context(), c); err != nil {+ t.Fatal(err)+ }+ if _, err := r.Exec(t.Context(), t.Context(), `return 1;`); !errors.Is(err, ErrCleanupUnconfirmed) {+ t.Fatalf("poison was cleared: %v", err)+ }+}++func TestReferenceRequiresOneExactNamedControl(t *testing.T) {+ r := nodeRuntime(t, noCalls(t), Limits{})+ result := execute(t, r, `const snap = text => ({content:[{type:"text",text}]});+const row = '- button "Save" [active] [ref=e5]';+const found = ui.ref(snap('- button "Save draft" [ref=e6]\n'+row), 'button','Save');+let rejected = 0;+for(const text of [row+'\n'+row, '- heading "Save" [ref=e2]']){+ try { ui.ref(snap(text),'button','Save') } catch { rejected++ }+}+return [found,rejected];`)+ if string(result.Value) != `["e5",2]` {+ t.Fatalf("lookup: %s", result.Value)+ }+}++func TestReferenceHandlesPlaywrightQuotedKeys(t *testing.T) {+ r := nodeRuntime(t, noCalls(t), Limits{})+ result := execute(t, r, `const snap = text => ({content:[{type:'text',text}]});+const button = "- 'button \"Order #42: Jo''s\" [active] [ref=e4]'";+const field = "- 'textbox \"Menu: title\" [ref=e3]': Value";+const matched = [ui.ref(snap(button),'button',"Order #42: Jo's"), ui.ref(snap(field),'textbox','Menu: title')];+try { ui.ref(snap(button+'\n'+button),'button',"Order #42: Jo's"); } catch { matched.push('ambiguous'); }+return matched;`)+ if string(result.Value) != `["e4","e3","ambiguous"]` {+ t.Fatalf("quoted lookup: %s", result.Value)+ }+}++func TestWindowObservationRevalidatesBeforeClick(t *testing.T) {+ var clicks int+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ if c.Method == "get_window_state" {+ return json.RawMessage(`{"content":[{"type":"text","text":"window_id=8 pid=42 snapshot_id=s17\n - [4] AXButton \"Save\""}]}`), nil+ }+ if c.Method != "click" || !strings.Contains(string(c.Arguments), `"element_token":"s17:4"`) {+ t.Fatalf("unexpected call %s %s", c.Method, c.Arguments)+ }+ clicks+++ return json.RawMessage(`{}`), nil+ }, Limits{})+ result := execute(t, r, `const w=ui.window(42,8);const first=await w.observe(), second=await w.observe();try{await first.click("AXButton","Save");return false}catch{}await second.click("AXButton","Save");return true`)+ if string(result.Value) != "true" || clicks != 1 {+ t.Fatal(result, clicks)+ }+}++func TestPageObservationInvalidatedByRawBrowserCall(t *testing.T) {+ writes := 0+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ switch c.Method {+ case "snapshot":+ return json.RawMessage(`{"content":[{"type":"text","text":"- button \"Save\" [ref=e7]"}]}`), nil+ case "click":+ writes+++ if string(c.Arguments) != `{"target":"e7"}` {+ t.Fatal(string(c.Arguments))+ }+ default:+ t.Fatal(c.Method)+ }+ return json.RawMessage(`{}`), nil+ }, Limits{})+ result := execute(t, r, `const p=await ui.page(), old=await p.observe();await ui.browser.snapshot({});try{await old.click("button","Save");return false}catch{}await (await p.observe()).click("button","Save");return true`)+ if string(result.Value) != "true" || writes != 1 {+ t.Fatal(result, writes)+ }+}++func TestPageActionContinuesFromReceiptAndReadsMissingSnapshotOnce(t *testing.T) {+ var calls []string+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ calls = append(calls, c.Method)+ var text string+ switch len(calls) {+ case 1:+ text = "- textbox \"Reference\" [ref=e1]"+ case 2:+ if c.Method != "type" || string(c.Arguments) != `{"target":"e1","text":"AB"}` {+ return nil, errors.New("incorrect field")+ }+ text = "Input delivered"+ case 3:+ text = "- button \"Save\" [ref=e4]"+ case 4:+ if c.Method != "click" || string(c.Arguments) != `{"target":"e4"}` {+ return nil, errors.New("incorrect control")+ }+ text = "### Snapshot\n```yaml\n- heading \"Saved\"\n```"+ default:+ return nil, errors.New("unexpected driver call")+ }+ return json.Marshal(map[string]any{"content": []map[string]string{{"type": "text", "text": text}}})+ }, Limits{})+ result := execute(t, r, `const page=await ui.page(), first=await page.observe();+const typed=await first.type("textbox","Reference","AB");+try { await first.type("textbox","Reference","AB"); return false; } catch {}+const saved=await typed.click("button","Save");+return saved.text.includes('heading "Saved"') && typed.content[0].text === "Input delivered";`)+ if string(result.Value) != "true" || strings.Join(calls, ",") != "snapshot,type,snapshot,click" {+ t.Fatalf("calls=%v result=%+v", calls, result)+ }+}++func TestWindowActionUsesBoundReadbackAndRefusesAnotherWindow(t *testing.T) {+ var calls []string+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ calls = append(calls, c.Method)+ var args struct {+ PID int `json:"pid"`+ Window int `json:"window_id"`+ Token string `json:"element_token"`+ }+ if json.Unmarshal(c.Arguments, &args) != nil || args.PID != 42 || args.Window != 8 {+ return nil, errors.New("incorrect window")+ }+ var view string+ switch len(calls) {+ case 1:+ view = "window_id=8 pid=42 snapshot_id=s01\n- [3] AXButton \"Open\""+ case 2:+ if args.Token != "s01:3" {+ return nil, errors.New("incorrect first token")+ }+ view = "window_id=8 pid=42 snapshot_id=s02\n- [7] AXButton \"Save\""+ case 3:+ if args.Token != "s02:7" {+ return nil, errors.New("incorrect second token")+ }+ view = "window_id=9 pid=42 snapshot_id=s03\n- [7] AXButton \"Save\""+ default:+ return nil, errors.New("unexpected driver call")+ }+ return json.Marshal(map[string]any{"content": []map[string]string{{"type": "text", "text": view}}})+ }, Limits{})+ result := execute(t, r, `const w=ui.window(42,8), first=await w.observe(), second=await first.click("AXButton","Open");+try {await first.click("AXButton","Open"); return false;} catch {}+const other=await second.click("AXButton","Save");+try {await other.click("AXButton","Save"); return false;} catch {return true;}`)+ if string(result.Value) != "true" || strings.Join(calls, ",") != "get_window_state,click,click" {+ t.Fatalf("calls=%v result=%+v", calls, result)+ }+}++func TestFormBatchResolvesEveryTargetBeforeDispatch(t *testing.T) {+ var fills int+ r := nodeRuntime(t, func(_ context.Context, c Call) (json.RawMessage, error) {+ switch c.Method {+ case "snapshot":+ return json.RawMessage(`{"content":[{"type":"text","text":"- textbox \"ID\" [ref=e1]\n- combobox \"Route\" [ref=e2]"}]}`), nil+ case "fill_form":+ fills+++ if string(c.Arguments) != `{"fields":[{"target":"e1","type":"textbox","name":"ID","value":"12"},{"target":"e2","type":"combobox","name":"Route","value":"East"}]}` {+ t.Errorf("batch arguments: %s", c.Arguments)+ }+ return json.RawMessage(`{"content":[{"type":"text","text":"filled"}]}`), nil+ default:+ return nil, errors.New("unexpected method")+ }+ }, Limits{})+ result := execute(t, r, `let v=await (await ui.page()).observe();+const id={type:"textbox",name:"ID",value:"12"},route={type:"combobox",name:"Route",value:"East"};+for (const invalid of [[id,{...route,name:"Missing"}],[id,id]]) {+ try {await v.fill(invalid); return false;} catch {}+}+const after=await v.fill([id,route]);+try {await v.fill([id]);return false;} catch {}+return after.text.includes("Route");`)+ if string(result.Value) != "true" || fills != 1 {+ t.Fatalf("batch count=%d result=%+v", fills, result)+ }+}diff --git a/apps/computer/package.json b/apps/computer/package.jsonindex 1200a71e..f50a43e8 100644--- a/apps/computer/package.json+++ b/apps/computer/package.json@@ -18,7 +18,8 @@},"dependencies": {"@earendil-works/pi-coding-agent": "1.2.0",- "@playwright/mcp": "0.0.83"+ "@playwright/mcp": "0.0.83",+ "quickjs-wasi": "3.6.2"},"devDependencies": {"@types/node": "26.0.1",diff --git a/apps/computer/scripts/bundle-computer-tools.mjs b/apps/computer/scripts/bundle-computer-tools.mjsindex a3f6bee6..76394812 100644--- a/apps/computer/scripts/bundle-computer-tools.mjs+++ b/apps/computer/scripts/bundle-computer-tools.mjs@@ -26,7 +26,22 @@ export const COMPUTER_TOOL_VERSIONS = Object.freeze({playwright: "0.0.83",pi: "1.2.0",cua: "0.35.4",+ quickjs: "3.6.2",});+// The entry imports the three sibling modules. Plain scripts need no+// optional QuickJS extensions; the bundled Pi also loads the base VM.+const quickjsFiles = [+ "LICENSE",+ "package.json",+ "quickjs.wasm",+ "dist/index.js",+ "dist/extensions.js",+ "dist/version.js",+ "dist/wasi-shim.js",+];+export const QUICKJS_TOOL_ASSETS = Object.freeze(+ quickjsFiles.map((name) => `node_modules/quickjs-wasi/${name}`),+);// Pinned Cua desktop drivers per release target. Windows drives the signed-in// desktop through the standalone driver; it needs no app bundle or SDK.const cuaArchive = (name, sha256, entry, required) =>@@ -103,6 +118,15 @@ async function stagePackages(destination) {dereference: false,filter: (entry) => {const parts = path.relative(source, entry).split(path.sep);+ if (+ name === "quickjs-wasi" &&+ manifest.version === COMPUTER_TOOL_VERSIONS.quickjs+ ) {+ const relative = parts.join("/");+ return (+ !relative || relative === "dist" || quickjsFiles.includes(relative)+ );+ }return (!parts.some((part) =>[@@ -141,6 +165,7 @@ async function stagePackages(destination) {}}for (const [name, version] of [+ ["quickjs-wasi", COMPUTER_TOOL_VERSIONS.quickjs],["@playwright/mcp", COMPUTER_TOOL_VERSIONS.playwright],["@earendil-works/pi-coding-agent", COMPUTER_TOOL_VERSIONS.pi],]) {@@ -409,6 +434,7 @@ export async function validatedComputerToolAssets(bundle, target) {for (const required of [manifest.playwright_entry,manifest.pi_extension,+ ...QUICKJS_TOOL_ASSETS,...(CUA_ARCHIVES[target]?.required ?? []),]) {if (!required || !expected.some((asset) => asset.path === required))diff --git a/apps/desktop/packaging/computer_tools_test.py b/apps/desktop/packaging/computer_tools_test.pyindex 6be8d466..91303775 100644--- a/apps/desktop/packaging/computer_tools_test.py+++ b/apps/desktop/packaging/computer_tools_test.py@@ -26,9 +26,9 @@ HOST_FIXTURE_TARGET = "win32-x64" if os.name == "nt" else "linux-x64"# The pins the shared validator holds the manifest to.FROZEN = json.loads(subprocess.check_output(["node", "--input-type=module", "-e",- "import { COMPUTER_TOOL_VERSIONS as versions, CUA_ARCHIVES as cua } from "+ "import { COMPUTER_TOOL_VERSIONS as versions, CUA_ARCHIVES as cua, QUICKJS_TOOL_ASSETS as quickjs } from "+ json.dumps("file://" + os.path.join(HERE, "..", "..", "..", "scripts", "computer-tool-bundle.mjs"))- + "; console.log(JSON.stringify({ versions, cua }))",+ + "; console.log(JSON.stringify({ versions, cua, quickjs }))",]))@@ -46,6 +46,8 @@ def stage(root, target):"node_modules/native/prebuilt.node": MACHO,}cua = FROZEN["cua"].get(target, {})+ for relative in FROZEN["quickjs"]:+ files[relative] = b"engine"for relative in cua.get("required", []):files[relative] = MACHO + relative.encode()assets = []@@ -159,7 +161,8 @@ class ComputerToolsTest(unittest.TestCase):archive = os.path.join(self.root, "Linger.tar.gz")with tarfile.open(archive, "w:gz") as out:out.add(app, arcname="Linger")- self.assertEqual(computer_tools.verify_archive(archive, "Linger/resources/", "linux-x64"), 3)+ self.assertEqual(computer_tools.verify_archive(archive, "Linger/resources/", "linux-x64"),+ 3 + len(FROZEN["quickjs"]))resources, _ = self.resources("win32-x64")archive = os.path.join(self.root, "Linger.zip")@@ -168,7 +171,8 @@ class ComputerToolsTest(unittest.TestCase):for name in files:path = os.path.join(root, name)out.write(path, "Linger/resources/" + os.path.relpath(path, resources))- self.assertEqual(computer_tools.verify_archive(archive, "Linger/resources/", "win32-x64"), 4)+ self.assertEqual(computer_tools.verify_archive(archive, "Linger/resources/", "win32-x64"),+ 4 + len(FROZEN["quickjs"]))bare = os.path.join(self.root, "bare.tar.gz")with tarfile.open(bare, "w:gz") as out:diff --git a/apps/node-services/release-lockfiles/computer.yaml b/apps/node-services/release-lockfiles/computer.yamlindex 16993a01..4c5defec 100644--- a/apps/node-services/release-lockfiles/computer.yaml+++ b/apps/node-services/release-lockfiles/computer.yaml@@ -20,6 +20,9 @@ importers:"@playwright/mcp":specifier: 0.0.83version: 0.0.83+ quickjs-wasi:+ specifier: 3.6.2+ version: 3.6.2devDependencies:"@types/node":specifier: 26.0.1diff --git a/docs/desktop-release.md b/docs/desktop-release.mdindex 4f05f1fd..1ce23fd7 100644--- a/docs/desktop-release.md+++ b/docs/desktop-release.md@@ -405,8 +405,10 @@ daemon from `resources/computer/`, so every package carries them asdependency package: the Node.js archive checksums in`scripts/local-computer-node-distributions.mjs`, the Cua driver checksums in`apps/computer/scripts/bundle-computer-tools.mjs` and the frozen pnpm-lockfile. A source build keeps staged tools that still validate against the-manifest and the Node.js pin recorded beside them, and links+lockfile. The package includes the pinned QuickJS JavaScript engine and its+WebAssembly binary for `computer.ui_exec`. The validator checks the engine+version and requires its files in the manifest. A source build keeps staged+tools that still validate against the manifest and the Node.js pin, and links`dist/computer/cli` and `dist/computer/runtime` to this machine's tools; delete`dist/computer-tools/` to stage them again. `packaging/computer_tools.py`copies them into the app, checks them with the same validator and checks thediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 418d6762..b46cebea 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -122,6 +122,9 @@ importers:'@playwright/mcp':specifier: 0.0.83version: 0.0.83+ quickjs-wasi:+ specifier: 3.6.2+ version: 3.6.2devDependencies:'@types/node':specifier: 26.0.1diff --git a/scripts/check-plan.mjs b/scripts/check-plan.mjsindex 8a3eef49..ac312ae5 100644--- a/scripts/check-plan.mjs+++ b/scripts/check-plan.mjs@@ -28,6 +28,7 @@ export const EVERYTHING_PATHS = [];const COMPUTER_GO_PATHS = [+ "apps/computer/package.json","apps/computer/local-daemon/","apps/computer/run-test.sh","contracts/generated/go/runnergateway/",diff --git a/scripts/check-plan.test.ts b/scripts/check-plan.test.tsindex 768e53e0..7e8e8025 100644--- a/scripts/check-plan.test.ts+++ b/scripts/check-plan.test.ts@@ -63,6 +63,8 @@ describe("CI outputs", () => {".github/workflows/ci.yml",],"computer-go": [+ "apps/computer/package.json",+ "pnpm-lock.yaml","apps/computer/local-daemon/internal/daemon/daemon.go","apps/computer/run-test.sh","contracts/generated/go/runnergateway/types.go",diff --git a/scripts/computer-tool-bundle.d.mts b/scripts/computer-tool-bundle.d.mtsindex 0775b958..35791336 100644--- a/scripts/computer-tool-bundle.d.mts+++ b/scripts/computer-tool-bundle.d.mts@@ -1,4 +1,5 @@export const COMPUTER_TOOL_VERSIONS: Readonly<Record<string, string>>;+export const QUICKJS_TOOL_ASSETS: readonly string[];export const CUA_ARCHIVES: Readonly<Record<string, { readonly entry: string; readonly required: string[] }>>;diff --git a/scripts/computer-tool-bundle.mjs b/scripts/computer-tool-bundle.mjsindex 80f2256f..8163d513 100644--- a/scripts/computer-tool-bundle.mjs+++ b/scripts/computer-tool-bundle.mjs@@ -21,6 +21,7 @@ import { stagePinnedNodeRuntime } from "./prepare-local-computer-release.mjs";export {COMPUTER_TOOL_VERSIONS,CUA_ARCHIVES,+ QUICKJS_TOOL_ASSETS,} from "../apps/computer/scripts/bundle-computer-tools.mjs";export { NODE_RUNTIME_RELEASES } from "./local-computer-node-distributions.mjs";diff --git a/scripts/computer-tool-bundle.test.ts b/scripts/computer-tool-bundle.test.tsindex 4b9dc47a..92d6fbbd 100644--- a/scripts/computer-tool-bundle.test.ts+++ b/scripts/computer-tool-bundle.test.ts@@ -15,6 +15,8 @@ import { promisify } from "node:util";import { afterEach, describe, expect, it } from "vitest";import {+ COMPUTER_TOOL_VERSIONS,+ QUICKJS_TOOL_ASSETS,nodeRuntimeEntry,recordSignedComputerTools,validatedComputerToolBundle,@@ -46,6 +48,7 @@ async function stagedBundle(target: string) {"node_modules/@playwright/mcp/cli.js": Buffer.from("console.log(1)\n"),"node_modules/native/prebuilt.node": macho("native"),};+ for (const name of QUICKJS_TOOL_ASSETS) files[name] = Buffer.from("engine");if (target.startsWith("darwin-")) {files["cua/CuaDriver.app/Contents/MacOS/cua-driver"] = macho("app");files["cua/cua-driver"] = macho("driver");@@ -65,7 +68,7 @@ async function stagedBundle(target: string) {path.join(tools, "manifest.json"),JSON.stringify({schema_version: 1,- versions: { playwright: "0.0.83", pi: "1.2.0", cua: "0.35.4" },+ versions: COMPUTER_TOOL_VERSIONS,target,playwright_entry: "node_modules/@playwright/mcp/cli.js",pi_extension: "extensions/pi-mcp.mjs",@@ -120,6 +123,17 @@ describe("Computer tool bundle", () => {).rejects.toThrow("not executable");});+ it("invalidates a cache that predates the pinned QuickJS tool", async () => {+ const { bundle, tools } = await stagedBundle("linux-x64");+ const file = path.join(tools, "manifest.json");+ const manifest = JSON.parse(await readFile(file, "utf8"));+ delete manifest.versions.quickjs;+ await writeFile(file, JSON.stringify(manifest));+ await expect(+ validatedComputerToolBundle(bundle, "linux-x64"),+ ).rejects.toThrow("Invalid Computer tool manifest");+ });+it("records re-signed Mach-O files but keeps vendor-signed ones as they were", async () => {const { bundle, tools } = await stagedBundle("darwin-arm64");for (const name of ["node_modules/native/prebuilt.node", "cua/cua-driver"])diff --git a/scripts/prepare-local-computer-release.test.ts b/scripts/prepare-local-computer-release.test.tsindex 20a4c3f6..0a19d395 100644--- a/scripts/prepare-local-computer-release.test.ts+++ b/scripts/prepare-local-computer-release.test.ts@@ -16,6 +16,10 @@ import { promisify } from "node:util";import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it } from "vitest";+import {+ stageComputerTools,+ validatedComputerToolAssets,+} from "../apps/computer/scripts/bundle-computer-tools.mjs";import {parseReleaseArguments,@@ -166,6 +170,43 @@ describe("Local Computer release", () => {}});+ it("runs the base QuickJS engine from the staged tool bundle", async () => {+ const root = await temporaryDirectory();+ const target = "linux-x64";+ await stageComputerTools(root, { target });+ const assets = await validatedComputerToolAssets(root, target);+ const tools = "cli/computer-tools";+ const engine = tools + "/node_modules/quickjs-wasi/";+ expect(assets.filter((name: string) => name.startsWith(engine))).toEqual(+ [+ "LICENSE",+ "dist/extensions.js",+ "dist/index.js",+ "dist/version.js",+ "dist/wasi-shim.js",+ "package.json",+ "quickjs.wasm",+ ].map((name) => engine + name),+ );+ const { stdout } = await execFileAsync(+ process.execPath,+ [+ "--input-type=module",+ "-e",+ `+ import { readFile } from "node:fs/promises";+ import { QuickJS } from "quickjs-wasi";+ const wasm = await readFile("node_modules/quickjs-wasi/quickjs.wasm");+ using vm = await QuickJS.create({ wasm });+ using value = vm.evalCode("6 * 7");+ console.log(value.toNumber());+ `,+ ],+ { cwd: path.join(root, tools) },+ );+ expect(stdout.trim()).toBe("42");+ }, 120_000);+it("builds byte-identical, reproducible dependency archives from the same inputs", async () => {const root = await temporaryDirectory();const outputs = [path.join(root, "first"), path.join(root, "second")];diff --git a/scripts/test-support/computer-tool-assets.ts b/scripts/test-support/computer-tool-assets.tsindex ece5f924..3944153b 100644--- a/scripts/test-support/computer-tool-assets.ts+++ b/scripts/test-support/computer-tool-assets.ts@@ -1,6 +1,10 @@import { createHash } from "node:crypto";import { mkdir, writeFile } from "node:fs/promises";import path from "node:path";+import {+ COMPUTER_TOOL_VERSIONS,+ QUICKJS_TOOL_ASSETS,+} from "../computer-tool-bundle.mjs";// Installer tests already replace Node and Go with fixture executables. Keep// tool assets small here too; the real pinned packages have separate protocol@@ -13,6 +17,7 @@ export const stageFixtureComputerTools = async (const files = ["extensions/pi-mcp.mjs","node_modules/@playwright/mcp/cli.js",+ ...QUICKJS_TOOL_ASSETS,];if (target.startsWith("darwin-"))files.push("cua/cua-driver", "cua/CuaDriver.app/Contents/MacOS/cua-driver");@@ -34,7 +39,7 @@ export const stageFixtureComputerTools = async (path.join(root, "manifest.json"),JSON.stringify({schema_version: 1,- versions: { playwright: "0.0.83", pi: "1.2.0", cua: "0.35.4" },+ versions: COMPUTER_TOOL_VERSIONS,target,playwright_entry: "node_modules/@playwright/mcp/cli.js",pi_extension: "extensions/pi-mcp.mjs",