Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Lent screen: say the real reason it is busy, free stale holds, and let bots work while the person does (#3721)

Milind Soniae1aada6b67b
diff --git a/electron/cloud-lending.node-test.mjs b/electron/cloud-lending.node-test.mjs
index a76200556e..1d416dbe94 100644
--- a/electron/cloud-lending.node-test.mjs
+++ b/electron/cloud-lending.node-test.mjs
@@ -7,6 +7,7 @@ import { randomUUID } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import { cloudLendingVerdict, createComputerSharing } from "./computer-sharing.mjs";
import { createLendingIndicator } from "./lending-indicator.mjs";
+import { PERSON_AWAY_SECONDS, personActiveText } from "./lent-screen-presence.mjs";
const ORIGIN = "https://omb-u-fixture.fly.dev";
const binding = { accountId: "acct_1", origin: ORIGIN };
@@ -93,7 +94,7 @@ async function lendingFixture(t, options = {}) {
// The maintainer flag is off, as for every Cloud Pro user.
enabled: async () => { maintainerChecks++; return false; },
cloud: () => cloud, home: path.join(dir, "home"),
- cuaConnection: async () => driver.connection,
+ cuaConnection: async () => driver.connection, ...(options.idleSeconds ? { idleSeconds: options.idleSeconds } : {}),
hostControl: options.hostControl ?? (async id => { leases.push(`acquire:${id}`); return { renew: async () => {}, release: async () => { leases.push(`release:${id}`); } }; }),
onChange: summary => summaries.push(summary),
});
@@ -280,6 +281,32 @@ for (const stalled of ["the Cloud's lease answer", "the renew"]) {
});
}
+test("while the person uses this computer, background screen calls run and one that would take their mouse waits, with the reason", async t => {
+ let idle = 0;
+ const { home, sharing, driver, leases } = await lendingFixture(t, { idleSeconds: () => idle });
+ await sharing.saveCloud(env, { folders: [], screen: true });
+ await connected(sharing, 1, home);
+ const run = async operation => {
+ const before = home.results.length;
+ home.push(operation);
+ await until(() => home.results.length === before + 1, operation.tool_name ?? operation.action);
+ return home.results.at(-1);
+ };
+ // Listing the tools never touches the screen, so it takes no screen lock.
+ assert.notEqual((await run({ action: "computer_tools" })).isError, true);
+ assert.deepEqual(leases, []);
+ assert.notEqual((await run({ action: "computer_call", tool_name: "click", arguments: { pid: 42, window_id: 7, element_index: 3 } })).isError, true);
+ for (const args of [{ x: 5, y: 5 }, { pid: 42, window_id: 7, x: 5, y: 5, delivery_mode: "foreground" }]) {
+ const refused = await run({ action: "computer_call", tool_name: "click", arguments: args });
+ assert.equal(refused.isError, true);
+ assert.equal(refused.content[0].text, personActiveText("click"));
+ }
+ assert.equal(leases.filter(entry => entry.startsWith("acquire:")).length, 1, "a refused call never takes the screen");
+ assert.equal((await readFile(driver.calls, "utf8")).trim().split("\n").length, 1, "nor reaches the driver");
+ idle = PERSON_AWAY_SECONDS;
+ assert.notEqual((await run({ action: "computer_call", tool_name: "click", arguments: { x: 5, y: 5 } })).isError, true);
+});
+
test("another Cloud account or another machine ends lending; a sign-in that needs renewing only pauses it", async t => {
{
const { folderPath, home, sharing, setCloud } = await lendingFixture(t);
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mts
index ada511dcff..f8c5b34515 100644
--- a/electron/computer-sharing.d.mts
+++ b/electron/computer-sharing.d.mts
@@ -77,6 +77,9 @@ export function createComputerSharing(options: {
hostControl?: (id: string, signal: AbortSignal) => Promise<{ renew(): Promise<unknown>; release(): Promise<unknown> }>;
/** The OS reports the screen locked: a screen action is refused with the fix instead of failing in the driver. */
screenLocked?: () => boolean;
+ /** Seconds since the person last touched this computer, or null when the system cannot tell: while they are using it,
+ * a lent screen call that would take their mouse, keyboard or front window waits, and background calls run. */
+ idleSeconds?: () => number | null;
/** Home directory whose credential and autostart locations are protected. */
home?: string;
activityFile?: string;
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index 124ce52788..7ba2d2deac 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -9,6 +9,7 @@ import { sharedCuaConnection } from "./shared-cua-connection.mjs";
export { sharedCuaConnection };
import { createLendingActivity, describeSharedOperation } from "./lending-activity.mjs";
import { cuaUnavailable, SCREEN_LOCKED } from "./lent-screen-failures.mjs";
+import { createLentScreenPresence } from "./lent-screen-presence.mjs";
import { BACKGROUND_HEADERS, CloudAsleepError, asleepAnswer, createCloudPowerGate } from "./cloud-power.mjs";
import { linkUrl, runDeviceLink } from "./device-link.mjs";
import { LINK_ASLEEP, linkPath } from "./device-link-protocol.mjs";
@@ -151,10 +152,11 @@ const BROWSE_NOTE_MS = 10 * 60_000;
* resumes by itself; at most every 15 minutes. `linkHeaders(env)`: the device link's sign-in, as the poll's fetch
* carries it (the session cookie). `myCloud()`: the saved server that is the person's own My Cloud, which gets this
* computer's internet connection by default (internetByDefault). */
-export function createComputerSharing({ file, fetch: fetchImpl, environments, cuaConnection, hostControl, screenLocked = () => false, protectedPaths = [], enabled = async () => false, home = os.homedir(), activityFile, cloud = () => null, onChange = () => {}, reconnect = null, now = Date.now, power = createCloudPowerGate(),
+export function createComputerSharing({ file, fetch: fetchImpl, environments, cuaConnection, hostControl, screenLocked = () => false, idleSeconds = () => null, protectedPaths = [], enabled = async () => false, home = os.homedir(), activityFile, cloud = () => null, onChange = () => {}, reconnect = null, now = Date.now, power = createCloudPowerGate(),
linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, myCloud = () => null }) {
const protectedRoots = [path.dirname(file), ...protectedPaths.filter(entry => typeof entry === "string" && entry), ...personalSecretPaths(home)];
const activity = createLendingActivity(activityFile ?? path.join(path.dirname(file), "lending-activity.jsonl"));
+ const presence = createLentScreenPresence({ idleSeconds, now });
let records = {};
try {
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -389,8 +391,11 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
let result;
try {
await lease(); jobSignal.throwIfAborted();
- if (grant.computer && ["computer_tools", "computer_call"].includes(job.operation.action)) {
- if (job.operation.action === "computer_call" && screenLocked()) throw new Error(SCREEN_LOCKED);
+ // Listing the tools never touches the screen, so only a call takes this computer's screen lock.
+ if (grant.computer && job.operation.action === "computer_call") {
+ if (screenLocked()) throw new Error(SCREEN_LOCKED);
+ const waits = presence.refusal(job.operation.tool_name, job.operation.arguments);
+ if (waits) throw new Error(waits);
if (!hostControl) throw new Error("The local computer control gate is unavailable");
control = await hostControl(job.id, jobSignal);
jobSignal.throwIfAborted();
@@ -408,6 +413,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
} catch (error) { result = sharedComputerError(error); live.cua?.close(); live.cua = null; }
finally {
clearInterval(heartbeat); ended = true;
+ if (control) presence.acted(job.operation.tool_name, job.operation.arguments);
await renewal?.catch(() => {});
await control?.release().catch(() => {});
executing = null; changed();
diff --git a/electron/host-screen-lease.d.mts b/electron/host-screen-lease.d.mts
new file mode 100644
index 0000000000..0c6ac02c7e
--- /dev/null
+++ b/electron/host-screen-lease.d.mts
@@ -0,0 +1,9 @@
+/** Said when the desktop's own server could not answer whether its screen is free: never a person. */
+export function screenCheckFailedText(detail: string): string;
+/** `hostControl` for createComputerSharing: this computer's screen lock, taken from the desktop's own server. */
+export function createHostScreenLease(options: {
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
+ url: () => string;
+ headers?: () => Record<string, string>;
+ timeoutMs?: number;
+}): (id: string, signal: AbortSignal) => Promise<{ renew(): Promise<void>; release(): Promise<void> }>;
diff --git a/electron/host-screen-lease.mjs b/electron/host-screen-lease.mjs
new file mode 100644
index 0000000000..d766bb0b52
--- /dev/null
+++ b/electron/host-screen-lease.mjs
@@ -0,0 +1,42 @@
+// This computer's screen lock, which the desktop's own server keeps: a lent screen call from the person's Cloud takes
+// it for as long as the call runs, so the desktop's own bots and that call never use the screen at once. Each refusal
+// says its real reason, because a bot told "a person is using it" waits for a person who is not there.
+
+/** The server did not answer the check, or answered something that is not "busy": nobody is using the computer. */
+export function screenCheckFailedText(detail) {
+ return `OpenMausBot on this computer could not check whether its screen is free (${detail}), so this call was not performed. ` +
+ "This is not a person using the computer. Try again in a few seconds; if it keeps happening, tell the person to quit and reopen OpenMausBot on that computer.";
+}
+
+async function refusal(response) {
+ const body = await response.json().catch(() => null);
+ const said = typeof body?.error === "string" && body.error.trim() ? body.error.trim().slice(0, 500) : "";
+ // A busy screen (409) and an organization's policy (403 managed_policy) are real answers: they reach the bot as said.
+ if (said && (response.status === 409 || body?.code === "managed_policy")) return said;
+ return screenCheckFailedText(`its server answered ${response.status}${said ? `: ${said.slice(0, 200)}` : ""}`);
+}
+
+/** `hostControl` for createComputerSharing. `url()` is the local server's lease route, read per call because the
+ * desktop's server can move to another port; `headers()` carries the desktop's own capability. */
+export function createHostScreenLease({ fetch: fetchImpl = globalThis.fetch, url, headers = () => ({}), timeoutMs = 3000 }) {
+ return async (id, signal) => {
+ const lease = async action => {
+ let response;
+ try {
+ response = await fetchImpl(url(), {
+ method: "POST",
+ headers: { ...headers(), "content-type": "application/json" },
+ body: JSON.stringify({ id, action }),
+ signal: action === "release" ? AbortSignal.timeout(timeoutMs) : AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
+ });
+ } catch (error) {
+ if (signal.aborted && action !== "release") throw error;
+ throw new Error(screenCheckFailedText(error?.name === "TimeoutError" ? `its server did not answer within ${timeoutMs / 1000} seconds` : "its server could not be reached"));
+ }
+ if (!response.ok) throw new Error(await refusal(response));
+ await response.body?.cancel?.().catch(() => {});
+ };
+ await lease("acquire");
+ return { renew: () => lease("acquire"), release: () => lease("release") };
+ };
+}
diff --git a/electron/host-screen-lease.node-test.mjs b/electron/host-screen-lease.node-test.mjs
new file mode 100644
index 0000000000..c68773bfd9
--- /dev/null
+++ b/electron/host-screen-lease.node-test.mjs
@@ -0,0 +1,51 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { createHostScreenLease, screenCheckFailedText } from "./host-screen-lease.mjs";
+
+const answer = (status, body) => async () => new Response(body === undefined ? "" : JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+const lease = fetch => createHostScreenLease({ fetch, url: () => "http://127.0.0.1:1/api/desktop/shared-computer-control", timeoutMs: 200 });
+const refusal = async fetch => {
+ try { await lease(fetch)("5d0c7a39-2b39-4b07-9a0e-0c58a7d55f21", new AbortController().signal); } catch (error) { return error.message; }
+ return null;
+};
+
+test("a busy screen and an organization's policy reach the bot as the server said them", async () => {
+ const busy = "Another bot on this computer, Researcher, is using its screen right now, so this call was not performed. It is not a person.";
+ assert.equal(await refusal(answer(409, { error: busy, code: "bot" })), busy);
+ assert.equal(await refusal(answer(403, { error: "Acme does not allow bots to use this computer.", code: "managed_policy" })), "Acme does not allow bots to use this computer.");
+});
+
+test("a screen check that fails says so, and never that a person is using the computer", async () => {
+ const cases = [
+ [answer(404, { error: "no route: POST /api/desktop/shared-computer-control" }), /its server answered 404: no route/],
+ [answer(403, { error: "Local desktop only" }), /its server answered 403: Local desktop only/],
+ [answer(401, { error: "unauthorized" }), /its server answered 401/],
+ [answer(500), /its server answered 500\)/],
+ [answer(400, { error: "Invalid computer lease" }), /its server answered 400/],
+ [async () => { throw new TypeError("fetch failed"); }, /its server could not be reached/],
+ [(_url, init) => new Promise((_resolve, reject) => init.signal.addEventListener("abort", () => reject(init.signal.reason))), /its server did not answer within 0.2 seconds/],
+ ];
+ for (const [fetch, detail] of cases) {
+ const said = await refusal(fetch);
+ assert.match(said, detail);
+ assert.match(said, /^OpenMausBot on this computer could not check whether its screen is free \(.*\), so this call was not performed\. This is not a person using the computer\./);
+ assert.doesNotMatch(said, /held by a person|in use locally/);
+ }
+ assert.match(screenCheckFailedText("x"), /quit and reopen OpenMausBot/);
+});
+
+test("an acquired lease renews with acquire and releases, sending the desktop's own capability", async () => {
+ const sent = [];
+ const fetch = async (url, init) => { sent.push([url, init.headers["X-Test"], JSON.parse(init.body).action]); return new Response("{\"ok\":true}", { status: 200 }); };
+ const control = await createHostScreenLease({ fetch, url: () => "http://127.0.0.1:9/lock", headers: () => ({ "X-Test": "cap" }) })("id", new AbortController().signal);
+ await control.renew(); await control.release();
+ assert.deepEqual(sent, [["http://127.0.0.1:9/lock", "cap", "acquire"], ["http://127.0.0.1:9/lock", "cap", "acquire"], ["http://127.0.0.1:9/lock", "cap", "release"]]);
+});
+
+test("a call ended by its own turn passes the abort on instead of blaming the server", async () => {
+ const stop = new AbortController();
+ const fetch = (_url, init) => new Promise((_resolve, reject) => init.signal.addEventListener("abort", () => reject(init.signal.reason)));
+ const pending = lease(fetch)("id", stop.signal);
+ stop.abort(new Error("the turn ended"));
+ await assert.rejects(pending, /the turn ended/);
+});
diff --git a/electron/lent-screen-presence.d.mts b/electron/lent-screen-presence.d.mts
new file mode 100644
index 0000000000..c3ad4e3af7
--- /dev/null
+++ b/electron/lent-screen-presence.d.mts
@@ -0,0 +1,8 @@
+export const PERSON_AWAY_SECONDS: number;
+/** Whether a lent screen call would take the person's mouse, keyboard or front window. */
+export function takesForeground(name: string, args: unknown): boolean;
+export function personActiveText(name: string): string;
+export function createLentScreenPresence(options?: { idleSeconds?: () => number | null; now?: () => number }): {
+ refusal(name: string, args: unknown): string | null;
+ acted(name: string, args: unknown): void;
+};
diff --git a/electron/lent-screen-presence.mjs b/electron/lent-screen-presence.mjs
new file mode 100644
index 0000000000..8cf1bf1adb
--- /dev/null
+++ b/electron/lent-screen-presence.mjs
@@ -0,0 +1,55 @@
+// Bots use a lent computer while the person uses it too, without fighting them for the mouse or keyboard. cua-driver
+// acts in the background by default: it reads and acts on an app's window through its accessibility tree and posts
+// input to that app alone, so the real pointer, the keyboard focus and the front app stay the person's. Only a call
+// that takes the foreground waits until nobody has touched the computer for a while.
+
+/** Nobody touched the keyboard, mouse or trackpad for this long: the person has stepped away. */
+export const PERSON_AWAY_SECONDS = 30;
+
+/** Never act: they read the screen, or only steer the bot's own drawn cursor and session. */
+const READS = new Set([
+ "list_apps", "list_windows", "get_window_state", "get_accessibility_tree", "get_desktop_state", "get_screen_size",
+ "get_cursor_position", "zoom", "get_browser_state", "start_session", "end_session", "get_session_state", "escalate_session",
+ "get_agent_cursor_state", "set_agent_cursor_enabled", "set_agent_cursor_motion", "set_agent_cursor_style", "move_cursor",
+]);
+
+/** Whether a lent screen call would take the person's mouse, keyboard or front app. `launch_app` opens hidden (the driver
+ * pushes focus back), and the browser tools drive the page over DevTools, so neither does. Every other action stays in
+ * the background only with a window to post to (`pid`): without one it lands on whatever app or field is in front. */
+export function takesForeground(name, args) {
+ const given = args && typeof args === "object" ? args : {};
+ if (READS.has(name) || name === "launch_app" || name.startsWith("browser_")) return false;
+ if (name === "bring_to_front" || name === "drag") return true;
+ if (given.delivery_mode === "foreground" || given.scope === "desktop") return true;
+ return !Number.isSafeInteger(given.pid);
+}
+
+export function personActiveText(name) {
+ return `The person is using this computer right now, so ${name} was not performed: it would take their mouse, keyboard or front window. ` +
+ "Do it in the background instead: give the app's pid and window_id (from launch_app or list_windows) and act on an element from get_window_state, " +
+ "without delivery_mode \"foreground\" or scope \"desktop\". " +
+ `If it can only be done in the foreground, wait until nobody has touched the computer for ${PERSON_AWAY_SECONDS} seconds, then observe it again and retry.`;
+}
+
+/** `idleSeconds()`: seconds since the person last touched this computer, or null when this system cannot tell (then
+ * nothing waits, as before). A foreground action's own input can read as a touch, so a touch no later than the end of
+ * the bot's last foreground action is the bot's, not the person's. A background action is never counted that way: a
+ * bot acting every second must not hide a person who is typing. */
+export function createLentScreenPresence({ idleSeconds = () => null, now = Date.now } = {}) {
+ let ownInputUntil = -Infinity;
+ return {
+ /** The plain reason a call must wait, or null when it may run now. */
+ refusal(name, args) {
+ if (!takesForeground(name, args)) return null;
+ const idle = idleSeconds();
+ if (typeof idle !== "number" || !Number.isFinite(idle) || idle >= PERSON_AWAY_SECONDS) return null;
+ // Seconds are whole, so the last touch was up to a second before `idle` says.
+ const touchedAfter = now() - (idle + 1) * 1000;
+ return touchedAfter <= ownInputUntil ? null : personActiveText(name);
+ },
+ /** Called when a call that reached the screen has ended. */
+ acted(name, args) {
+ if (takesForeground(name, args)) ownInputUntil = now();
+ },
+ };
+}
diff --git a/electron/lent-screen-presence.node-test.mjs b/electron/lent-screen-presence.node-test.mjs
new file mode 100644
index 0000000000..01840a909f
--- /dev/null
+++ b/electron/lent-screen-presence.node-test.mjs
@@ -0,0 +1,55 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { createLentScreenPresence, PERSON_AWAY_SECONDS, personActiveText, takesForeground } from "./lent-screen-presence.mjs";
+
+test("which lent screen calls would take the person's mouse, keyboard or front window", () => {
+ const window = { pid: 42, window_id: 7 };
+ for (const [name, args] of [
+ ["get_window_state", {}], ["get_desktop_state", {}], ["list_windows", {}], ["zoom", {}], ["move_cursor", { x: 1, y: 1 }],
+ ["start_session", { session: "s" }], ["launch_app", { name: "FreeShow" }], ["browser_click", { ref: "e1" }],
+ ["click", { ...window, element_index: 3 }], ["click", { ...window, x: 4, y: 4 }], ["type_text", { ...window, element_index: 2, text: "hi" }],
+ ["press_key", { ...window, key: "return" }], ["hotkey", { ...window, keys: ["cmd", "s"] }], ["scroll", { ...window, direction: "down" }],
+ ["set_value", { ...window, element_index: 1, value: "x" }], ["click", { ...window, element_index: 3, delivery_mode: "background" }],
+ ]) assert.equal(takesForeground(name, args), false, `${name} ${JSON.stringify(args)} stays in the background`);
+ for (const [name, args] of [
+ ["bring_to_front", window], ["drag", { ...window, from_x: 1, from_y: 1, to_x: 2, to_y: 2 }],
+ ["click", { ...window, element_index: 3, delivery_mode: "foreground" }], ["press_key", { ...window, key: "a", scope: "desktop" }],
+ // No window: it lands on whatever app or field the person has in front.
+ ["click", { x: 4, y: 4 }], ["type_text", { text: "hi" }], ["press_key", { key: "return" }], ["hotkey", { keys: ["cmd", "q"] }],
+ ["click", undefined], ["click", { pid: "42" }],
+ ]) assert.equal(takesForeground(name, args), true, `${name} ${JSON.stringify(args)} takes the foreground`);
+});
+
+test("a foreground call waits while the person is using the computer; background calls never wait", () => {
+ let idle = 0, clock = 1_000_000;
+ const presence = createLentScreenPresence({ idleSeconds: () => idle, now: () => clock });
+ assert.equal(presence.refusal("click", { pid: 42, window_id: 7, element_index: 3 }), null);
+ assert.equal(presence.refusal("click", { x: 1, y: 1 }), personActiveText("click"));
+ idle = PERSON_AWAY_SECONDS - 1;
+ assert.equal(presence.refusal("drag", {}), personActiveText("drag"));
+ idle = PERSON_AWAY_SECONDS;
+ assert.equal(presence.refusal("drag", {}), null);
+ // A system that cannot tell idle time waits for nothing, as before.
+ for (const unknown of [null, undefined, Number.NaN]) {
+ assert.equal(createLentScreenPresence({ idleSeconds: () => unknown }).refusal("bring_to_front", {}), null);
+ }
+ assert.equal(createLentScreenPresence().refusal("bring_to_front", {}), null);
+});
+
+test("the bot's own foreground input is not mistaken for the person; the person's next touch is", () => {
+ let idle = PERSON_AWAY_SECONDS, clock = 1_000_000;
+ const presence = createLentScreenPresence({ idleSeconds: () => idle, now: () => clock });
+ assert.equal(presence.refusal("click", { x: 1, y: 1 }), null);
+ clock += 400; presence.acted("click", { x: 1, y: 1 });
+ // The click itself reset the system's idle time.
+ clock += 600; idle = 0;
+ assert.equal(presence.refusal("type_text", { text: "a" }), null, "the bot's own click");
+ clock += 3_000; idle = 3;
+ assert.equal(presence.refusal("type_text", { text: "a" }), null, "still the bot's click, three seconds on");
+ // The person touched the trackpad well after the bot's last foreground action.
+ clock += 5_000; idle = 0;
+ assert.equal(presence.refusal("type_text", { text: "a" }), personActiveText("type_text"));
+ // A background action is never counted as the bot's own touch, however often it runs.
+ presence.acted("click", { pid: 42, window_id: 7, element_index: 1 });
+ assert.equal(presence.refusal("type_text", { text: "a" }), personActiveText("type_text"));
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index e4fc3b7f7b..ddba449193 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -86,6 +86,7 @@ import environmentsModule from "./environments.cjs";
import localOriginModule from "./local-origin.cjs";
import { buildApplicationMenu } from "./menu.mjs";
import { createComputerSharing, isHomeFolder, sharedCuaConnection, validateSharedFolders } from "./computer-sharing.mjs";
+import { createHostScreenLease } from "./host-screen-lease.mjs";
import { acquireDataDirLease } from "./data-dir-lease.mjs";
import { switchLocalEnvironment } from "./environment-switch.mjs";
import { createManagedDesktopClient, createManagedDesktopRelay, createManagedDesktopStore } from "./managed-desktop.mjs";
@@ -1511,20 +1512,8 @@ function sharingController() {
cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, power: cloudPower, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }),
linkHeaders: async env => ({ cookie: (await session.defaultSession.cookies.get({ url: env.origin })).map(cookie => `${cookie.name}=${cookie.value}`).join("; ") }),
onChange: summary => { lendingIndicator().update({ lending: summary.lending.length > 0, internetOnly: summary.internetOnly, terminal: summary.terminal, busy: Boolean(summary.busy && summary.lending.includes(summary.busy.env)) }); loginItem.follow(summary.lending.length > 0); },
- cuaConnection: () => cuaReady, screenLocked: () => powerMonitor.getSystemIdleState(1) === "locked",
- hostControl: async (id, signal) => {
- const lease = async action => {
- const response = await fetch(`http://127.0.0.1:${SERVER_PORT}/api/desktop/shared-computer-control`, {
- method: "POST",
- headers: desktopServerHeaders({ "content-type": "application/json" }, { packaged: app.isPackaged, token: desktopMutationToken }),
- body: JSON.stringify({ id, action }),
- signal: action === "release" ? AbortSignal.timeout(3000) : AbortSignal.any([signal, AbortSignal.timeout(3000)]),
- });
- if (!response.ok) throw new Error("This computer is in use locally or held by a person. Wait, then observe it again before acting.");
- };
- await lease("acquire");
- return { renew: () => lease("acquire"), release: () => lease("release") };
- },
+ cuaConnection: () => cuaReady, screenLocked: () => powerMonitor.getSystemIdleState(1) === "locked", idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime(),
+ hostControl: createHostScreenLease({ url: () => `http://127.0.0.1:${SERVER_PORT}/api/desktop/shared-computer-control`, headers: () => desktopServerHeaders({}, { packaged: app.isPackaged, token: desktopMutationToken }) }),
});
return computerSharing;
}
diff --git a/server/cloud-lending-browser.e2e.test.ts b/server/cloud-lending-browser.e2e.test.ts
index e8cc899543..c2ed63cfb7 100644
--- a/server/cloud-lending-browser.e2e.test.ts
+++ b/server/cloud-lending-browser.e2e.test.ts
@@ -13,6 +13,8 @@ import { afterAll, beforeAll, expect, it } from "vitest";
import { launchVerificationServer, type VerificationServer } from "../scripts/control-omb.ts";
import { createComputerSharing } from "../electron/computer-sharing.mjs";
import { helperMissing, SCREEN_LOCKED } from "../electron/lent-screen-failures.mjs";
+import { createHostScreenLease } from "../electron/host-screen-lease.mjs";
+import { personActiveText } from "../electron/lent-screen-presence.mjs";
import { cloudPairingSignature } from "./cloud-home.ts";
import { LENT_BROWSER_NO_ENDPOINT, LENT_SCREEN_BROWSING } from "./lent-screen-guidance.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
@@ -39,6 +41,9 @@ const proxies: ChildProcess[] = [];
/** What the PC's screen does next; the scripted driver reads it on every call. */
const screen = { file: "", set(mode: "normal" | "exit" | "hang") { writeFileSync(this.file, JSON.stringify({ mode })); } };
let locked = false;
+/** Seconds since the person last touched the PC; null: the PC cannot tell. */
+let idle: number | null = null;
+let leaseUrl = "";
let signedIn = true;
let driver: { mcpCommand: string; mcpArgs: string[]; mcpEnv: Record<string, string> } | { mode: "unavailable"; reason: string };
const channel = { lose: null as null | "answer" | "poll", lost: 0, abandoned: [] as AbortController[] };
@@ -176,18 +181,12 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
screen.set("normal");
driver = { mcpCommand: process.execPath, mcpArgs: [writeDriver(home)], mcpEnv: {} };
const env = { id: "my-cloud", name: "My Cloud", origin: base };
- // The desktop's own lease on its screen, as Electron main takes it from its local server.
- const lease = async (id: string, action: string, signal?: AbortSignal) => {
- const response = await fetch(`${lender.info.url}/api/desktop/shared-computer-control`, {
- method: "POST", headers: { "content-type": "application/json", origin: lender.info.url }, body: JSON.stringify({ id, action }),
- signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3000)]) : AbortSignal.timeout(3000),
- });
- if (!response.ok) throw new Error("This computer is in use locally or held by a person. Wait, then observe it again before acting.");
- };
+ // The desktop's own lease on its screen, taken from its local server the way Electron main takes it.
+ leaseUrl = `${lender.info.url}/api/desktop/shared-computer-control`;
connector = createComputerSharing({
file: join(home, "pc-profile", "computer-sharing.json"), environments: () => [env],
- cuaConnection: async () => driver, screenLocked: () => locked,
- hostControl: async (id: string, signal: AbortSignal) => { await lease(id, "acquire", signal); return { renew: () => lease(id, "acquire"), release: () => lease(id, "release") }; },
+ cuaConnection: async () => driver, screenLocked: () => locked, idleSeconds: () => idle,
+ hostControl: createHostScreenLease({ url: () => leaseUrl, headers: () => ({ origin: lender.info.url }) }),
cloud: () => ({ status: signedIn ? "connected" : "unverified", accountId: "acct_fixture", origin: base }),
home: join(home, "pc-home"),
// The PC's network to its Cloud, which a test can make lose a poll's answer, or leave a poll hanging as a dead connection does.
@@ -241,16 +240,45 @@ it("a browser task through the lent PC: the browser tools explain the screen rou
expect(said(page)).toContain("Total: 42.00 EUR");
}, hostTimeout(60_000));
-it("the PC's screen held locally answers in one sentence, and works once it is free", async () => {
- const held = await fetch(`${lender.info.url}/api/desktop/shared-computer-control`, { method: "POST", headers: { "content-type": "application/json", origin: lender.info.url }, body: JSON.stringify({ id: "5d0c7a39-2b39-4b07-9a0e-0c58a7d55f21", action: "acquire" }) });
- expect(held.status).toBe(200);
- const busy = await screenCall("get_desktop_state");
- expect(busy.isError).toBe(true);
- expect(said(busy)).toBe("This computer is in use locally or held by a person. Wait, then observe it again before acting.");
- await fetch(`${lender.info.url}/api/desktop/shared-computer-control`, { method: "POST", headers: { "content-type": "application/json", origin: lender.info.url }, body: JSON.stringify({ id: "5d0c7a39-2b39-4b07-9a0e-0c58a7d55f21", action: "release" }) });
+const lenderLease = (id: string, action: string) => fetch(leaseUrl, { method: "POST", headers: { "content-type": "application/json", origin: lender.info.url }, body: JSON.stringify({ id, action }) });
+
+it("a screen lock an earlier lent call left behind, or a person holding a bot's other computer, never blocks the lent screen", async () => {
+ // An earlier lent call whose release never arrived (the app crashed, or the release timed out) still holds the lock.
+ expect((await lenderLease("5d0c7a39-2b39-4b07-9a0e-0c58a7d55f21", "acquire")).status).toBe(200);
+ expect((await screenCall("get_desktop_state")).isError).toBeFalsy();
+ // The person took control of a desktop bot's own cloud computer and never handed it back: that is another computer.
+ const bot = await (await fetch(`${lender.info.url}/api/bots`, { method: "POST", headers: { "content-type": "application/json", origin: lender.info.url }, body: JSON.stringify({ name: "Desk bot" }) })).json() as { bot: { id: string } };
+ const take = await fetch(`${lender.info.url}/api/bots/${bot.bot.id}/computer/control`, { method: "POST", headers: { "content-type": "application/json", origin: lender.info.url }, body: JSON.stringify({ action: "take" }) });
+ expect((await take.json() as { held: boolean }).held).toBe(true);
+ const free = await screenCall("get_desktop_state");
+ expect(free.isError, said(free)).toBeFalsy();
+}, hostTimeout(30_000));
+
+it("a screen the PC's own server cannot check says so in one sentence, never that a person is using it", async () => {
+ const right = leaseUrl;
+ leaseUrl = `${lender.info.url}/api/desktop/not-the-screen-lock`;
+ const refused = await screenCall("get_desktop_state");
+ leaseUrl = right;
+ expect(refused.isError).toBe(true);
+ expect(said(refused)).toMatch(/^OpenMausBot on this computer could not check whether its screen is free \(its server answered 404.*\), so this call was not performed\. This is not a person using the computer\./);
expect((await screenCall("get_desktop_state")).isError).toBeFalsy();
}, hostTimeout(30_000));
+it("while the person uses the PC, background calls run and a call that would take their mouse waits with the reason", async () => {
+ idle = 0;
+ const listing = await call("shared_computer", { computer_id: computerId, action: "computer_tools" });
+ expect(listing.isError, said(listing)).toBeFalsy();
+ expect((await screenCall("launch_app", { name: "Google Chrome", urls: [pageUrl] })).isError).toBeFalsy();
+ expect(said(await screenCall("get_window_state", { pid: 4242, window_id: 7 }))).toContain("Total: 42.00 EUR");
+ expect((await screenCall("click", { pid: 4242, window_id: 7, element_index: 3 })).isError).toBeFalsy();
+ const front = await screenCall("click", { x: 10, y: 10 });
+ expect(front.isError).toBe(true);
+ expect(said(front)).toBe(personActiveText("click"));
+ idle = 45;
+ expect((await screenCall("click", { x: 10, y: 10 })).isError).toBeFalsy();
+ idle = null;
+}, hostTimeout(30_000));
+
it("a locked screen says to unlock it, and works once unlocked", async () => {
locked = true;
const refused = await screenCall("get_desktop_state");
diff --git a/server/index.ts b/server/index.ts
index 1127cde9f1..b7c1aa1e80 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2168,7 +2168,7 @@ const directTurnBots = new Map<string, BotRecord>();
const turnPromptBytes = new Map<string, { stable: number; volatile: number }>();
let providerFleetReloading = false;
const turnResources = new TurnResources();
-const sharedComputerControl = new SharedComputerControl(turnResources, () => store.bots.some(bot => botComputerControlSnapshot(bot.id).held));
+const sharedComputerControl = new SharedComputerControl(turnResources, (owner) => store.botByThread(owner.threadId)?.name);
const turnResourceOwners = new Map<string, TurnOwner>();
const turnComputerResources = new Map<string, { owner: TurnOwner; resource: string }>();
const teamComputerTurns = new Map<string, { owner: TurnOwner; computerId: string; botId: string }>();
@@ -13261,7 +13261,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
else {
const refusal = managedPolicy.computerRefusal("thisComputer");
if (refusal) return json(res, 403, { error: refusal, code: "managed_policy" });
- sharedComputerControl.acquire(body.id);
+ const busy = sharedComputerControl.acquire(body.id); if (busy) return json(res, 409, { error: busy, code: "bot" });
}
return json(res, 200, { ok: true });
}
diff --git a/server/lent-screen-guidance.test.ts b/server/lent-screen-guidance.test.ts
index 8eb38e36fd..af27afa937 100644
--- a/server/lent-screen-guidance.test.ts
+++ b/server/lent-screen-guidance.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { LENT_BROWSER_NO_ENDPOINT, LENT_SCREEN_BROWSING, lentScreenResult } from "./lent-screen-guidance.ts";
+import { LENT_BROWSER_NO_ENDPOINT, LENT_SCREEN_BACKGROUND, LENT_SCREEN_BROWSING, lentScreenResult } from "./lent-screen-guidance.ts";
import { omittedFromErrorNote } from "./mcp-error-result.ts";
const call = (tool_name: string) => ({ action: "computer_call", tool_name });
@@ -7,9 +7,15 @@ const failed = (text: string) => ({ content: [{ type: "text", text }], isError:
const texts = (result: unknown) => (result as { content: { text: string }[] }).content.map((part) => part.text);
describe("a lent screen's answers carry the fix", () => {
- it("lists the screen tools with how to browse there", () => {
+ it("lists the screen tools with how to browse there and how to work beside the person", () => {
const listing = { content: [{ type: "text", text: "{\"tools\":[]}" }] };
- expect(texts(lentScreenResult({ action: "computer_tools" }, listing))).toEqual(["{\"tools\":[]}", LENT_SCREEN_BROWSING]);
+ expect(texts(lentScreenResult({ action: "computer_tools" }, listing))).toEqual(["{\"tools\":[]}", LENT_SCREEN_BROWSING, LENT_SCREEN_BACKGROUND]);
+ });
+
+ it("an older desktop's \"in use\" no longer sends the bot waiting for a person", () => {
+ const old = texts(lentScreenResult(call("get_window_state"), failed("This computer is in use locally or held by a person. Wait, then observe it again before acting.")));
+ expect(old).toHaveLength(1);
+ expect(old[0]).toMatch(/^This computer did not let this call use its screen, so it was not performed\. .*it is not necessarily a person\. Try again in a minute/);
});
it("turns a browser that needs DevTools setup into the screen route, whatever shape the driver used", () => {
diff --git a/server/lent-screen-guidance.ts b/server/lent-screen-guidance.ts
index bc8818ff6c..04e43e1a93 100644
--- a/server/lent-screen-guidance.ts
+++ b/server/lent-screen-guidance.ts
@@ -8,6 +8,10 @@ type ToolResult = { content?: Part[]; isError?: boolean };
export const LENT_SCREEN_BROWSING =
"To browse on this lent screen: launch_app with urls opens the page in the person's own browser, signed in as they are; read it with get_window_state (include_screenshot when the tree is thin) and act with click, type_text and press_key. get_browser_state and the browser_* tools work only when that browser already has a DevTools endpoint, which most do not.";
+/** The person may be using the computer while a bot does: background actions run, foreground ones wait for them to step away. */
+export const LENT_SCREEN_BACKGROUND =
+ "The person may be using this computer while you work. Act in the background so you never take their mouse or keyboard: give the app's pid and window_id (from launch_app or list_windows) and act on elements from get_window_state. A call with delivery_mode \"foreground\", scope \"desktop\", drag, bring_to_front or no window waits until they have stepped away.";
+
export const LENT_BROWSER_NO_ENDPOINT =
"This computer's browser has no DevTools endpoint, and setting one up is not part of a lent screen, so get_browser_state and the browser_* tools cannot drive it: do not retry them. Use the screen instead: launch_app with urls opens the page in the person's own browser; read it with get_window_state and act with click, type_text and press_key.";
@@ -21,6 +25,9 @@ const RAW_FAILURES: ReadonlyArray<[RegExp, string]> = [
"Computer control stopped on this computer: its helper, cua-driver, exited. Try the action once more; if it fails the same way, tell the person that Windows Security may have quarantined cua-driver.exe (restore it from Protection history, or reinstall OpenMausBot) and to restart OpenMausBot."],
[/^Computer control is unavailable\. Enable it in the local app and grant OS permissions first\.$/u,
"Computer control is not running on this computer. Tell the person in one sentence to open OpenMausBot on it: on Windows, restore cua-driver.exe if Windows Security quarantined it (Protection history) or reinstall; on a Mac, allow Accessibility and Screen Recording for OpenMausBot. Then try again."],
+ // Older desktops say this for any failed screen check, though it is rarely a person.
+ [/^This computer is in use locally or held by a person\. Wait, then observe it again before acting\.$/u,
+ "This computer did not let this call use its screen, so it was not performed. Another bot on it may be using the screen, or OpenMausBot on it could not check; it is not necessarily a person. Try again in a minute; if it keeps saying this, tell the person to update OpenMausBot on that computer, or quit and reopen it."],
[/^fetch failed$/u,
"OpenMausBot on this computer is not answering its own screen-control check. Tell the person to restart OpenMausBot on that computer, then try again."],
];
@@ -35,7 +42,7 @@ export function lentScreenResult(operation: { action: string; tool_name?: string
if (operation.action !== "computer_tools" && operation.action !== "computer_call") return value;
if (!value || typeof value !== "object" || !Array.isArray((value as ToolResult).content)) return value;
const result = textOnlyErrorResult(value as ToolResult);
- if (operation.action === "computer_tools") return result.isError ? result : withPart(result, LENT_SCREEN_BROWSING);
+ if (operation.action === "computer_tools") return result.isError ? result : withPart(withPart(result, LENT_SCREEN_BROWSING), LENT_SCREEN_BACKGROUND);
if (result.isError) {
const text = textOf(result);
const fix = RAW_FAILURES.find(([pattern]) => pattern.test(text));
diff --git a/server/shared-computer-control.ts b/server/shared-computer-control.ts
index 37f0696359..ae27de25b9 100644
--- a/server/shared-computer-control.ts
+++ b/server/shared-computer-control.ts
@@ -1,24 +1,42 @@
-import { TurnResources } from "./turn-resources.ts";
+import { TurnResources, type TurnOwner } from "./turn-resources.ts";
-/** Leases expire if Electron crashes; human takeover always wins renewal. */
+/** Leases expire if Electron crashes. */
const LEASE_EXPIRY_MS = 40_000;
+const HOST = "computer:host";
+const SHARED = "shared:";
+
+/** Said when another bot's turn on this computer holds its screen. Never a person: a person at this computer is noticed by
+ * the desktop itself, from its own keyboard and mouse. */
+export function hostScreenBusyText(holder?: string): string {
+ return `${holder ? `Another bot on this computer, ${holder},` : "Another bot on this computer"} is using its screen right now, so this call was not performed. ` +
+ "It is not a person. Work on something that does not need the screen, then try again in a minute.";
+}
type SharedComputerLease = { timer: NodeJS.Timeout; generation: number; lastActivity: number };
+/** Keeps this desktop's own bot turns and a lent screen call from the person's Cloud from using the screen at once. */
export class SharedComputerControl {
private leases = new Map<string, SharedComputerLease>();
private resources: TurnResources;
- private held: () => boolean;
- constructor(resources: TurnResources, held: () => boolean) { this.resources = resources; this.held = held; }
- acquire(id: string) {
- const owner = { threadId: `shared:${id}`, generation: id };
- if (this.held() || !this.resources.claim("computer:host", owner)) {
+ private holderName: (owner: TurnOwner) => string | undefined;
+ constructor(resources: TurnResources, holderName: (owner: TurnOwner) => string | undefined = () => undefined) {
+ this.resources = resources; this.holderName = holderName;
+ }
+ /** Undefined when the screen is now this call's; otherwise the plain reason it is not. */
+ acquire(id: string): string | undefined {
+ const owner = { threadId: `${SHARED}${id}`, generation: id };
+ // The desktop runs one lent call at a time, so an older lent call's lease is always stale: a newer call frees it.
+ const holder = this.resources.holder(HOST);
+ if (holder?.threadId.startsWith(SHARED) && holder.generation !== id) this.release(holder.generation);
+ if (!this.resources.claim(HOST, owner)) {
+ const blocker = this.resources.blocker(HOST, owner);
this.release(id);
- throw Object.assign(new Error("This computer is in use locally or held by a person. Wait, then observe it again before acting."), { status: 409 });
+ return hostScreenBusyText(blocker && this.holderName(blocker));
}
this.arm(id);
+ return undefined;
}
- /** Skips the takeover checks: a heartbeat for a pending operation must not lose its own screen. */
+ /** A heartbeat for a pending operation: never loses its own screen. */
renew(id: string) {
if (this.leases.has(id)) this.arm(id);
}
@@ -38,7 +56,7 @@ export class SharedComputerControl {
release(id: string) {
const lease = this.leases.get(id);
if (lease) { clearTimeout(lease.timer); this.leases.delete(id); }
- this.resources.release({ threadId: `shared:${id}`, generation: id });
+ this.resources.release({ threadId: `${SHARED}${id}`, generation: id });
}
close() { for (const id of this.leases.keys()) this.release(id); }
}
diff --git a/server/shared-computers.test.ts b/server/shared-computers.test.ts
index c16531f363..a54fa54300 100644
--- a/server/shared-computers.test.ts
+++ b/server/shared-computers.test.ts
@@ -4,7 +4,7 @@ import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { LentComputers, provenRequestPerson, SharedComputers, sharedComputerScopeRefusal } from "./shared-computers.ts";
-import { SharedComputerControl } from "./shared-computer-control.ts";
+import { hostScreenBusyText, SharedComputerControl } from "./shared-computer-control.ts";
import { TurnResources } from "./turn-resources.ts";
const secret = "a".repeat(64);
@@ -350,19 +350,35 @@ describe("server-side scope check (audit M1)", () => {
});
});
-it("shared screen calls respect local turns, human takeover, lease expiry and release", async () => {
+it("shared screen calls respect local turns, lease expiry and release, and say which bot holds the screen", async () => {
vi.useFakeTimers();
- const resources = new TurnResources(); let held = false;
- const control = new SharedComputerControl(resources, () => held);
+ const resources = new TurnResources();
+ const control = new SharedComputerControl(resources, (owner) => (owner.threadId === "local" ? "Researcher" : undefined));
const local = { threadId: "local", generation: "first" };
resources.claim("computer:host", local);
- expect(() => control.acquire("remote")).toThrow(/in use locally/);
- resources.release(local); control.acquire("remote");
+ expect(control.acquire("remote")).toBe(hostScreenBusyText("Researcher"));
+ expect(control.acquire("remote")).toMatch(/^Another bot on this computer, Researcher, is using its screen right now, so this call was not performed\. It is not a person\./);
+ resources.release(local); expect(control.acquire("remote")).toBeUndefined();
expect(resources.claim("computer:host", local)).toBe(false);
- held = true; expect(() => control.acquire("remote")).toThrow(/held by a person/);
- held = false; control.acquire("remote");
await vi.advanceTimersByTimeAsync(40_001);
expect(resources.claim("computer:host", local)).toBe(true);
- resources.release(local); control.acquire("remote"); control.close();
+ resources.release(local); expect(control.acquire("remote")).toBeUndefined(); control.close();
expect(resources.claim("computer:host", local)).toBe(true);
+ resources.release(local);
+ // A turn of a bot this server does not name (a waiting one, say) is still another bot, never a person.
+ resources.claim("computer:host", { threadId: "gone", generation: "g" });
+ expect(control.acquire("remote")).toBe(hostScreenBusyText());
+});
+
+it("a lent call's screen lock left behind by an earlier lent call frees itself for the next one", () => {
+ const resources = new TurnResources();
+ const control = new SharedComputerControl(resources);
+ const earlier = randomUUID(), next = randomUUID();
+ expect(control.acquire(earlier)).toBeUndefined();
+ // The desktop never released it (it crashed, or the release timed out): the next lent call still gets the screen.
+ expect(control.acquire(next)).toBeUndefined();
+ expect(resources.holder("computer:host")).toEqual({ threadId: `shared:${next}`, generation: next });
+ expect(control.acquire(next)).toBeUndefined();
+ control.release(next);
+ expect(resources.free("computer:host")).toBe(true);
});