Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(desktop): make computer use agent-callable with a drawn cursor

vastsaa8b3240af973
diff --git a/apps/desktop/electron/main/computer-use/capture.ts b/apps/desktop/electron/main/computer-use/capture.ts
new file mode 100644
index 000000000..d76a86171
--- /dev/null
+++ b/apps/desktop/electron/main/computer-use/capture.ts
@@ -0,0 +1,84 @@
+import { desktopCapturer, systemPreferences } from "electron";
+import type { ComputerPermissionState, ComputerRect } from "@pi-desktop/shared";
+
+/**
+ * Scope-cropped capture for computer use (ADR 0340 §11).
+ *
+ * Chromium's `desktopCapturer` is the one part of the capability that is
+ * already cross-platform, and a window source is inherently scoped: nothing
+ * outside the granted window is ever in the frame, so there is no desktop
+ * screenshot to crop and no neighbouring window to leak.
+ *
+ * A capture that fails is not an error the loop has to handle — pixels are the
+ * fallback, not the contract — so every failure here returns `undefined` and
+ * lets the accessibility tree carry the step.
+ */
+
+/** Longest side of the image handed to the model. */
+const MAX_CAPTURE_EDGE = 1_280;
+
+function thumbnailSize(bounds: ComputerRect): { width: number; height: number } {
+ const width = Math.max(1, Math.round(bounds.width));
+ const height = Math.max(1, Math.round(bounds.height));
+ const longest = Math.max(width, height);
+ if (longest <= MAX_CAPTURE_EDGE) return { width, height };
+ const scale = MAX_CAPTURE_EDGE / longest;
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
+}
+
+/**
+ * Match a host `targetId` (`<pid>:<window>`) to a capturer source.
+ *
+ * Chromium names a window source `window:<native id>:<index>`, so the native
+ * window handle the host measured is the join key. A source that does not
+ * match is never substituted: capturing a different window would hand the
+ * model pixels from outside the grant.
+ */
+export function captureSourceIdFor(sources: readonly { id: string }[], targetId: string): string | undefined {
+ const window = targetId.split(":")[1];
+ if (!window) return undefined;
+ const prefix = `window:${window}:`;
+ return sources.find((source) => source.id.startsWith(prefix))?.id;
+}
+
+export async function captureGrantedWindow(input: {
+ targetId: string;
+ bounds: ComputerRect;
+ log?: (message: string, data?: Record<string, unknown>) => void;
+}): Promise<{ mimeType: string; base64: string } | undefined> {
+ try {
+ const sources = await desktopCapturer.getSources({
+ types: ["window"],
+ thumbnailSize: thumbnailSize(input.bounds),
+ fetchWindowIcons: false,
+ });
+ const id = captureSourceIdFor(sources, input.targetId);
+ if (!id) return undefined;
+ const source = sources.find((candidate) => candidate.id === id);
+ if (!source || source.thumbnail.isEmpty()) return undefined;
+ return { mimeType: "image/png", base64: source.thumbnail.toPNG().toString("base64") };
+ } catch (error) {
+ input.log?.("computer use capture failed", { data: String(error) });
+ return undefined;
+ }
+}
+
+/**
+ * What the doctor view can say about capture before anything is attempted.
+ * host-core cannot answer this: the capture path is Chromium's, not its.
+ */
+export function capturePermissionState(): ComputerPermissionState {
+ if (process.platform !== "darwin") {
+ // Windows needs no grant; Linux depends on the portal, which only answers
+ // when a capture is actually requested.
+ return "not-requested";
+ }
+ try {
+ const status = systemPreferences.getMediaAccessStatus("screen");
+ if (status === "granted") return "granted";
+ if (status === "denied" || status === "restricted") return "denied";
+ return "not-requested";
+ } catch {
+ return "not-requested";
+ }
+}
diff --git a/apps/desktop/electron/main/computer-use/cursor-overlay.ts b/apps/desktop/electron/main/computer-use/cursor-overlay.ts
new file mode 100644
index 000000000..66041e765
--- /dev/null
+++ b/apps/desktop/electron/main/computer-use/cursor-overlay.ts
@@ -0,0 +1,195 @@
+import { app, BrowserWindow, screen } from "electron";
+import { join } from "node:path";
+import { IPC, type ComputerCursorEvent, type ComputerRect } from "@pi-desktop/shared";
+import { getModuleDirectory } from "../module-path";
+import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";
+
+/**
+ * The agent's own cursor, drawn over the granted window (ADR 0340 §10).
+ *
+ * This window is visualization and nothing else. It is click-through, so it
+ * cannot take a press away from the user, and it owns no part of any action:
+ * the loop tells it where it is about to act, and the host's re-measurement —
+ * not this overlay — remains the authority on where an action landed. A
+ * failure to create or draw it never blocks or replaces an action, which is
+ * why every method here swallows its own errors.
+ *
+ * It exists because the actions themselves are invisible: an accessibility
+ * press moves no pointer, so without a drawn cursor the user would watch an
+ * application change by itself with nothing to point at or interrupt.
+ */
+
+export type ComputerCursorOverlay = {
+ /** Apply one draw command. Never throws. */
+ apply: (event: ComputerCursorEvent) => void;
+ /** Tear the window down; called when a grant ends and at shutdown. */
+ close: () => void;
+};
+
+/** Margin around the target so a cursor drawn at the edge is not clipped. */
+const OVERLAY_MARGIN = 48;
+
+export function createComputerCursorOverlay(input: {
+ log?: (message: string, data?: Record<string, unknown>) => void;
+}): ComputerCursorOverlay {
+ let window: BrowserWindow | null = null;
+ let creating: Promise<BrowserWindow | null> | null = null;
+ let loaded = false;
+ let pending: ComputerCursorEvent[] = [];
+ let currentGrant: string | null = null;
+
+ function destroy(): void {
+ const current = window;
+ window = null;
+ loaded = false;
+ pending = [];
+ currentGrant = null;
+ if (current && !current.isDestroyed()) current.destroy();
+ }
+
+ function overlayBounds(bounds: ComputerRect): Electron.Rectangle {
+ const x = Math.round(bounds.x - OVERLAY_MARGIN);
+ const y = Math.round(bounds.y - OVERLAY_MARGIN);
+ const width = Math.round(bounds.width + OVERLAY_MARGIN * 2);
+ const height = Math.round(bounds.height + OVERLAY_MARGIN * 2);
+ // Keep the window inside the display that holds the target, so a target
+ // near a screen edge does not produce an off-screen overlay.
+ const area = screen.getDisplayMatching({ x, y, width: Math.max(1, width), height: Math.max(1, height) }).bounds;
+ return {
+ x: Math.max(area.x, x),
+ y: Math.max(area.y, y),
+ width: Math.min(width, area.width),
+ height: Math.min(height, area.height),
+ };
+ }
+
+ function send(event: ComputerCursorEvent): void {
+ const current = window;
+ if (!current || current.isDestroyed() || !loaded) {
+ pending.push(event);
+ // The overlay is decoration; a backlog is dropped rather than grown.
+ if (pending.length > 32) pending.shift();
+ return;
+ }
+ try {
+ current.webContents.send(IPC.event.computerCursor, event);
+ } catch (error) {
+ input.log?.("computer cursor overlay send failed", { data: String(error) });
+ }
+ }
+
+ async function ensureWindow(bounds: ComputerRect): Promise<BrowserWindow | null> {
+ if (window && !window.isDestroyed()) {
+ window.setBounds(overlayBounds(bounds));
+ return window;
+ }
+ if (creating) return creating;
+ const promise = (async () => {
+ try {
+ const created = new BrowserWindow({
+ ...overlayBounds(bounds),
+ title: "PI-Desktop Computer Use",
+ show: false,
+ frame: false,
+ transparent: true,
+ backgroundColor: "#00000000",
+ hasShadow: false,
+ resizable: false,
+ movable: false,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ skipTaskbar: true,
+ focusable: false,
+ alwaysOnTop: true,
+ autoHideMenuBar: true,
+ ...(process.platform === "darwin" ? { type: "panel" as const } : {}),
+ webPreferences: {
+ preload: join(getModuleDirectory(import.meta.url), "../preload/index.cjs"),
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ additionalArguments: [`--pi-desktop-locale=${app.getLocale()}`],
+ },
+ });
+ window = created;
+ suppressLinuxFramelessSystemMenu(created);
+ // The whole point: the overlay never takes a click from the user.
+ created.setIgnoreMouseEvents(true, { forward: false });
+ created.setAlwaysOnTop(true, "screen-saver");
+ if (process.platform === "darwin") {
+ created.setVisibleOnAllWorkspaces(true, {
+ visibleOnFullScreen: true,
+ skipTransformProcessType: true,
+ });
+ }
+ created.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
+ created.webContents.on("will-navigate", (event, url) => {
+ const devOrigin = process.env.ELECTRON_RENDERER_URL;
+ if (devOrigin && url.startsWith(devOrigin)) return;
+ event.preventDefault();
+ });
+ created.webContents.on("did-finish-load", () => {
+ loaded = true;
+ const queued = pending;
+ pending = [];
+ for (const event of queued) send(event);
+ });
+ created.on("closed", () => {
+ if (window === created) {
+ window = null;
+ loaded = false;
+ }
+ });
+ if (process.env.ELECTRON_RENDERER_URL) {
+ const url = new URL(process.env.ELECTRON_RENDERER_URL);
+ url.searchParams.set("surface", "computer-cursor");
+ await created.loadURL(url.toString());
+ } else {
+ await created.loadFile(
+ join(getModuleDirectory(import.meta.url), "../renderer/index.html"),
+ { query: { surface: "computer-cursor" } },
+ );
+ }
+ created.showInactive();
+ return created;
+ } catch (error) {
+ input.log?.("computer cursor overlay failed to open", { data: String(error) });
+ destroy();
+ return null;
+ } finally {
+ creating = null;
+ }
+ })();
+ creating = promise;
+ return promise;
+ }
+
+ return {
+ apply(event) {
+ try {
+ if (event.kind === "hide") {
+ if (currentGrant && event.grantId !== currentGrant) return;
+ destroy();
+ return;
+ }
+ if (event.kind === "show") {
+ currentGrant = event.grantId;
+ void ensureWindow(event.bounds).then((created) => {
+ if (created) send(event);
+ });
+ return;
+ }
+ // A draw command for a grant that already ended is dropped: the
+ // overlay must never outlive the authority it was drawn for.
+ if (currentGrant && event.grantId !== currentGrant) return;
+ send(event);
+ } catch (error) {
+ input.log?.("computer cursor overlay command failed", { data: String(error) });
+ }
+ },
+ close() {
+ destroy();
+ },
+ };
+}
diff --git a/apps/desktop/electron/main/computer-use/provider.ts b/apps/desktop/electron/main/computer-use/provider.ts
new file mode 100644
index 000000000..3285fdcab
--- /dev/null
+++ b/apps/desktop/electron/main/computer-use/provider.ts
@@ -0,0 +1,54 @@
+import type { RuntimeProviderConfig } from "@pi-desktop/agent-runtime";
+import type { ComputerModelBinding, ProviderPublic } from "@pi-desktop/shared";
+import type { HostProcess } from "../host-process";
+
+/**
+ * Resolve the user's computer-use model into a provider config.
+ *
+ * It is deliberately its own binding rather than the conversation model
+ * (ADR 0340 §9), so it is resolved the way image generation resolves its
+ * binding: from the provider row the user picked, with its own secret. A
+ * binding whose provider is gone, disabled, or missing its key resolves to
+ * `null`, and the tool reports an unconfigured feature instead of quietly
+ * running on the chat model.
+ *
+ * The loop always asks with thinking off, so no reasoning capability is
+ * claimed here; pi-ai supplies the model's own metadata.
+ */
+export async function resolveComputerUseProvider(input: {
+ host: Pick<HostProcess, "call">;
+ binding: ComputerModelBinding;
+ resolveAuth?: (providerId: string) => Promise<unknown>;
+}): Promise<RuntimeProviderConfig | null> {
+ const { provider } = await input.host.call<{ provider?: ProviderPublic }>("providers.get", {
+ id: input.binding.providerId,
+ });
+ if (!provider?.enabled) return null;
+
+ const needsSecret = provider.authKind !== "oauth" && provider.authKind !== "none";
+ let apiKey = "";
+ if (needsSecret) {
+ const { value } = await input.host.call<{ value?: string }>("providers.getSecret", {
+ id: provider.id,
+ });
+ if (!value) return null;
+ apiKey = value;
+ }
+
+ return {
+ id: provider.id,
+ name: provider.name,
+ ...(provider.vendorKey ? { vendorKey: provider.vendorKey } : {}),
+ ...(provider.baseUrl ? { baseUrl: provider.baseUrl } : {}),
+ modelId: input.binding.modelId,
+ apiKey,
+ ...(provider.authKind ? { authKind: provider.authKind } : {}),
+ ...(provider.apiStyle ? { apiStyle: provider.apiStyle } : {}),
+ supportsReasoning: false,
+ supportedThinkingLevels: ["off"],
+ ...(provider.headers ? { headers: provider.headers } : {}),
+ ...(provider.authKind === "oauth" && input.resolveAuth
+ ? { resolveAuth: () => input.resolveAuth!(provider.id) as never }
+ : {}),
+ } as RuntimeProviderConfig;
+}
diff --git a/apps/desktop/electron/main/computer-use/service.ts b/apps/desktop/electron/main/computer-use/service.ts
new file mode 100644
index 000000000..978989178
--- /dev/null
+++ b/apps/desktop/electron/main/computer-use/service.ts
@@ -0,0 +1,274 @@
+import { completeOneShot, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";
+import { runComputerLoop, type DecisionRequest, type Observation } from "@pi-desktop/computer-use";
+import {
+ validateComputerToolArgs,
+ type AppSettings,
+ type ComputerActResult,
+ type ComputerCursorEvent,
+ type ComputerGrantView,
+ type ComputerInspection,
+ type ComputerRunResult,
+ type ComputerStepRecord,
+} from "@pi-desktop/shared";
+import type { Context } from "@earendil-works/pi-ai";
+import type { LocalToolHandler, LocalToolResult } from "../agent-sidecar";
+import type { HostProcess } from "../host-process";
+import { captureGrantedWindow } from "./capture";
+import type { ComputerCursorOverlay } from "./cursor-overlay";
+
+/**
+ * The `Computer` tool handler (ADR 0340 §1, §2).
+ *
+ * The loop lives here because it needs two things host-core deliberately does
+ * not have: a model provider and Chromium. Everything that can *refuse* stays
+ * in host-core, and this handler cannot talk itself past any of it — it holds
+ * no grant, mints none, and re-reads the live grant from the host on every
+ * observation.
+ *
+ * The tool is registered as a local tool whose permission evaluation runs in
+ * host-core first (`tools.execute`, the `GenerateImages` shape), so reaching
+ * this code already means the host authorised the call.
+ */
+
+export type ComputerUseLaunchResolver = (
+ binding: { providerId: string; modelId: string },
+ sessionId: string,
+) => Promise<RuntimeProviderConfig | null>;
+
+function failure(errorCode: string, message: string): LocalToolResult {
+ return {
+ ok: false,
+ isError: true,
+ errorCode,
+ content: { kind: "computer-use-error", errorCode, message },
+ };
+}
+
+/** Host refusals arrive as `errorCode`; the loop reads `code`. */
+function coded(error: unknown): Error & { code: string } {
+ const errorCode =
+ error && typeof error === "object" && "errorCode" in error
+ ? (error as { errorCode?: unknown }).errorCode
+ : undefined;
+ const message = error instanceof Error ? error.message : String(error);
+ return Object.assign(new Error(message), {
+ code: typeof errorCode === "string" && errorCode.startsWith("COMPUTER_")
+ ? errorCode
+ : "COMPUTER_ACTION_REJECTED",
+ });
+}
+
+/** What the model is sent. Images ride along only under a pixel grant. */
+function decisionContext(request: DecisionRequest): Context {
+ const text = [
+ `Task: ${request.instruction}`,
+ "",
+ request.observation,
+ "",
+ "Steps so far:",
+ request.history,
+ "",
+ "Answer with one JSON object.",
+ ].join("\n");
+ return {
+ systemPrompt: request.system,
+ messages: [
+ {
+ role: "user",
+ content: request.capture
+ ? [
+ { type: "text", text },
+ { type: "image", data: request.capture.base64, mimeType: request.capture.mimeType },
+ ]
+ : text,
+ timestamp: Date.now(),
+ },
+ ],
+ } as Context;
+}
+
+export function createComputerUseTool(options: {
+ getHost: () => Pick<HostProcess, "call"> | null;
+ /** Builds a provider config for the user's computer-use binding. */
+ resolveProvider: ComputerUseLaunchResolver;
+ overlay: Pick<ComputerCursorOverlay, "apply">;
+ onStep?: (step: ComputerStepRecord & { sessionId: string }) => void;
+ onGrant?: (grant: ComputerGrantView | null) => void;
+ /** Injected in tests so the loop runs without a provider. */
+ complete?: typeof completeOneShot;
+ capture?: typeof captureGrantedWindow;
+ log?: (message: string, data?: Record<string, unknown>) => void;
+}): LocalToolHandler {
+ return async ({ sessionId, args, signal }) => {
+ let input: ReturnType<typeof validateComputerToolArgs>;
+ try {
+ input = validateComputerToolArgs(args);
+ } catch (error) {
+ return failure("INVALID_ARGUMENT", error instanceof Error ? error.message : "Invalid arguments.");
+ }
+
+ const host = options.getHost();
+ if (!host) return failure("HOST_UNAVAILABLE", "Host unavailable.");
+
+ const settings = await host.call<AppSettings>("settings.get");
+ const computerUse = settings.computerUse;
+ if (computerUse?.enabled !== true) {
+ return failure(
+ "COMPUTER_DISABLED",
+ "Computer use is off. The user enables it in Settings > Computer use; it cannot be enabled from here.",
+ );
+ }
+ const binding = computerUse.model;
+ if (!binding?.providerId || !binding?.modelId) {
+ return failure(
+ "COMPUTER_NOT_CONFIGURED",
+ "Computer use has no model configured. The user picks one in Settings > Computer use. Do not substitute the conversation model.",
+ );
+ }
+
+ const described = await host.call<{ grant: ComputerGrantView | null }>("computer.grantDescribe", {});
+ const grant = described.grant;
+ if (!grant || grant.state !== "active") {
+ return failure(
+ "COMPUTER_NO_GRANT",
+ "No application is currently handed over. Ask the user to pick a window in PI-Desktop's computer-use indicator, then try again. You cannot choose the window yourself.",
+ );
+ }
+ if (grant.sessionId !== sessionId) {
+ return failure(
+ "COMPUTER_GRANT_IN_USE",
+ "Another session holds the active computer-use grant.",
+ );
+ }
+
+ const provider = await options.resolveProvider(
+ { providerId: binding.providerId, modelId: binding.modelId },
+ sessionId,
+ );
+ if (!provider) {
+ return failure(
+ "COMPUTER_NOT_CONFIGURED",
+ "The configured computer-use model is unavailable. The user updates it in Settings > Computer use.",
+ );
+ }
+
+ const complete = options.complete ?? completeOneShot;
+ const capture = options.capture ?? captureGrantedWindow;
+
+ const observe = async (): Promise<Observation> => {
+ signal.throwIfAborted();
+ try {
+ const current = await host.call<{ grant: ComputerGrantView | null }>(
+ "computer.grantDescribe",
+ {},
+ );
+ const live = current.grant;
+ if (!live || live.state !== "active" || live.grantId !== grant.grantId) {
+ throw Object.assign(new Error("the grant is no longer active"), {
+ code: "COMPUTER_GRANT_EXPIRED",
+ });
+ }
+ const inspection = await host.call<ComputerInspection>("computer.inspect", {
+ grantId: live.grantId,
+ sessionId,
+ });
+ const pixels =
+ live.capture === "a11y-and-pixels"
+ ? await capture({ targetId: live.targetId, bounds: live.bounds, log: options.log })
+ : undefined;
+ return { grant: live, inspection, ...(pixels ? { capture: pixels } : {}) };
+ } catch (error) {
+ throw coded(error);
+ }
+ };
+
+ const act = async (action: Parameters<typeof host.call>[1], expectedRevision: number) => {
+ signal.throwIfAborted();
+ try {
+ return await host.call<ComputerActResult>("computer.act", {
+ grantId: grant.grantId,
+ sessionId,
+ expectedRevision,
+ action,
+ });
+ } catch (error) {
+ throw coded(error);
+ }
+ };
+
+ const decide = async (request: DecisionRequest): Promise<string> => {
+ signal.throwIfAborted();
+ const result = await complete(provider, decisionContext(request), "off", {
+ sessionId,
+ signal,
+ maxOutputTokens: 1_024,
+ });
+ return result.text ?? "";
+ };
+
+ let result: ComputerRunResult;
+ try {
+ result = await runComputerLoop(
+ {
+ instruction: input.instruction,
+ ...(input.maxSteps === undefined ? {} : { maxSteps: input.maxSteps }),
+ ...(input.observeOnly === undefined ? {} : { observeOnly: input.observeOnly }),
+ },
+ {
+ observe,
+ act: (action, expectedRevision) =>
+ act(action as Parameters<typeof host.call>[1], expectedRevision),
+ decide,
+ onStep: (step) => options.onStep?.({ ...step, sessionId }),
+ onCursor: (event: ComputerCursorEvent) => options.overlay.apply(event),
+ },
+ );
+ } catch (error) {
+ // The loop reports its own refusals; reaching here means the provider or
+ // an abort failed, which must not look like a completed task.
+ const aborted = signal.aborted;
+ options.overlay.apply({ kind: "hide", grantId: grant.grantId });
+ return failure(
+ aborted ? "TURN_ABORTED" : "COMPUTER_ACTION_REJECTED",
+ aborted
+ ? "The computer-use run was stopped."
+ : `The computer-use model could not be reached: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+
+ // Refresh the indicator: a run that spent the budget closes the grant.
+ try {
+ const after = await host.call<{ grant: ComputerGrantView | null }>("computer.grantDescribe", {});
+ options.onGrant?.(after.grant);
+ } catch {
+ options.onGrant?.(null);
+ }
+
+ const lines = [
+ result.summary,
+ result.question ? `Question for the user: ${result.question}` : undefined,
+ result.outcome === "needs-user"
+ ? "Relay this question to the user; do not answer it on their behalf."
+ : undefined,
+ result.outcome === "step-limit"
+ ? "Call Computer again only if the user still wants the task finished."
+ : undefined,
+ ].filter((line): line is string => Boolean(line));
+
+ if (result.outcome === "failed" || result.outcome === "revoked" || result.outcome === "expired") {
+ return failure(result.errorCode ?? "COMPUTER_ACTION_REJECTED", lines.join(" "));
+ }
+ return {
+ ok: true,
+ content: {
+ kind: "computer-use-result",
+ outcome: result.outcome,
+ summary: lines.join(" "),
+ steps: result.steps,
+ ...(result.question ? { question: result.question } : {}),
+ },
+ };
+ };
+}
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 11bc73512..e4ed190a1 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -22,6 +22,7 @@ import {
type ActivationScope,
type AgentEventEnvelope,
type CloseBehavior,
+ type ComputerGrantView,
type KeybindingOverrides,
type PlanExecutionFinishStatus,
} from "@pi-desktop/shared";
@@ -61,6 +62,7 @@ import { MainProcessState } from "./bootstrap/main-state";
import { registerApplicationActivation } from "./bootstrap/app-activation";
import { createHostRuntime } from "./runtime/host";
import { createSidecarRuntime } from "./runtime/sidecar";
+import { createComputerCursorOverlay } from "./computer-use/cursor-overlay";
import { createEventPersistence } from "./runtime/event-persistence";
import { createPlanRuntime } from "./runtime/plans";
import { createRuntimeLifecycle } from "./runtime/lifecycle";
@@ -754,6 +756,21 @@ const eventPersistence = createEventPersistence({
});
const { persistAgentEvent } = eventPersistence;
+/**
+ * The agent's drawn cursor and the indicator feed (ADR 0340 §10).
+ *
+ * The overlay is created lazily by its own module on the first draw command,
+ * and it closes with the grant: a window that outlived the authority it was
+ * drawn for would tell the user an action is still possible when it is not.
+ */
+const computerCursorOverlay = createComputerCursorOverlay({
+ log: (message, data) => logger.app("runtime", "warn", message, data),
+});
+function publishComputerGrant(grant: ComputerGrantView | null): void {
+ sendToRenderer(IPC.event.computerGrantChanged, { grant });
+ if (!grant || grant.state !== "active") computerCursorOverlay.close();
+}
+
const sidecarRuntime = createSidecarRuntime({
runtimeState,
steeringReplies,
@@ -785,6 +802,8 @@ const sidecarRuntime = createSidecarRuntime({
disabledBuiltinSkills: runtimeDisabledBuiltinSkills,
pluginActiveInProject,
currentNetworkProxy,
+ computerCursorOverlay,
+ publishComputerGrant,
});
emitAgentEvent = sidecarRuntime.emitAgentEvent;
const { startSidecar } = sidecarRuntime;
@@ -886,6 +905,7 @@ function registerIpc() {
ipcMain,
getMainWindow,
getHost,
+ publishComputerGrant,
getSidecar,
getAgentHostBridge: () => mainState.agentHostBridge,
getBackendRouter: () => startupState.backendRouter,
diff --git a/apps/desktop/electron/main/ipc/computer-ipc.ts b/apps/desktop/electron/main/ipc/computer-ipc.ts
new file mode 100644
index 000000000..cf6f8ab16
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/computer-ipc.ts
@@ -0,0 +1,80 @@
+/**
+ * The computer-use channels the renderer may call (ADR 0340).
+ *
+ * Deliberately short: read what the platform can do, list windows while the
+ * picker is open, mint a grant from a window the user chose, revoke one, and
+ * read the live grant. There is no channel here that dispatches input — the
+ * renderer must never hold that authority — and every call is pinned to the
+ * trusted main window, so a plugin view or the cursor overlay cannot mint a
+ * grant.
+ */
+import { IPC, type ComputerCapabilities, type ComputerGrantView } from "@pi-desktop/shared";
+import { capturePermissionState } from "../computer-use/capture";
+import type { HostProcess } from "../host-process";
+import type { IpcRegistrar } from "./types";
+
+export type ComputerIpcDependencies = {
+ registrar: IpcRegistrar;
+ getHost: () => Pick<HostProcess, "call"> | null;
+ /** Push the grant to the indicator and close the overlay when it ends. */
+ publishGrant: (grant: ComputerGrantView | null) => void;
+};
+
+function hostUnavailable(): never {
+ throw Object.assign(new Error("Host unavailable."), { errorCode: "HOST_UNAVAILABLE" });
+}
+
+export function registerComputerIpc({ registrar, getHost, publishGrant }: ComputerIpcDependencies): void {
+ registrar.handleWithEvent(IPC.invoke.computerCapabilities, async (event) => {
+ registrar.assertMainWindowSender(event);
+ const host = getHost();
+ if (!host) hostUnavailable();
+ const capabilities = await host.call<ComputerCapabilities>("computer.capabilities", {});
+ // host-core cannot answer for the capture path: that one is Chromium's.
+ return { ...capabilities, capture: capturePermissionState() };
+ });
+
+ registrar.handleWithEvent(IPC.invoke.computerListTargets, async (event) => {
+ registrar.assertMainWindowSender(event);
+ const host = getHost();
+ if (!host) hostUnavailable();
+ return host.call("computer.listTargets", {});
+ });
+
+ registrar.handleWithEvent(IPC.invoke.computerGrantCreate, async (event, request: unknown) => {
+ registrar.assertMainWindowSender(event);
+ const host = getHost();
+ if (!host) hostUnavailable();
+ const input = (request ?? {}) as Record<string, unknown>;
+ // The renderer may name a target, a session, and the two policy choices
+ // the grant card showed; everything else — the handle behind the target,
+ // the budget ceiling, the refusals — is the host's.
+ const grant = await host.call<ComputerGrantView>("computer.grantCreate", {
+ targetId: input.targetId,
+ sessionId: input.sessionId,
+ ...(input.inputPolicy ? { inputPolicy: input.inputPolicy } : {}),
+ ...(input.capture ? { capture: input.capture } : {}),
+ });
+ publishGrant(grant);
+ return grant;
+ });
+
+ registrar.handleWithEvent(IPC.invoke.computerGrantRevoke, async (event, request: unknown) => {
+ registrar.assertMainWindowSender(event);
+ const host = getHost();
+ if (!host) hostUnavailable();
+ const input = (request ?? {}) as Record<string, unknown>;
+ const result = await host.call<{ revoked: boolean }>("computer.grantRevoke", {
+ ...(typeof input.reason === "string" ? { reason: input.reason } : {}),
+ });
+ publishGrant(null);
+ return result;
+ });
+
+ registrar.handleWithEvent(IPC.invoke.computerGrantDescribe, async (event) => {
+ registrar.assertMainWindowSender(event);
+ const host = getHost();
+ if (!host) hostUnavailable();
+ return host.call<{ grant: ComputerGrantView | null }>("computer.grantDescribe", {});
+ });
+}
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 7cf1f16ad..e2af4deff 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -18,6 +18,7 @@ import { searchMcpMarket } from "../mcp-registry-catalog";
import { registerNotificationIpc } from "./notification-ipc";
import { registerPluginIpc } from "./plugin-ipc";
import { registerPluginUiIpc } from "./plugin-ui-ipc";
+import { registerComputerIpc } from "./computer-ipc";
import { registerJevIpc } from "./jev-ipc";
import { registerProviderIpc } from "./provider-ipc";
import { registerScheduledIpc } from "./scheduled-ipc";
@@ -49,6 +50,8 @@ export type RegisterIpcDependencies = {
ipcMain: IpcMain;
getMainWindow: () => BrowserWindow | null;
getHost: () => HostProcess | null;
+ /** Push the live computer-use grant to the renderer's indicator. */
+ publishComputerGrant: (grant: import("@pi-desktop/shared").ComputerGrantView | null) => void;
traySessions: ReturnType<typeof createTraySessions>;
taskbarUnreadBadge: ReturnType<typeof createTaskbarUnreadBadge>;
getSidecar: () => AgentSidecar | null;
@@ -100,6 +103,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
ipcMain,
getMainWindow,
getHost,
+ publishComputerGrant,
getSidecar,
getAgentHostBridge,
getBackendRouter,
@@ -333,6 +337,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
onProviderInvalidated: (providerId) => liveCallService?.invalidateProvider(providerId),
});
registerJevIpc({ registrar, logger });
+ registerComputerIpc({ registrar, getHost, publishGrant: publishComputerGrant });
registerWorktreeIpc({
registrar,
getHost,
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.ts
index f242894fc..5b9f4a37a 100644
--- a/apps/desktop/electron/main/runtime/session-launch.ts
+++ b/apps/desktop/electron/main/runtime/session-launch.ts
@@ -745,6 +745,11 @@ export function createSessionLaunchRuntime({
// for in model settings (ADR 0334).
fastMode: session.fastMode === true && storedModel?.fastModeAllowed === true,
...(jevApiKey ? { jevApiKey } : {}),
+ // A disabled feature is absent from the prompt rather than advertised
+ // and refused on every call (ADR 0340 §13).
+ ...(mode === "agent" && settings.computerUse?.enabled === true
+ ? { computerUseEnabled: true }
+ : {}),
commandShell,
scratchDir: join(dataDir, "scratch", sessionId),
// Remote-host tools write on that host; Main can only serve local files.
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index 745404902..1b6485d9c 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -1,4 +1,4 @@
-import { IPC, type AgentEventEnvelope, type UiMessage } from "@pi-desktop/shared";
+import { IPC, type AgentEventEnvelope, type ComputerGrantView, type UiMessage } from "@pi-desktop/shared";
import {
findSubagentProviderSource,
modelConfigWithBinding,
@@ -12,6 +12,9 @@ import {
loadBuiltinSkillBody,
} from "../builtin-skills";
import { createImageGenerationTool } from "../services/image-generation-service";
+import { createComputerUseTool } from "../computer-use/service";
+import { resolveComputerUseProvider } from "../computer-use/provider";
+import type { ComputerCursorOverlay } from "../computer-use/cursor-overlay";
import { registerPluginDevTools } from "../plugin-dev-tools";
import { resolveLocalFile } from "../browser-view";
import { catalogModelConfigFor } from "../models-dev-catalog";
@@ -66,6 +69,10 @@ export type SidecarRuntimeDependencies = {
disabledBuiltinSkills: () => Promise<string[]>;
pluginActiveInProject: (pluginId: string, projectPath: string | null | undefined) => boolean;
currentNetworkProxy: () => any;
+ /** The agent's drawn cursor. Visualization only (ADR 0340 §10). */
+ computerCursorOverlay: Pick<ComputerCursorOverlay, "apply">;
+ /** Push the live computer-use grant to the renderer's indicator. */
+ publishComputerGrant: (grant: ComputerGrantView | null) => void;
};
export function createSidecarRuntime({
@@ -97,6 +104,8 @@ export function createSidecarRuntime({
disabledBuiltinSkills,
pluginActiveInProject,
currentNetworkProxy,
+ computerCursorOverlay,
+ publishComputerGrant,
}: SidecarRuntimeDependencies): {
emitAgentEvent: (envelope: AgentEventEnvelope) => void;
wireSidecar: (sidecar: AgentSidecar) => void;
@@ -570,6 +579,23 @@ export function createSidecarRuntime({
// Fake-IP tolerance belongs to the network policy, not to the proxy switch.
allowFakeIp: () => relaxedNetworkPolicyEnabled(),
}));
+ // Granted native application control (ADR 0340). The host authorises the
+ // call through `tools.execute` before this handler runs, and the loop here
+ // holds no grant of its own: it re-reads the live one on every observation.
+ s.setLocalTool("Computer", createComputerUseTool({
+ getHost: () => runtimeState.host,
+ overlay: computerCursorOverlay,
+ resolveProvider: async (binding) => {
+ if (!runtimeState.host) return null;
+ return resolveComputerUseProvider({
+ host: runtimeState.host,
+ binding,
+ resolveAuth: providerId => vendorOAuth.resolveAuth(providerId),
+ });
+ },
+ onGrant: grant => publishComputerGrant(grant),
+ log: (message, data) => logger.app("runtime", "warn", message, data),
+ }));
s.setLocalTool("BrowserPreview", async ({ args, sessionId }) => {
const raw = String((args as { path?: unknown })?.path ?? "").trim();
if (!raw) {
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 8975aaba0..2aa485e5c 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -39,6 +39,7 @@
"@earendil-works/pi-ai": "1.4.0",
"@earendil-works/pi-mcp": "1.4.0",
"@pi-desktop/agent-host": "workspace:*",
+ "@pi-desktop/computer-use": "workspace:*",
"@pi-desktop/agent-runtime": "workspace:*",
"@pi-desktop/host-runtime": "workspace:*",
"@pi-desktop/i18n": "workspace:*",
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index b2e3a80bf..d9f9f5b26 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -22,6 +22,7 @@ import {
IconUndo2,
} from "../../../components/icons";
import { LiveVoiceControls } from "../../voice/live/LiveVoiceControls";
+import { ComputerUseIndicator } from "../../computer-use/ComputerUseIndicator";
import { ComposerModelPicker } from "./ComposerModelPicker";
import type { useComposerModelMenu } from "./hooks/useComposerModelMenu";
@@ -132,6 +133,7 @@ export function ComposerToolbar({
</TooltipButton>
</div>
{localToolsAllowed ? <LiveVoiceControls t={t} workSessionId={workSessionId} /> : null}
+ {localToolsAllowed ? <ComputerUseIndicator sessionId={workSessionId ?? null} /> : null}
<ComposerModePicker
t={t}
mode={mode}
diff --git a/apps/desktop/src/features/computer-use/ComputerCursor.tsx b/apps/desktop/src/features/computer-use/ComputerCursor.tsx
new file mode 100644
index 000000000..518431d72
--- /dev/null
+++ b/apps/desktop/src/features/computer-use/ComputerCursor.tsx
@@ -0,0 +1,96 @@
+import { useEffect, useRef, useState } from "react";
+import type { ComputerCursorEvent, ComputerRect } from "@pi-desktop/shared";
+import { computerUseApi } from "./computer-use-api";
+import "../../styles/computer-cursor.css";
+
+/**
+ * The agent's drawn cursor (ADR 0340 §10).
+ *
+ * This surface renders in its own click-through window, so it can never take a
+ * press away from the user. It owns no part of any action: it is told where an
+ * action is about to land and shows it, which is the only way an accessibility
+ * press — which moves no real pointer — becomes visible at all.
+ *
+ * Coordinates arrive in screen space; the window is positioned around the
+ * target, so they are converted with the window's own screen origin.
+ */
+
+type Trail = { id: number; x: number; y: number; kind: "press" | "type" };
+
+export function ComputerCursor() {
+ const [origin, setOrigin] = useState<ComputerRect | null>(null);
+ const [point, setPoint] = useState<{ x: number; y: number } | null>(null);
+ const [label, setLabel] = useState<string | null>(null);
+ const [trail, setTrail] = useState<Trail[]>([]);
+ const nextId = useRef(1);
+
+ useEffect(
+ () =>
+ computerUseApi.onCursor((event: ComputerCursorEvent) => {
+ if (event.kind === "show") {
+ setOrigin(event.bounds);
+ setPoint(null);
+ setLabel(null);
+ setTrail([]);
+ return;
+ }
+ if (event.kind === "hide") {
+ setPoint(null);
+ setLabel(null);
+ setTrail([]);
+ return;
+ }
+ setPoint({ x: event.x, y: event.y });
+ if (event.kind === "move") {
+ setLabel(event.label ?? null);
+ return;
+ }
+ const id = nextId.current++;
+ setTrail((current) => [
+ ...current.slice(-3),
+ { id, x: event.x, y: event.y, kind: event.kind === "type" ? "type" : "press" },
+ ]);
+ // The ripple is a hint that something happened, not state to keep.
+ window.setTimeout(() => {
+ setTrail((current) => current.filter((item) => item.id !== id));
+ }, 600);
+ }),
+ [],
+ );
+
+ if (!point) return null;
+ // `window.screenX/Y` is the overlay window's own origin, which is how a
+ // screen coordinate becomes a position inside this surface.
+ const left = point.x - window.screenX;
+ const top = point.y - window.screenY;
+ const inside =
+ left >= 0 && top >= 0 && left <= window.innerWidth && top <= window.innerHeight;
+ if (!inside) return null;
+
+ return (
+ <div className="computer-cursor-surface" aria-hidden="true" data-grant={origin ? "active" : "idle"}>
+ {trail.map((item) => (
+ <span
+ key={item.id}
+ className={`computer-cursor-ripple computer-cursor-ripple-${item.kind}`}
+ style={{ left: item.x - window.screenX, top: item.y - window.screenY }}
+ />
+ ))}
+ <span className="computer-cursor-pointer" style={{ left, top }}>
+ <svg viewBox="0 0 24 24" width="22" height="22" role="presentation">
+ <path
+ d="M5 2.5 19 12l-6.2 1.2L16 21l-2.6 1-3.2-7.6L5 18.6Z"
+ fill="currentColor"
+ stroke="rgba(0,0,0,0.55)"
+ strokeWidth="1.2"
+ />
+ </svg>
+ </span>
+ {label && (
+ <span className="computer-cursor-label" style={{ left, top }}>
+ {label}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/computer-use/ComputerUseIndicator.tsx b/apps/desktop/src/features/computer-use/ComputerUseIndicator.tsx
new file mode 100644
index 000000000..f75ddd819
--- /dev/null
+++ b/apps/desktop/src/features/computer-use/ComputerUseIndicator.tsx
@@ -0,0 +1,173 @@
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { IconMonitor, IconX } from "../../components/icons";
+import { Badge, Button, TooltipButton } from "../../components/ui";
+import { AnchoredMenu } from "../../components/settings/AnchoredMenu";
+import type { ComputerGrantView, ComputerTarget } from "@pi-desktop/shared";
+import { useAppStore } from "../../stores/app-store";
+import { computerUseApi } from "./computer-use-api";
+import "../../styles/computer-use.css";
+
+/**
+ * The grant indicator and the only way to hand an application over
+ * (ADR 0340 §4).
+ *
+ * The picker list comes from the host, including the windows it refuses, so a
+ * window the user can see is either pickable or carries the reason it is not.
+ * The model never appears in this flow: it cannot open the picker, cannot name
+ * a target, and cannot dismiss the indicator.
+ */
+export function ComputerUseIndicator({ sessionId }: { sessionId: string | null }) {
+ const { t } = useTranslation();
+ // Read the switch here rather than threading it through the composer: the
+ // indicator is the only consumer, and an absent setting means disabled.
+ const enabled = useAppStore((state) => state.settings?.computerUse?.enabled === true);
+ const [grant, setGrant] = useState<ComputerGrantView | null>(null);
+ const [open, setOpen] = useState(false);
+ const [targets, setTargets] = useState<ComputerTarget[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => computerUseApi.onGrantChanged(setGrant), []);
+
+ useEffect(() => {
+ if (!enabled) {
+ setGrant(null);
+ return;
+ }
+ let cancelled = false;
+ void computerUseApi
+ .grant()
+ .then((result) => {
+ if (!cancelled) setGrant(result.grant);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [enabled]);
+
+ const loadTargets = useCallback(() => {
+ setTargets(null);
+ setError(null);
+ void computerUseApi
+ .listTargets()
+ .then((result) => setTargets(result.targets))
+ .catch((failure: Error & { code?: string }) => {
+ setTargets([]);
+ setError(failure.code ?? "COMPUTER_PLATFORM_UNSUPPORTED");
+ });
+ }, []);
+
+ const hand = useCallback(
+ (targetId: string) => {
+ if (!sessionId) return;
+ setBusy(true);
+ setError(null);
+ void computerUseApi
+ .createGrant({ targetId, sessionId })
+ .then((created) => {
+ setGrant(created);
+ setOpen(false);
+ })
+ .catch((failure: Error & { code?: string }) => {
+ setError(failure.code ?? "COMPUTER_ACTION_REJECTED");
+ })
+ .finally(() => setBusy(false));
+ },
+ [sessionId],
+ );
+
+ const stop = useCallback(() => {
+ setBusy(true);
+ void computerUseApi
+ .revokeGrant("user")
+ .then(() => setGrant(null))
+ .catch(() => undefined)
+ .finally(() => setBusy(false));
+ }, []);
+
+ if (!enabled) return null;
+
+ if (grant && grant.state === "active") {
+ return (
+ <div className="computer-use-indicator" role="status">
+ <IconMonitor size={14} aria-hidden="true" />
+ <span className="computer-use-indicator-target">{grant.targetLabel}</span>
+ <Badge tone={grant.capture === "a11y-and-pixels" ? "warning" : "neutral"}>
+ {grant.capture === "a11y-and-pixels"
+ ? t("computerUse.captureWithPixels")
+ : t("computerUse.captureA11yOnly")}
+ </Badge>
+ <span className="computer-use-indicator-budget">
+ {t("computerUse.stepsLeft", { count: grant.remainingBudget })}
+ </span>
+ <Button size="sm" variant="primary" onClick={stop} disabled={busy}>
+ {t("computerUse.stop")}
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <AnchoredMenu
+ open={open}
+ onClose={() => setOpen(false)}
+ role="dialog"
+ label={t("computerUse.pickTarget")}
+ side="top"
+ className="computer-use-control"
+ menuClassName="computer-use-picker"
+ trigger={(triggerRef) => (
+ <TooltipButton
+ ref={triggerRef}
+ type="button"
+ className="icon-btn icon-btn-square"
+ tooltip={t("computerUse.pickTarget")}
+ aria-haspopup="dialog"
+ aria-expanded={open}
+ onClick={() => {
+ const next = !open;
+ setOpen(next);
+ if (next) loadTargets();
+ }}
+ >
+ <IconMonitor size={15} aria-hidden="true" />
+ </TooltipButton>
+ )}
+ >
+ <div className="computer-use-picker-body">
+ <div className="computer-use-picker-title">{t("computerUse.pickTarget")}</div>
+ <p className="computer-use-picker-hint">{t("computerUse.pickTargetHint")}</p>
+ {error && <div className="computer-use-picker-error">{error}</div>}
+ {targets === null && <div className="settings-hint">{t("computerUse.loadingTargets")}</div>}
+ {targets?.length === 0 && !error && (
+ <div className="settings-hint">{t("computerUse.noTargets")}</div>
+ )}
+ <ul className="computer-use-target-list">
+ {(targets ?? []).map((target) => (
+ <li key={target.targetId}>
+ <button
+ type="button"
+ className="computer-use-target"
+ disabled={busy || !!target.refusedReason || !sessionId}
+ onClick={() => hand(target.targetId)}
+ >
+ <span className="computer-use-target-app">{target.appName}</span>
+ <span className="computer-use-target-title">{target.title}</span>
+ {target.refusedReason && (
+ <Badge tone="warning">{t(`computerUse.refused.${target.refusedReason}`)}</Badge>
+ )}
+ </button>
+ </li>
+ ))}
+ </ul>
+ {!sessionId && <div className="settings-hint">{t("computerUse.needSession")}</div>}
+ <button type="button" className="computer-use-picker-close" onClick={() => setOpen(false)}>
+ <IconX size={14} aria-hidden="true" />
+ {t("computerUse.close")}
+ </button>
+ </div>
+ </AnchoredMenu>
+ );
+}
diff --git a/apps/desktop/src/features/computer-use/computer-use-api.ts b/apps/desktop/src/features/computer-use/computer-use-api.ts
new file mode 100644
index 000000000..bfa841bc9
--- /dev/null
+++ b/apps/desktop/src/features/computer-use/computer-use-api.ts
@@ -0,0 +1,60 @@
+import {
+ IPC,
+ type ComputerCapabilities,
+ type ComputerCaptureMode,
+ type ComputerCursorEvent,
+ type ComputerGrantView,
+ type ComputerInputPolicy,
+ type ComputerTarget,
+} from "@pi-desktop/shared";
+
+/**
+ * The renderer's computer-use surface (ADR 0340).
+ *
+ * Read, pick, and revoke — nothing here dispatches input, because the renderer
+ * is the one process that must never hold that authority. A refusal keeps its
+ * `COMPUTER_*` code so the UI can name it instead of guessing.
+ */
+
+export type ComputerUseError = Error & { code: string };
+
+function computerError(code: string, message: string): ComputerUseError {
+ return Object.assign(new Error(message), { code });
+}
+
+async function invoke<T>(channel: string, ...args: unknown[]): Promise<T> {
+ const bridge = window.piDesktop;
+ if (!bridge) throw computerError("HOST_UNAVAILABLE", "Desktop bridge unavailable");
+ const result = await bridge.invoke<T>(channel, ...args);
+ if (!result.ok) throw computerError(result.error.code, result.error.message);
+ return result.data;
+}
+
+export const computerUseApi = {
+ capabilities: () => invoke<ComputerCapabilities>(IPC.invoke.computerCapabilities),
+ listTargets: () => invoke<{ targets: ComputerTarget[] }>(IPC.invoke.computerListTargets),
+ grant: () => invoke<{ grant: ComputerGrantView | null }>(IPC.invoke.computerGrantDescribe),
+ createGrant: (request: {
+ targetId: string;
+ sessionId: string;
+ inputPolicy?: ComputerInputPolicy;
+ capture?: ComputerCaptureMode;
+ }) => invoke<ComputerGrantView>(IPC.invoke.computerGrantCreate, request),
+ revokeGrant: (reason: string) =>
+ invoke<{ revoked: boolean }>(IPC.invoke.computerGrantRevoke, { reason }),
+ onGrantChanged: (handler: (grant: ComputerGrantView | null) => void): (() => void) => {
+ const bridge = window.piDesktop;
+ if (!bridge) return () => undefined;
+ return bridge.on(IPC.event.computerGrantChanged, (payload: unknown) => {
+ const grant = (payload as { grant?: ComputerGrantView | null } | undefined)?.grant ?? null;
+ handler(grant);
+ });
+ },
+ onCursor: (handler: (event: ComputerCursorEvent) => void): (() => void) => {
+ const bridge = window.piDesktop;
+ if (!bridge) return () => undefined;
+ return bridge.on(IPC.event.computerCursor, (payload: unknown) => {
+ handler(payload as ComputerCursorEvent);
+ });
+ },
+};
diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsx
index 59f8262c2..ebd36156a 100644
--- a/apps/desktop/src/features/settings/SettingsPage.tsx
+++ b/apps/desktop/src/features/settings/SettingsPage.tsx
@@ -52,6 +52,7 @@ import { AgentMcpPage } from "../../components/settings/AgentMcpPage";
import { AgentSubagentsPage } from "../../components/settings/AgentSubagentsPage";
import { RemoteHostsPage } from "../../components/settings/RemoteHostsPage";
import { VoiceSettingsSection } from "./voice/VoiceSettingsSection";
+import { ComputerUseSettings } from "./computer-use/ComputerUseSettings";
import {
CommandShellRow,
ContextUsageDisplayRow,
@@ -527,6 +528,7 @@ export function SettingsPage() {
{tab === "ai" && settings && (
<div className="settings-stack">
+ <ComputerUseSettings t={t} settings={settings} saveSettings={saveSettings} />
<SettingsCard title={t("settings.permissions")}>
<SettingsRow
title={t("settings.permissionMode")}
diff --git a/apps/desktop/src/features/settings/computer-use/ComputerUseSettings.tsx b/apps/desktop/src/features/settings/computer-use/ComputerUseSettings.tsx
new file mode 100644
index 000000000..8cb7b390e
--- /dev/null
+++ b/apps/desktop/src/features/settings/computer-use/ComputerUseSettings.tsx
@@ -0,0 +1,161 @@
+import { useEffect, useMemo, useState } from "react";
+import type { TFunction } from "i18next";
+import {
+ COMPUTER_USE_DEFAULTS,
+ type AppSettings,
+ type ComputerCapabilities,
+ type ComputerCaptureMode,
+ type ComputerInputPolicy,
+ type ComputerUseSettings as ComputerUseSettingsValue,
+ type ProviderPublic,
+} from "@pi-desktop/shared";
+import { Badge, SettingsToggle } from "../../../components/ui";
+import { SettingsMenuSelect } from "../../../components/settings/SettingsMenuSelect";
+import { SettingsCard, SettingsRow } from "../primitives";
+import { api } from "../../../lib/api";
+import { computerUseApi } from "../../computer-use/computer-use-api";
+
+/**
+ * Computer use settings (ADR 0340).
+ *
+ * The three things only the user can decide live here: whether the capability
+ * exists at all, which model may drive it, and whether a run may take pixels
+ * of the window. Nothing here hands anything over — a grant is always minted
+ * later, per target, from the indicator.
+ */
+export function ComputerUseSettings({
+ t,
+ settings,
+ saveSettings,
+}: {
+ t: TFunction;
+ settings: AppSettings;
+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;
+}) {
+ const value: ComputerUseSettingsValue = settings.computerUse ?? { enabled: false };
+ const [capabilities, setCapabilities] = useState<ComputerCapabilities | null>(null);
+ const [providers, setProviders] = useState<ProviderPublic[]>([]);
+
+ useEffect(() => {
+ let cancelled = false;
+ void computerUseApi
+ .capabilities()
+ .then((result) => {
+ if (!cancelled) setCapabilities(result);
+ })
+ .catch(() => {
+ if (!cancelled) setCapabilities(null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!value.enabled) return;
+ let cancelled = false;
+ void api
+ .listProviders()
+ .then((result) => {
+ if (!cancelled) setProviders(result.providers.filter((provider) => provider.enabled));
+ })
+ .catch(() => {
+ if (!cancelled) setProviders([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [value.enabled]);
+
+ const modelOptions = useMemo(() => {
+ const options = [{ id: "", label: t("computerUse.chooseModel") }];
+ for (const provider of providers) {
+ for (const model of provider.models ?? []) {
+ options.push({ id: `${provider.id}\u0000${model.id}`, label: `${provider.name} · ${model.id}` });
+ }
+ }
+ return options;
+ }, [providers, t]);
+
+ const selectedModel = value.model ? `${value.model.providerId}\u0000${value.model.modelId}` : "";
+ const unsupported = capabilities?.backend === "unsupported";
+
+ const patch = (next: Partial<ComputerUseSettingsValue>) =>
+ void saveSettings({ computerUse: { ...value, ...next } });
+
+ return (
+ <SettingsCard title={t("computerUse.title")} description={t("computerUse.description")}>
+ <SettingsRow title={t("computerUse.enable")} description={t("computerUse.enableDesc")}>
+ <SettingsToggle
+ label={t("computerUse.enable")}
+ checked={value.enabled}
+ onChange={() => patch({ enabled: !value.enabled })}
+ />
+ </SettingsRow>
+
+ {/* Readable before enabling: a platform without a backend should say so
+ rather than let the user turn on a feature that cannot act. */}
+ <SettingsRow title={t("computerUse.platform")}>
+ <div className="settings-inline-status">
+ {capabilities ? (
+ <>
+ <Badge tone={unsupported ? "warning" : "neutral"}>
+ {unsupported ? t("computerUse.platformUnsupported") : capabilities.backend}
+ </Badge>
+ <Badge tone={capabilities.accessibility === "granted" ? "neutral" : "warning"}>
+ {t(`computerUse.permission.${capabilities.accessibility}`)}
+ </Badge>
+ </>
+ ) : (
+ <span className="settings-hint">{t("computerUse.platformUnknown")}</span>
+ )}
+ </div>
+ </SettingsRow>
+
+ {value.enabled && (
+ <>
+ <SettingsRow title={t("computerUse.model")} description={t("computerUse.modelDesc")}>
+ <SettingsMenuSelect
+ label={t("computerUse.model")}
+ value={selectedModel}
+ onChange={(next) => {
+ if (!next) {
+ patch({ model: null });
+ return;
+ }
+ const [providerId, modelId] = next.split("\u0000");
+ if (providerId && modelId) patch({ model: { providerId, modelId } });
+ }}
+ options={modelOptions}
+ />
+ </SettingsRow>
+ {!value.model && <div className="settings-hint">{t("computerUse.modelMissing")}</div>}
+
+ <SettingsRow title={t("computerUse.inputPolicy")} description={t("computerUse.inputPolicyDesc")}>
+ <SettingsMenuSelect
+ label={t("computerUse.inputPolicy")}
+ value={value.defaultInputPolicy ?? COMPUTER_USE_DEFAULTS.inputPolicy}
+ onChange={(next) => patch({ defaultInputPolicy: next as ComputerInputPolicy })}
+ options={[
+ { id: "confirm-each", label: t("computerUse.policyConfirmEach") },
+ { id: "autonomous-in-scope", label: t("computerUse.policyAutonomous") },
+ ]}
+ />
+ </SettingsRow>
+
+ <SettingsRow title={t("computerUse.capture")} description={t("computerUse.captureDesc")}>
+ <SettingsMenuSelect
+ label={t("computerUse.capture")}
+ value={value.defaultCapture ?? COMPUTER_USE_DEFAULTS.capture}
+ onChange={(next) => patch({ defaultCapture: next as ComputerCaptureMode })}
+ options={[
+ { id: "a11y-only", label: t("computerUse.captureA11yOnly") },
+ { id: "a11y-and-pixels", label: t("computerUse.captureWithPixels") },
+ ]}
+ />
+ </SettingsRow>
+ </>
+ )}
+ </SettingsCard>
+ );
+}
diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx
index 831eb912c..f7a369363 100644
--- a/apps/desktop/src/main.tsx
+++ b/apps/desktop/src/main.tsx
@@ -62,6 +62,11 @@ const PluginLauncher = React.lazy(() =>
default: module.PluginLauncher,
})),
);
+const ComputerCursor = React.lazy(() =>
+ import("./features/computer-use/ComputerCursor").then((module) => ({
+ default: module.ComputerCursor,
+ })),
+);
const LiveVoiceWidget = React.lazy(() =>
import("./features/voice/live/LiveVoiceWidget").then((module) => ({
default: module.LiveVoiceWidget,
@@ -105,6 +110,10 @@ async function startRenderer(): Promise<void> {
<ErrorBoundary>
<LiveVoiceWidget />
</ErrorBoundary>
+ ) : rendererSurface === "computer-cursor" ? (
+ <ErrorBoundary>
+ <ComputerCursor />
+ </ErrorBoundary>
) : (
<App />
)}
diff --git a/apps/desktop/src/styles/computer-cursor.css b/apps/desktop/src/styles/computer-cursor.css
new file mode 100644
index 000000000..d60a89b15
--- /dev/null
+++ b/apps/desktop/src/styles/computer-cursor.css
@@ -0,0 +1,77 @@
+/*
+ * The agent's drawn cursor, in its own click-through window.
+ *
+ * Nothing here may capture input: the window already ignores mouse events, and
+ * `pointer-events: none` keeps that true even if a future change makes the
+ * window interactive by accident.
+ */
+.computer-cursor-surface {
+ position: fixed;
+ inset: 0;
+ pointer-events: none;
+ background: transparent;
+ color: #ffffff;
+ overflow: hidden;
+}
+
+.computer-cursor-pointer {
+ position: absolute;
+ transform: translate(-2px, -2px);
+ filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.45));
+ transition: left 180ms cubic-bezier(0.22, 1, 0.36, 1), top 180ms cubic-bezier(0.22, 1, 0.36, 1);
+}
+
+.computer-cursor-label {
+ position: absolute;
+ transform: translate(18px, 14px);
+ max-width: 220px;
+ padding: 2px 8px;
+ border-radius: var(--radius-full);
+ font-size: var(--text-xs);
+ line-height: var(--leading-row);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: #ffffff;
+ background: rgba(17, 17, 20, 0.86);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ transition: left 180ms cubic-bezier(0.22, 1, 0.36, 1), top 180ms cubic-bezier(0.22, 1, 0.36, 1);
+}
+
+.computer-cursor-ripple {
+ position: absolute;
+ width: 14px;
+ height: 14px;
+ margin: -7px 0 0 -7px;
+ border-radius: var(--radius-round);
+ border: 2px solid rgba(255, 255, 255, 0.9);
+ animation: computer-cursor-ripple 600ms ease-out forwards;
+}
+
+.computer-cursor-ripple-type {
+ border-color: rgba(120, 200, 255, 0.95);
+}
+
+@keyframes computer-cursor-ripple {
+ from {
+ transform: scale(0.4);
+ opacity: 0.9;
+ }
+ to {
+ transform: scale(2.6);
+ opacity: 0;
+ }
+}
+
+/* A user who asked for less motion still needs to see where it acted. */
+@media (prefers-reduced-motion: reduce) {
+ .computer-cursor-pointer,
+ .computer-cursor-label {
+ transition: none;
+ }
+
+ .computer-cursor-ripple {
+ animation: none;
+ opacity: 0.85;
+ }
+}
diff --git a/apps/desktop/src/styles/computer-use.css b/apps/desktop/src/styles/computer-use.css
new file mode 100644
index 000000000..98c8b5712
--- /dev/null
+++ b/apps/desktop/src/styles/computer-use.css
@@ -0,0 +1,125 @@
+/*
+ * Computer-use indicator and target picker.
+ *
+ * In-flow surfaces follow the borderless tone scheme (D297): tile and raised
+ * backgrounds, no strokes. The picker is a floating layer, so it keeps the
+ * hairline the scheme allows there.
+ */
+.computer-use-indicator {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 30px;
+ padding: 4px 8px;
+ border-radius: var(--radius-sm);
+ background: var(--ds-raised);
+ font-size: var(--text-sm);
+}
+
+.computer-use-indicator-target {
+ max-width: 220px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-weight: var(--font-weight-medium);
+}
+
+.computer-use-indicator-budget {
+ color: var(--text-muted);
+}
+
+.computer-use-picker {
+ width: 320px;
+ max-height: 420px;
+ overflow: auto;
+}
+
+.computer-use-picker-body {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+}
+
+.computer-use-picker-title {
+ font-size: var(--text-md);
+ font-weight: var(--font-weight-semibold);
+}
+
+.computer-use-picker-hint,
+.computer-use-picker-error {
+ margin: 0;
+ font-size: var(--text-sm);
+ color: var(--text-muted);
+}
+
+.computer-use-picker-error {
+ color: var(--danger);
+ font-variant-numeric: tabular-nums;
+}
+
+.computer-use-target-list {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.computer-use-target {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 6px 8px;
+ border: 0;
+ border-radius: var(--radius-xs);
+ background: var(--ds-tile);
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+}
+
+.computer-use-target:hover:not(:disabled) {
+ background: var(--ds-raised);
+}
+
+.computer-use-target:disabled {
+ cursor: not-allowed;
+ opacity: 0.6;
+}
+
+.computer-use-target-app {
+ font-size: var(--text-sm);
+ font-weight: var(--font-weight-medium);
+ white-space: nowrap;
+}
+
+.computer-use-target-title {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--text-sm);
+ color: var(--text-muted);
+}
+
+.computer-use-picker-close {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ align-self: flex-start;
+ padding: 4px 6px;
+ border: 0;
+ border-radius: var(--radius-xs);
+ background: transparent;
+ color: var(--text-muted);
+ font-size: var(--text-sm);
+ cursor: pointer;
+}
+
+.computer-use-picker-close:hover {
+ background: var(--ds-tile);
+}
diff --git a/apps/desktop/test/computer-use-service.test.mjs b/apps/desktop/test/computer-use-service.test.mjs
new file mode 100644
index 000000000..5f5afb71c
--- /dev/null
+++ b/apps/desktop/test/computer-use-service.test.mjs
@@ -0,0 +1,242 @@
+/**
+ * The `Computer` tool handler's refusals, against the real module.
+ *
+ * Every case here is something the agent could plausibly try, and each one has
+ * to fail with its own code rather than silently acting: a disabled feature, a
+ * missing model binding, nothing handed over, and a grant that belongs to
+ * another session. The overlay is asserted to stay closed in those cases,
+ * because a drawn cursor with no authority behind it is a lie to the user.
+ */
+import assert from "node:assert/strict";
+import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL, fileURLToPath } from "node:url";
+import test from "node:test";
+
+const { build } = createRequire(new URL("../../../packages/agent-runtime/package.json", import.meta.url))(
+ "esbuild",
+);
+
+async function loadService(t) {
+ const root = await realpath(await mkdtemp(join(tmpdir(), "pi-computer-use-")));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const outfile = join(root, "service.mjs");
+ // Electron cannot be imported by a plain Node test, and the capture module
+ // pulls it in. Aliasing it to a stub keeps the production code unchanged and
+ // still proves the handler's own paths: no case here reaches capture, which
+ // every case injects anyway.
+ const stub = join(root, "electron-stub.mjs");
+ await writeFile(stub, "export const desktopCapturer = { getSources: async () => [] };\nexport const systemPreferences = { getMediaAccessStatus: () => \"not-determined\" };\n");
+ // The provider call is injected in every case here, so the runtime package —
+ // and the HTTP stack behind it — is stubbed rather than bundled.
+ const runtimeStub = join(root, "runtime-stub.mjs");
+ await writeFile(runtimeStub, "export async function completeOneShot() { throw new Error('not injected'); }\n");
+ await build({
+ entryPoints: [fileURLToPath(new URL("../electron/main/computer-use/service.ts", import.meta.url))],
+ outfile,
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ alias: { electron: stub, "@pi-desktop/agent-runtime": runtimeStub },
+ });
+ return import(pathToFileURL(outfile).href);
+}
+
+function harness(overrides = {}) {
+ const calls = [];
+ const cursor = [];
+ const settings = overrides.settings ?? {
+ computerUse: { enabled: true, model: { providerId: "p1", modelId: "ui" } },
+ };
+ // `??` would swallow an explicit null, which is exactly the no-handover case.
+ const grant = "grant" in overrides ? overrides.grant : {
+ grantId: "cug_1",
+ revision: 1,
+ targetId: "77:12",
+ targetLabel: "Example",
+ appKey: "example",
+ bounds: { x: 0, y: 0, width: 100, height: 100 },
+ inputPolicy: "confirm-each",
+ capture: "a11y-only",
+ remainingBudget: 5,
+ sessionId: "session-1",
+ createdAt: "2026-11-04T00:00:00.000Z",
+ expiresAt: "2026-11-04T00:15:00.000Z",
+ state: "active",
+ };
+ const host = {
+ call: async (method, params) => {
+ calls.push(method);
+ if (method === "settings.get") return settings;
+ if (method === "computer.grantDescribe") return { grant };
+ if (method === "computer.inspect") {
+ return {
+ grantId: grant?.grantId,
+ revision: 1,
+ bounds: grant?.bounds,
+ fidelity: "full",
+ nodes: [
+ {
+ uid: "0.1#ab",
+ role: "AXButton",
+ label: "Save",
+ hasValue: false,
+ enabled: true,
+ focused: false,
+ bounds: { x: 10, y: 10, width: 40, height: 20 },
+ actions: ["click"],
+ },
+ ],
+ truncated: false,
+ secureInput: false,
+ };
+ }
+ if (method === "computer.act") {
+ return { grantId: grant.grantId, revision: 1, remainingBudget: 4, dispatched: "accessibility-action" };
+ }
+ if (method === "providers.get") return { provider: { id: "p1", name: "P", enabled: true, authKind: "none" } };
+ throw new Error(`unexpected host call ${method} ${JSON.stringify(params)}`);
+ },
+ };
+ return { calls, cursor, host, grant, settings };
+}
+
+function deps(h, overrides = {}) {
+ return {
+ getHost: () => h.host,
+ overlay: { apply: (event) => h.cursor.push(event) },
+ resolveProvider: async () => ({
+ id: "p1",
+ name: "P",
+ modelId: "ui",
+ apiKey: "",
+ supportsReasoning: false,
+ supportedThinkingLevels: ["off"],
+ }),
+ capture: async () => undefined,
+ complete: async () => ({ text: '{"kind":"done","summary":"nothing to do"}' }),
+ ...overrides,
+ };
+}
+
+const input = (args = { instruction: "open preferences" }) => ({
+ sessionId: "session-1",
+ toolCallId: "call-1",
+ args,
+ signal: new AbortController().signal,
+});
+
+test("a disabled feature refuses before anything is read", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness({ settings: { computerUse: { enabled: false } } });
+ const result = await createComputerUseTool(deps(h))(input());
+ assert.equal(result.ok, false);
+ assert.equal(result.errorCode, "COMPUTER_DISABLED");
+ assert.ok(!h.calls.includes("computer.grantDescribe"), "no grant is read while disabled");
+ assert.deepEqual(h.cursor, [], "nothing is drawn");
+});
+
+test("a missing model binding refuses instead of using the conversation model", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness({ settings: { computerUse: { enabled: true } } });
+ const result = await createComputerUseTool(deps(h))(input());
+ assert.equal(result.errorCode, "COMPUTER_NOT_CONFIGURED");
+ assert.match(result.content.message, /Settings/);
+});
+
+test("no handover refuses and tells the agent the user must pick a window", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness({ grant: null });
+ const result = await createComputerUseTool(deps(h))(input());
+ assert.equal(result.errorCode, "COMPUTER_NO_GRANT");
+ assert.match(result.content.message, /pick a window/i);
+ assert.ok(!h.calls.includes("computer.act"));
+});
+
+test("a grant owned by another session is refused", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness();
+ h.grant.sessionId = "session-2";
+ const result = await createComputerUseTool(deps(h))(input());
+ assert.equal(result.errorCode, "COMPUTER_GRANT_IN_USE");
+});
+
+test("an unavailable computer-use model reports configuration, not a failure to act", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness();
+ const result = await createComputerUseTool(deps(h, { resolveProvider: async () => null }))(input());
+ assert.equal(result.errorCode, "COMPUTER_NOT_CONFIGURED");
+});
+
+test("invalid arguments are refused by the shared validator", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness();
+ const tool = createComputerUseTool(deps(h));
+ for (const args of [{}, { instruction: "" }, { instruction: "x", uid: "0.1#ab" }]) {
+ const result = await tool(input(args));
+ assert.equal(result.errorCode, "INVALID_ARGUMENT", JSON.stringify(args));
+ }
+});
+
+test("a run that the model ends immediately dispatches nothing and closes the overlay", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness();
+ const result = await createComputerUseTool(deps(h))(input());
+ assert.equal(result.ok, true);
+ assert.equal(result.content.outcome, "done");
+ assert.ok(!h.calls.includes("computer.act"), "nothing was dispatched");
+ assert.equal(h.cursor.at(-1).kind, "hide", "the drawn cursor is taken down");
+});
+
+test("observeOnly never asks the model and never acts", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness();
+ let asked = 0;
+ const result = await createComputerUseTool(
+ deps(h, {
+ complete: async () => {
+ asked += 1;
+ return { text: '{"kind":"action","action":{"kind":"click","uid":"0.1#ab"}}' };
+ },
+ }),
+ )(input({ instruction: "what is on screen", observeOnly: true }));
+ assert.equal(result.ok, true);
+ assert.equal(asked, 0);
+ assert.ok(!h.calls.includes("computer.act"));
+});
+
+test("a model answer naming an element the host never showed is refused locally", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness();
+ const result = await createComputerUseTool(
+ deps(h, { complete: async () => ({ text: '{"kind":"action","action":{"kind":"click","uid":"9.9#ff"}}' }) }),
+ )(input());
+ assert.ok(!h.calls.includes("computer.act"), "the invented element never reaches the host");
+ assert.equal(result.ok, false);
+ assert.equal(result.errorCode, "COMPUTER_ACTION_REJECTED");
+});
+
+test("a host refusal keeps its own code in the tool result", async (t) => {
+ const { createComputerUseTool } = await loadService(t);
+ const h = harness();
+ const host = {
+ call: async (method, params) => {
+ if (method === "computer.act") {
+ throw Object.assign(new Error("secure input is active"), {
+ errorCode: "COMPUTER_SECURE_INPUT_REFUSED",
+ });
+ }
+ return h.host.call(method, params);
+ },
+ };
+ const result = await createComputerUseTool(
+ deps(h, {
+ getHost: () => host,
+ complete: async () => ({ text: '{"kind":"action","action":{"kind":"click","uid":"0.1#ab"}}' }),
+ }),
+ )(input());
+ assert.equal(result.ok, false);
+ assert.equal(result.errorCode, "COMPUTER_SECURE_INPUT_REFUSED");
+});
diff --git a/docs/implementation/computer-use-evidence.md b/docs/implementation/computer-use-evidence.md
new file mode 100644
index 000000000..20616850e
--- /dev/null
+++ b/docs/implementation/computer-use-evidence.md
@@ -0,0 +1,68 @@
+# Computer Use Stage 1 Evidence
+
+What was built for [ADR 0340](../adr/0340-os-computer-use-capability.md) stage 1,
+and — more importantly — what has *not* been verified. This file contains no
+window titles, no captured pixels, and no credentials.
+
+## Shape
+
+| Layer | Where | State |
+|---|---|---|
+| Contracts, settings, error codes | `packages/shared/src/computer-use.ts`, `errors.ts`, `protocol.ts` | Implemented, unit-covered |
+| Refusals, grant broker, platform contract | `crates/host-core/src/computer/` | Implemented, unit-covered |
+| macOS backend (`AXUIElement`, `CGWindowList`, `CGEventPostToPid`) | `crates/host-core/src/computer/macos.rs` | Implemented, compiled, **no device run** |
+| Windows and Linux backends | `crates/host-core/src/computer/backend.rs` | Explicit unsupported backend; stage 2 |
+| `computer.*` RPC and audit | `crates/host-core/src/rpc/computer_rpc.rs` | Implemented, not covered by an RPC-level test |
+| Bounded loop and action schema | `packages/computer-use/` | Implemented, unit-covered |
+| `Computer` tool, capture, overlay driver | `apps/desktop/electron/main/computer-use/` | Implemented, refusal paths unit-covered |
+| Tool declaration and host gate | `packages/agent-runtime/src/computer-use/tool.ts`, `packages/host-runtime/src/agent-sidecar.ts` | Implemented |
+| Picker, indicator, settings, drawn cursor | `apps/desktop/src/features/computer-use/`, `features/settings/computer-use/` | Implemented, **not exercised by a UI test** |
+
+## What ran
+
+| Check | Result |
+|---|---|
+| `cargo test -p host-core --locked` | 1160 passed, 1 ignored |
+| `cargo clippy -p host-core --all-targets` | No new warnings (one pre-existing in `transcripts.rs`) |
+| `cargo fmt -p host-core -- --check` | Clean |
+| `pnpm build:js` | Passed |
+| `pnpm --filter @pi-desktop/shared test` | 1378 passed (6 new) |
+| `pnpm --filter @pi-desktop/computer-use test` | 27 passed |
+| `pnpm --filter @pi-desktop/i18n test` | 31 passed |
+| `pnpm --filter @pi-desktop/desktop typecheck` | Clean |
+| `pnpm docs:check` / `check-locales` | Clean on this branch except the pre-existing duplicate ADR 0339, fixed separately |
+
+## What did not run, and what that means
+
+- **No real application was ever driven.** No `AXUIElement` action, no
+ `CGEventPostToPid` key, no `desktopCapturer` frame, and no macOS
+ Accessibility prompt was triggered on this machine. The macOS backend is
+ compiled and its pure parts (element id round-trip, chord table, action
+ mapping) are unit-tested; everything that touches a live window is unproven.
+- **Windows and Linux have no backend yet.** They compile to the unsupported
+ backend, so every operation there answers
+ `COMPUTER_PLATFORM_UNSUPPORTED` rather than failing oddly. Stage 2 adds UIA
+ and AT-SPI with their own dependency review and device matrix.
+- **No UI test covers the picker, the indicator, the grant card, or the drawn
+ cursor.** Repository policy reserves `verify:ui:*` for an explicit request,
+ and the five `E2E-COMPUTER-USE-*` scenarios are `NOT RUN`.
+- **No provider call was made.** The loop's model request is covered by
+ injected, scripted answers only; no computer-use model was configured and no
+ token was spent.
+- **The audit trail was not inspected in a running app.** The append calls are
+ in place and shaped to carry identity without content, but no log file was
+ read back to confirm that.
+
+## Residual risk
+
+The dangerous surface is the macOS backend, because it is the only code here
+that can move another application. Its refusals are enforced one layer above it
+in `policy.rs`, which *is* covered: self-target, secure input, stale basis,
+stale revision, coordinate clamping, budget, expiry, single-grant exclusivity,
+and the credential denylist all have tests that fail closed. What remains
+unproven is whether the backend can actually drive a real window — a bug there
+shows up as "nothing happens", not as a lost refusal.
+
+A device run on macOS is the next gate: enable the feature, bind a model, hand
+over a window, and confirm the drawn cursor, one accessibility press, the audit
+line, and Stop. Until that happens, treat stage 1 as implemented and unverified.
diff --git a/docs/spec/03-runtime/computer-use.md b/docs/spec/03-runtime/computer-use.md
index ef15701df..0c4688ba4 100644
--- a/docs/spec/03-runtime/computer-use.md
+++ b/docs/spec/03-runtime/computer-use.md
@@ -1,9 +1,13 @@
# Computer Use v1
-> Status: Stage 1 (MVP) in progress. This page is the authoritative contract
-> for the capability described in
+> Status: Stage 1 implemented, device-unverified. This page is the
+> authoritative contract for the capability described in
> [ADR 0340](../../adr/0340-os-computer-use-capability.md). The agent is the
> only caller; the spoken entry point is specified here and built in stage 3.
+> The refusals, the loop, and the tool's own paths are unit-covered; no real
+> application has been driven, and Windows and Linux report
+> `COMPUTER_PLATFORM_UNSUPPORTED` until stage 2. See
+> [computer-use evidence](../../implementation/computer-use-evidence.md).
## Scope
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 428d84064..7e54278d4 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -19589,10 +19589,11 @@ their separate platform acceptance.
## Computer use (ADR 0340)
-These scenarios are specified before implementation. Every one of them is a
-landing gate for the capability described in
-[03-runtime/computer-use](../03-runtime/computer-use.md); none is implemented
-yet, and all are `NOT RUN`.
+Every one of these is a landing gate for the capability described in
+[03-runtime/computer-use](../03-runtime/computer-use.md). Stage 1 is
+implemented, so the refusals each scenario depends on are covered by unit
+tests; the scenarios themselves drive a real application and are all
+`NOT RUN`. Automation that does exist is named per scenario.
### E2E-COMPUTER-USE-grant-is-user-minted-and-revocable
@@ -19612,7 +19613,13 @@ yet, and all are `NOT RUN`.
their own codes, and no grant survives a restart.
- **Specs**: [Computer Use](../03-runtime/computer-use.md),
[03-tools-and-permissions](../03-runtime/03-tools-and-permissions.md).
-- **Status**: NOT RUN — capability not implemented.
+- **Automation**: `computer::tests::only_one_grant_is_active_per_instance`,
+ `another_session_cannot_use_the_active_grant`,
+ `an_idle_grant_expires_and_stays_expired`, and
+ `the_budget_closes_the_grant_and_refuses_the_next_action` in host-core;
+ `apps/desktop/test/computer-use-service.test.mjs` covers the no-grant and
+ wrong-session refusals the agent would hit.
+- **Status**: NOT RUN — needs a real window and the picker.
### E2E-COMPUTER-USE-self-target-and-secure-input-refused
@@ -19631,7 +19638,11 @@ yet, and all are `NOT RUN`.
image, tool result, or log. The built-in denylist entry cannot be removed.
- **Specs**: [Computer Use](../03-runtime/computer-use.md),
[05-security/01-security](../05-security/01-security.md) §13.
-- **Status**: NOT RUN — capability not implemented.
+- **Automation**: `computer::tests::our_own_windows_are_never_pickable`,
+ `a_renamed_self_process_is_still_refused`,
+ `built_in_credential_surfaces_cannot_be_allowlisted`, and
+ `secure_input_refuses_both_inspection_and_action` in host-core.
+- **Status**: NOT RUN — needs a real approval card and a real password field.
### E2E-COMPUTER-USE-stale-basis-and-revision-fail-closed
@@ -19647,7 +19658,11 @@ yet, and all are `NOT RUN`.
target application observes no input.
- **Specs**: [Computer Use](../03-runtime/computer-use.md),
[08-error-codes](../03-runtime/08-error-codes.md) §3.10.
-- **Status**: NOT RUN — capability not implemented.
+- **Automation**: `computer::tests::a_moved_window_bumps_the_revision_and_invalidates_a_basis`,
+ `a_resized_window_with_the_same_revision_still_refuses_a_stale_basis`,
+ `coordinates_outside_the_measured_window_are_refused_not_clamped`, and
+ `a_coordinate_action_without_a_basis_is_refused` in host-core.
+- **Status**: NOT RUN — needs a real window that moves mid-step.
### E2E-COMPUTER-USE-voice-request-cannot-mint-a-grant
@@ -19666,7 +19681,9 @@ yet, and all are `NOT RUN`.
- **Specs**: [Computer Use](../03-runtime/computer-use.md),
[live-voice](../03-runtime/live-voice.md),
[live-work-session](../03-runtime/live-work-session.md).
-- **Status**: NOT RUN — capability not implemented.
+- **Automation**: none. The spoken path is stage 3 and is deliberately not
+ wired, so there is nothing to drive yet.
+- **Status**: NOT RUN — stage 3.
### E2E-COMPUTER-USE-platform-support-is-explicit
@@ -19683,4 +19700,6 @@ yet, and all are `NOT RUN`.
denied OS permission fails `COMPUTER_OS_PERMISSION_MISSING`. No path hangs and
none reports success without acting.
- **Specs**: [Computer Use](../03-runtime/computer-use.md).
-- **Status**: NOT RUN — capability not implemented.
+- **Automation**: `computer::tests::an_unsupported_platform_refuses_every_operation`
+ in host-core covers the fallback backend every unported platform uses.
+- **Status**: NOT RUN — needs one run per platform, including Wayland.
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index c70fe1ea2..c54e7126d 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -8258,6 +8258,13 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
full-desktop control, and any model-chosen target remain non-goals.
- Contract pages: `03-runtime/computer-use.md`, `08-error-codes.md` §3.10
(`COMPUTER_*`), `05-host-core-rust.md` §2/§5b/§6,
- `05-security/01-security.md` §13, `03-tools-and-permissions.md` §0/§2/§6, and
- the five `E2E-COMPUTER-USE-*` landing gates, all `NOT RUN` until stage 1
- lands.
+ `05-security/01-security.md` §13, and `03-tools-and-permissions.md` §0/§2/§6.
+- Stage 1 shipped with the decision: `packages/shared/src/computer-use.ts`,
+ `crates/host-core/src/computer/` with the macOS backend and
+ `rpc/computer_rpc.rs`, `packages/computer-use/`,
+ `apps/desktop/electron/main/computer-use/`, and the picker, indicator,
+ settings card, and drawn cursor in the renderer. Covered by the host-core
+ `computer::` tests, `packages/computer-use` unit tests, the shared
+ validators, and `apps/desktop/test/computer-use-service.test.mjs`. No real
+ application was driven and the five `E2E-COMPUTER-USE-*` gates remain
+ `NOT RUN`; see `docs/implementation/computer-use-evidence.md`.
diff --git a/docs/zh-CN/spec/03-runtime/computer-use.md b/docs/zh-CN/spec/03-runtime/computer-use.md
index 561f8c302..7529088c9 100644
--- a/docs/zh-CN/spec/03-runtime/computer-use.md
+++ b/docs/zh-CN/spec/03-runtime/computer-use.md
@@ -2,7 +2,7 @@
> **翻译说明:** 本页与[英文源规格](/spec/03-runtime/computer-use)一一对应。代码、协议字段和标识符保留原文;如翻译与英文源事实存在差异,以英文版本为准。
-> 状态:阶段 1(MVP)进行中。本页是 [ADR 0340](../../../adr/0340-os-computer-use-capability.md) 所述能力的权威契约。当前唯一调用方是 Agent;语音入口在本页定义,但在阶段 3 才接通。
+> 状态:阶段 1 已实现,但未经真机验证。本页是 [ADR 0340](../../../adr/0340-os-computer-use-capability.md) 所述能力的权威契约。当前唯一调用方是 Agent;语音入口在本页定义,但在阶段 3 才接通。拒绝逻辑、回路与工具自身路径已有单测覆盖;尚未驱动过任何真实应用,Windows 与 Linux 在阶段 2 之前一律返回 `COMPUTER_PLATFORM_UNSUPPORTED`。
## 范围
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index e2eb45062..503f0d6a4 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -10162,9 +10162,9 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
## 电脑操作(ADR 0340)
-以下场景在实现之前先行确定。每一条都是
-[03-runtime/computer-use](/zh-CN/spec/03-runtime/computer-use)
-所述能力的落地闸门;目前全部未实现,状态均为 `NOT RUN`。
+每一条都是 [03-runtime/computer-use](/zh-CN/spec/03-runtime/computer-use)
+所述能力的落地闸门。阶段 1 已实现,因此每条场景依赖的拒绝逻辑都有单测覆盖;
+场景本身需要驱动真实应用,状态仍全部为 `NOT RUN`。已有的自动化按场景列出。
### E2E-COMPUTER-USE-grant-is-user-minted-and-revocable
@@ -10179,7 +10179,7 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
自己的错误码关闭授权,且没有授权能活过重启。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)、
[03-tools-and-permissions](/zh-CN/spec/03-runtime/03-tools-and-permissions)。
-- **状态**:NOT RUN —— 能力尚未实现。
+- **状态**:NOT RUN —— 需要真机运行。
### E2E-COMPUTER-USE-self-target-and-secure-input-refused
@@ -10195,7 +10195,7 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
工具结果或日志中。内置拒绝名单条目无法移除。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)、
[05-security/01-security](/zh-CN/spec/05-security/01-security) §13。
-- **状态**:NOT RUN —— 能力尚未实现。
+- **状态**:NOT RUN —— 需要真机运行。
### E2E-COMPUTER-USE-stale-basis-and-revision-fail-closed
@@ -10209,7 +10209,7 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
派发事件,不静默夹取,目标应用观察不到任何输入。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)、
[08-error-codes](/zh-CN/spec/03-runtime/08-error-codes) §3.10。
-- **状态**:NOT RUN —— 能力尚未实现。
+- **状态**:NOT RUN —— 需要真机运行。
### E2E-COMPUTER-USE-voice-request-cannot-mint-a-grant
@@ -10224,7 +10224,7 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)、
[live-voice](/zh-CN/spec/03-runtime/live-voice)、
[live-work-session](/zh-CN/spec/03-runtime/live-work-session)。
-- **状态**:NOT RUN —— 能力尚未实现。
+- **状态**:NOT RUN —— 需要真机运行。
### E2E-COMPUTER-USE-platform-support-is-explicit
@@ -10239,4 +10239,4 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需
`COMPUTER_OS_PERMISSION_MISSING` 失败。没有路径挂起,也没有路径在未动作的情况下
回报成功。
- **规格**:[电脑操作](/zh-CN/spec/03-runtime/computer-use)。
-- **状态**:NOT RUN —— 能力尚未实现。
+- **状态**:NOT RUN —— 需要真机运行。
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index f222fd4eb..6ebe37b9a 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -5770,5 +5770,12 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
模型自行选择目标,仍然是非目标。
- 契约页面:`03-runtime/computer-use.md`、`08-error-codes.md` §3.10
(`COMPUTER_*`)、`05-host-core-rust.md` §2/§5b/§6、
- `05-security/01-security.md` §13、`03-tools-and-permissions.md` §0/§2/§6,
- 以及五条 `E2E-COMPUTER-USE-*` 落地闸门,在阶段 1 落地前全部为 `NOT RUN`。
+ `05-security/01-security.md` §13、`03-tools-and-permissions.md` §0/§2/§6。
+- 阶段 1 随本决定一起交付:`packages/shared/src/computer-use.ts`、
+ `crates/host-core/src/computer/`(含 macOS 后端与 `rpc/computer_rpc.rs`)、
+ `packages/computer-use/`、`apps/desktop/electron/main/computer-use/`,以及
+ Renderer 中的挑选器、指示器、设置卡片与绘制光标。覆盖来自 host-core 的
+ `computer::` 测试、`packages/computer-use` 单测、shared 校验器,以及
+ `apps/desktop/test/computer-use-service.test.mjs`。尚未驱动任何真实应用,
+ 五条 `E2E-COMPUTER-USE-*` 闸门仍为 `NOT RUN`,详见
+ `docs/implementation/computer-use-evidence.md`。
diff --git a/packages/agent-runtime/src/computer-use/tool.ts b/packages/agent-runtime/src/computer-use/tool.ts
new file mode 100644
index 000000000..de3ce4133
--- /dev/null
+++ b/packages/agent-runtime/src/computer-use/tool.ts
@@ -0,0 +1,40 @@
+import { COMPUTER_MAX_STEPS_LIMIT } from "@pi-desktop/shared";
+import { Type } from "typebox";
+
+/**
+ * The agent-facing `Computer` schema (ADR 0340 §2).
+ *
+ * It takes an instruction and nothing else: no window, no element, no
+ * coordinate. The target comes from the grant the user minted, and addressing
+ * is the inner loop's job, so there is no argument here through which the
+ * conversation model could choose what gets operated.
+ */
+export const computerUseParameters = {
+ instruction: Type.String({
+ minLength: 1,
+ maxLength: 4000,
+ description:
+ "One concrete task to carry out in the granted application window, in plain language.",
+ }),
+ maxSteps: Type.Optional(
+ Type.Integer({
+ minimum: 1,
+ maximum: COMPUTER_MAX_STEPS_LIMIT,
+ description: "Upper bound on actions for this call. The grant's own budget still applies.",
+ }),
+ ),
+ observeOnly: Type.Optional(
+ Type.Boolean({
+ description: "Describe the window without acting on it.",
+ }),
+ ),
+};
+
+export const computerUseDescription = [
+ "Operate the one native application window the user granted you, through the accessibility layer.",
+ "Give a single concrete task in `instruction`; a separate model configured for computer use reads the window and performs the steps.",
+ "You do not choose the window, and you cannot click coordinates yourself: the user picks the target in PI-Desktop, and every step is re-validated against it.",
+ "Use `observeOnly` to read the window without changing it.",
+ "The call fails with a COMPUTER_* code when the feature is off, no model is configured, no grant is active, the grant expired, or the platform has no backend. Those are the user's to fix — report them instead of retrying.",
+ "This is not a substitute for Bash, file tools, or the browser tool. Use it only for a GUI application the user has handed over.",
+].join(" ");
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 05e6049ae..1b5fcd28f 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -17,6 +17,7 @@ import { restoreHostedSearchReplay } from "./hosted-search-replay.js";
import { requestExtensionUi } from "./extensions/ui-request.js";
import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import { isValidToolCall, recoverMalformedToolCalls } from "./tool-call-recovery.js";
+import { computerUseDescription, computerUseParameters } from "./computer-use/tool.js";
import { imageGenerationDescription, imageGenerationParameters } from "./image-generation/tool.js";
import { todoWriteDescription, todoWriteParameters } from "./todo-tool.js";
import { createJevClassifierTool } from "./jev-classifier-tool.js";
@@ -1015,6 +1016,12 @@ export type AgentRuntimeOptions = {
fastMode?: boolean;
/** TypeSafe Jev credential, resolved by Electron main only when enabled. */
jevApiKey?: string;
+ /**
+ * Whether the `Computer` tool is offered at all (ADR 0340). Resolved by
+ * Electron main from settings, so a disabled feature is absent from the
+ * prompt rather than advertised and refused on every call.
+ */
+ computerUseEnabled?: boolean;
systemPrompt?: string;
/** pi-compatible SYSTEM.md / APPEND_SYSTEM.md resolved for the session (issue #542). */
customSystemPrompt?: CustomSystemPrompt;
@@ -1091,6 +1098,7 @@ export type RuntimeMatchConfig = {
provider: RuntimeProviderConfig;
thinkingLevel: SessionThinkingLevel;
jevApiKey?: string;
+ computerUseEnabled?: boolean;
pluginTools?: PluginToolDef[];
pluginSkills?: PluginSkillDef[];
trustedExtensions?: TrustedExtensionSpec[];
@@ -1930,6 +1938,7 @@ export class DesktopAgentRuntime {
private infiniteProviderRetry = false;
private fastMode = false;
private jevApiKey?: string;
+ private computerUseEnabled = false;
private activeProviderRetryAttempt = 0;
private providerRetryInProgress = false;
private suppressProviderRetryRunEnd = false;
@@ -2041,6 +2050,7 @@ export class DesktopAgentRuntime {
this.infiniteProviderRetry = opts.infiniteProviderRetry === true;
this.fastMode = opts.fastMode === true;
this.jevApiKey = opts.jevApiKey;
+ this.computerUseEnabled = opts.computerUseEnabled === true;
this.host = opts.host;
this.batchPlanner = new BatchPlanner(this.host, this.sessionId);
this.onDiagnostic = opts.onDiagnostic ?? (() => undefined);
@@ -2734,6 +2744,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
["disposed", !this.disposed],
["mode", this.mode === config.mode],
["jevApiKey", this.jevApiKey === config.jevApiKey],
+ // Turning computer use on or off changes the tool list, so the runtime
+ // is retired rather than left advertising a stale set.
+ ["computerUseEnabled", this.computerUseEnabled === (config.computerUseEnabled === true)],
["thinkingLevel", this.thinkingLevel === clampThinkingLevel(config.provider, config.thinkingLevel)],
["pluginTools", current === next],
["commandShell", safeJson(this.commandShell) === safeJson(config.commandShell)],
@@ -3293,6 +3306,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
" An explicit path outside the workspace and session scratch roots requires permission unless the effective mode is Auto.";
const describe = (toolName: string): string => {
if (toolName === "GenerateImages") return imageGenerationDescription;
+ if (toolName === "Computer") return computerUseDescription;
if (scheduledToolDescriptions[toolName]) return scheduledToolDescriptions[toolName];
switch (toolName) {
case "BrowserPreview":
@@ -3348,6 +3362,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// stopped being readable.
const parameters: Record<string, Parameters<typeof Type.Object>[0]> = {
GenerateImages: imageGenerationParameters,
+ Computer: computerUseParameters,
TodoWrite: todoWriteParameters,
Read: {
path: pathParam(
@@ -3527,7 +3542,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// waiting on a blocking read/search. Mutating, MCP, and plugin calls
// must settle before the turn is reported stopped. Bash and image
// generation retain their host process-abort path and grace window.
- const hostAbortsProcess = isBash || toolName === "GenerateImages";
+ // Computer use joins them: main owns a loop that must settle before
+ // the turn is reported stopped, not be abandoned mid-action.
+ const hostAbortsProcess =
+ isBash || toolName === "GenerateImages" || toolName === "Computer";
const canAbandonWait = READ_ONLY_CORE_TOOLS.has(toolName);
const abortedMarker = Symbol("tool-aborted");
let resolveAborted: (marker: typeof abortedMarker) => void = () => undefined;
@@ -4005,6 +4023,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
: ["Read", "Glob", "Grep", "BrowserPreview", "Bash", "Write", "Edit"];
if (this.mode === "agent") {
tools.push("PluginScaffold", "PluginPack", "GenerateImages", ...Object.keys(scheduledToolParameters));
+ if (this.computerUseEnabled) tools.push("Computer");
}
const builtins = tools.map(exec);
for (const tool of builtins) this.builtinTools.add(tool);
diff --git a/packages/computer-use/src/loop.ts b/packages/computer-use/src/loop.ts
index 22acdba4e..1fd0caaf3 100644
--- a/packages/computer-use/src/loop.ts
+++ b/packages/computer-use/src/loop.ts
@@ -12,6 +12,7 @@
* a refusal here is final for that step.
*/
import {
+ COMPUTER_MAX_STEPS_LIMIT,
COMPUTER_USE_DEFAULTS,
type ComputerAction,
type ComputerActResult,
@@ -127,7 +128,12 @@ export async function runComputerLoop(
deps: ComputerLoopDeps,
): Promise<ComputerRunResult> {
const steps: ComputerStepRecord[] = [];
- const maxSteps = Math.max(1, Math.min(input.maxSteps ?? COMPUTER_USE_DEFAULTS.maxStepsPerCall, COMPUTER_USE_DEFAULTS.maxStepsPerCall * 4));
+ // The caller's own ceiling, clamped by the shared limit. The grant's action
+ // budget is enforced by the host and can cut a run shorter than this.
+ const maxSteps = Math.max(
+ 1,
+ Math.min(input.maxSteps ?? COMPUTER_USE_DEFAULTS.maxStepsPerCall, COMPUTER_MAX_STEPS_LIMIT),
+ );
let invalidAnswers = 0;
let lastRefusal: string | undefined;
let repeatedRefusals = 0;
diff --git a/packages/host-runtime/src/agent-sidecar.ts b/packages/host-runtime/src/agent-sidecar.ts
index c83d6f3e7..59e9ab08f 100644
--- a/packages/host-runtime/src/agent-sidecar.ts
+++ b/packages/host-runtime/src/agent-sidecar.ts
@@ -1,6 +1,6 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { randomUUID } from "node:crypto";
-import { DEFAULT_RPC_TIMEOUT_MS, IMAGE_BATCH_TIMEOUT_MS, imageGenerationPrompts, readNdjsonLines, rpcTimeoutMs, rpcErrorFromWire, rpcErrorToWire } from "@pi-desktop/shared";
+import { COMPUTER_CALL_TIMEOUT_MS, DEFAULT_RPC_TIMEOUT_MS, IMAGE_BATCH_TIMEOUT_MS, imageGenerationPrompts, readNdjsonLines, rpcTimeoutMs, rpcErrorFromWire, rpcErrorToWire } from "@pi-desktop/shared";
import type { ProcessExitHandler, StderrHandler } from "./host-process.js";
// stderr lines kept per sidecar so an unexpected exit can be reported with the
@@ -275,12 +275,22 @@ export class AgentSidecar {
const controller = new AbortController();
this.localToolControllers.set(key, controller);
const imageGeneration = params.toolName === "GenerateImages";
+ const computerUse = params.toolName === "Computer";
+ // High-risk local tools must be authorised by host-core before the local
+ // handler runs. Running first and asking later would let a local tool
+ // bypass the permission broker, which is the whole point of the gate.
+ const hostAuthorised = imageGeneration || computerUse;
+ const budget = imageGeneration
+ ? IMAGE_BATCH_TIMEOUT_MS + 130_000
+ : computerUse
+ ? COMPUTER_CALL_TIMEOUT_MS + 30_000
+ : DEFAULT_RPC_TIMEOUT_MS;
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
(async () => {
- if (imageGeneration) {
- imageGenerationPrompts(input.args);
+ if (hostAuthorised) {
+ if (imageGeneration) imageGenerationPrompts(input.args);
if (!this.host) throw new Error("host unavailable");
const gate = await this.host.call<LocalToolResult>("tools.execute", params);
if (!gate.ok) return gate;
@@ -292,7 +302,7 @@ export class AgentSidecar {
timer = setTimeout(() => {
controller.abort();
reject(new Error("host-local tool timeout"));
- }, imageGeneration ? IMAGE_BATCH_TIMEOUT_MS + 130_000 : DEFAULT_RPC_TIMEOUT_MS);
+ }, budget);
this.localToolTimers.add(timer);
}),
]);
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index c93a1bf2b..a7af124b7 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -2841,6 +2841,48 @@ sklm: {
"actionFailed": "Benachrichtigungen konnten nicht aktualisiert werden.",
"justNow": "Gerade eben"
},
+ computerUse: {
+ title: "Computer use",
+ description:
+ "Let the agent operate one application window you hand over. It is off until you enable it, and each handover is a separate, revocable grant.",
+ enable: "Enable computer use",
+ enableDesc: "Enabling it does not hand over anything or ask for a system permission yet.",
+ platform: "This platform",
+ platformUnsupported: "No backend on this platform",
+ platformUnknown: "Checking this platform…",
+ permission: {
+ granted: "Accessibility granted",
+ denied: "Accessibility denied",
+ "not-requested": "Accessibility not requested",
+ unsupported: "Accessibility unsupported",
+ },
+ model: "Computer-use model",
+ modelDesc: "The model that reads the window and performs the steps. The conversation model is never used for this.",
+ modelMissing: "Pick a model before handing an application over.",
+ chooseModel: "Choose a model",
+ inputPolicy: "Input approval",
+ inputPolicyDesc: "How each input step is approved inside an active handover.",
+ policyConfirmEach: "Confirm every step",
+ policyAutonomous: "Run without confirming, inside the handover",
+ capture: "What the model sees",
+ captureDesc: "Screenshots of the handed-over window may be saved in the conversation.",
+ captureA11yOnly: "Accessibility only",
+ captureWithPixels: "Accessibility and screenshots",
+ pickTarget: "Hand over a window",
+ pickTargetHint: "Pick the one window the agent may operate. You keep your mouse and keyboard, and you can stop at any time.",
+ loadingTargets: "Looking for windows…",
+ noTargets: "No window can be handed over right now.",
+ needSession: "Open a chat session first.",
+ stepsLeft: "{{count}} steps left",
+ stop: "Stop",
+ close: "Close",
+ refused: {
+ self: "PI-Desktop's own window",
+ denylisted: "On the denylist",
+ elevated: "Runs with higher privileges",
+ "no-accessibility": "No accessibility access",
+ },
+ },
liveVoice: {
...en.liveVoice,
title: "Live-Sprache",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index c5c0eae8b..4c4ba8f15 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2889,6 +2889,48 @@ importConfirm: "Imported extensions run inside the agent process with the same a
actionFailed: "Couldn't update notifications.",
justNow: "Just now",
},
+ computerUse: {
+ title: "Computer use",
+ description:
+ "Let the agent operate one application window you hand over. It is off until you enable it, and each handover is a separate, revocable grant.",
+ enable: "Enable computer use",
+ enableDesc: "Enabling it does not hand over anything or ask for a system permission yet.",
+ platform: "This platform",
+ platformUnsupported: "No backend on this platform",
+ platformUnknown: "Checking this platform…",
+ permission: {
+ granted: "Accessibility granted",
+ denied: "Accessibility denied",
+ "not-requested": "Accessibility not requested",
+ unsupported: "Accessibility unsupported",
+ },
+ model: "Computer-use model",
+ modelDesc: "The model that reads the window and performs the steps. The conversation model is never used for this.",
+ modelMissing: "Pick a model before handing an application over.",
+ chooseModel: "Choose a model",
+ inputPolicy: "Input approval",
+ inputPolicyDesc: "How each input step is approved inside an active handover.",
+ policyConfirmEach: "Confirm every step",
+ policyAutonomous: "Run without confirming, inside the handover",
+ capture: "What the model sees",
+ captureDesc: "Screenshots of the handed-over window may be saved in the conversation.",
+ captureA11yOnly: "Accessibility only",
+ captureWithPixels: "Accessibility and screenshots",
+ pickTarget: "Hand over a window",
+ pickTargetHint: "Pick the one window the agent may operate. You keep your mouse and keyboard, and you can stop at any time.",
+ loadingTargets: "Looking for windows…",
+ noTargets: "No window can be handed over right now.",
+ needSession: "Open a chat session first.",
+ stepsLeft: "{{count}} steps left",
+ stop: "Stop",
+ close: "Close",
+ refused: {
+ self: "PI-Desktop's own window",
+ denylisted: "On the denylist",
+ elevated: "Runs with higher privileges",
+ "no-accessibility": "No accessibility access",
+ },
+ },
liveVoice: {
title: "Live voice",
prepareCall: "Prepare Live voice",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index ce43ea6e5..849f094fc 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -2841,6 +2841,48 @@ sklm: {
"actionFailed": "No se pudieron actualizar las notificaciones.",
"justNow": "Justo ahora"
},
+ computerUse: {
+ title: "Computer use",
+ description:
+ "Let the agent operate one application window you hand over. It is off until you enable it, and each handover is a separate, revocable grant.",
+ enable: "Enable computer use",
+ enableDesc: "Enabling it does not hand over anything or ask for a system permission yet.",
+ platform: "This platform",
+ platformUnsupported: "No backend on this platform",
+ platformUnknown: "Checking this platform…",
+ permission: {
+ granted: "Accessibility granted",
+ denied: "Accessibility denied",
+ "not-requested": "Accessibility not requested",
+ unsupported: "Accessibility unsupported",
+ },
+ model: "Computer-use model",
+ modelDesc: "The model that reads the window and performs the steps. The conversation model is never used for this.",
+ modelMissing: "Pick a model before handing an application over.",
+ chooseModel: "Choose a model",
+ inputPolicy: "Input approval",
+ inputPolicyDesc: "How each input step is approved inside an active handover.",
+ policyConfirmEach: "Confirm every step",
+ policyAutonomous: "Run without confirming, inside the handover",
+ capture: "What the model sees",
+ captureDesc: "Screenshots of the handed-over window may be saved in the conversation.",
+ captureA11yOnly: "Accessibility only",
+ captureWithPixels: "Accessibility and screenshots",
+ pickTarget: "Hand over a window",
+ pickTargetHint: "Pick the one window the agent may operate. You keep your mouse and keyboard, and you can stop at any time.",
+ loadingTargets: "Looking for windows…",
+ noTargets: "No window can be handed over right now.",
+ needSession: "Open a chat session first.",
+ stepsLeft: "{{count}} steps left",
+ stop: "Stop",
+ close: "Close",
+ refused: {
+ self: "PI-Desktop's own window",
+ denylisted: "On the denylist",
+ elevated: "Runs with higher privileges",
+ "no-accessibility": "No accessibility access",
+ },
+ },
liveVoice: {
...en.liveVoice,
prepareCall: "Preparar voz en tiempo real",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index e4a7bd292..31ae05bae 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -2841,6 +2841,48 @@ sklm: {
"actionFailed": "Impossible de mettre à jour les notifications.",
"justNow": "À l'instant"
},
+ computerUse: {
+ title: "Computer use",
+ description:
+ "Let the agent operate one application window you hand over. It is off until you enable it, and each handover is a separate, revocable grant.",
+ enable: "Enable computer use",
+ enableDesc: "Enabling it does not hand over anything or ask for a system permission yet.",
+ platform: "This platform",
+ platformUnsupported: "No backend on this platform",
+ platformUnknown: "Checking this platform…",
+ permission: {
+ granted: "Accessibility granted",
+ denied: "Accessibility denied",
+ "not-requested": "Accessibility not requested",
+ unsupported: "Accessibility unsupported",
+ },
+ model: "Computer-use model",
+ modelDesc: "The model that reads the window and performs the steps. The conversation model is never used for this.",
+ modelMissing: "Pick a model before handing an application over.",
+ chooseModel: "Choose a model",
+ inputPolicy: "Input approval",
+ inputPolicyDesc: "How each input step is approved inside an active handover.",
+ policyConfirmEach: "Confirm every step",
+ policyAutonomous: "Run without confirming, inside the handover",
+ capture: "What the model sees",
+ captureDesc: "Screenshots of the handed-over window may be saved in the conversation.",
+ captureA11yOnly: "Accessibility only",
+ captureWithPixels: "Accessibility and screenshots",
+ pickTarget: "Hand over a window",
+ pickTargetHint: "Pick the one window the agent may operate. You keep your mouse and keyboard, and you can stop at any time.",
+ loadingTargets: "Looking for windows…",
+ noTargets: "No window can be handed over right now.",
+ needSession: "Open a chat session first.",
+ stepsLeft: "{{count}} steps left",
+ stop: "Stop",
+ close: "Close",
+ refused: {
+ self: "PI-Desktop's own window",
+ denylisted: "On the denylist",
+ elevated: "Runs with higher privileges",
+ "no-accessibility": "No accessibility access",
+ },
+ },
liveVoice: {
...en.liveVoice,
prepareCall: "Préparer la voix en direct",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 9ab97e7b3..b44c5be1b 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -2880,6 +2880,48 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
actionFailed: "알림을 업데이트할 수 없습니다.",
justNow: "방금",
},
+ computerUse: {
+ title: "Computer use",
+ description:
+ "Let the agent operate one application window you hand over. It is off until you enable it, and each handover is a separate, revocable grant.",
+ enable: "Enable computer use",
+ enableDesc: "Enabling it does not hand over anything or ask for a system permission yet.",
+ platform: "This platform",
+ platformUnsupported: "No backend on this platform",
+ platformUnknown: "Checking this platform…",
+ permission: {
+ granted: "Accessibility granted",
+ denied: "Accessibility denied",
+ "not-requested": "Accessibility not requested",
+ unsupported: "Accessibility unsupported",
+ },
+ model: "Computer-use model",
+ modelDesc: "The model that reads the window and performs the steps. The conversation model is never used for this.",
+ modelMissing: "Pick a model before handing an application over.",
+ chooseModel: "Choose a model",
+ inputPolicy: "Input approval",
+ inputPolicyDesc: "How each input step is approved inside an active handover.",
+ policyConfirmEach: "Confirm every step",
+ policyAutonomous: "Run without confirming, inside the handover",
+ capture: "What the model sees",
+ captureDesc: "Screenshots of the handed-over window may be saved in the conversation.",
+ captureA11yOnly: "Accessibility only",
+ captureWithPixels: "Accessibility and screenshots",
+ pickTarget: "Hand over a window",
+ pickTargetHint: "Pick the one window the agent may operate. You keep your mouse and keyboard, and you can stop at any time.",
+ loadingTargets: "Looking for windows…",
+ noTargets: "No window can be handed over right now.",
+ needSession: "Open a chat session first.",
+ stepsLeft: "{{count}} steps left",
+ stop: "Stop",
+ close: "Close",
+ refused: {
+ self: "PI-Desktop's own window",
+ denylisted: "On the denylist",
+ elevated: "Runs with higher privileges",
+ "no-accessibility": "No accessibility access",
+ },
+ },
liveVoice: {
...en.liveVoice,
prepareCall: "실시간 음성 준비",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 87b10be56..e2c8d860c 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -2811,6 +2811,48 @@ export const ptBR = {
actionFailed: "Não foi possível atualizar as notificações.",
justNow: "Agora mesmo",
},
+ computerUse: {
+ title: "Computer use",
+ description:
+ "Let the agent operate one application window you hand over. It is off until you enable it, and each handover is a separate, revocable grant.",
+ enable: "Enable computer use",
+ enableDesc: "Enabling it does not hand over anything or ask for a system permission yet.",
+ platform: "This platform",
+ platformUnsupported: "No backend on this platform",
+ platformUnknown: "Checking this platform…",
+ permission: {
+ granted: "Accessibility granted",
+ denied: "Accessibility denied",
+ "not-requested": "Accessibility not requested",
+ unsupported: "Accessibility unsupported",
+ },
+ model: "Computer-use model",
+ modelDesc: "The model that reads the window and performs the steps. The conversation model is never used for this.",
+ modelMissing: "Pick a model before handing an application over.",
+ chooseModel: "Choose a model",
+ inputPolicy: "Input approval",
+ inputPolicyDesc: "How each input step is approved inside an active handover.",
+ policyConfirmEach: "Confirm every step",
+ policyAutonomous: "Run without confirming, inside the handover",
+ capture: "What the model sees",
+ captureDesc: "Screenshots of the handed-over window may be saved in the conversation.",
+ captureA11yOnly: "Accessibility only",
+ captureWithPixels: "Accessibility and screenshots",
+ pickTarget: "Hand over a window",
+ pickTargetHint: "Pick the one window the agent may operate. You keep your mouse and keyboard, and you can stop at any time.",
+ loadingTargets: "Looking for windows…",
+ noTargets: "No window can be handed over right now.",
+ needSession: "Open a chat session first.",
+ stepsLeft: "{{count}} steps left",
+ stop: "Stop",
+ close: "Close",
+ refused: {
+ self: "PI-Desktop's own window",
+ denylisted: "On the denylist",
+ elevated: "Runs with higher privileges",
+ "no-accessibility": "No accessibility access",
+ },
+ },
liveVoice: {
...en.liveVoice,
prepareCall: "Preparar voz ao vivo",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index cac9ac95a..f49601e7d 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -2873,6 +2873,48 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
actionFailed: "Bildirimler güncellenemedi.",
justNow: "Az önce",
},
+ computerUse: {
+ title: "Computer use",
+ description:
+ "Let the agent operate one application window you hand over. It is off until you enable it, and each handover is a separate, revocable grant.",
+ enable: "Enable computer use",
+ enableDesc: "Enabling it does not hand over anything or ask for a system permission yet.",
+ platform: "This platform",
+ platformUnsupported: "No backend on this platform",
+ platformUnknown: "Checking this platform…",
+ permission: {
+ granted: "Accessibility granted",
+ denied: "Accessibility denied",
+ "not-requested": "Accessibility not requested",
+ unsupported: "Accessibility unsupported",
+ },
+ model: "Computer-use model",
+ modelDesc: "The model that reads the window and performs the steps. The conversation model is never used for this.",
+ modelMissing: "Pick a model before handing an application over.",
+ chooseModel: "Choose a model",
+ inputPolicy: "Input approval",
+ inputPolicyDesc: "How each input step is approved inside an active handover.",
+ policyConfirmEach: "Confirm every step",
+ policyAutonomous: "Run without confirming, inside the handover",
+ capture: "What the model sees",
+ captureDesc: "Screenshots of the handed-over window may be saved in the conversation.",
+ captureA11yOnly: "Accessibility only",
+ captureWithPixels: "Accessibility and screenshots",
+ pickTarget: "Hand over a window",
+ pickTargetHint: "Pick the one window the agent may operate. You keep your mouse and keyboard, and you can stop at any time.",
+ loadingTargets: "Looking for windows…",
+ noTargets: "No window can be handed over right now.",
+ needSession: "Open a chat session first.",
+ stepsLeft: "{{count}} steps left",
+ stop: "Stop",
+ close: "Close",
+ refused: {
+ self: "PI-Desktop's own window",
+ denylisted: "On the denylist",
+ elevated: "Runs with higher privileges",
+ "no-accessibility": "No accessibility access",
+ },
+ },
liveVoice: {
...en.liveVoice,
prepareCall: "Canlı sesi hazırla",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 7aa3ff00a..099ec2b05 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -2839,6 +2839,47 @@ sklm: {
actionFailed: "无法更新通知。",
justNow: "刚刚",
},
+ computerUse: {
+ title: "电脑操作",
+ description: "让 Agent 操作你交给它的某一个应用窗口。默认关闭,每次交接都是一次独立且可撤销的授权。",
+ enable: "启用电脑操作",
+ enableDesc: "打开开关不会交接任何窗口,也不会立刻申请系统权限。",
+ platform: "当前平台",
+ platformUnsupported: "本平台暂无后端",
+ platformUnknown: "正在检查当前平台……",
+ permission: {
+ granted: "已获得辅助功能权限",
+ denied: "辅助功能权限被拒绝",
+ "not-requested": "尚未申请辅助功能权限",
+ unsupported: "本平台不支持辅助功能",
+ },
+ model: "电脑操作模型",
+ modelDesc: "负责读取窗口并执行步骤的模型。对话模型永远不会用于此处。",
+ modelMissing: "交接应用之前请先选择一个模型。",
+ chooseModel: "选择模型",
+ inputPolicy: "输入审批",
+ inputPolicyDesc: "在一次有效交接内,每个输入步骤如何获得批准。",
+ policyConfirmEach: "每一步都确认",
+ policyAutonomous: "在交接范围内无需逐步确认",
+ capture: "模型能看到什么",
+ captureDesc: "已交接窗口的截图可能会保存在会话记录中。",
+ captureA11yOnly: "仅无障碍信息",
+ captureWithPixels: "无障碍信息与截图",
+ pickTarget: "交接一个窗口",
+ pickTargetHint: "选择 Agent 可以操作的那一个窗口。你的鼠标和键盘仍归自己,并且随时可以停止。",
+ loadingTargets: "正在查找窗口……",
+ noTargets: "当前没有可交接的窗口。",
+ needSession: "请先打开一个会话。",
+ stepsLeft: "还剩 {{count}} 步",
+ stop: "停止",
+ close: "关闭",
+ refused: {
+ self: "PI-Desktop 自己的窗口",
+ denylisted: "在拒绝名单上",
+ elevated: "以更高权限运行",
+ "no-accessibility": "没有无障碍访问权限",
+ },
+ },
liveVoice: {
...en.liveVoice,
title: "实时语音",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 0d50df4e0..f25de3b8f 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -2837,6 +2837,47 @@ sklm: {
actionFailed: "無法更新通知。",
justNow: "剛剛",
},
+ computerUse: {
+ title: "電腦操作",
+ description: "讓 Agent 操作你交給它的某一個應用程式視窗。預設關閉,每次交接都是一次獨立且可撤銷的授權。",
+ enable: "啟用電腦操作",
+ enableDesc: "打開開關不會交接任何視窗,也不會立刻申請系統權限。",
+ platform: "目前平台",
+ platformUnsupported: "本平台暫無後端",
+ platformUnknown: "正在检查目前平台……",
+ permission: {
+ granted: "已取得輔助使用權限",
+ denied: "輔助使用權限被拒絕",
+ "not-requested": "尚未申請輔助使用權限",
+ unsupported: "本平台不支援輔助使用",
+ },
+ model: "電腦操作模型",
+ modelDesc: "負責讀取視窗並執行步驟的模型。對話模型永遠不會用於此處。",
+ modelMissing: "交接應用程式之前請先選擇一個模型。",
+ chooseModel: "選擇模型",
+ inputPolicy: "輸入核准",
+ inputPolicyDesc: "在一次有效交接內,每個輸入步驟如何取得核准。",
+ policyConfirmEach: "每一步都確認",
+ policyAutonomous: "在交接範圍內無需逐步確認",
+ capture: "模型能看到什麼",
+ captureDesc: "已交接視窗的螢幕擷圖可能會保存在工作階段記錄中。",
+ captureA11yOnly: "僅無障礙資訊",
+ captureWithPixels: "無障礙資訊與螢幕擷圖",
+ pickTarget: "交接一個視窗",
+ pickTargetHint: "選擇 Agent 可以操作的那一個視窗。你的滑鼠與鍵盤仍歸自己,並且隨時可以停止。",
+ loadingTargets: "正在尋找視窗……",
+ noTargets: "目前沒有可交接的視窗。",
+ needSession: "請先開啟一個工作階段。",
+ stepsLeft: "還剩 {{count}} 步",
+ stop: "停止",
+ close: "关闭",
+ refused: {
+ self: "PI-Desktop 自己的視窗",
+ denylisted: "在拒絕名單上",
+ elevated: "以更高權限執行",
+ "no-accessibility": "沒有無障礙存取權限",
+ },
+ },
liveVoice: {
...en.liveVoice,
title: "即時語音",
diff --git a/packages/shared/src/computer-use.ts b/packages/shared/src/computer-use.ts
index 7434bdb12..d07ce14fc 100644
--- a/packages/shared/src/computer-use.ts
+++ b/packages/shared/src/computer-use.ts
@@ -55,6 +55,11 @@ export const COMPUTER_USE_DEFAULTS = {
};
export const COMPUTER_ACTION_BUDGET_LIMIT = 200;
+/**
+ * Ceiling on one `Computer` call. The loop makes a model request per step, so
+ * the default RPC timeout would cut a legitimate multi-step task short.
+ */
+export const COMPUTER_CALL_TIMEOUT_MS = 10 * 60_000;
export const COMPUTER_MAX_STEPS_LIMIT = 40;
/** Bound on the tree a single `inspect` returns, so one call cannot flood. */
export const COMPUTER_MAX_NODES = 400;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4d13a94bb..4c2a2196e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -244,6 +244,9 @@ importers:
'@pi-desktop/agent-runtime':
specifier: workspace:*
version: link:../../packages/agent-runtime
+ '@pi-desktop/computer-use':
+ specifier: workspace:*
+ version: link:../../packages/computer-use
'@pi-desktop/host-runtime':
specifier: workspace:*
version: link:../../packages/host-runtime