Skip to content
96 changes: 80 additions & 16 deletions electron/cua.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ export function setCuaStateListener(listener) {
stateListener = typeof listener === "function" ? listener : () => {};
}

function persistAndNotify(next) {
const connection = connectionStore.persist(next);
stateListener(connection);
return connection;
}

export function resolveDriverBinary() {
if (process.env.CUA_DRIVER_PATH) return process.env.CUA_DRIVER_PATH;
if (app.isPackaged) {
Expand Down Expand Up @@ -124,6 +130,29 @@ async function loadEmbeddedSdk() {
return import(pathToFileURL(path.join(process.resourcesPath, "cua-sdk", "cua-sdk.mjs")).href);
}

async function attachStandalone() {
const driver = fs.existsSync(INSTALLED_DRIVER) ? INSTALLED_DRIVER : null;
if (!driver) return null;
if (!(await socketAlive(STANDALONE_SOCKET))) {
// Launch CuaDriver.app through LaunchServices so Accessibility /
// Screen Recording stay on com.trycua.driver — the identity this
// machine already granted — instead of the freshly signed OpenMausBot.
spawnSync("open", ["-a", "CuaDriver"], { timeout: 8000 });
for (let i = 0; i < 25; i++) {
if (await socketAlive(STANDALONE_SOCKET)) break;
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
if (!(await socketAlive(STANDALONE_SOCKET))) return null;
return {
mode: "standalone",
socketPath: STANDALONE_SOCKET,
mcpCommand: driver,
mcpArgs: ["mcp"],
mcpEnv: { ...CUA_ENV },
};
}

async function startEmbedded(binary) {
// Import from the staged Resources tree in production. The app intentionally
// excludes general node_modules, so a bare package import only works in dev.
Expand All @@ -139,22 +168,33 @@ async function startEmbedded(binary) {
].filter(Boolean).join(" and ");
throw new Error(`${missing || "macOS permissions"} required; grant access in System Settings and restart OpenMausBot`);
}
embeddedHost = new sdk.EmbeddedCuaDriverHost(binary, HOST_BUNDLE_ID);
const conn = await embeddedHost.start();
return {
mode: "embedded",
socketPath: conn.socketPath,
mcpCommand: binary,
mcpArgs: ["mcp", "--embedded", "--socket", conn.socketPath],
mcpEnv: { ...CUA_ENV, CUA_DRIVER_EMBEDDED: "1", CUA_DRIVER_HOST_BUNDLE_ID: HOST_BUNDLE_ID },
};
const host = new sdk.EmbeddedCuaDriverHost(binary, HOST_BUNDLE_ID);
try {
const conn = await host.start();
embeddedHost = host;
return {
mode: "embedded",
socketPath: conn.socketPath,
mcpCommand: binary,
mcpArgs: ["mcp", "--embedded", "--socket", conn.socketPath],
mcpEnv: { ...CUA_ENV, CUA_DRIVER_EMBEDDED: "1", CUA_DRIVER_HOST_BUNDLE_ID: HOST_BUNDLE_ID },
};
} catch (err) {
try {
await host.stop();
} catch {
// startup already failed; stop is best-effort before destroy
}
host.uniffiDestroy?.();
throw err;
}
}

export async function startCua() {
if (process.platform === "linux") return ensureLinuxRuntime().initialize();
const binary = resolveDriverBinary();
if (!binary) {
return connectionStore.persist({
return persistAndNotify({
mode: "unavailable",
reason: "cua-driver binary not found",
});
Expand All @@ -168,10 +208,13 @@ export async function startCua() {
try {
nextConnection = await startEmbedded(binary);
} catch (err) {
nextConnection = {
mode: "unavailable",
reason: `embedded host failed: ${err?.message ?? err}`,
};
nextConnection = await attachStandalone();
if (!nextConnection) {
nextConnection = {
mode: "unavailable",
reason: `embedded host failed: ${err?.message ?? err}`,
};
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
} else if (await socketAlive(STANDALONE_SOCKET)) {
// Dev machine with CuaDriver.app's daemon already running.
Expand All @@ -190,7 +233,7 @@ export async function startCua() {
};
}

return connectionStore.persist(nextConnection);
return persistAndNotify(nextConnection);
}

export function cuaPermissionsStatus() {
Expand Down Expand Up @@ -227,7 +270,7 @@ export async function stopCua() {
embeddedHost = null;
}
if (connectionStore.get()) {
connectionStore.persist({ mode: "unavailable", reason: "desktop-host-stopped" });
persistAndNotify({ mode: "unavailable", reason: "desktop-host-stopped" });
}
}

Expand Down Expand Up @@ -262,6 +305,27 @@ export function registerCuaIpc() {
return ensureLinuxRuntime().getStatus();
});
ipcMain.handle("cua:linux-retry", async () => {
if (process.platform === "darwin") {
try {
await stopCua();
const connection = await startCua();
const ready = connection?.mode === "embedded" || connection?.mode === "standalone";
return {
enabled: ready,
status: ready ? "ready" : "error",
reasonCode: ready ? undefined : "permissions-required",
message: connection?.reason,
};
} catch (error) {
console.error("[cua] macOS retry failed:", error);
return {
enabled: false,
status: "error",
reasonCode: "permissions-required",
message: error instanceof Error ? error.message : String(error),
};
}
}
if (process.platform !== "linux") {
return { enabled: false, status: "unavailable", reasonCode: "unsupported-platform" };
}
Expand Down
1 change: 1 addition & 0 deletions electron/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,7 @@ ipcMain.handle("perm:open-settings", (_event, pane) => {
mic: "Privacy_Microphone",
screen: "Privacy_ScreenCapture",
speech: "Privacy_SpeechRecognition",
accessibility: "Privacy_Accessibility",
};
// own-property lookup only — a renderer-supplied "__proto__"/"constructor"
// would otherwise resolve up the prototype chain to a truthy object
Expand Down
24 changes: 24 additions & 0 deletions scripts/cua-mac-arches.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export const DEFAULT_MAC_ARCHES = ["arm64", "x64"];

/** Which darwin CUA trees to stage. electron-builder packages both arches
* unless the caller opts into a one-arch local stage. An empty override
* is never a silent no-op. */
export function resolveCuaMacArches(env = process.env) {
const raw = env.OPENMAUSBOT_CUA_ARCHES;
if (raw === undefined) return [...DEFAULT_MAC_ARCHES];
const arches = raw.split(",").map((arch) => arch.trim()).filter(Boolean);
if (arches.length === 0) {
throw new Error(
"OPENMAUSBOT_CUA_ARCHES is empty; omit the variable to stage arm64 and x64",
);
}
if (env.OPENMAUSBOT_CUA_ARCHES_PARTIAL !== "1") {
const missing = DEFAULT_MAC_ARCHES.filter((arch) => !arches.includes(arch));
if (missing.length) {
throw new Error(
`OPENMAUSBOT_CUA_ARCHES omits ${missing.join(", ")} but electron-builder packages both arm64 and x64. Set OPENMAUSBOT_CUA_ARCHES_PARTIAL=1 for a one-arch local stage.`,
);
}
}
return arches;
}
24 changes: 24 additions & 0 deletions scripts/cua-mac-arches.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MAC_ARCHES, resolveCuaMacArches } from "./cua-mac-arches.mjs";

describe("resolveCuaMacArches", () => {
it("defaults to both packaging targets", () => {
expect(resolveCuaMacArches({})).toEqual(DEFAULT_MAC_ARCHES);
});

it("rejects an empty override even when PARTIAL=1", () => {
expect(() => resolveCuaMacArches({ OPENMAUSBOT_CUA_ARCHES: "", OPENMAUSBOT_CUA_ARCHES_PARTIAL: "1" })).toThrow(
/OPENMAUSBOT_CUA_ARCHES is empty/,
);
expect(() => resolveCuaMacArches({ OPENMAUSBOT_CUA_ARCHES: " , ", OPENMAUSBOT_CUA_ARCHES_PARTIAL: "1" })).toThrow(
/OPENMAUSBOT_CUA_ARCHES is empty/,
);
});

it("rejects a one-arch override unless PARTIAL=1", () => {
expect(() => resolveCuaMacArches({ OPENMAUSBOT_CUA_ARCHES: "arm64" })).toThrow(/omits x64/);
expect(resolveCuaMacArches({ OPENMAUSBOT_CUA_ARCHES: "arm64", OPENMAUSBOT_CUA_ARCHES_PARTIAL: "1" })).toEqual([
"arm64",
]);
});
});
3 changes: 2 additions & 1 deletion scripts/prepare-cua.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { build } from "esbuild";
import { resolveCuaMacArches } from "./cua-mac-arches.mjs";

if (process.platform !== "darwin") throw new Error("prepare-cua is macOS-only");

Expand Down Expand Up @@ -107,7 +108,7 @@ if (!details.isFile() || (details.mode & 0o111) === 0) {
// not on a user's Intel Mac); the SDK's dylib/.node are genuinely per-arch,
// pulled from the two darwin native packages that pnpm installs because of
// supportedArchitectures in package.json.
const MAC_ARCHES = ["arm64", "x64"];
const MAC_ARCHES = resolveCuaMacArches(process.env);

const { stdout: archList } = await run("/usr/bin/lipo", ["-archs", binary]);
for (const arch of MAC_ARCHES) {
Expand Down
11 changes: 9 additions & 2 deletions server/auto-approve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,16 @@ describe("autoDecision", () => {
expect(autoDecision({ alwaysAllow: ["Bash"] }, "Bash", "sudo rm -rf /var")).toBeNull();
});

it("never delegates a local-computer request to auto or remembered grants", () => {
it("auto-approves a local-computer request when Auto mode is on", () => {
expect(
autoDecision({ autoApprove: true }, "mcp__computer__click", "Click the Submit button", {
scope: "local-computer",
}),
).toBe("auto-approved mcp__computer__click");
});

it("does not let always-allow cover host control without Auto mode", () => {
const bot = {
autoApprove: true,
alwaysAllow: ["mcp__computer__click", "local-computer:mcp__computer__click"],
};
expect(
Expand Down
9 changes: 4 additions & 5 deletions server/auto-approve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,10 @@ export function autoVerdict(
if (sensitive) return { approve: null, source: "sensitive-guard", rule: sensitive };
return { approve: null, source: "no-grant" };
}
if (context?.scope === "local-computer") {
// The user's active desktop is never delegated to bot auto mode or a
// remembered cloud/tool grant in the Linux beta. Same attribution rule
// as the unattended block: a guard that would have carded anyway keeps
// its own name, the block is the story only when it changed the outcome.
if (context?.scope === "local-computer" && !bot.autoApprove) {
// Host control is not covered by a remembered always-allow grant.
// After the Auto-on-this-computer warning, unclassified GUI actions
// (click/type) may auto-approve; destructive/sensitive still card.
if (grant) return { approve: null, source: "local-computer-block", rule: grant.rule };
if (destructive) return { approve: null, source: "destructive-guard", rule: destructive };
if (sensitive) return { approve: null, source: "sensitive-guard", rule: sensitive };
Expand Down
39 changes: 29 additions & 10 deletions server/drivers/acp/kimi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,28 @@ function stripTomlLineComment(line: string): string {
return line;
}

/** Decode a TOML basic-string escape at `text[i]` (`i` points at the `\\`). */
function takeTomlBasicEscape(text: string, i: number): { value: string; next: number } {
/** Decode a TOML basic-string escape at `text[i]` (`i` points at the `\\`).
* Invalid / unknown / surrogate / out-of-range sequences return ok:false so
* the heading is not canonicalized to a colliding alias. */
function takeTomlBasicEscape(
text: string,
i: number,
): { ok: true; value: string; next: number } | { ok: false } {
const code = text[i + 1];
if (code === undefined) return { ok: false };
if (code === "u") {
const hex = text.slice(i + 2, i + 6);
if (/^[0-9a-fA-F]{4}$/.test(hex)) {
return { value: String.fromCharCode(parseInt(hex, 16)), next: i + 6 };
}
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return { ok: false };
const point = parseInt(hex, 16);
if (point >= 0xd800 && point <= 0xdfff) return { ok: false };
return { ok: true, value: String.fromCharCode(point), next: i + 6 };
}
if (code === "U") {
const hex = text.slice(i + 2, i + 10);
if (/^[0-9a-fA-F]{8}$/.test(hex)) {
const point = parseInt(hex, 16);
return { value: point <= 0x10ffff ? String.fromCodePoint(point) : "", next: i + 10 };
}
if (!/^[0-9a-fA-F]{8}$/.test(hex)) return { ok: false };
const point = parseInt(hex, 16);
if (point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff)) return { ok: false };
return { ok: true, value: String.fromCodePoint(point), next: i + 10 };
}
const named: Record<string, string> = {
b: "\b",
Expand All @@ -94,7 +101,8 @@ function takeTomlBasicEscape(text: string, i: number): { value: string; next: nu
'"': '"',
"\\": "\\",
};
return { value: named[code ?? ""] ?? code ?? "", next: i + 2 };
if (!(code in named)) return { ok: false };
return { ok: true, value: named[code]!, next: i + 2 };
}

/** Canonical `a.b.c` form of a `[table]` heading, quotes and comments removed. */
Expand All @@ -117,6 +125,7 @@ function canonicalizeTomlHeading(heading: string): string | null {
while (i < inner.length && inner[i] !== q) {
if (q === '"' && inner[i] === "\\") {
const taken = takeTomlBasicEscape(inner, i);
if (!taken.ok) return null;
value += taken.value;
i = taken.next;
continue;
Expand Down Expand Up @@ -185,6 +194,11 @@ function tomlTables(text: string): Array<{ name: string; headingStart: number; b
continue;
}
if (mode === "basic") {
if (text[i] === "\n") {
mode = "out";
i += 1;
continue;
}
if (text[i] === "\\") {
i += 2;
continue;
Expand All @@ -194,6 +208,11 @@ function tomlTables(text: string): Array<{ name: string; headingStart: number; b
continue;
}
if (mode === "literal") {
if (text[i] === "\n") {
mode = "out";
i += 1;
continue;
}
if (text[i] === "'") mode = "out";
i += 1;
continue;
Expand Down
13 changes: 13 additions & 0 deletions server/drivers/claude-catalog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ describe("readClaudeModelCatalog", () => {
],
});
});

it("does not list settings.model as a Custom leftover", () => {
const home = mkdtempSync(join(tmpdir(), "omb-claude-leftover-"));
scratchDirs.push(home);
const dir = join(home, ".claude");
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, "settings.json"),
JSON.stringify({ model: "orcarouter/Qwen3.8-27B-Uncensored-GGUF" }),
);

expect(readClaudeModelCatalog({ HOME: home })).toEqual(STATIC_CLAUDE_MODELS);
});
});

describe("ClaudeDriver catalog", () => {
Expand Down
30 changes: 30 additions & 0 deletions server/drivers/claude.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,36 @@ describe("ClaudeDriver turns (fake CLI)", () => {
expect(seen.env.ANTHROPIC_AUTH_TOKEN).toBe("unsloth-secret");
});

it("injects a leftover API id when a local host is serving that model", async () => {
const previousFetch = globalThis.fetch;
globalThis.fetch = (async (url: string | URL) => {
if (String(url).includes(":8888")) {
return new Response(JSON.stringify({ data: [{ id: "orcarouter/Qwen3.8-27B-Uncensored-GGUF" }] }), { status: 200 });
}
return new Response("nope", { status: 500 });
}) as typeof fetch;
try {
await create(undefined, { UNSLOTH_STUDIO_AUTH_TOKEN: "unsloth-secret" });
const dump = join(scratch, "dump-leftover.json");
process.env.FAKE_CLAUDE_DUMP = dump;

await instance.adapter.sendTurn({
threadId: "t-leftover-local",
text: "hi",
model: "orcarouter/Qwen3.8-27B-Uncensored-GGUF",
});
await recorder.until((e) => e.type === "turn.completed");

const seen = JSON.parse(readFileSync(dump, "utf8"));
expect(seen.argv[seen.argv.indexOf("--model") + 1]).toBe("orcarouter/Qwen3.8-27B-Uncensored-GGUF");
expect(seen.env.ANTHROPIC_BASE_URL).toBe("http://127.0.0.1:8888");
expect(seen.env.ANTHROPIC_AUTH_TOKEN).toBe("unsloth-secret");
expect(seen.env.ANTHROPIC_API_KEY).toBe("unsloth-secret");
} finally {
globalThis.fetch = previousFetch;
}
});

it("mounts the agents comms proxy as an MCP server and pre-allows its tools", async () => {
await create();
const dump = join(scratch, "dump.json");
Expand Down
Loading
Loading