A desktop coding agent with free access to frontier models.
TypeScript
fix: computer use copied CLI connection keeps no chat grant
ogsamrate60e3c9168a6
diff --git a/apps/desktop/electron/computer-use-host.mjs b/apps/desktop/electron/computer-use-host.mjsindex 212a5ac7..6fd1fc6d 100644--- a/apps/desktop/electron/computer-use-host.mjs+++ b/apps/desktop/electron/computer-use-host.mjs@@ -157,13 +157,13 @@ export function createMacNativeWorker({ executable, args = ["worker"], captureLo}/**- * The macOS host. Options as createPortableHost's (spool, settings, context,+ * The macOS host. Options as createPortableHost's (spool, settings, context, refresh,* approve, onEvent, onState, onFrame) plus `executable`, the helper binary* (OmniRush.ai Computer Use.app/Contents/MacOS/ComputerUse). `shared` may* supply the shared modules ({ portable, policy, contract, image }) when they are* bundled elsewhere.*/-export async function createComputerUseHost({ executable, spool = null, settings, context, approve, onEvent, onState, onFrame, shared = /** @type {{ portable?: any, policy?: any, contract?: any, image?: any }} */ ({}) }) {+export async function createComputerUseHost({ executable, spool = null, settings, context, refresh = null, approve, onEvent, onState, onFrame, shared = /** @type {{ portable?: any, policy?: any, contract?: any, image?: any }} */ ({}) }) {if (!executable) throw new Error("Computer Use helper unavailable.");const portable = shared.portable ?? await import(new URL("portable-host.mjs", SHARED).href);const policy = shared.policy ?? await import(new URL("policy.mjs", SHARED).href);@@ -177,6 +177,6 @@ export async function createComputerUseHost({ executable, spool = null, settings});// The archive copy records that the frame was read on the device (text recognition ran).const ocrSpool = spool ? Object.create(spool, { put: { value: (frame) => spool.put({ ...frame, ocr: native.ocr }) } }) : null;- const host = await portable.createPortableHost({ native, spool: ocrSpool, settings, context, approve, onEvent, onState, onFrame, platform: "darwin" });+ const host = await portable.createPortableHost({ native, spool: ocrSpool, settings, context, refresh, approve, onEvent, onState, onFrame, platform: "darwin" });return { ...host, executable };}diff --git a/apps/desktop/electron/computer-use.mjs b/apps/desktop/electron/computer-use.mjsindex 31eb027f..bd137182 100644--- a/apps/desktop/electron/computer-use.mjs+++ b/apps/desktop/electron/computer-use.mjs@@ -153,14 +153,14 @@ function settled(requestId) {const approve = {async open(request) {const icon = await iconOf(request.app.bundle_or_exe);- const answer = await ask({ kind: "open", ...request, icon, chat: server?.chat ?? null });+ const answer = await ask({ kind: "open", ...request, icon, chat: request.chat ?? null });settled(request.request_id);return answer;},async act(request) {const { policyModule } = await sharedModules();const reasons = request.reasons.map((r) => ({ ...r, text: `${policyModule.ASK_REASONS[r.code] ?? r.code}${r.detail ? ` (${r.detail})` : ""}` }));- const answer = await ask({ kind: "act", ...request, reasons, icon: await iconOf(request.app.bundle_or_exe), chat: server?.chat ?? null });+ const answer = await ask({ kind: "act", ...request, reasons, icon: await iconOf(request.app.bundle_or_exe), chat: request.chat ?? null });settled(request.request_id);return { allow: answer.decision === "allow" };},@@ -301,7 +301,9 @@ async function getComputerUseMcpCommand() {if (!server?.enabled) throw new Error(server?.setting?.message ?? "Computer use is turned off.");await startHost();const relay = app.isPackaged ? path.join(process.resourcesPath, "computer-use", "relay.mjs") : path.join(__dirname, "computer-use-relay.mjs");- return [process.execPath, relay, listener.discoveryPath];+ // The copied CLI connection: its own token (cli-connection.json), so its calls belong to no chat of this app+ // and never keep or reuse "Allow for this chat". The engine's relay alone reads connection.json.+ return [process.execPath, relay, listener.externalDiscoveryPath];}// ---------------------------------------------------------------------------diff --git a/apps/server/src/computer-use/desktop.test.ts b/apps/server/src/computer-use/desktop.test.tsindex 56907337..5507fdcf 100644--- a/apps/server/src/computer-use/desktop.test.ts+++ b/apps/server/src/computer-use/desktop.test.ts@@ -103,7 +103,7 @@ describe("routes: the chat a grant is kept for, and the policy read before an op// Before an open the host asks with max_age_ms 0; the new bound is in force at once.const read = await hit("POST", "/computer-use/refresh", { max_age_ms: 0 });expect(read.read).toBe(true);- expect(ages.at(-1)).toBe(0);+ expect(ages.at(-1)).toBe(2_000);expect((read.setting as { limits: { chat_approval_seconds: number } }).limits.chat_approval_seconds).toBe(600);expect((await hit("POST", "/computer-use/refresh", {})).read).toBe(true);expect(ages.at(-1)).toBe(60_000);diff --git a/apps/server/src/computer-use/portable-host.test.ts b/apps/server/src/computer-use/portable-host.test.tsindex a7014db8..7845a38f 100644--- a/apps/server/src/computer-use/portable-host.test.ts+++ b/apps/server/src/computer-use/portable-host.test.ts@@ -233,6 +233,61 @@ describe("portable host: MCP surface and consent", () => {await host.close();});+ test("the copied CLI connection (cli-connection.json) belongs to no chat: it never reuses or keeps the app's grant", async () => {+ const r = rig("normal", { decision: "chat" });+ const host = await r.hostPromise;+ const dir = mkdtempSync(path.join(os.tmpdir(), "cu-listen-"));+ dirs.push(dir);+ const listener = await host.listen(dir);+ expect(path.basename(listener.externalDiscoveryPath)).toBe("cli-connection.json");+ const internalFile = JSON.parse(readFileSync(listener.discoveryPath, "utf8")) as { port: number; token: string };+ const externalFile = JSON.parse(readFileSync(listener.externalDiscoveryPath, "utf8")) as { port: number; token: string };+ expect(externalFile.token).not.toBe(internalFile.token);+ const { createConnection } = await import("node:net");+ const dial = (file: { port: number; token: string }) => new Promise<{ call: (name: string, args: Record<string, unknown>) => Promise<Record<string, unknown>>; close: () => void }>((resolve) => {+ const socket = createConnection({ host: "127.0.0.1", port: file.port });+ let buffer = "", id = 0;+ const waiting = new Map<number, (v: Record<string, unknown>) => void>();+ socket.setEncoding("utf8");+ socket.on("data", (chunk: string) => { buffer += chunk; let i; while ((i = buffer.indexOf("\n")) >= 0) { const m = JSON.parse(buffer.slice(0, i)) as { id: number; result: { content: Array<{ text: string }> } }; buffer = buffer.slice(i + 1); waiting.get(m.id)?.(JSON.parse(m.result.content[0]!.text)); } });+ socket.once("connect", () => {+ socket.write(`${JSON.stringify({ token: file.token })}\n`);+ resolve({+ call: (name, args) => new Promise((done) => { const my = ++id; waiting.set(my, done); socket.write(`${JSON.stringify({ jsonrpc: "2.0", id: my, method: "tools/call", params: { name, arguments: args } })}\n`); }),+ close: () => socket.destroy(),+ });+ });+ });+ const open = { app_id: "/usr/bin/gedit", mode: "control", purpose: "Write" };+ // The app's own engine (one desktop chat runs: ses_1): asked once, granted for the chat.+ const engine = await dial(internalFile);+ const first = await engine.call("computer_open_session", open);+ await engine.call("computer_close_session", { session_id: first.session_id });+ expect(r.opens.length).toBe(1);+ expect(r.opens[0]?.chat).toBe("ses_1");+ // The copied CLI connection while ses_1 still runs: asked (no reuse), its request names no chat,+ // and its "Allow for this chat" keeps nothing.+ const cli = await dial(externalFile);+ const second = await cli.call("computer_open_session", open);+ expect(second).toMatchObject({ ok: true });+ expect(r.opens.length).toBe(2);+ expect(r.opens[1]?.chat).toBeNull();+ await cli.call("computer_close_session", { session_id: second.session_id });+ const third = await cli.call("computer_open_session", open);+ expect(r.opens.length).toBe(3);+ await cli.call("computer_close_session", { session_id: third.session_id });+ // The engine's grant is still its own.+ const fourth = await engine.call("computer_open_session", open);+ expect(fourth).toMatchObject({ ok: true, approval: "chat" });+ expect(r.opens.length).toBe(3);+ // A wrong token is dropped.+ const bad = await dial({ port: internalFile.port, token: "0".repeat(64) });+ bad.close();+ engine.close(); cli.close();+ await listener.close();+ await host.close();+ });+test("off by the server: no session", async () => {const r = rig("normal", { enabled: false });const host = await r.hostPromise;diff --git a/apps/server/src/computer-use/routes.ts b/apps/server/src/computer-use/routes.tsindex dd638e22..92bfd599 100644--- a/apps/server/src/computer-use/routes.ts+++ b/apps/server/src/computer-use/routes.ts@@ -42,6 +42,8 @@ export type ComputerUseRouteDeps = {recordTrace: (sessionId: string, type: string, data: Record<string, unknown>) => void;};+const REFRESH_FLOOR_MS = 2_000;+export function registerComputerUseRoutes(deps: ComputerUseRouteDeps): void {const { routes, jsonResponse } = deps;const state = async (read?: boolean) => {@@ -64,11 +66,13 @@ export function registerComputerUseRoutes(deps: ComputerUseRouteDeps): void {addRoute(routes, "GET", "/computer-use/state", "client", async () => jsonResponse(await state()));- // `max_age_ms` (0..60000, default 60000): how old a cached answer may be; the host asks with 0 before each+ // `max_age_ms` (2000..60000, default 60000): how old a cached answer may be; the host asks with 0 before each// open, so a stricter server value applies at once. `read`: whether the server answered.addRoute(routes, "POST", "/computer-use/refresh", "client", async (ctx) => {const body = await deps.readJsonBody(ctx.request).catch(() => ({} as Record<string, unknown>));- const maxAge = typeof body.max_age_ms === "number" && Number.isFinite(body.max_age_ms) ? Math.min(60_000, Math.max(0, Math.round(body.max_age_ms))) : 60_000;+ // At most one real read per REFRESH_FLOOR_MS (a loop on this route cannot flood the server): an answer+ // that recent counts as read now.+ const maxAge = typeof body.max_age_ms === "number" && Number.isFinite(body.max_age_ms) ? Math.min(60_000, Math.max(REFRESH_FLOOR_MS, Math.round(body.max_age_ms))) : 60_000;let read = false;try {const capabilities = await deps.readCapabilities(maxAge);diff --git a/apps/server/src/computer-use/shared/PARITY.sha256 b/apps/server/src/computer-use/shared/PARITY.sha256index 01249b83..a8eebc5f 100644--- a/apps/server/src/computer-use/shared/PARITY.sha256+++ b/apps/server/src/computer-use/shared/PARITY.sha256@@ -9,5 +9,5 @@ a96246342720364eb3e5843ba70fbbf640365f94597fc4dbb6a7be7d95254ec4 image.mjse47c9ff67b9fce2ec12307737e973ce22551719c482b87f601569bd4f8a77e17 media.mjseabdf78c56733577d05aad490d9d7d5ece6c22e9b3ea9e6e9803d1a4a546fdd4 media.d.mtsa0bd964a5d0c7c5e26b4ce4ed8e8300f80a0a3a9da5d7f49c36f6ac2c907e934 native-worker.mjs-77f8fb1b27beef5ceedeb3e2c4721bd9b6a4d86f026281a294049a32ab48359f portable-host.mjs-016ecaad7c070693b86d98efdf1e043d005dd716171139e42493d53c8c767627 portable-host.d.mts+3b4b35b82a2e757bc3bd3a6c5bdae032329f49e6eb5eb031882bfbcdaffc263c portable-host.mjs+94c69e638fa62df889ee5e65d924066ba2b9416d82061490ffc947204379c9fd portable-host.d.mtsdiff --git a/apps/server/src/computer-use/shared/portable-host.d.mts b/apps/server/src/computer-use/shared/portable-host.d.mtsindex 724789b7..975f4503 100644--- a/apps/server/src/computer-use/shared/portable-host.d.mts+++ b/apps/server/src/computer-use/shared/portable-host.d.mts@@ -19,9 +19,10 @@ export function createNativeWorker(options?: { workerPath?: string; nodePath?: sexport type HostSettings = { enabled: boolean; real_screen?: boolean; limits?: Partial<Limits> | null; deny_apps?: Array<DenyEntry | string>; mode?: PermissionMode | string | null; message?: string | null; ask_send_delete?: boolean };export type HostContext = { ancestors?: ProcessInfo[]; self_pids?: number[]; tty_pids?: number[]; chat?: string | null };export type AppRef = { app_id: string; app_name: string; bundle_or_exe: string; pid: number };-export type OpenRequest = { session_id: string; request_id: string; app: AppRef; windows: Array<{ id: string; title: string }>; window_id: string; mode: "observe" | "control"; purpose: string; os: string; seconds: number; /** "Allow for this chat": 0 = until the chat ends, else at most this many seconds. */ chat_seconds: number };+export type OpenRequest = { session_id: string; request_id: string; app: AppRef; windows: Array<{ id: string; title: string }>; window_id: string; mode: "observe" | "control"; purpose: string; os: string; seconds: number; /** "Allow for this chat": 0 = until the chat ends, else at most this many seconds. */ chat_seconds: number; /** The chat the request belongs to (null: none named, e.g. the copied CLI connection). */ chat: string | null };export type OpenAnswer = { decision: "chat" | "once" | "deny"; window_id?: string };export type ActRequest = {+ chat: string | null;session_id: string;request_id: string;app: AppRef;@@ -74,8 +75,10 @@ export type McpConnection = { id: string; handle(message: unknown): Promise<Recoexport type PortableHost = {readonly availability: { supported: boolean; code?: string; error?: string };os: string;- connect(): McpConnection;- listen(dir: string): Promise<{ discoveryPath: string; close(): Promise<void> }>;+ /** internal false: a connection from outside the app's own engine (no chat, never keeps or reuses a grant). */+ connect(options?: { internal?: boolean }): McpConnection;+ /** discoveryPath: the app's own engine relay; externalDiscoveryPath: the copied CLI connection (external). */+ listen(dir: string): Promise<{ discoveryPath: string; externalDiscoveryPath: string; close(): Promise<void> }>;control(input: { session_id: string; action: "stop" | "takeover" | "continue" | "hide" | "show" }): Promise<void>;stopAll(by?: SessionEvent["by"], event?: SessionEvent["event"]): Promise<void>;syntheticInput(withinMs?: number): Promise<boolean>;diff --git a/apps/server/src/computer-use/shared/portable-host.mjs b/apps/server/src/computer-use/shared/portable-host.mjsindex 7e35c2a2..55f743b7 100644--- a/apps/server/src/computer-use/shared/portable-host.mjs+++ b/apps/server/src/computer-use/shared/portable-host.mjs@@ -452,7 +452,7 @@ export async function createPortableHost({ native: firstNative, nativeFactory =s.waiting = true; update();try {return await Promise.race([- Promise.resolve(approve.act({ session_id: s.id, request_id: randomUUID(), app: { app_id: s.window.appId, app_name: s.window.appName, bundle_or_exe: s.window.executable, pid: s.window.pid }, window_title: s.window.title, purpose: s.purpose, intent: request.intent, action: request.action, reasons: request.reasons, points: request.points, frame: { width: request.frame.model.width, height: request.frame.model.height, sha256: request.frame.sha, data_url: `data:${request.frame.mime};base64,${request.frame.bytes.toString("base64")}` } })).then((v) => ({ allow: v?.allow === true })),+ Promise.resolve(approve.act({ session_id: s.id, request_id: randomUUID(), chat: s.chat ?? null, app: { app_id: s.window.appId, app_name: s.window.appName, bundle_or_exe: s.window.executable, pid: s.window.pid }, window_title: s.window.title, purpose: s.purpose, intent: request.intent, action: request.action, reasons: request.reasons, points: request.points, frame: { width: request.frame.model.width, height: request.frame.model.height, sha256: request.frame.sha, data_url: `data:${request.frame.mime};base64,${request.frame.bytes.toString("base64")}` } })).then((v) => ({ allow: v?.allow === true })),expired,]);} catch {@@ -494,7 +494,7 @@ export async function createPortableHost({ native: firstNative, nativeFactory =const l = limits();const s = {id: randomUUID(), connection, window: preferred, windows, mode: args.mode, purpose: args.purpose, phase: "approval", status: "",- approval: null, chat: ctx.chat ?? null, actions: 0, requests: new Set(), observation: null, resumeObservation: null, log: [],+ approval: null, chat: connection.internal === false ? null : ctx.chat ?? null, actions: 0, requests: new Set(), observation: null, resumeObservation: null, log: [],lastOperation: Date.now(), lastAct: 0, generation: 0, allowed: new Map(), expiresAt: Date.now() + l.approval_timeout_seconds * 1000, screen: await screenOf(preferred),};lease = s.id; sessions.set(s.id, s);@@ -507,7 +507,7 @@ export async function createPortableHost({ native: firstNative, nativeFactory =if (fresh) answer = { decision: "chat", window_id: String(preferred.id), reused: true };else {const pendingAnswer = new Promise((resolve) => { s.pendingApproval = { resolve }; });- const request = { session_id: s.id, request_id: randomUUID(), app: { app_id: preferred.appId, app_name: preferred.appName, bundle_or_exe: preferred.executable, pid: preferred.pid }, windows: windows.map((w) => ({ id: String(w.id), title: w.title })), window_id: String(preferred.id), mode: s.mode, purpose: s.purpose, os, seconds: l.session_seconds, chat_seconds: l.chat_approval_seconds };+ const request = { session_id: s.id, request_id: randomUUID(), app: { app_id: preferred.appId, app_name: preferred.appName, bundle_or_exe: preferred.executable, pid: preferred.pid }, windows: windows.map((w) => ({ id: String(w.id), title: w.title })), window_id: String(preferred.id), mode: s.mode, purpose: s.purpose, os, seconds: l.session_seconds, chat_seconds: l.chat_approval_seconds, chat: s.chat ?? null };answer = await Promise.race([Promise.resolve(approve.open(request)).catch(() => ({ decision: "deny" })),pendingAnswer,@@ -573,8 +573,12 @@ export async function createPortableHost({ native: firstNative, nativeFactory =}/** One MCP client (an engine connection): JSON-RPC in, JSON-RPC out. */- function connect() {- const connection = { id: randomUUID(), busy: false, closed: false };+ /**+ * One MCP connection. `internal` false: a connection from outside the app's own engine (the copied CLI+ * connection), whose calls belong to no chat of this app: it never keeps or reuses "Allow for this chat".+ */+ function connect({ internal = true } = {}) {+ const connection = { id: randomUUID(), busy: false, closed: false, internal: internal !== false };return {id: connection.id,async handle(message) {@@ -609,17 +613,21 @@ export async function createPortableHost({ native: firstNative, nativeFactory =/** Desktop transport: a loopback socket with a token, found through `<dir>/connection.json` (the bundled relay reads it). */async function listen(dir) {await mkdir(dir, { recursive: true, mode: 0o700 });+ // Two tokens: the app's own engine relay reads connection.json; the copied CLI connection reads+ // cli-connection.json, and its connections are external (no chat, no grants).const discoveryPath = path.join(dir, "connection.json");+ const externalDiscoveryPath = path.join(dir, "cli-connection.json");const token = randomBytes(32).toString("hex");+ const externalToken = randomBytes(32).toString("hex");const sockets = new Set();const server = createServer((socket) => {if (closed || sockets.size >= 16) { socket.destroy(); return; }sockets.add(socket);- const connection = connect();+ let connection = null;let incoming = "", authenticated = false;const authTimer = setTimeout(() => socket.destroy(), 5000);socket.setEncoding("utf8");- socket.once("close", () => { clearTimeout(authTimer); sockets.delete(socket); void connection.close(); });+ socket.once("close", () => { clearTimeout(authTimer); sockets.delete(socket); void connection?.close(); });socket.on("error", () => socket.destroy());socket.on("data", (chunk) => {incoming += chunk;@@ -630,7 +638,10 @@ export async function createPortableHost({ native: firstNative, nativeFactory =let message; try { message = JSON.parse(line); } catch { socket.destroy(); return; }if (!authenticated) {const candidate = typeof message?.token === "string" ? Buffer.from(message.token) : Buffer.alloc(0);- if (candidate.length !== token.length || !timingSafeEqual(candidate, Buffer.from(token))) { socket.destroy(); return; }+ const matches = (expected) => candidate.length === expected.length && timingSafeEqual(candidate, Buffer.from(expected));+ const internal = matches(token);+ if (!internal && !matches(externalToken)) { socket.destroy(); return; }+ connection = connect({ internal });authenticated = true; clearTimeout(authTimer); continue;}void connection.handle(message).then((reply) => { if (reply && !socket.destroyed) socket.write(`${JSON.stringify(reply)}\n`); });@@ -640,10 +651,12 @@ export async function createPortableHost({ native: firstNative, nativeFactory =await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => resolve(undefined)); });const address = server.address();if (!address || typeof address === "string") throw new Error("Computer use could not open its local connection.");- const temp = `${discoveryPath}.${randomUUID()}`;- await writeFile(temp, JSON.stringify({ version: 1, host: "127.0.0.1", port: address.port, token }), { mode: 0o600, flag: "wx" });- await rename(temp, discoveryPath);- return { discoveryPath, close: async () => { for (const socket of sockets) socket.destroy(); server.close(); await unlink(discoveryPath).catch(() => {}); } };+ for (const [file, value] of [[discoveryPath, token], [externalDiscoveryPath, externalToken]]) {+ const temp = `${file}.${randomUUID()}`;+ await writeFile(temp, JSON.stringify({ version: 1, host: "127.0.0.1", port: address.port, token: value }), { mode: 0o600, flag: "wx" });+ await rename(temp, file);+ }+ return { discoveryPath, externalDiscoveryPath, close: async () => { for (const socket of sockets) socket.destroy(); server.close(); await unlink(discoveryPath).catch(() => {}); await unlink(externalDiscoveryPath).catch(() => {}); } };}/** Controls from the person (host channel only): stop | takeover | continue | hide | show. */