A desktop coding agent with free access to frontier models.
TypeScript
fix: computer use stays off once turned off
ogsamrat37e8e173ca49
diff --git a/apps/desktop/electron/computer-use-gate.mjs b/apps/desktop/electron/computer-use-gate.mjsnew file mode 100644index 00000000..5073e973--- /dev/null+++ b/apps/desktop/electron/computer-use-gate.mjs@@ -0,0 +1,28 @@+// Ordering for the computer-use host (computer-use.mjs), kept apart so it can be tested without Electron.+//+// - Starts: a start takes the generation when it begins; turning computer use off (or stopping the host) moves+// the generation on, so a start still in flight finds itself stale before it publishes anything (host, listener,+// host.json) and closes what it made.+// - State answers: each read of the local server's state takes a number when it is sent; an answer older than one+// already applied is dropped, so a slow or out-of-order answer can never bring back access a newer one took away.+export function createHostGate() {+ let generation = 0;+ let asked = 0;+ let applied = 0;+ return {+ /** The generation a start belongs to (take it before the first await). */+ begin: () => generation,+ /** Whether a start of `taken` may still publish. */+ current: (taken) => taken === generation,+ /** Off or stop: every start in flight is stale from now on. */+ revoke: () => { generation += 1; },+ /** A number for a state read, taken when it is sent. */+ ask: () => (asked += 1),+ /** Whether the answer to read `n` may be applied (and marks it applied). */+ fresh: (n) => {+ if (n < applied) return false;+ applied = n;+ return true;+ },+ };+}diff --git a/apps/desktop/electron/computer-use-gate.test.mjs b/apps/desktop/electron/computer-use-gate.test.mjsnew file mode 100644index 00000000..fa1aeba8--- /dev/null+++ b/apps/desktop/electron/computer-use-gate.test.mjs@@ -0,0 +1,61 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createHostGate } from "./computer-use-gate.mjs";++test("computer use gate: off during a start makes it stale, a later start is current", () => {+ const gate = createHostGate();+ const first = gate.begin();+ assert.equal(gate.current(first), true);+ gate.revoke(); // turned off while the first start awaits the host+ assert.equal(gate.current(first), false, "the first start must not publish");+ const second = gate.begin();+ assert.equal(gate.current(second), true);+ assert.equal(gate.current(first), false);+});++test("computer use gate: repeated starts after off never revive the old one", () => {+ const gate = createHostGate();+ const taken = [];+ for (let i = 0; i < 5; i += 1) { taken.push(gate.begin()); gate.revoke(); }+ assert.ok(taken.every((g) => !gate.current(g)));+});++test("computer use gate: an older state answer cannot undo a newer one", () => {+ const gate = createHostGate();+ const slowOn = gate.ask(); // sent first, answers late (still on)+ const quickOff = gate.ask(); // sent second, answers first (off)+ assert.equal(gate.fresh(quickOff), true);+ assert.equal(gate.fresh(slowOn), false, "the stale 'on' is dropped");+ const next = gate.ask();+ assert.equal(gate.fresh(next), true);+ assert.equal(gate.fresh(next), true, "the same answer may be applied again");+});++// The host start as computer-use.mjs runs it, with a fake host: off during the delayed start leaves nothing+// published (no host, no listener, no host.json), and the fake's close ran.+test("computer use gate: a delayed start turned off publishes nothing", async () => {+ const gate = createHostGate();+ const published = { host: null, listener: null, hostJson: null };+ const closed = [];+ let allowed = true;+ /** @type {(value: { id: string }) => void} */+ let release = () => {};+ const delayed = new Promise((resolve) => { release = resolve; });+ async function start() {+ const taken = gate.begin();+ const stale = () => !gate.current(taken) || !allowed;+ const created = await delayed;+ if (stale()) { closed.push("host"); return null; }+ const listener = { close: () => closed.push("listener") };+ if (stale()) { listener.close(); closed.push("host"); return null; }+ Object.assign(published, { host: created, listener, hostJson: "written" });+ return created;+ }+ const starts = [start(), start(), start()]; // repeated connections while the first start waits+ allowed = false; gate.revoke(); // the person turns computer use off+ release({ id: "host" });+ assert.deepEqual(await Promise.all(starts), [null, null, null]);+ assert.deepEqual(published, { host: null, listener: null, hostJson: null });+ assert.deepEqual(closed, ["host", "host", "host"]);+});diff --git a/apps/desktop/electron/computer-use.mjs b/apps/desktop/electron/computer-use.mjsindex 286076ee..c87f412a 100644--- a/apps/desktop/electron/computer-use.mjs+++ b/apps/desktop/electron/computer-use.mjs@@ -24,6 +24,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";import { app, BrowserWindow, clipboard, Notification, screen, session } from "electron";import { startAgentBrowser } from "./computer-use-agent-browser.mjs";import { testAnswersAllowed } from "./computer-use-answers.mjs";+import { createHostGate } from "./computer-use-gate.mjs";import { createComputerUseHost } from "./computer-use-host.mjs";import { createComputerPreview } from "./computer-use-preview.mjs";@@ -67,6 +68,8 @@ let deps = null;let server = null; // the last /computer-use/state answerlet host = null;let hostPromise = null;+// Starts in flight go stale on off/stop; older state answers never undo newer ones (computer-use-gate.mjs).+const gate = createHostGate();let listener = null;let preview = null;let shared = null;@@ -203,24 +206,33 @@ async function stopRealScreen() {else for (const s of host.state()) if (s.display !== "virtual" && s.phase !== "ended") await host.control({ session_id: s.id, action: "stop" }).catch(() => {});}+/** Whether the host may run now: the server says on, this OS can, and the person has not turned it off here. */+function allowedNow() {+ return server?.enabled === true && supported() && Boolean(shared?.policyModule) && deviceOn();+}+function hostSettings() {const setting = server?.setting ?? {};- return { enabled: server?.enabled === true, real_screen: serverRealScreen, real_screen_opt_in: serverRealScreen, real_screen_on: realScreenOn(), virtual_display: setting.virtual_display !== false, limits: setting.limits ?? null, deny_apps: setting.deny_apps ?? [], message: setting.message ?? null };+ return { enabled: allowedNow(), real_screen: serverRealScreen, real_screen_opt_in: serverRealScreen, real_screen_on: realScreenOn(), virtual_display: setting.virtual_display !== false, limits: setting.limits ?? null, deny_apps: setting.deny_apps ?? [], message: setting.message ?? null };}async function hostContext() {const metrics = (() => { try { return app.getAppMetrics().map((m) => m.pid); } catch { return []; } })();// The chat now (the one that just called), not the last poll's.+ const asked = gate.ask();const fresh = await serverFetch("/computer-use/state").catch(() => null);- if (fresh) server = fresh;+ if (fresh && gate.fresh(asked)) server = fresh;// No fresh answer: no chat, never the last poll's.return { ancestors: shared?.ancestors ?? [], self_pids: [process.pid, ...metrics], chat: fresh ? fresh.chat ?? null : null };}/** Before each open: the server's switch and limits read now (not a cached answer). False when unread. */async function hostRefresh() {+ const asked = gate.ask();const fresh = await serverFetch("/computer-use/refresh", { method: "POST", body: JSON.stringify({ max_age_ms: 0 }) }).catch(() => null);if (!fresh) { serverRealScreen = false; return false; }+ // An answer older than one already applied cannot give anything back.+ if (!gate.fresh(asked)) return false;server = fresh;// Only the server's answer just read can say yes; anything else is no.serverRealScreen = fresh.read === true && saysRealScreen(fresh);@@ -234,7 +246,16 @@ async function reportEvent(event) {async function startHost() {if (hostPromise) return hostPromise;- hostPromise = (async () => {+ const taken = gate.begin();+ // Turned off (or stopped) while this start was in flight: close what it made, publish nothing.+ const stale = () => !gate.current(taken) || !allowedNow();+ const abandon = async (made, madeListener) => {+ await madeListener?.close().catch(() => {});+ await made?.stopAll?.("server").catch(() => {});+ await made?.close?.().catch(() => {});+ throw Object.assign(new Error("Computer use is turned off."), { code: "computer_use_stale_start" });+ };+ const pending = (async () => {const { hostModule, mediaModule, policyModule, contractModule, imageModule, virtualModule, virtualWorker } = await sharedModules();const spool = server?.spool ? mediaModule.createMediaSpool(server.spool) : null;const onState = () => { pushStatus(); scheduleRefresh(); };@@ -261,6 +282,7 @@ async function startHost() {const nativeFactory = () => hostModule.createNativeWorker({ nodePath: process.execPath, nodeEnv: { ELECTRON_RUN_AS_NODE: "1" }, koffiPath: koffiPath() });created = await hostModule.createPortableHost({ native: nativeFactory(), nativeFactory, ...callbacks });}+ if (stale()) return abandon(created);preview = createComputerPreview();preview.bind(created);host = created;@@ -269,18 +291,27 @@ async function startHost() {realScreenNoticeShown = true;try { if (Notification.isSupported()) new Notification({ title: "Computer use can use your own screen", body: "The agent can click and type in your apps without asking. Stop it any time with Stop; turn it off in Settings > Computer use." }).show(); } catch { /* best effort */ }}- listener = await created.listen(path.join(profileDir(), "computer-use"));+ const madeListener = await created.listen(path.join(profileDir(), "computer-use"));+ // Checked again right before anything is published (host.json, the listener the relays find).+ if (stale()) { if (host === created) { host = null; preview?.close(); preview = null; } return abandon(created, madeListener); }+ listener = madeListener;const relay = app.isPackaged ? path.join(process.resourcesPath, "computer-use", "relay.mjs") : path.join(__dirname, "computer-use-relay.mjs");const command = [process.execPath, relay, listener.discoveryPath];const environment = { ELECTRON_RUN_AS_NODE: "1" };await serverFetch("/computer-use/host", { method: "POST", headers: secretHeaders, body: JSON.stringify({ command, environment }) });+ // Off while host.json was being written: take it back now.+ if (stale()) { await stopHost("server"); throw Object.assign(new Error("Computer use is turned off."), { code: "computer_use_stale_start" }); }pushStatus();return created;- })().catch((error) => { hostPromise = null; host = null; throw error; });- return hostPromise;+ })().catch((error) => { if (hostPromise === pending) { hostPromise = null; host = null; } throw error; });+ hostPromise = pending;+ return pending;}async function stopHost(by = "server") {+ // A start still in flight goes stale and closes what it made (startHost).+ gate.revoke();+ hostPromise = null;const current = host;await serverFetch("/computer-use/host", { method: "POST", headers: secretHeaders, body: JSON.stringify({ host: null }) }).catch(() => {});if (!current) return;@@ -303,8 +334,9 @@ async function apply(next) {if (!serverRealScreen) await stopRealScreen();const wanted = server?.enabled && supported() && deviceOn();if (wanted && !hostPromise && Date.now() - failedAt < 60_000) { pushStatus(); return; }- if (wanted) await startHost().catch((error) => { failedAt = Date.now(); deps?.log?.("computer use host did not start", error); });- else if (host) await stopHost("server");+ // A start made stale by off is no failure (the next on starts at once).+ if (wanted) await startHost().catch((error) => { if (error?.code === "computer_use_stale_start") return; failedAt = Date.now(); deps?.log?.("computer use host did not start", error); });+ else if (host || hostPromise) await stopHost("server");pushStatus();}@@ -314,7 +346,8 @@ function scheduleRefresh() {if (open && !refreshTimer) {refreshTimer = setInterval(() => {// A failed read is a no for the person's screen (fail closed); the agent's own display keeps running.- void serverFetch("/computer-use/refresh", { method: "POST", body: "{}" }).then(apply).catch(() => { serverRealScreen = false; void stopRealScreen(); });+ const asked = gate.ask();+ void serverFetch("/computer-use/refresh", { method: "POST", body: "{}" }).then((answer) => (gate.fresh(asked) ? apply(answer) : undefined)).catch(() => { serverRealScreen = false; void stopRealScreen(); });}, 60_000);refreshTimer.unref?.();} else if (!open && refreshTimer) {@@ -325,7 +358,7 @@ function scheduleRefresh() {/** Starts following the switch (main.mjs, once the local server runs). */export function initComputerUse(options) {deps = options;- const poll = () => void serverFetch("/computer-use/state").then(apply).catch(() => {});+ const poll = () => { const asked = gate.ask(); void serverFetch("/computer-use/state").then((answer) => (gate.fresh(asked) ? apply(answer) : undefined)).catch(() => {}); };poll();// The state route is local: the chat in use and the switch are read every few seconds.pollTimer = setInterval(poll, 5_000);@@ -373,8 +406,12 @@ async function computerUseControl(value) {function getComputerUseMcpEnvironment() { return { ELECTRON_RUN_AS_NODE: "1" }; }async function getComputerUseMcpCommand() {+ await sharedModules();+ // The person's off on this device counts as much as the server's: no host, listener or tools.if (!server?.enabled) throw new Error(server?.setting?.message ?? "Computer use is turned off.");+ if (!allowedNow()) throw new Error("Computer use is turned off on this computer.");await startHost();+ if (!listener || !allowedNow()) throw new Error("Computer use is turned off.");const relay = app.isPackaged ? path.join(process.resourcesPath, "computer-use", "relay.mjs") : path.join(__dirname, "computer-use-relay.mjs");// The copied CLI connection: its own token (cli-connection.json), so its calls belong to no chat of this app.// The engine's relay alone reads engine-connection.json.diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex eceed3b5..ec1b5844 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,7 +27,7 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/prepare-box-helpers.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/browser-task.test.mjs electron/background-rendering.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/window-size.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/build-variant.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/computer-use-agent-browser.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs electron/app-request-secret.test.mjs electron/disk-cleanup.test.mjs electron/lima-packaging.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/prepare-box-helpers.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/browser-task.test.mjs electron/background-rendering.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/window-size.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/build-variant.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/computer-use-gate.test.mjs electron/computer-use-agent-browser.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs electron/app-request-secret.test.mjs electron/disk-cleanup.test.mjs electron/lima-packaging.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},diff --git a/apps/server/src/computer-use/shared/PARITY.sha256 b/apps/server/src/computer-use/shared/PARITY.sha256index 7548ec1b..cc46a148 100644--- a/apps/server/src/computer-use/shared/PARITY.sha256+++ b/apps/server/src/computer-use/shared/PARITY.sha256@@ -2,7 +2,7 @@# A change to one must be ported to the other and this list updated in both.da1cc6c26f3bf6758d3e2ce70e87bce383f68ee0ec6c85bbdc33b1f9a6c407fa contract.mjs30cfcead85a5b2b54005ba6a0a67a43d9950de944b4615861ce9342bf043d4a4 contract.d.mts-324712aabed354250269e6e517beed77876c1bdab8aeb1452b078cd2bfa6a1b9 policy.mjs+504c328799cbacfb1407448235b54d82b22ef48c9d5c8daf865f859f851fd039 policy.mjse5807c6426f21853825a7db9248882da11dffa1fef9f3499a665f39e752dbbb0 policy.d.mtsda515baa8aec2b533685d20c2be7ae007acc6b116db0386f8180e6779cb80f5c image.mjs7c1a3224b7efd215656a94c38cf3152fe7a2444f25a6162988528978acf5458d image.d.mtsdiff --git a/apps/server/src/computer-use/shared/policy.mjs b/apps/server/src/computer-use/shared/policy.mjsindex 874d395c..49ace5db 100644--- a/apps/server/src/computer-use/shared/policy.mjs+++ b/apps/server/src/computer-use/shared/policy.mjs@@ -177,12 +177,16 @@ export const REAL_SCREEN_OFF_MESSAGE = "Computer use on the person's own screen/*** Engine permission rules for every mode (computer use on or off): the agent can neither run the command that- * turns the real screen on nor write the setting. Appended after the mode's own rules (the last match wins); the- * engine's matcher treats \\ as / (Windows paths match too).+ * turns the real screen on nor write the person's settings (real-screen.json, and device.json with the device's+ * on/off), so it can never undo the person's choice for the next start. Appended after the mode's own rules (the+ * last match wins); the engine's matcher treats \\ as / (Windows paths match too).*/export const REAL_SCREEN_DENY_RULES = Object.freeze({- bash: Object.freeze({ "*computer real-screen*": "deny", "*computerUseRealScreen*": "deny", "*OMNIRUSH_COMPUTER_USE_REAL_SCREEN*": "deny", "*computer-use/real-screen.json*": "deny" }),- edit: Object.freeze({ "*computer-use/real-screen.json": "deny" }),+ bash: Object.freeze({+ "*computer real-screen*": "deny", "*computerUseRealScreen*": "deny", "*OMNIRUSH_COMPUTER_USE_REAL_SCREEN*": "deny", "*computer-use/real-screen.json*": "deny",+ "*computer-use*real-screen.json*": "deny", "*computer-use*device.json*": "deny", "*\"computerUse\"*": "deny", "*computerUse\\\"*": "deny",+ }),+ edit: Object.freeze({ "*computer-use/real-screen.json": "deny", "*computer-use/device.json": "deny" }),});/**