Skip to content

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

fix(windows): foreground typing lands every character, and a sent menu click is not reported as failed (#3769)

Milind Sonif5f9692b61b9
diff --git a/docs/verification/local-computer-launch.md b/docs/verification/local-computer-launch.md
index 7fe4e031e7..e0da5d0ce6 100644
--- a/docs/verification/local-computer-launch.md
+++ b/docs/verification/local-computer-launch.md
@@ -78,6 +78,27 @@ custom `CUA_DRIVER_PATH` executables. An explicit override remains untouched;
an incomplete installed package reports a missing-driver error rather than
silently falling back to the console binary.
+### Foreground typing and menu clicks
+
+The bundled Windows driver (0.28.2) sends a foreground `type_text` as one burst
+of key packets, which Windows 11 Notepad scrambles, and answers a click that
+picks a menu item with `foreground_unavailable` after the click worked. With a
+driver older than 0.35.0, OpenMausBot types such text one character at a time
+and tells the bot that the click was sent:
+
+```sh
+node --test electron/paced-typing.node-test.mjs electron/shared-computer-access.node-test.mjs
+pnpm exec vitest run server/local-computer-proxy.test.ts server/mcp-bridge.test.ts \
+ server/local-computer-guidance.test.ts server/unconfirmed-click.test.ts \
+ server/lent-screen-guidance.test.ts
+```
+
+A fake driver scrambles a burst the way the report showed (" Zeile Drei"
+became " iiiiiiiiii"); the proxy test runs the real local proxy against it, and
+the shared-access test the lent-screen path. No Windows app is driven. A
+driver of 0.35.0 or later types one character at a time itself, and these
+calls then reach it unchanged.
+
The portable conversion checks use synthetic inert PE data:
```sh
diff --git a/electron/paced-typing.d.mts b/electron/paced-typing.d.mts
new file mode 100644
index 0000000000..f772a575f7
--- /dev/null
+++ b/electron/paced-typing.d.mts
@@ -0,0 +1,8 @@
+export const MAX_PACED_CHARACTERS: number;
+export function typesInOneBurst(platform: string, driverVersion: unknown, name: string, args: unknown): boolean;
+export function typingUnits(text: string): string[];
+export function withoutLeakedToolTags(text: string): string;
+export function typeOneCharacterAtATime(
+ call: (name: string, args: Record<string, unknown>) => Promise<unknown>,
+ args: Record<string, unknown> & { text: string },
+): Promise<Record<string, unknown>>;
diff --git a/electron/paced-typing.mjs b/electron/paced-typing.mjs
new file mode 100644
index 0000000000..9470ad162a
--- /dev/null
+++ b/electron/paced-typing.mjs
@@ -0,0 +1,158 @@
+// cua-driver before 0.35.0 sends a Windows foreground type_text as one SendInput burst of Unicode key packets
+// (platform-windows/src/input/keyboard.rs, send_text_synthesized_after_focus), and modern Notepad reads a packet ahead of
+// translating the one before it, so later characters land in place of earlier ones: " Zeile Drei" came out " iiiiiiiiii".
+// https://github.com/trycua/cua/issues/4830 — 0.35.0 paces the text itself. With an older driver each character goes as
+// its own type_text, after its window is confirmed in front.
+
+/** The first driver that types foreground text one character at a time itself. */
+const PACED_FROM = [0, 35, 0];
+/** At about 50 ms a character this stays well inside the 45 seconds a lent screen's call has, and the 60 an engine gives one. */
+export const MAX_PACED_CHARACTERS = 300;
+/** The driver's own list of tool-call tags a model can leak into the end of `text` (cua-driver-core/src/text_sanitize.rs). */
+const LEAKED_TAGS = new Set(["text", "parameter", "invoke", "function_calls", "function_call", "tool_use", "tool_call",
+ "antml:parameter", "antml:invoke", "antml:function_calls"]);
+
+const asciiLower = (value) => value.replace(/[A-Z]+/gu, (letters) => letters.toLowerCase());
+
+function olderThanPacing(version) {
+ const parts = /^(\d+)\.(\d+)\.(\d+)/u.exec(typeof version === "string" ? version : "")?.slice(1).map(Number);
+ if (!parts) return false;
+ for (const [index, part] of parts.entries()) if (part !== PACED_FROM[index]) return part < PACED_FROM[index];
+ return false;
+}
+
+const desktopScope = (args) => args.scope === "desktop" && args.pid === undefined && args.window_id === undefined;
+
+/** Whether this driver would type `args` as one burst. A window the driver knows only from an element_token cannot be
+ * held in front from here, so that call goes on as it came. */
+export function typesInOneBurst(platform, driverVersion, name, args) {
+ if (platform !== "win32" || name !== "type_text" || !olderThanPacing(driverVersion)) return false;
+ if (!args || typeof args !== "object" || typeof args.text !== "string") return false;
+ if (desktopScope(args)) return true;
+ return typeof args.delivery_mode === "string" && args.delivery_mode.toLowerCase() === "foreground" &&
+ Number.isSafeInteger(args.pid) && (args.window_id !== undefined || args.element_token === undefined);
+}
+
+/** One entry per character as the driver reads them: a CRLF pair is one line break, which it types as one Return. */
+export function typingUnits(text) {
+ const units = [];
+ for (const character of text) {
+ if (character === "\n" && units.at(-1) === "\r") units[units.length - 1] = "\r\n";
+ else units.push(character);
+ }
+ return units;
+}
+
+function opensTag(before, name) {
+ const lower = asciiLower(before);
+ const opener = `<${name}`;
+ for (let at = lower.indexOf(opener); at !== -1; at = lower.indexOf(opener, at + opener.length)) {
+ const next = lower[at + opener.length];
+ if (next === undefined || next === ">" || /\s/u.test(next)) return true;
+ }
+ return false;
+}
+
+/** The driver drops a trailing run of unbalanced tool-call closing tags from the whole text; sent a character at a time
+ * it would never see them whole, so the same rule runs here first. */
+export function withoutLeakedToolTags(text) {
+ const trimmed = text.trimEnd();
+ let end = trimmed.length;
+ for (;;) {
+ const head = trimmed.slice(0, end).trimEnd();
+ end = head.length;
+ const open = head.lastIndexOf("</");
+ if (!head.endsWith(">") || open === -1) break;
+ const name = head.slice(open + 2, -1);
+ if (!name || /\s/u.test(name) || !LEAKED_TAGS.has(asciiLower(name)) || opensTag(head.slice(0, open), asciiLower(name))) break;
+ end = open;
+ }
+ return end === trimmed.length ? text : trimmed.slice(0, end).trimEnd();
+}
+
+const failure = (text) => ({ content: [{ type: "text", text }], isError: true });
+
+async function attempt(call, name, args) {
+ try {
+ const result = await call(name, args);
+ return result && typeof result === "object" ? result : failure(`${name} returned no result`);
+ } catch (error) {
+ return failure(error instanceof Error ? error.message : String(error));
+ }
+}
+
+const SAID = new Set(["content", "structuredContent", "isError"]);
+/** A driver answer's protocol fields (resultType, _meta) without what it said. */
+const envelope = (result) => Object.fromEntries(Object.entries(result).filter(([key]) => !SAID.has(key)));
+
+/** bring_to_front reports windows as "0x…" text; 0 when it named none. */
+const handle = (value) => typeof value === "string" && /^0x[0-9a-f]+$/iu.test(value) ? Number.parseInt(value, 16) : 0;
+
+/** Asked before each character, bring_to_front also says whether the window was still in front. */
+async function inFront(call, pid, window) {
+ const front = await attempt(call, "bring_to_front", { pid, ...(window === undefined ? {} : { window_id: window }) });
+ const shown = front.isError ? null : front.structuredContent;
+ return { ok: Boolean(shown), before: handle(shown?.previous_fg_hwnd), target: handle(shown?.target_hwnd) };
+}
+
+/** The driver's own foreground typing puts back the window that was in front; bring_to_front never does. */
+async function giveFrontBack(call, before, target) {
+ if (!before || before === target) return;
+ const windows = (await attempt(call, "list_windows", {})).structuredContent?.windows;
+ const owner = Array.isArray(windows) ? windows.find((entry) => entry?.window_id === before)?.pid : undefined;
+ if (Number.isSafeInteger(owner)) await attempt(call, "bring_to_front", { pid: owner, window_id: before });
+}
+
+const tooLong = (count) => failure(
+ "type_text was not performed: on this Windows computer, text typed in the foreground goes in one character at a time so that each one lands, " +
+ `and one call types at most ${MAX_PACED_CHARACTERS} characters; this text has ${count}. ` +
+ `Type it in parts of at most ${MAX_PACED_CHARACTERS} characters, one type_text call after another.`);
+
+const typedOnly = (done, total) => `Only the first ${done} of ${total} characters were typed; the rest were not sent.`;
+const READ_AGAIN = "Read the field again with get_window_state before typing the rest.";
+
+/** Types `args.text` through `call(name, args)`, which resolves to each tool result, and answers as the one call it was. */
+export async function typeOneCharacterAtATime(call, args) {
+ const units = typingUnits(withoutLeakedToolTags(args.text));
+ if (units.length < 2) return attempt(call, "type_text", args);
+ if (units.length > MAX_PACED_CHARACTERS) return tooLong(units.length);
+ const desktop = desktopScope(args);
+ const session = args.session === undefined ? {} : { session: args.session };
+ let window = args.window_id;
+ let giveBackTo = 0;
+ let typed;
+ let stopped;
+ for (const [index, unit] of units.entries()) {
+ if (!desktop) {
+ const front = await inFront(call, args.pid, window);
+ if (index === 0) {
+ giveBackTo = front.before;
+ window ??= front.target || undefined;
+ } else if (!front.ok || front.before !== front.target) {
+ // Whatever came to the front keeps it: the rest is not typed rather than fought for.
+ if (front.ok) giveBackTo = front.before;
+ stopped = { ...envelope(typed), isError: true, content: [{ type: "text", text:
+ `${typedOnly(index, units.length)} The window being typed into was no longer in front, so typing stopped; someone may be using this computer. ${READ_AGAIN}` }] };
+ break;
+ }
+ }
+ // Later characters go where the first went, never to its element or point again: focusing those anew could move the caret.
+ const later = desktop ? { scope: "desktop", ...session } : { pid: args.pid, window_id: window, delivery_mode: args.delivery_mode, ...session };
+ const result = await attempt(call, "type_text", { ...(index === 0 ? args : later), text: unit });
+ if (result.isError) {
+ stopped = index === 0 ? result : { ...result, content: [
+ { type: "text", text: `${typedOnly(index, units.length)} Typing the next one failed. ${READ_AGAIN} The failure:` },
+ ...(Array.isArray(result.content) ? result.content : []),
+ ] };
+ break;
+ }
+ typed = result;
+ }
+ if (!desktop) await giveFrontBack(call, giveBackTo, window);
+ if (stopped) return stopped;
+ const said = desktop
+ ? `Typed ${units.length} character(s) into the foreground application (scope:desktop), one at a time.`
+ : `✅ Typed ${units.length} char(s) on pid ${args.pid} via SendInput (delivery_mode:foreground), one character at a time.`;
+ // The last character's own answer keeps the driver's structured result, which a strict client holds to the tool's schema.
+ return { ...typed, content: [{ type: "text", text: said }] };
+}
diff --git a/electron/paced-typing.node-test.mjs b/electron/paced-typing.node-test.mjs
new file mode 100644
index 0000000000..9078905275
--- /dev/null
+++ b/electron/paced-typing.node-test.mjs
@@ -0,0 +1,164 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { MAX_PACED_CHARACTERS, typeOneCharacterAtATime, typesInOneBurst, typingUnits, withoutLeakedToolTags } from "./paced-typing.mjs";
+
+const NOTEPAD = { pid: 4242, window: 0x30a5c };
+const CHAT = { pid: 77, window: 0x1f00 };
+const hex = (value) => `0x${value.toString(16)}`;
+
+/** Notepad behind cua-driver 0.28.2, as the reporter saw it: in one SendInput burst the first character lands and every
+ * later one becomes the burst's last. */
+function windowsDriver({ front = CHAT.window, onType } = {}) {
+ const owners = new Map([[NOTEPAD.window, NOTEPAD.pid], [CHAT.window, CHAT.pid]]);
+ const firstWindow = (pid) => [...owners].find(([, owner]) => owner === pid)?.[0];
+ const state = { front, document: "", calls: [] };
+ state.call = async (name, args) => {
+ state.calls.push({ name, args });
+ if (name === "bring_to_front") {
+ const target = args.window_id ?? firstWindow(args.pid);
+ const previous = state.front;
+ state.front = target;
+ return { content: [{ type: "text", text: "✅ bring_to_front" }],
+ structuredContent: { previous_fg_hwnd: hex(previous), now_fg_hwnd: hex(target), target_hwnd: hex(target), landed_on_target: true } };
+ }
+ if (name === "list_windows") {
+ return { content: [{ type: "text", text: "windows" }], structuredContent: { windows: [...owners].map(([window_id, pid]) => ({ window_id, pid })) } };
+ }
+ if (name !== "type_text") throw new Error(`unexpected ${name}`);
+ const target = args.scope === "desktop" ? state.front : args.window_id ?? firstWindow(args.pid);
+ if (target !== NOTEPAD.window) return { content: [{ type: "text", text: "typed elsewhere" }], isError: true };
+ const previous = state.front;
+ state.front = target;
+ const text = args.text === "\r\n" || args.text === "\r" ? "\n" : args.text;
+ state.document += text.length < 2 ? text : text[0] + text.at(-1).repeat(text.length - 1);
+ if (previous !== target) state.front = previous;
+ onType?.(state);
+ return { content: [{ type: "text", text: `✅ Typed ${[...args.text].length} char(s) on pid ${args.pid} via SendInput (delivery_mode:foreground).` }],
+ structuredContent: { effect: "unverifiable", route: "global_input", delivery: { mode: "foreground" } } };
+ };
+ return state;
+}
+
+const foreground = (text, extra = {}) => ({ pid: NOTEPAD.pid, window_id: NOTEPAD.window, delivery_mode: "foreground", text, ...extra });
+const named = (state, name) => state.calls.filter((call) => call.name === name);
+const said = (result) => result.content.map((part) => part.text).join("\n");
+
+test("only a burst-typing driver on Windows gets its foreground text one character at a time", () => {
+ const args = foreground("abc");
+ assert.equal(typesInOneBurst("win32", "0.28.2", "type_text", args), true);
+ assert.equal(typesInOneBurst("win32", "0.34.9", "type_text", { ...args, delivery_mode: "Foreground" }), true);
+ assert.equal(typesInOneBurst("win32", "0.28.2", "type_text", { scope: "desktop", text: "abc" }), true);
+ for (const [platform, version, name, given] of [
+ ["darwin", "0.28.2", "type_text", args], ["linux", "0.28.2", "type_text", args],
+ // The driver paces this itself from 0.35.0 on; an unknown driver keeps its own behaviour.
+ ["win32", "0.35.0", "type_text", args], ["win32", "1.0.0", "type_text", args], ["win32", undefined, "type_text", args], ["win32", "nightly", "type_text", args],
+ ["win32", "0.28.2", "press_key", args],
+ // Background typing posts characters to the window or sets its value: no burst.
+ ["win32", "0.28.2", "type_text", { ...args, delivery_mode: "background" }], ["win32", "0.28.2", "type_text", { pid: NOTEPAD.pid, text: "abc" }],
+ ["win32", "0.28.2", "type_text", { scope: "desktop", pid: NOTEPAD.pid, text: "abc" }],
+ ["win32", "0.28.2", "type_text", { delivery_mode: "foreground", element_token: "t-1", pid: NOTEPAD.pid, text: "abc" }],
+ ["win32", "0.28.2", "type_text", { ...args, pid: "4242" }], ["win32", "0.28.2", "type_text", { ...args, text: 7 }],
+ ]) assert.equal(typesInOneBurst(platform, version, name, given), false, `${platform} ${version} ${name} ${JSON.stringify(given)}`);
+});
+
+test("a character is what the driver reads as one: a code point, or one line break for CRLF", () => {
+ assert.deepEqual(typingUnits("a\r\nb\rc\nd"), ["a", "\r\n", "b", "\r", "c", "\n", "d"]);
+ assert.deepEqual(typingUnits("\n\r"), ["\n", "\r"]);
+ assert.deepEqual(typingUnits("🙂ä"), ["🙂", "ä"]);
+ assert.deepEqual(typingUnits("é"), ["e", "́"]);
+ assert.deepEqual(typingUnits(""), []);
+});
+
+test("tool-call closing tags a model leaked into the end of the text go, as the driver drops them", () => {
+ const close = (name) => `\x3c/${name}\x3e`;
+ assert.equal(withoutLeakedToolTags(`End of document.\n${close("text")}\n${close("invoke")}`), "End of document.");
+ assert.equal(withoutLeakedToolTags(`Some body.\n${close("antml:parameter")}\n${close("antml:invoke")}\n${close("antml:function_calls")}`), "Some body.");
+ assert.equal(withoutLeakedToolTags(`Hello <b>world</b>\n${close("text")}`), "Hello <b>world</b>");
+ for (const kept of [`\x3ctext\x3efoo${close("text")}`, `\x3cparameter name="foo"\x3ebody${close("parameter")}`, "Hello world </div>",
+ "Lorem ipsum dolor sit amet. ", "", "trailing spaces stay "]) assert.equal(withoutLeakedToolTags(kept), kept);
+});
+
+test("the reported sentences land whole, each character after its window is confirmed in front, and the chat gets the front back", async () => {
+ for (const text of [" Zeile Drei", " 28", " : , .", "Zeile 3: Vordergrund echt, Notiz, 28.10.2026"]) {
+ const burst = windowsDriver({ front: NOTEPAD.window });
+ await burst.call("type_text", foreground(text));
+ assert.notEqual(burst.document, text, "one burst reproduces the report");
+
+ const driver = windowsDriver();
+ const result = await typeOneCharacterAtATime(driver.call, foreground(text, { element_index: 3, session: "bot-1" }));
+ assert.equal(driver.document, text);
+ assert.equal(result.isError, undefined);
+ assert.equal(said(result), `✅ Typed ${[...text].length} char(s) on pid ${NOTEPAD.pid} via SendInput (delivery_mode:foreground), one character at a time.`);
+ assert.deepEqual(result.structuredContent, { effect: "unverifiable", route: "global_input", delivery: { mode: "foreground" } });
+ const typed = named(driver, "type_text");
+ assert.deepEqual(typed.map((call) => call.args.text), [...text]);
+ // The element is focused once; later characters name only the window, so nothing moves the caret.
+ assert.deepEqual(typed[0].args, foreground(text[0], { element_index: 3, session: "bot-1" }));
+ for (const call of typed.slice(1)) assert.deepEqual(call.args, foreground(call.args.text, { session: "bot-1" }));
+ assert.deepEqual(driver.calls.map((call) => call.name), [...[...text].flatMap(() => ["bring_to_front", "type_text"]), "list_windows", "bring_to_front"]);
+ assert.deepEqual(driver.calls.at(-1).args, { pid: CHAT.pid, window_id: CHAT.window });
+ assert.equal(driver.front, CHAT.window);
+ }
+});
+
+test("a line break goes as one Return, a window named by the driver alone is kept, and the front stays when it was the window's", async () => {
+ const driver = windowsDriver({ front: NOTEPAD.window });
+ await typeOneCharacterAtATime(driver.call, { pid: NOTEPAD.pid, delivery_mode: "foreground", text: "a\r\nb" });
+ assert.equal(driver.document, "a\nb");
+ assert.deepEqual(named(driver, "type_text").map((call) => [call.args.text, call.args.window_id]), [["a", undefined], ["\r\n", NOTEPAD.window], ["b", NOTEPAD.window]]);
+ assert.equal(named(driver, "list_windows").length, 0);
+});
+
+test("someone else taking the front stops the typing and keeps it theirs", async () => {
+ const driver = windowsDriver({ onType: (state) => { if (state.document.length === 3) state.front = CHAT.window; } });
+ const result = await typeOneCharacterAtATime(driver.call, foreground("Hello"));
+ assert.equal(driver.document, "Hel");
+ assert.equal(result.isError, true);
+ assert.match(said(result), /^Only the first 3 of 5 characters were typed; the rest were not sent\. The window being typed into was no longer in front/);
+ assert.deepEqual(driver.calls.at(-1), { name: "bring_to_front", args: { pid: CHAT.pid, window_id: CHAT.window } });
+ assert.equal(driver.front, CHAT.window);
+});
+
+test("a failed character ends the typing with what was typed and the driver's own reason", async () => {
+ const driver = windowsDriver();
+ const failing = async (name, args) => (name === "type_text" && args.text === "l"
+ ? { content: [{ type: "text", text: "foreground_unavailable: … no input was sent" }], isError: true, structuredContent: { code: "tool_invocation_failed" } }
+ : driver.call(name, args));
+ const result = await typeOneCharacterAtATime(failing, foreground("Hello"));
+ assert.equal(driver.document, "He");
+ assert.equal(result.isError, true);
+ assert.deepEqual(result.content.map((part) => part.text), [
+ "Only the first 2 of 5 characters were typed; the rest were not sent. Typing the next one failed. Read the field again with get_window_state before typing the rest. The failure:",
+ "foreground_unavailable: … no input was sent",
+ ]);
+ assert.equal(driver.front, CHAT.window);
+
+ const first = await typeOneCharacterAtATime(async (name, args) => (name === "type_text" ? { content: [{ type: "text", text: "window_id is required" }], isError: true } : driver.call(name, args)), foreground("Hi"));
+ assert.deepEqual(first, { content: [{ type: "text", text: "window_id is required" }], isError: true });
+ const thrown = await typeOneCharacterAtATime(async (name, args) => { if (name === "type_text") throw new Error("Computer control is disconnected"); return driver.call(name, args); }, foreground("Hi"));
+ assert.deepEqual(thrown, { content: [{ type: "text", text: "Computer control is disconnected" }], isError: true });
+});
+
+test("desktop scope types into whatever is in front without bringing anything forward", async () => {
+ const driver = windowsDriver({ front: NOTEPAD.window });
+ const result = await typeOneCharacterAtATime(driver.call, { scope: "desktop", text: "abc" });
+ assert.equal(driver.document, "abc");
+ assert.deepEqual(driver.calls.map((call) => [call.name, call.args]), [["type_text", { scope: "desktop", text: "a" }], ["type_text", { scope: "desktop", text: "b" }], ["type_text", { scope: "desktop", text: "c" }]]);
+ assert.equal(said(result), "Typed 3 character(s) into the foreground application (scope:desktop), one at a time.");
+});
+
+test("one character, an over-long text and leaked tags", async () => {
+ const one = windowsDriver({ front: NOTEPAD.window });
+ await typeOneCharacterAtATime(one.call, foreground("x", { element_index: 2 }));
+ assert.deepEqual(one.calls, [{ name: "type_text", args: foreground("x", { element_index: 2 }) }]);
+
+ const long = windowsDriver();
+ const refused = await typeOneCharacterAtATime(long.call, foreground("a".repeat(MAX_PACED_CHARACTERS + 1)));
+ assert.equal(refused.isError, true);
+ assert.match(said(refused), /^type_text was not performed: .* at most 300 characters; this text has 301\. Type it in parts/);
+ assert.deepEqual(long.calls, []);
+
+ const leaked = windowsDriver();
+ await typeOneCharacterAtATime(leaked.call, foreground("ok\n\x3c/parameter\x3e"));
+ assert.equal(leaked.document, "ok");
+});
diff --git a/electron/shared-computer-access.mjs b/electron/shared-computer-access.mjs
index 26da72d910..1b59189651 100644
--- a/electron/shared-computer-access.mjs
+++ b/electron/shared-computer-access.mjs
@@ -6,6 +6,7 @@ import { createHash } from "node:crypto";
import { spawn } from "node:child_process";
import readline from "node:readline";
import { lentScreenArguments, lentScreenToolListing } from "./lent-screen-tools.mjs";
+import { typeOneCharacterAtATime, typesInOneBurst } from "./paced-typing.mjs";
import { helperMissing } from "./lent-screen-failures.mjs";
/** Reads stay under the 4 MB body that carries a result to the server (base64 of 2 MiB is 2.8 MB); writes stay small. */
@@ -212,7 +213,7 @@ export function sharedCommand(command, cwd, signal, seconds = COMMAND_SECONDS) {
}
/** Persistent transport: Cua observation references survive to the next call. Ending sharing closes this, not the app's daemon. */
-export function createSharedCua(connection) {
+export function createSharedCua(connection, { platform = process.platform } = {}) {
const child = spawn(connection.mcpCommand, connection.mcpArgs, {
stdio: ["pipe", "pipe", "ignore"], windowsHide: true,
env: { ...hostEnvironment(), ...connection.mcpEnv },
@@ -247,7 +248,11 @@ export function createSharedCua(connection) {
signal?.addEventListener("abort", abort, { once: true });
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
});
- const ready = request("initialize", { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "omb-shared-desktop", version: "1" } }).then(() => child.stdin.write('{"jsonrpc":"2.0","method":"notifications/initialized"}\n'));
+ let driver;
+ const ready = request("initialize", { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "omb-shared-desktop", version: "1" } }).then(answer => {
+ driver = answer?.serverInfo;
+ child.stdin.write('{"jsonrpc":"2.0","method":"notifications/initialized"}\n');
+ });
ready.catch(() => {});
return {
async call(operation, signal) {
@@ -260,6 +265,9 @@ export function createSharedCua(connection) {
// Every tool and argument is checked here: nothing the server sends reaches the driver unless a lent screen accepts it.
const lent = lentScreenArguments(operation.tool_name, operation.arguments);
if (lent.error) throw new Error(lent.error);
+ if (typesInOneBurst(platform, driver?.version, operation.tool_name, lent.arguments)) {
+ return typeOneCharacterAtATime((name, args) => request("tools/call", { name, arguments: args }, signal), lent.arguments);
+ }
return request("tools/call", { name: operation.tool_name, arguments: lent.arguments }, signal);
},
close() { lines.close(); fail(new Error("Computer sharing stopped")); },
diff --git a/electron/shared-computer-access.node-test.mjs b/electron/shared-computer-access.node-test.mjs
index 35b1060ad3..5d4dc5172f 100644
--- a/electron/shared-computer-access.node-test.mjs
+++ b/electron/shared-computer-access.node-test.mjs
@@ -389,6 +389,41 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n'); });`
await assert.rejects(cua.call({ action: "computer_tools" }, signal), /disconnected/);
});
+test("a lent Windows screen types foreground text one character at a time on a driver that sends it in one burst", async t => {
+ const { dir } = await fixture(t);
+ const script = path.join(dir, "cua-windows-fixture.mjs");
+ // Notepad behind cua-driver 0.28.2: of one SendInput burst only the first character lands, the rest repeat the last.
+ await writeFile(script, `import readline from 'node:readline'; let front = 7, document = ''; const calls = [];
+const hex = value => '0x' + value.toString(16);
+const answer = (name, args) => { calls.push(name);
+ if (name === 'bring_to_front') { const previous = front; front = args.window_id; return { content: [], structuredContent: { previous_fg_hwnd: hex(previous), target_hwnd: hex(front) } }; }
+ if (name === 'list_windows') return { content: [], structuredContent: { windows: [{ window_id: 7, pid: 70 }, { window_id: 9, pid: 90 }] } };
+ if (name === 'type_text') { const text = args.text; document += text.length < 2 ? text : text[0] + text.at(-1).repeat(text.length - 1); return { content: [{ type: 'text', text: 'typed' }], structuredContent: { effect: 'unverifiable', route: 'global_input' } }; }
+ return { content: [{ type: 'text', text: JSON.stringify({ document, calls, front }) }] }; };
+readline.createInterface({input:process.stdin}).on('line', line => { const m=JSON.parse(line); if(!m.id)return;
+const result=m.method==='initialize'?{protocolVersion:'2024-11-05',capabilities:{tools:{}},serverInfo:{name:'cua-driver',version:'0.28.2'}}:answer(m.params.name, m.params.arguments);
+process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n'); });`);
+ const signal = new AbortController().signal;
+ const typing = { action: "computer_call", tool_name: "type_text", arguments: { pid: 90, window_id: 9, delivery_mode: "foreground", text: "Notiz, 28.10" } };
+ const state = async cua => JSON.parse((await cua.call({ action: "computer_call", tool_name: "get_screen_size" }, signal)).content[0].text);
+ for (const platform of ["win32", "darwin"]) {
+ const cua = createSharedCua({ mcpCommand: process.execPath, mcpArgs: [script] }, { platform });
+ t.after(() => cua.close());
+ const typed = await cua.call(typing, signal);
+ const after = await state(cua);
+ if (platform === "win32") {
+ assert.equal(after.document, "Notiz, 28.10");
+ assert.equal(typed.content[0].text, "✅ Typed 12 char(s) on pid 90 via SendInput (delivery_mode:foreground), one character at a time.");
+ assert.deepEqual(after.calls, [..."Notiz, 28.10"].flatMap(() => ["bring_to_front", "type_text"]).concat("list_windows", "bring_to_front", "get_screen_size"));
+ assert.equal(after.front, 7);
+ } else {
+ assert.equal(after.document, "N00000000000");
+ assert.deepEqual(after.calls, ["type_text", "get_screen_size"]);
+ }
+ cua.close();
+ }
+});
+
test("a protected directory spelled in another case is still refused", async t => {
const { dir, folder, grant, run } = await fixture(t);
if (!(await spellings(dir)).case) return t.skip("this filesystem is case-sensitive, so no case variant names the same directory");
diff --git a/server/lent-screen-guidance.test.ts b/server/lent-screen-guidance.test.ts
index af27afa937..5d7eda6e6c 100644
--- a/server/lent-screen-guidance.test.ts
+++ b/server/lent-screen-guidance.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { LENT_BROWSER_NO_ENDPOINT, LENT_SCREEN_BACKGROUND, LENT_SCREEN_BROWSING, lentScreenResult } from "./lent-screen-guidance.ts";
import { omittedFromErrorNote } from "./mcp-error-result.ts";
+import { CLICK_SENT_UNCONFIRMED } from "./unconfirmed-click.ts";
const call = (tool_name: string) => ({ action: "computer_call", tool_name });
const failed = (text: string) => ({ content: [{ type: "text", text }], isError: true });
@@ -41,6 +42,17 @@ describe("a lent screen's answers carry the fix", () => {
expect(texts(lentScreenResult(call("click"), failed("Computer control is unavailable. Enable it in the local app and grant OS permissions first.")))[0]).toMatch(/^Computer control is not running on this computer\./);
expect(texts(lentScreenResult(call("click"), failed("fetch failed")))[0]).toMatch(/restart OpenMausBot on that computer/);
});
+ it("answers a click that was sent but whose after-check failed as sent; the same words from typing stay a failure", () => {
+ const after = failed("foreground_unavailable: exact target HWND 0x30a5c or a verified same-process post-action window was not foreground after the click (actual foreground HWND 0x1f00)");
+ for (const tool of ["click", "double_click", "right_click"]) {
+ const answer = lentScreenResult(call(tool), after) as { isError?: boolean };
+ expect(texts(answer)).toEqual([CLICK_SENT_UNCONFIRMED]);
+ expect(answer.isError).toBeUndefined();
+ }
+ // type_text focuses a field with this click and then types nothing.
+ expect(lentScreenResult(call("type_text"), after)).toEqual(after);
+ });
+
it("passes a lent screen's error on as text only, and its successful screenshots unchanged", () => {
const image = { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" };
const refused = { content: [{ type: "text", text: "refused" }, image], isError: true };
diff --git a/server/lent-screen-guidance.ts b/server/lent-screen-guidance.ts
index 04e43e1a93..f9d39d4e6c 100644
--- a/server/lent-screen-guidance.ts
+++ b/server/lent-screen-guidance.ts
@@ -1,6 +1,7 @@
// What a bot is told when it uses the apps and screen of a computer lent to this server. The desktop relays cua-driver's
// answers unchanged and older desktops send raw failures, so the plain fix is added here, on the server.
import { textOnlyErrorResult } from "./mcp-error-result.ts";
+import { CLICK_TOOLS, unconfirmedClickResult } from "./unconfirmed-click.ts";
type Part = { type?: unknown; text?: unknown };
type ToolResult = { content?: Part[]; isError?: boolean };
@@ -43,6 +44,8 @@ export function lentScreenResult(operation: { action: string; tool_name?: string
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(withPart(result, LENT_SCREEN_BROWSING), LENT_SCREEN_BACKGROUND);
+ const sent = CLICK_TOOLS.has(operation.tool_name ?? "") ? unconfirmedClickResult(result) : null;
+ if (sent) return sent;
if (result.isError) {
const text = textOf(result);
const fix = RAW_FAILURES.find(([pattern]) => pattern.test(text));
diff --git a/server/local-computer-guidance.test.ts b/server/local-computer-guidance.test.ts
index 585835a877..e4bbd7aede 100644
--- a/server/local-computer-guidance.test.ts
+++ b/server/local-computer-guidance.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
-import { localComputerCallQuery, localComputerResultLine, OWN_PROFILE_UNAVAILABLE } from "./local-computer-guidance.ts";
+import { localComputerCallQuery, localComputerRelay, localComputerResultLine, OWN_PROFILE_UNAVAILABLE } from "./local-computer-guidance.ts";
+import type { ChildCalls } from "./mcp-bridge.ts";
+import { CLICK_SENT_UNCONFIRMED } from "./unconfirmed-click.ts";
// cua-driver 0.28.2's answer to browser_prepare {strategy:{kind:"existing_profile"}} from a standard-mode daemon, verbatim.
const EXISTING_PROFILE_REFUSAL = JSON.stringify({
@@ -69,3 +71,44 @@ describe("localComputerResultLine", () => {
}
});
});
+
+describe("localComputerRelay", () => {
+ const child = (answer: (name: string, args: Record<string, unknown>) => Record<string, unknown>, driverVersion = "0.28.2") => {
+ const calls: Array<[string, Record<string, unknown>]> = [];
+ const relayed: ChildCalls = { driverVersion, call: async (name, args) => { calls.push([name, args]); return answer(name, args); } };
+ return { calls, relayed };
+ };
+ const typing = { name: "type_text", arguments: { pid: 4242, window_id: 7, delivery_mode: "foreground", text: "hi" } };
+ const after = "foreground_unavailable: exact target HWND 0x7 or a verified same-process post-action window was not foreground after the click (actual foreground HWND 0x9)";
+ const front = { content: [{ type: "text", text: "front" }], structuredContent: { previous_fg_hwnd: "0x7", target_hwnd: "0x7" } };
+ const typed = { content: [{ type: "text", text: "typed" }], structuredContent: { effect: "unverifiable", route: "global_input" } };
+
+ it("leaves macOS and Linux calls to the driver as they came", () => {
+ for (const platform of ["darwin", "linux"]) {
+ const { relayed } = child(() => ({}));
+ expect(localComputerRelay(platform)(typing, relayed)).toBeNull();
+ expect(localComputerRelay(platform)({ name: "click", arguments: { pid: 1, x: 1, y: 1 } }, relayed)).toBeNull();
+ }
+ });
+
+ it("on Windows types foreground text one character at a time on a driver that sends it in one burst", async () => {
+ const { calls, relayed } = child((name) => (name === "bring_to_front" ? front : typed));
+ const answer = await localComputerRelay("win32")(typing, relayed);
+ expect(calls.filter(([name]) => name === "type_text").map(([, args]) => args.text)).toEqual(["h", "i"]);
+ expect(answer).toMatchObject({ content: [{ type: "text", text: expect.stringMatching(/^✅ Typed 2 char\(s\) on pid 4242 .*one character at a time\.$/) }] });
+ expect(localComputerRelay("win32")(typing, child(() => typed, "0.35.0").relayed)).toBeNull();
+ expect(localComputerRelay("win32")({ name: "type_text", arguments: { pid: 4242, window_id: 7, text: "hi" } }, relayed)).toBeNull();
+ });
+
+ it("on Windows answers a sent click whose after-check failed as the click it was, and every other answer as it is", async () => {
+ for (const name of ["click", "double_click", "right_click"]) {
+ const { calls, relayed } = child(() => ({ content: [{ type: "text", text: after }], isError: true }));
+ const answer = await localComputerRelay("win32")({ name, arguments: { pid: 4242, window_id: 7, x: 10, y: 20, delivery_mode: "foreground" } }, relayed);
+ expect(calls).toEqual([[name, { pid: 4242, window_id: 7, x: 10, y: 20, delivery_mode: "foreground" }]]);
+ expect(answer).toMatchObject({ content: [{ type: "text", text: CLICK_SENT_UNCONFIRMED }] });
+ }
+ const refused = { content: [{ type: "text", text: "foreground_unavailable: … no mouse input was sent" }], isError: true };
+ expect(await localComputerRelay("win32")({ name: "click", arguments: {} }, child(() => refused).relayed)).toBe(refused);
+ expect(localComputerRelay("win32")({ name: "get_window_state", arguments: {} }, child(() => ({})).relayed)).toBeNull();
+ });
+});
diff --git a/server/local-computer-guidance.ts b/server/local-computer-guidance.ts
index ab07a60df5..fc3682f111 100644
--- a/server/local-computer-guidance.ts
+++ b/server/local-computer-guidance.ts
@@ -1,7 +1,10 @@
// cua-driver 0.28.2 refuses browser_prepare's existing_profile strategy in standard mode unless its daemon was launched with
// --grant existing-profile or an authorization host, and its embedded host (SDK through 0.37.0) takes neither. The refusal
// names only those two, so a bot relays them to the person, who has no way to act on either.
+import { typeOneCharacterAtATime, typesInOneBurst } from "../electron/paced-typing.mjs";
import { describeComputerCall } from "../shared/your-computer.ts";
+import type { ChildCalls, ToolCall } from "./mcp-bridge.ts";
+import { CLICK_TOOLS, unconfirmedClickResult } from "./unconfirmed-click.ts";
type JsonObject = Record<string, unknown>;
@@ -45,3 +48,16 @@ export function localComputerCallQuery(frame: unknown): Record<string, string> {
const { app, site } = describeComputerCall(frame);
return { ...(app ? { app } : {}), ...(site ? { site } : {}) };
}
+
+/** The calls this computer's driver gets in a form of its own. Only on Windows: there foreground text is typed one
+ * character at a time, and a click whose after-check failed is answered as the sent click it was. */
+export function localComputerRelay(platform: string) {
+ return (call: ToolCall, child: ChildCalls): Promise<unknown> | null => {
+ if (platform !== "win32") return null;
+ if (typesInOneBurst(platform, child.driverVersion, call.name, call.arguments)) {
+ return typeOneCharacterAtATime(child.call, call.arguments as ToolCall["arguments"] & { text: string });
+ }
+ if (!CLICK_TOOLS.has(call.name)) return null;
+ return child.call(call.name, call.arguments).then((result) => unconfirmedClickResult(result) ?? result);
+ };
+}
diff --git a/server/local-computer-proxy.test.ts b/server/local-computer-proxy.test.ts
index 01a56627f1..60e164d892 100644
--- a/server/local-computer-proxy.test.ts
+++ b/server/local-computer-proxy.test.ts
@@ -12,6 +12,7 @@ import { describe, expect, it } from "vitest";
import { CONTROL_UNCONFIRMED } from "./control-client.ts";
import { gatedLocalComputer } from "./local-computer.ts";
import { OWN_PROFILE_UNAVAILABLE } from "./local-computer-guidance.ts";
+import { CLICK_SENT_UNCONFIRMED } from "./unconfirmed-click.ts";
import { SPAWNED_PROXIES } from "./proxy-paths.ts";
import { wideSchema } from "./testing/oversized-tool-schema.ts";
import { TOOL_SCHEMA_PROFILE_ENV } from "./tool-schema-profile.ts";
@@ -241,6 +242,80 @@ readline.createInterface({input: process.stdin}).on("line", (line) => {
}
});
+ it.each(["win32", "darwin"] as const)("%s: a foreground type_text reaches the driver so that every character lands", async (platform) => {
+ // Notepad behind cua-driver 0.28.2 on Windows: of one SendInput burst only the first character lands, the rest repeat the last.
+ const driver = `
+const readline = require("node:readline");
+const hex = (value) => "0x" + value.toString(16);
+const owners = { [0x30a5c]: 4242, [0x1f00]: 77 };
+let front = 0x1f00, document = "";
+const calls = [];
+const answer = (name, args) => {
+ calls.push(name);
+ if (name === "bring_to_front") {
+ const target = args.window_id, previous = front;
+ front = target;
+ return { content: [{ type: "text", text: "front" }], structuredContent: { previous_fg_hwnd: hex(previous), now_fg_hwnd: hex(target), target_hwnd: hex(target), landed_on_target: true } };
+ }
+ if (name === "list_windows") return { content: [{ type: "text", text: "windows" }], structuredContent: { windows: Object.entries(owners).map(([id, pid]) => ({ window_id: Number(id), pid })) } };
+ if (name === "type_text") {
+ const text = args.text;
+ document += text.length < 2 ? text : text[0] + text.at(-1).repeat(text.length - 1);
+ return { content: [{ type: "text", text: "typed" }], structuredContent: { effect: "unverifiable", route: "global_input", delivery: { mode: "foreground" } } };
+ }
+ if (name === "click") return { content: [{ type: "text", text: "foreground_unavailable: exact target HWND 0x30a5c or a verified same-process post-action window was not foreground after the click (actual foreground HWND 0x1f00)" }], isError: true, structuredContent: { code: "tool_invocation_failed" } };
+ return { content: [{ type: "text", text: JSON.stringify({ document, calls, front }) }] };
+};
+readline.createInterface({input: process.stdin}).on("line", (line) => {
+ const message = JSON.parse(line);
+ if (message.id === undefined) return;
+ const result = message.method === "initialize"
+ ? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "cua-driver", version: "0.28.2" } }
+ : answer(message.params.name, message.params.arguments);
+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }) + "\\n");
+});
+`;
+ const server = createServer((_request, response) => {
+ response.writeHead(200, { "content-type": "application/json" });
+ response.end(JSON.stringify({ held: false, helpOpen: false }));
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const connection = gatedLocalComputer(
+ { command: process.execPath, args: ["-e", driver], env: {}, platform, scope: "local-computer" },
+ { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/control`, token: "typing-fixture-token" },
+ );
+ const child = spawn(connection.command, connection.args, { env: { ...process.env, ...connection.env }, stdio: ["pipe", "pipe", "pipe"] });
+ try {
+ const lines = createInterface({ input: child.stdout! })[Symbol.asyncIterator]();
+ const rpc = async (id: number, method: string, params: Record<string, unknown> = {}) => {
+ child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
+ const answer = JSON.parse((await lines.next()).value as string);
+ expect(answer.id).toBe(id);
+ return answer.result;
+ };
+ const state = async (id: number) => JSON.parse((await rpc(id, "tools/call", { name: "read_fixture", arguments: {} })).content[0].text);
+ await rpc(1, "initialize");
+ const text = " Zeile Drei";
+ const typed = await rpc(2, "tools/call", { name: "type_text", arguments: { pid: 4242, window_id: 0x30a5c, delivery_mode: "foreground", text } });
+ const after = await state(3);
+ const clicked = await rpc(4, "tools/call", { name: "click", arguments: { pid: 4242, window_id: 0x30a5c, x: 10, y: 20, delivery_mode: "foreground" } });
+ if (platform === "win32") {
+ expect(after.document).toBe(text);
+ expect(typed.content[0].text).toBe("✅ Typed 11 char(s) on pid 4242 via SendInput (delivery_mode:foreground), one character at a time.");
+ expect(after.calls).toEqual([...[...text].flatMap(() => ["bring_to_front", "type_text"]), "list_windows", "bring_to_front", "read_fixture"]);
+ expect(after.front).toBe(0x1f00);
+ expect(clicked).toEqual({ content: [{ type: "text", text: CLICK_SENT_UNCONFIRMED }], structuredContent: { effect: "unverifiable", route: "global_input", delivery: { mode: "foreground" } } });
+ } else {
+ expect(after.document).toBe(" iiiiiiiiii");
+ expect(after.calls).toEqual(["type_text", "read_fixture"]);
+ expect(clicked.isError).toBe(true);
+ }
+ } finally {
+ child.kill("SIGKILL");
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ });
+
it("rejects malformed environment and missing authority without printing connection secrets", () => {
for (const overrides of [
{ OMB_CUA_ARGS: "not-json-private-value" },
diff --git a/server/local-computer-proxy.ts b/server/local-computer-proxy.ts
index 1771faebfa..54528b4f8b 100644
--- a/server/local-computer-proxy.ts
+++ b/server/local-computer-proxy.ts
@@ -1,11 +1,12 @@
// The descriptor and turn token travel in environment variables, never argv or logs.
import { runMcpBridge } from "./mcp-bridge.ts";
import { augmentedPath } from "./env-path.ts";
-import { localComputerCallQuery, localComputerResultLine } from "./local-computer-guidance.ts";
+import { localComputerCallQuery, localComputerRelay, localComputerResultLine } from "./local-computer-guidance.ts";
const {
OMB_CUA_COMMAND: command,
OMB_CUA_ARGS: encodedArgs,
+ OMB_CUA_PLATFORM: platform,
OMB_CONTROL_URL: url,
OMB_CONTROL_TOKEN: token,
...childEnv
@@ -34,4 +35,5 @@ runMcpBridge({
label: "Local Cua Driver",
gate: { url: url!, token: token!, describe: localComputerCallQuery },
rewriteResponse: localComputerResultLine,
+ relay: localComputerRelay(platform ?? process.platform),
});
diff --git a/server/local-computer.test.ts b/server/local-computer.test.ts
index 54f6780303..9c4aea938d 100644
--- a/server/local-computer.test.ts
+++ b/server/local-computer.test.ts
@@ -97,7 +97,7 @@ describe("local computer descriptor contract", () => {
};
const gated = gatedLocalComputer(connection, { url: "http://127.0.0.1:1234/control", token: "fixture-token" });
expect(gated).toMatchObject({ command: process.execPath, args: ["--experimental-strip-types", SPAWNED_PROXIES.localComputer], platform: "linux", scope: "local-computer", generation: connection.generation });
- expect(gated.env).toEqual({ ...connection.env, ELECTRON_RUN_AS_NODE: "1", OMB_CUA_COMMAND: connection.command, OMB_CUA_ARGS: JSON.stringify(connection.args), OMB_CONTROL_URL: "http://127.0.0.1:1234/control", OMB_CONTROL_TOKEN: "fixture-token" });
+ expect(gated.env).toEqual({ ...connection.env, ELECTRON_RUN_AS_NODE: "1", OMB_CUA_COMMAND: connection.command, OMB_CUA_ARGS: JSON.stringify(connection.args), OMB_CUA_PLATFORM: "linux", OMB_CONTROL_URL: "http://127.0.0.1:1234/control", OMB_CONTROL_TOKEN: "fixture-token" });
expect(gated.args.join(" ")).not.toContain("fixture-token");
expect(connection.env).not.toHaveProperty("OMB_CONTROL_TOKEN");
});
diff --git a/server/local-computer.ts b/server/local-computer.ts
index 0c90f46da5..61c60b191e 100644
--- a/server/local-computer.ts
+++ b/server/local-computer.ts
@@ -39,6 +39,7 @@ export function gatedLocalComputer(
ELECTRON_RUN_AS_NODE: "1",
OMB_CUA_COMMAND: connection.command,
OMB_CUA_ARGS: JSON.stringify(connection.args),
+ OMB_CUA_PLATFORM: connection.platform,
OMB_CONTROL_URL: control.url,
OMB_CONTROL_TOKEN: control.token,
},
diff --git a/server/mcp-bridge.test.ts b/server/mcp-bridge.test.ts
index cb9afa72c1..6ae017b138 100644
--- a/server/mcp-bridge.test.ts
+++ b/server/mcp-bridge.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import { CONTROL_REFUSAL_PLAIN, CONTROL_UNCONFIRMED, CONTROL_WAITED, type ControlState } from "./control-client.ts";
import {
+ createChildCalls,
createGateInterceptor,
createInactivityWatchdog,
createLineSplitter,
@@ -160,7 +161,7 @@ describe("createGateInterceptor", () => {
const refused: string[] = [];
const intercept = createGateInterceptor({
check,
- forward: (line) => forwarded.push(line),
+ forward: (line) => { forwarded.push(line); },
refuse: (line) => refused.push(line),
});
return { forwarded, refused, intercept };
@@ -264,7 +265,7 @@ describe("createGateInterceptor", () => {
const refused: string[] = [];
const intercept = createGateInterceptor({
check: () => new Promise<ControlState>((resolve) => checks.push(resolve)),
- forward: (line) => forwarded.push(line),
+ forward: (line) => { forwarded.push(line); },
refuse: (line) => refused.push(line),
actWithinMs: 1_000,
});
@@ -288,6 +289,67 @@ describe("createGateInterceptor", () => {
vi.useRealTimers();
}
});
+
+ it("checks the next call only once a relayed one has acted, so the agent's calls act in order", async () => {
+ const order: string[] = [];
+ let finishRelay!: () => void;
+ const relayed = new Promise<void>((resolve) => (finishRelay = resolve));
+ const intercept = createGateInterceptor({
+ check: async (checked: any) => { order.push(`check:${checked.id}`); return free; },
+ forward: (line) => {
+ const id = JSON.parse(line).id;
+ order.push(`fwd:${id}`);
+ return id === 1 ? relayed.then(() => { order.push("relayed:1"); }) : undefined;
+ },
+ refuse: (line) => order.push(`ref:${JSON.parse(line).id}`),
+ });
+ const first = intercept(frame("tools/call", 1));
+ const second = intercept(frame("tools/call", 2));
+ await drain();
+ expect(order).toEqual(["check:1", "fwd:1"]);
+ finishRelay();
+ await Promise.all([first, second]);
+ expect(order).toEqual(["check:1", "fwd:1", "relayed:1", "check:2", "fwd:2"]);
+ });
+});
+
+describe("createChildCalls", () => {
+ it("calls the child under ids of its own with the agent's metadata, and keeps those answers from the agent", async () => {
+ const written: any[] = [];
+ const children = createChildCalls((line) => written.push(JSON.parse(line)));
+ const meta = { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {} };
+ const typed = children.forCall(meta).call("type_text", { text: "a" });
+ const plain = children.forCall(undefined).call("list_windows", {});
+ expect(written).toEqual([
+ { jsonrpc: "2.0", id: "omb-bridge-1", method: "tools/call", params: { name: "type_text", arguments: { text: "a" }, _meta: meta } },
+ { jsonrpc: "2.0", id: "omb-bridge-2", method: "tools/call", params: { name: "list_windows", arguments: {} } },
+ ]);
+ expect(children.take(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { content: [] } }))).toBe(false);
+ expect(children.take(JSON.stringify({ jsonrpc: "2.0", id: "omb-bridge-1", result: { content: [{ type: "text", text: "typed" }] } }))).toBe(true);
+ expect(children.take(JSON.stringify({ jsonrpc: "2.0", id: "omb-bridge-2", error: { code: -32602, message: "Missing required per-request MCP metadata" } }))).toBe(true);
+ await expect(typed).resolves.toEqual({ content: [{ type: "text", text: "typed" }] });
+ await expect(plain).resolves.toEqual({ content: [{ type: "text", text: "Missing required per-request MCP metadata" }], isError: true });
+ expect(children.take(JSON.stringify({ jsonrpc: "2.0", id: "omb-bridge-1", result: {} }))).toBe(false);
+ });
+
+ it("learns the driver's version from its initialize answer or its per-request metadata", () => {
+ const legacy = createChildCalls(() => {});
+ expect(legacy.forCall(undefined).driverVersion).toBeUndefined();
+ expect(legacy.take(JSON.stringify({ jsonrpc: "2.0", id: 0, result: { serverInfo: { name: "cua-driver", version: "0.28.2" } } }))).toBe(false);
+ expect(legacy.forCall(undefined).driverVersion).toBe("0.28.2");
+ const modern = createChildCalls(() => {});
+ modern.take(JSON.stringify({ jsonrpc: "2.0", id: 3, result: { tools: [], _meta: { "io.modelcontextprotocol/serverInfo": { name: "cua-driver", version: "0.38.0" } } } }));
+ expect(modern.forCall(undefined).driverVersion).toBe("0.38.0");
+ });
+
+ it("ends every waiting call, and any later one, when the child is gone", async () => {
+ const children = createChildCalls(() => {});
+ const waiting = children.forCall(undefined).call("type_text", { text: "a" });
+ children.close();
+ const closed = { content: [{ type: "text", text: "Computer-control transport closed" }], isError: true };
+ await expect(waiting).resolves.toEqual(closed);
+ await expect(children.forCall(undefined).call("type_text", { text: "b" })).resolves.toEqual(closed);
+ });
});
describe("createMcpBridgeInterceptor", () => {
@@ -299,7 +361,7 @@ describe("createMcpBridgeInterceptor", () => {
const answered: string[] = [];
const intercept = createMcpBridgeInterceptor({
answer: (line) => answered.push(line),
- forward: (line) => forwarded.push(line),
+ forward: (line) => { forwarded.push(line); },
});
intercept(frame("ping", 1));
expect(answered).toEqual(['{"jsonrpc":"2.0","id":1,"result":{}}']);
@@ -311,7 +373,7 @@ describe("createMcpBridgeInterceptor", () => {
const answered: string[] = [];
const intercept = createMcpBridgeInterceptor({
answer: (line) => answered.push(line),
- forward: (line) => forwarded.push(line),
+ forward: (line) => { forwarded.push(line); },
});
intercept(JSON.stringify({ jsonrpc: "2.0", method: "ping", params: {} }));
expect(answered).toEqual([]);
@@ -323,7 +385,7 @@ describe("createMcpBridgeInterceptor", () => {
const answered: string[] = [];
const intercept = createMcpBridgeInterceptor({
answer: (line) => answered.push(line),
- forward: (line) => forwarded.push(line),
+ forward: (line) => { forwarded.push(line); },
});
for (const line of [frame("initialize", 1), frame("tools/list", 2), "not json"]) {
expect(intercept(line)).toBeUndefined();
@@ -337,7 +399,7 @@ describe("createMcpBridgeInterceptor", () => {
const answered: string[] = [];
const intercept = createMcpBridgeInterceptor({
answer: (line) => answered.push(line),
- forward: (line) => forwarded.push(line),
+ forward: (line) => { forwarded.push(line); },
gate: { check: async () => ({ held: true, helpOpen: false, reason: "person" }) },
});
intercept(frame("ping", 1));
@@ -355,7 +417,7 @@ describe("createMcpBridgeInterceptor", () => {
const answered: string[] = [];
const intercept = createMcpBridgeInterceptor({
answer: (line) => answered.push(line),
- forward: (line) => forwarded.push(line),
+ forward: (line) => { forwarded.push(line); },
gate: { check: async () => ({ held: true, helpOpen: false, reason: "person" }) },
});
intercept(frame("tools/list", 1));
diff --git a/server/mcp-bridge.ts b/server/mcp-bridge.ts
index 5250679184..93c183df54 100644
--- a/server/mcp-bridge.ts
+++ b/server/mcp-bridge.ts
@@ -91,6 +91,18 @@ export function createInactivityWatchdog(options: {
};
}
+export interface ToolCall {
+ name: string;
+ arguments: Record<string, unknown>;
+}
+
+/** What a relay may do with the child: tools/call of its own, whose answers never reach the agent. */
+export interface ChildCalls {
+ call(name: string, args: Record<string, unknown>): Promise<Record<string, unknown>>;
+ /** From the child's initialize answer, or its per-request metadata; undefined until one is seen. */
+ readonly driverVersion: string | undefined;
+}
+
export interface BridgeOptions {
command: string;
args: string[];
@@ -101,6 +113,9 @@ export interface BridgeOptions {
/** `describe`: what a tools/call would open, passed to the gate so the person can be asked in plain words. */
gate?: { url: string; token: string; describe?: (frame: unknown) => Record<string, string> };
rewriteResponse?: (line: string) => string;
+ /** A tools/call the bridge carries out itself through the child, answering the agent with what this resolves to; null
+ * forwards the frame as it came. Frames after it wait, so the agent's calls still act in order. */
+ relay?: (call: ToolCall, child: ChildCalls) => Promise<unknown> | null;
}
/** MCP stdio is one JSON-RPC frame per line, so line boundaries are the only safe place to inspect or inject. */
@@ -131,7 +146,7 @@ export function createLineSplitter(onLine: (line: string) => void): {
/** Serialized: the check is async, and answering frame N+1 before frame N would reorder the agent's protocol stream. */
export function createGateInterceptor(options: {
check: (frame: unknown) => Promise<ControlState>;
- forward: (line: string) => void;
+ forward: (line: string) => void | Promise<void>;
refuse: (line: string) => void;
actWithinMs?: number;
}): (line: string) => Promise<void> {
@@ -146,12 +161,13 @@ export function createGateInterceptor(options: {
} catch {
}
if (!frame || frame.method !== "tools/call") {
- options.forward(line);
+ await options.forward(line);
return;
}
const state = await options.check(frame).catch((): ControlState => ({ held: true, helpOpen: false, blockedReason: CONTROL_UNCONFIRMED }));
if (!state.held && Date.now() - arrivedAt <= actWithinMs) {
- options.forward(line);
+ // A relayed call is checked once, when it arrives; the next frame's check waits until it has acted.
+ await options.forward(line);
return;
}
options.refuse(
@@ -168,7 +184,7 @@ export function createGateInterceptor(options: {
export interface McpBridgeInterceptorOptions {
answer: (line: string) => void;
- forward: (line: string) => void;
+ forward: (line: string) => void | Promise<void>;
gate?: { check: (frame: unknown) => Promise<ControlState> };
}
@@ -178,7 +194,7 @@ export function createMcpBridgeInterceptor(
): (line: string) => void | Promise<void> {
const afterPing = options.gate
? createGateInterceptor({ check: options.gate.check, forward: options.forward, refuse: options.answer })
- : (line: string) => { options.forward(line); };
+ : (line: string) => options.forward(line);
return (line: string) => {
let frame: any = null;
try {
@@ -196,6 +212,81 @@ export function createMcpBridgeInterceptor(
};
}
+const OWN_ID = "omb-bridge-";
+const SERVER_INFO_META = "io.modelcontextprotocol/serverInfo";
+
+function isObject(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+function failed(text: string): Record<string, unknown> {
+ return { content: [{ type: "text", text }], isError: true };
+}
+
+/** A tools/call request the agent waits on, as a relay sees it; anything else is not the relay's to answer. */
+function relayableCall(line: string): { id: unknown; call: ToolCall; meta: unknown } | null {
+ let frame: any = null;
+ try {
+ frame = JSON.parse(line);
+ } catch {
+ return null;
+ }
+ const params = frame?.method === "tools/call" && frame.id !== undefined && frame.id !== null ? frame.params : null;
+ if (!isObject(params) || typeof params.name !== "string") return null;
+ return { id: frame.id, call: { name: params.name, arguments: isObject(params.arguments) ? params.arguments : {} }, meta: params._meta };
+}
+
+/** The bridge's own calls on the child, under ids the agent never sees. */
+export function createChildCalls(write: (line: string) => void) {
+ let sequence = 0;
+ let driverVersion: string | undefined;
+ let closed = false;
+ const waiting = new Map<string, (result: Record<string, unknown>) => void>();
+ return {
+ /** Each call carries the agent's own `_meta`: a driver spoken to with per-request metadata refuses a call without it. */
+ forCall(meta: unknown): ChildCalls {
+ return {
+ call(name, args) {
+ if (closed) return Promise.resolve(failed("Computer-control transport closed"));
+ const id = `${OWN_ID}${++sequence}`;
+ return new Promise((resolve) => {
+ waiting.set(id, resolve);
+ write(JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args, ...(meta === undefined ? {} : { _meta: meta }) } }));
+ });
+ },
+ get driverVersion() {
+ return driverVersion;
+ },
+ };
+ },
+ /** Notes the driver's version, and keeps an answer to one of the bridge's calls from the agent (true when it did). */
+ take(line: string): boolean {
+ const versioned = driverVersion === undefined && line.includes("serverInfo");
+ const ours = waiting.size > 0 && line.includes(OWN_ID);
+ if (!versioned && !ours) return false;
+ let frame: any = null;
+ try {
+ frame = JSON.parse(line);
+ } catch {
+ return false;
+ }
+ const version = frame?.result?.serverInfo?.version ?? frame?.result?._meta?.[SERVER_INFO_META]?.version;
+ if (versioned && typeof version === "string") driverVersion = version;
+ const resolve = ours && typeof frame?.id === "string" ? waiting.get(frame.id) : undefined;
+ if (!resolve) return false;
+ waiting.delete(frame.id);
+ resolve(isObject(frame.result) ? frame.result : failed(String(frame.error?.message ?? "Computer control returned no result")));
+ return true;
+ },
+ /** The child is gone: every call still waiting, and any made later, ends as a failure. */
+ close() {
+ closed = true;
+ for (const resolve of waiting.values()) resolve(failed("Computer-control transport closed"));
+ waiting.clear();
+ },
+ };
+}
+
export function runMcpBridge(options: BridgeOptions): void {
const env = options.env ?? { ...process.env, PATH: augmentedPath() };
const { command, args } = resolveCliSpawn(options.command, options.args, env);
@@ -214,13 +305,35 @@ export function runMcpBridge(options: BridgeOptions): void {
: null;
const answer = (line: string) => process.stdout.write(line + "\n");
- const forward = (line: string) => child.stdin.write(line + "\n");
+ const toolLists = createToolListNormalizer(toolSchemaProfileFromEnv(), (line) => process.stderr.write(`${options.label}: ${line}\n`));
+ // Injected responses must never land inside one of the child's half-written frames.
+ const rewrite = options.rewriteResponse ?? ((line: string) => line);
+ const respond = (line: string) => process.stdout.write(textOnlyErrorResultLine(rewrite(toolLists.rewriteResponse(line))) + "\n");
+ const children = createChildCalls((line) => child.stdin.write(line + "\n"));
+ const send = async (line: string) => {
+ const frame = line.includes('"tools/call"') ? relayableCall(line) : null;
+ const relayed = frame && options.relay?.(frame.call, children.forCall(frame.meta));
+ if (!frame || !relayed) {
+ child.stdin.write(line + "\n");
+ return;
+ }
+ const result = await relayed.catch((error: unknown) => failed(error instanceof Error ? error.message : String(error)));
+ respond(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result }));
+ };
+ let sending: Promise<void> = Promise.resolve();
+ const forward = (line: string): void | Promise<void> => {
+ if (!options.relay) {
+ child.stdin.write(line + "\n");
+ return;
+ }
+ sending = sending.then(() => send(line)).catch(() => {});
+ return sending;
+ };
const intercept = createMcpBridgeInterceptor({
answer,
forward,
...(client ? { gate: { check: (frame: unknown) => client.state(true, options.gate?.describe?.(frame)) } } : {}),
});
- const toolLists = createToolListNormalizer(toolSchemaProfileFromEnv(), (line) => process.stderr.write(`${options.label}: ${line}\n`));
let pendingInput = Promise.resolve();
const inbound = createLineSplitter((line) => {
toolLists.observeRequest(line);
@@ -236,9 +349,9 @@ export function runMcpBridge(options: BridgeOptions): void {
void pendingInput.finally(() => child.stdin.end());
});
- // Injected responses must never land inside one of the child's half-written frames.
- const rewrite = options.rewriteResponse ?? ((line: string) => line);
- const outbound = createLineSplitter((line) => process.stdout.write(textOnlyErrorResultLine(rewrite(toolLists.rewriteResponse(line))) + "\n"));
+ const outbound = createLineSplitter((line) => {
+ if (!children.take(line)) respond(line);
+ });
child.stdout.on("data", (chunk) => outbound.push(chunk));
child.stdout.on("end", () => outbound.flush());
@@ -275,6 +388,7 @@ export function runMcpBridge(options: BridgeOptions): void {
process.stderr.write(`could not connect to ${options.label}: ${error.message}\n`);
process.exitCode = 1;
watchdog?.stop();
+ children.close();
detach();
});
child.on("close", (code, signal) => {
@@ -282,6 +396,7 @@ export function runMcpBridge(options: BridgeOptions): void {
// process.exit() here would discard buffered stdout mid-frame: set exitCode and let stdio drain.
process.exitCode = process.exitCode ?? code ?? 1;
watchdog?.stop();
+ children.close();
detach();
});
diff --git a/server/unconfirmed-click.test.ts b/server/unconfirmed-click.test.ts
new file mode 100644
index 0000000000..3d2333536b
--- /dev/null
+++ b/server/unconfirmed-click.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { CLICK_SENT_UNCONFIRMED, unconfirmedClickResult } from "./unconfirmed-click.ts";
+
+// cua-driver 0.28.2's own words (platform-windows/src/input/mouse.rs), with the conforming error envelope it adds.
+const failed = (text: string, extra: Record<string, unknown> = {}) => ({ content: [{ type: "text", text }], isError: true, structuredContent: { code: "tool_invocation_failed" }, ...extra });
+const AFTER = "foreground_unavailable: exact target HWND 0x30a5c or a verified same-process post-action window was not foreground after the click (actual foreground HWND 0x1f00)";
+
+describe("a Windows click whose after-check failed", () => {
+ it("is answered as the sent, unconfirmed click it was, in the shape the driver gives a confirmed one", () => {
+ expect(unconfirmedClickResult(failed(AFTER))).toEqual({
+ content: [{ type: "text", text: CLICK_SENT_UNCONFIRMED }],
+ structuredContent: { effect: "unverifiable", route: "global_input", delivery: { mode: "foreground" } },
+ });
+ // A driver spoken to with per-request metadata keeps its protocol fields.
+ const meta = { "io.modelcontextprotocol/serverInfo": { name: "cua-driver", version: "0.28.2" } };
+ expect(unconfirmedClickResult(failed(AFTER, { resultType: "complete", _meta: meta }))).toMatchObject({ resultType: "complete", _meta: meta });
+ expect(CLICK_SENT_UNCONFIRMED).not.toMatch(/HWND|foreground_unavailable/);
+ });
+
+ it("leaves every refusal from before the click alone: those sent nothing", () => {
+ for (const before of [
+ "foreground_unavailable: Windows did not activate exact target HWND 0x30a5c (actual foreground HWND 0x1f00); no mouse input was sent",
+ "foreground_unavailable: exact target HWND 0x30a5c disappeared before mouse input could be sent",
+ "foreground_unavailable: Windows did not confirm keyboard focus on exact UIA element [3] in HWND 0x30a5c; no keyboard input was sent",
+ "SendInput inserted fewer modifier or mouse events than expected for the foreground click.",
+ ]) expect(unconfirmedClickResult(failed(before))).toBeNull();
+ expect(unconfirmedClickResult({ content: [{ type: "text", text: AFTER }] })).toBeNull();
+ expect(unconfirmedClickResult(null)).toBeNull();
+ });
+});
diff --git a/server/unconfirmed-click.ts b/server/unconfirmed-click.ts
new file mode 100644
index 0000000000..ffa9b5400c
--- /dev/null
+++ b/server/unconfirmed-click.ts
@@ -0,0 +1,35 @@
+// cua-driver 0.28.2 (and its main branch in October 2026) checks after a Windows foreground click that the clicked window,
+// or a window it owns, is in front (platform-windows/src/input/mouse.rs). A click that picks a menu item closes the menu,
+// and one that opens or closes a window moves the front elsewhere, so the check fails after the click was sent, and the
+// driver answers foreground_unavailable as if nothing happened: the bot then repeats the click or reports a failure.
+
+type JsonObject = Record<string, unknown>;
+
+/** Only this check runs after the input; every check before it says no input was sent. */
+const AFTER_THE_CLICK = /^foreground_unavailable: .* was not foreground after the click\b/u;
+
+export const CLICK_TOOLS: ReadonlySet<string> = new Set(["click", "double_click", "right_click"]);
+
+export const CLICK_SENT_UNCONFIRMED =
+ "The click was sent. Afterwards a different window was in front, which is what happens when a click picks a menu item " +
+ "(the menu closes) or opens or closes a window, so where it landed is not confirmed. Do not click again until you have " +
+ "checked the result with get_window_state.";
+
+function isObject(value: unknown): value is JsonObject {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+/** The driver's answer when only its after-click check failed, told as the sent, unconfirmed click it was; otherwise null. */
+export function unconfirmedClickResult(result: unknown): JsonObject | null {
+ if (!isObject(result) || result.isError !== true || !Array.isArray(result.content)) return null;
+ const said = result.content.some((part) => isObject(part) && part.type === "text" && typeof part.text === "string" && AFTER_THE_CLICK.test(part.text));
+ if (!said) return null;
+ // Its protocol fields (resultType, _meta) stay; what it said does not.
+ const envelope = Object.fromEntries(Object.entries(result).filter(([key]) => !["content", "structuredContent", "isError"].includes(key)));
+ return {
+ ...envelope,
+ content: [{ type: "text", text: CLICK_SENT_UNCONFIRMED }],
+ // What the driver answers for a foreground click whose check passes: a strict client holds success to this schema.
+ structuredContent: { effect: "unverifiable", route: "global_input", delivery: { mode: "foreground" } },
+ };
+}