Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(computer-use): request Accessibility from the settings row
vastsaa4e1d19610f0
diff --git a/apps/desktop/electron/main/computer-use/permission.ts b/apps/desktop/electron/main/computer-use/permission.tsnew file mode 100644index 000000000..d40d3f96a--- /dev/null+++ b/apps/desktop/electron/main/computer-use/permission.ts@@ -0,0 +1,16 @@+import { shell } from "electron";+import { needsAccessibilityRequest, type ComputerCapabilities } from "@pi-desktop/shared";++/** Fixed OS pane only; neither renderer nor model can supply an external URL. */+export const ACCESSIBILITY_SETTINGS_URL =+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";++/** TCC may not show another prompt, so expose the switch in System Settings. */+export async function openAccessibilitySettings(+ capabilities: ComputerCapabilities,+ openExternal: (url: string) => Promise<void> = (url) => shell.openExternal(url),+): Promise<boolean> {+ if (!needsAccessibilityRequest(capabilities)) return false;+ await openExternal(ACCESSIBILITY_SETTINGS_URL);+ return true;+}diff --git a/apps/desktop/electron/main/ipc/computer-ipc.ts b/apps/desktop/electron/main/ipc/computer-ipc.tsindex fcc50e291..0bdfb6ba6 100644--- a/apps/desktop/electron/main/ipc/computer-ipc.ts+++ b/apps/desktop/electron/main/ipc/computer-ipc.ts@@ -10,6 +10,7 @@*/import { IPC, type ComputerCapabilities, type ComputerGrantView } from "@pi-desktop/shared";import { capturePermissionState } from "../computer-use/capture";+import { openAccessibilitySettings } from "../computer-use/permission";import type { HostProcess } from "../host-process";import type { IpcRegistrar } from "./types";@@ -34,6 +35,23 @@ export function registerComputerIpc({ registrar, getHost, publishGrant }: Computreturn { ...capabilities, capture: capturePermissionState() };});+ // The user's click: the host asks macOS for Accessibility, and when the+ // answer is still "no" main opens the pane that holds the switch. The reply+ // is the same capability object the row already renders, so the badge updates+ // without a second round trip.+ registrar.handleWithEvent(IPC.invoke.computerRequestPermission, async (event) => {+ registrar.assertMainWindowSender(event);+ const host = getHost();+ if (!host) hostUnavailable();+ const capabilities = await host.call<ComputerCapabilities>(+ "computer.requestPermission",+ {},+ );+ const view = { ...capabilities, capture: capturePermissionState() };+ await openAccessibilitySettings(view);+ return view;+ });+registrar.handleWithEvent(IPC.invoke.computerListTargets, async (event) => {registrar.assertMainWindowSender(event);const host = getHost();diff --git a/apps/desktop/src/features/computer-use/computer-use-api.ts b/apps/desktop/src/features/computer-use/computer-use-api.tsindex d21cbf2a0..70054ad4f 100644--- a/apps/desktop/src/features/computer-use/computer-use-api.ts+++ b/apps/desktop/src/features/computer-use/computer-use-api.ts@@ -32,6 +32,7 @@ async function invoke<T>(channel: string, ...args: unknown[]): Promise<T> {export const computerUseApi = {capabilities: () => invoke<ComputerCapabilities>(IPC.invoke.computerCapabilities),+ requestPermission: () => invoke<ComputerCapabilities>(IPC.invoke.computerRequestPermission),listTargets: () => invoke<{ targets: ComputerTarget[] }>(IPC.invoke.computerListTargets),grant: () => invoke<{ grant: ComputerGrantView | null }>(IPC.invoke.computerGrantDescribe),createGrant: (request: {diff --git a/apps/desktop/src/features/computer-use/use-computer-permission.ts b/apps/desktop/src/features/computer-use/use-computer-permission.tsnew file mode 100644index 000000000..7098cbbca--- /dev/null+++ b/apps/desktop/src/features/computer-use/use-computer-permission.ts@@ -0,0 +1,87 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { needsAccessibilityRequest, type ComputerCapabilities } from "@pi-desktop/shared";+import { computerUseApi } from "./computer-use-api";++/** Settings owns permission requests; focus/visibility only rechecks OS state. */+export function useComputerPermission() {+ const [capabilities, setCapabilities] = useState<ComputerCapabilities | null>(null);+ const [requesting, setRequesting] = useState(false);+ const [waiting, setWaiting] = useState(false);+ const [errorCode, setErrorCode] = useState<string | null>(null);+ const mounted = useRef(false);+ const sequence = useRef(0);+ const pending = useRef(false);+ const refreshAfterRequest = useRef(false);++ const reportError = useCallback((error: unknown) => {+ const code = error instanceof Error && "code" in error && typeof error.code === "string"+ ? error.code : "INTERNAL";+ setErrorCode(code);+ }, []);++ const refresh = useCallback(async () => {+ if (!mounted.current) return;+ if (pending.current) {+ refreshAfterRequest.current = true;+ return;+ }+ const revision = ++sequence.current;+ try {+ const result = await computerUseApi.capabilities();+ if (!mounted.current || revision !== sequence.current) return;+ setCapabilities(result);+ if (!needsAccessibilityRequest(result)) {+ setWaiting(false);+ setErrorCode(null);+ }+ } catch (error) {+ if (mounted.current && revision === sequence.current) reportError(error);+ }+ }, [reportError]);++ useEffect(() => {+ mounted.current = true;+ void refresh();+ const onFocus = () => { void refresh(); };+ const onVisibility = () => { if (!document.hidden) void refresh(); };+ window.addEventListener("focus", onFocus);+ document.addEventListener("visibilitychange", onVisibility);+ return () => {+ mounted.current = false;+ sequence.current += 1;+ pending.current = false;+ refreshAfterRequest.current = false;+ window.removeEventListener("focus", onFocus);+ document.removeEventListener("visibilitychange", onVisibility);+ };+ }, [refresh]);++ const requestPermission = useCallback(async () => {+ if (!mounted.current || pending.current || !capabilities || !needsAccessibilityRequest(capabilities)) return;+ pending.current = true;+ const revision = ++sequence.current;+ setRequesting(true);+ setWaiting(false);+ setErrorCode(null);+ try {+ const result = await computerUseApi.requestPermission();+ if (!mounted.current || revision !== sequence.current) return;+ setCapabilities(result);+ setWaiting(needsAccessibilityRequest(result));+ } catch (error) {+ if (mounted.current && revision === sequence.current) reportError(error);+ } finally {+ if (mounted.current && revision === sequence.current) {+ pending.current = false;+ setRequesting(false);+ // The system pane can return focus before the request IPC completes.+ if (refreshAfterRequest.current) {+ refreshAfterRequest.current = false;+ void refresh();+ }+ }+ }+ }, [capabilities, refresh, reportError]);++ return { capabilities, requesting, waiting, errorCode, requestPermission };+}diff --git a/apps/desktop/src/features/settings/computer-use/ComputerUseSettings.tsx b/apps/desktop/src/features/settings/computer-use/ComputerUseSettings.tsxindex adc1123f4..8524f2b2a 100644--- a/apps/desktop/src/features/settings/computer-use/ComputerUseSettings.tsx+++ b/apps/desktop/src/features/settings/computer-use/ComputerUseSettings.tsx@@ -3,17 +3,17 @@ import type { TFunction } from "i18next";import {COMPUTER_USE_DEFAULTS,type AppSettings,- type ComputerCapabilities,type ComputerCaptureMode,type ComputerInputPolicy,type ComputerUseSettings as ComputerUseSettingsValue,type ProviderPublic,+ needsAccessibilityRequest,} from "@pi-desktop/shared";-import { Badge, SettingsToggle } from "../../../components/ui";+import { Badge, Button, 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";+import { useComputerPermission } from "../../computer-use/use-computer-permission";/*** Computer use settings (ADR 0342).@@ -33,24 +33,9 @@ export function ComputerUseSettings({saveSettings: (patch: Partial<AppSettings>) => Promise<void>;}) {const value: ComputerUseSettingsValue = settings.computerUse ?? { enabled: false };- const [capabilities, setCapabilities] = useState<ComputerCapabilities | null>(null);+ const { capabilities, requesting, waiting, errorCode, requestPermission } = useComputerPermission();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;@@ -96,21 +81,41 @@ export function ComputerUseSettings({{/* Readable before enabling: a platform without a backend should say sorather than let the user turn on a feature that cannot act. */}<SettingsRow title={t("computerUse.platform")}>- <div className="settings-inline-status">+ <div className="computer-use-platform-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>+ {needsAccessibilityRequest(capabilities) ? (+ <Button+ size="sm"+ className="computer-use-permission-button"+ title={t("computerUse.requestPermission")}+ disabled={requesting}+ aria-busy={requesting}+ onClick={() => { void requestPermission(); }}+ >+ {requesting ? t("computerUse.requestingPermission") : t(`computerUse.permission.${capabilities.accessibility}`)}+ </Button>+ ) : (+ <Badge tone={capabilities.accessibility === "granted" ? "neutral" : "warning"}>+ {t(`computerUse.permission.${capabilities.accessibility}`)}+ </Badge>+ )}</>) : (<span className="settings-hint">{t("computerUse.platformUnknown")}</span>)}</div></SettingsRow>+ {(waiting || errorCode) && (+ <p className="computer-use-picker-error" role="status">+ {errorCode+ ? t("computerUse.permissionRequestFailed", { code: errorCode })+ : t("computerUse.permissionPending")}+ </p>+ )}{value.enabled && (<>diff --git a/apps/desktop/src/styles/computer-use.css b/apps/desktop/src/styles/computer-use.cssindex 98c8b5712..ea76923ea 100644--- a/apps/desktop/src/styles/computer-use.css+++ b/apps/desktop/src/styles/computer-use.css@@ -123,3 +123,21 @@.computer-use-picker-close:hover {background: var(--ds-tile);}++.computer-use-platform-status {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-wrap: wrap;+ gap: 8px;+}++.computer-use-permission-button {+ border-radius: var(--radius-full);+ background: color-mix(in oklab, var(--ds-warning) 16%, transparent);+ color: var(--ds-warning);+}++.computer-use-permission-button:hover:not(:disabled) {+ background: color-mix(in oklab, var(--ds-warning) 24%, transparent);+}diff --git a/apps/desktop/test/computer-use-permission-ipc.test.mjs b/apps/desktop/test/computer-use-permission-ipc.test.mjsnew file mode 100644index 000000000..86f8392b4--- /dev/null+++ b/apps/desktop/test/computer-use-permission-ipc.test.mjs@@ -0,0 +1,99 @@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import test from "node:test";+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");++test("permission IPC trusts only main, requests the host and opens only the fixed OS pane", async (t) => {+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "computer-permission-ipc-"));+ t.after(() => rm(temp, { recursive: true, force: true }));+ const stub = join(temp, "electron.mjs");+ await writeFile(stub, `+export const shell = { openExternal: async (url) => {+ globalThis.computerPermissionFixture.urls.push(url);+ if (globalThis.computerPermissionFixture.openError) throw new Error("Fixture pane unavailable");+} };+export const desktopCapturer = { getSources: async () => { throw new Error("Permission requests must not capture"); } };+export const systemPreferences = { getMediaAccessStatus: () => "granted" };+`);+ const outfile = join(temp, "ipc.mjs");+ await build({+ stdin: { contents: `+export { registerComputerIpc } from "./apps/desktop/electron/main/ipc/computer-ipc";+export { IPC } from "@pi-desktop/shared";+`, resolveDir: root },+ outfile, bundle: true, platform: "node", format: "esm",+ alias: { electron: stub, "@pi-desktop/shared": join(root, "packages/shared/src") },+ });+ const { registerComputerIpc, IPC } = await import(pathToFileURL(outfile).href);+ const fixture = { urls: [], openError: false };+ globalThis.computerPermissionFixture = fixture;+ t.after(() => { delete globalThis.computerPermissionFixture; });+ const callbacks = new Map();+ const calls = [];+ let missingHost = false;+ let hostError = null;+ const capabilities = {+ platform: "darwin", backend: "macos-ax", fidelity: "full",+ accessibility: "not-requested", capture: "not-requested",+ };+ registerComputerIpc({+ registrar: {+ handleWithEvent(channel, callback) { callbacks.set(channel, callback); },+ assertMainWindowSender(event) {+ if (!event.trusted) throw new Error("Untrusted sender");+ },+ },+ getHost: () => missingHost ? null : {+ async call(method, params) {+ calls.push({ method, params });+ if (hostError) throw hostError;+ return { ...capabilities };+ },+ },+ publishGrant() { throw new Error("Requesting permission must not create or publish a scope grant"); },+ });+ const request = callbacks.get(IPC.invoke.computerRequestPermission);+ assert.ok(request, "request channel is registered");+ await assert.rejects(request({ trusted: false }), /Untrusted sender/);+ assert.deepEqual(calls, []);+ assert.deepEqual(fixture.urls, []);++ missingHost = true;+ await assert.rejects(request({ trusted: true }), { errorCode: "HOST_UNAVAILABLE" });+ missingHost = false;+ const result = await request({ trusted: true }, { url: "https://not-accepted.invalid", targetId: "not-accepted" });+ assert.equal(result.accessibility, "not-requested");+ assert.equal(result.capture, "granted");+ assert.deepEqual(calls, [{ method: "computer.requestPermission", params: {} }]);+ assert.deepEqual(fixture.urls, ["x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"]);++ fixture.urls.length = 0;+ capabilities.accessibility = "granted";+ assert.equal((await request({ trusted: true })).accessibility, "granted");+ assert.deepEqual(fixture.urls, []);++ capabilities.accessibility = "denied";+ await request({ trusted: true });+ assert.equal(fixture.urls.length, 1);+ fixture.openError = true;+ await assert.rejects(request({ trusted: true }), /Fixture pane unavailable/);+ fixture.openError = false;+ fixture.urls.length = 0;++ hostError = Object.assign(new Error("Platform unsupported"), { errorCode: "COMPUTER_PLATFORM_UNSUPPORTED" });+ await assert.rejects(request({ trusted: true }), { errorCode: "COMPUTER_PLATFORM_UNSUPPORTED" });+ assert.deepEqual(fixture.urls, []);+ hostError = null;+ capabilities.platform = "linux";+ capabilities.backend = "unsupported";+ capabilities.accessibility = "unsupported";+ await request({ trusted: true });+ assert.deepEqual(fixture.urls, []);+});diff --git a/apps/desktop/test/computer-use-permission-user-path.test.mjs b/apps/desktop/test/computer-use-permission-user-path.test.mjsnew file mode 100644index 000000000..81d1eb64d--- /dev/null+++ b/apps/desktop/test/computer-use-permission-user-path.test.mjs@@ -0,0 +1,200 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+const fixture = String.raw`+import React from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";+import { IPC } from "@pi-desktop/shared";+import { ComputerUseSettings } from "../../apps/desktop/src/features/settings/computer-use/ComputerUseSettings";++await i18n.init({ lng: "en", keySeparator: false,+ resources: { en: { translation: flattenCatalog(catalogs.en) } },+ interpolation: { escapeValue: false } });+const initial = { platform: "darwin", backend: "macos-ax", fidelity: "full",+ accessibility: "not-requested", capture: "not-requested" };+let capabilities = { ...initial };+let holdRead = false;+let reads = [];+let requests = [];+let requestCount = 0;+let readCount = 0;+window.piDesktop = {+ on() { return () => {}; },+ async invoke(channel) {+ if (channel === IPC.invoke.computerCapabilities) {+ readCount += 1;+ if (holdRead) return new Promise((resolve) => reads.push(resolve));+ return { ok: true, data: { ...capabilities } };+ }+ if (channel === IPC.invoke.computerRequestPermission) {+ requestCount += 1;+ return new Promise((resolve) => requests.push(resolve));+ }+ throw new Error("Unexpected IPC: " + channel);+ },+};+const rootNode = createRoot(document.getElementById("root"));+const render = () => flushSync(() => rootNode.render(React.createElement(ComputerUseSettings, {+ t: i18n.t.bind(i18n), settings: { computerUse: { enabled: false } },+ saveSettings() { throw new Error("Requesting permission must not enable computer use or create a grant"); },+})));+const frame = () => new Promise(requestAnimationFrame);+const settle = async () => { await frame(); await frame(); };+function check(condition, message) { if (!condition) throw new Error(message); }+async function until(predicate, message) {+ for (let attempt = 0; attempt < 120; attempt += 1) {+ if (predicate()) return;+ await frame();+ }+ throw new Error(message + ": " + document.body.textContent);+}+const button = () => [...document.querySelectorAll("button")]+ .find((node) => /Accessibility not requested|Accessibility denied/.test(node.textContent));+const message = () => document.querySelector('[role="status"]');+function reply(data = capabilities) { requests.shift()({ ok: true, data: { ...data } }); }++window.computerPermissionProbe = async () => {+ render();+ await until(() => document.body.textContent.includes("Accessibility not requested"), "status missing");+ check(requestCount === 0, "opening Settings requested OS permission");+ check(button(), "missing Accessibility status must be a clickable button");+ button().focus();+ check(document.activeElement === button(), "request button is not keyboard focusable");+ const trigger = button();+ flushSync(() => { trigger.click(); trigger.click(); });+ await settle();+ check(requestCount === 1, "duplicate clicks launched duplicate requests");+ check(document.querySelector('button[aria-busy="true"]')?.disabled, "pending request has no disabled busy feedback");+ capabilities.accessibility = "not-requested";+ reply();+ await until(() => !!button() && !button().disabled, "request button did not recover");+ check(message()?.textContent.includes("System Settings"), "still-missing permission has no manual-grant guidance");+ capabilities.accessibility = "granted";+ const beforeFocus = readCount;+ window.dispatchEvent(new Event("focus"));+ await until(() => document.body.textContent.includes("Accessibility granted"), "returning from System Settings did not refresh permission");+ check(readCount > beforeFocus && !button(), "granted permission remained actionable");+ check(!message(), "waiting guidance remained after granting permission");++ capabilities.accessibility = "denied";+ window.dispatchEvent(new Event("focus"));+ await until(() => !!button(), "denied permission cannot be requested again");+ flushSync(() => button().click());+ requests.shift()({ ok: false, error: { code: "HOST_UNAVAILABLE", message: "Fixture host stopped" } });+ await until(() => message()?.textContent.includes("HOST_UNAVAILABLE"), "request failure is not visible");+ check(!button().disabled, "failed request cannot be retried");+ flushSync(() => button().click());+ reply({ ...capabilities, accessibility: "granted" });+ await until(() => document.body.textContent.includes("Accessibility granted"), "retry did not update status");++ // A capabilities read started before a request must not overwrite its result.+ capabilities = { ...initial };+ window.dispatchEvent(new Event("focus"));+ await until(() => !!button(), "reset did not refresh");+ holdRead = true;+ window.dispatchEvent(new Event("focus"));+ await until(() => reads.length === 1, "controlled read did not start");+ flushSync(() => button().click());+ reply({ ...initial, accessibility: "granted" });+ await until(() => document.body.textContent.includes("Accessibility granted"), "grant result missing");+ reads.shift()({ ok: true, data: { ...initial } });+ await settle();+ check(!button(), "stale read overwrote granted permission");+ holdRead = false;++ // Returning while the request is still pending queues a fresh check.+ capabilities = { ...initial };+ window.dispatchEvent(new Event("focus"));+ await until(() => !!button(), "pending-focus reset missing");+ flushSync(() => button().click());+ capabilities.accessibility = "granted";+ window.dispatchEvent(new Event("focus"));+ reply(initial);+ await until(() => document.body.textContent.includes("Accessibility granted"), "focus during request lost the final grant");++ capabilities = { ...initial, platform: "linux", backend: "unsupported", accessibility: "unsupported" };+ window.dispatchEvent(new Event("focus"));+ await until(() => document.body.textContent.includes("Accessibility unsupported"), "unsupported status missing");+ check(!button(), "unsupported platform offers an OS request");++ // Unmount removes refresh listeners and discards pending request results.+ capabilities = { ...initial };+ window.dispatchEvent(new Event("focus"));+ await until(() => !!button(), "unmount reset missing");+ flushSync(() => button().click());+ flushSync(() => rootNode.unmount());+ const afterUnmount = readCount;+ window.dispatchEvent(new Event("focus"));+ reply();+ await settle();+ check(readCount === afterUnmount, "unmounted settings retained focus listeners");+ return { passed: true, requestCount };+};+`;++test("computer-use Settings explicitly requests permission, refreshes, retries and cleans up", {+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,+}, async () => {+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "computer-permission-ui-"));+ try {+ await build({+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"' },+ alias: {+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),+ "@pi-desktop/shared": join(root, "packages/shared/src"),+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ i18next: join(root, "apps/desktop/node_modules/i18next"),+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await writeFile(join(temp, "index.html"),+ '<!doctype html><meta charset="utf-8"><div id="root"></div><script type="module" src="renderer.js"></script>');+ await writeFile(join(temp, "main.cjs"), `+const { app, BrowserWindow } = require("electron");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+app.whenReady().then(async () => {+ const win = new BrowserWindow({ show: false, width: 640, height: 480,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });+ try {+ await win.loadFile(path.join(__dirname, "index.html"));+ console.log("COMPUTER_PERMISSION_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.computerPermissionProbe()")));+ app.exit(0);+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }+});`);+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {+ env, stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) {+ stream.setEncoding("utf8");+ stream.on("data", (chunk) => { output += chunk; });+ }+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+ } finally { clearTimeout(timer); }+ assert.equal(code, 0, output.slice(-6000));+ const line = output.split(/\r?\n/).find((item) => item.startsWith("COMPUTER_PERMISSION_PROBE "));+ assert.ok(line, output.slice(-6000));+ assert.deepEqual(JSON.parse(line.slice("COMPUTER_PERMISSION_PROBE ".length)), { passed: true, requestCount: 6 });+ } finally { await rm(temp, { recursive: true, force: true }); }+});diff --git a/crates/host-core/src/computer/backend.rs b/crates/host-core/src/computer/backend.rsindex c5ced5414..114c6b589 100644--- a/crates/host-core/src/computer/backend.rs+++ b/crates/host-core/src/computer/backend.rs@@ -84,6 +84,17 @@ pub struct RawInspection {pub trait Desktop: Send + Sync {fn capabilities(&self) -> Capabilities;+ /// Ask the OS to grant the permission this backend needs, and report what+ /// it says now.+ ///+ /// This is the one backend call a user can trigger directly, and it only+ /// ever *asks*: macOS shows its own dialog, and the grant decision stays in+ /// System Settings. A platform with no permission model refuses, so the+ /// caller can tell "not grantable here" from "asked and still not allowed".+ fn request_permission(&self) -> Result<PermissionState, DesktopError> {+ Err(DesktopError::Unsupported)+ }+/// Every window the platform can enumerate, unfiltered. Policy removes and/// annotates entries; a backend never hides one, because a target the user/// can see but the picker silently dropped is indistinguishable from a bug.diff --git a/crates/host-core/src/computer/macos/ffi.rs b/crates/host-core/src/computer/macos/ffi.rsindex bb50a8cdf..68009189a 100644--- a/crates/host-core/src/computer/macos/ffi.rs+++ b/crates/host-core/src/computer/macos/ffi.rs@@ -80,11 +80,28 @@ extern "C" {number_type: CFIndex,out: *mut c_void,) -> Boolean;+ /// Builds a dictionary from parallel key/value arrays. The callbacks are+ /// `NULL` here, which means the dictionary borrows both arrays for its whole+ /// lifetime — fine for the synchronous trust call that is its only user.+ pub(super) fn CFDictionaryCreate(+ allocator: CFTypeRef,+ keys: *const CFTypeRef,+ values: *const CFTypeRef,+ num_values: CFIndex,+ key_callbacks: *const c_void,+ value_callbacks: *const c_void,+ ) -> CFDictionaryRef;+ /// The shared boolean CoreFoundation hands out for `true`. Immortal, so it+ /// is never released.+ pub(super) static kCFBooleanTrue: CFTypeRef;}#[link(name = "ApplicationServices", kind = "framework")]extern "C" {pub(super) fn AXIsProcessTrusted() -> Boolean;+ /// The OS handles an asynchronous prompt when this option is true.+ pub(super) fn AXIsProcessTrustedWithOptions(options: CFDictionaryRef) -> Boolean;+ pub(super) static kAXTrustedCheckOptionPrompt: CFStringRef;pub(super) fn AXUIElementCreateApplication(pid: i32) -> AXUIElementRef;pub(super) fn AXUIElementCopyAttributeValue(element: AXUIElementRef,diff --git a/crates/host-core/src/computer/macos/mod.rs b/crates/host-core/src/computer/macos/mod.rsindex 157b50f8e..a3e7d0a5a 100644--- a/crates/host-core/src/computer/macos/mod.rs+++ b/crates/host-core/src/computer/macos/mod.rs@@ -37,6 +37,32 @@ impl MacDesktop {unsafe { AXIsProcessTrusted() != 0 }}+ /// Ask TCC to show its Accessibility prompt without granting trust ourselves.+ fn prompt_for_trust(&self) -> Result<bool, DesktopError> {+ // SAFETY: both keys and values are immutable framework constants. The+ // dictionary borrows them and is released after the synchronous call;+ // the prompt itself is asynchronous and does not change the return value.+ unsafe {+ let keys = [kAXTrustedCheckOptionPrompt];+ let values = [kCFBooleanTrue];+ let options = CFDictionaryCreate(+ std::ptr::null(),+ keys.as_ptr(),+ values.as_ptr(),+ 1,+ std::ptr::null(),+ std::ptr::null(),+ );+ if options.is_null() {+ return Err(DesktopError::Failed(+ "could not create Accessibility prompt options".into(),+ ));+ }+ let options = CfOwned(options);+ Ok(AXIsProcessTrustedWithOptions(options.as_ref()) != 0)+ }+ }+/// The AX element for one window, re-resolved from the application each/// time: holding an `AXUIElementRef` across calls would mean acting on a/// window that may already be gone.@@ -452,6 +478,17 @@ impl Desktop for MacDesktop {}}+ fn request_permission(&self) -> Result<PermissionState, DesktopError> {+ if self.trusted() {+ return Ok(PermissionState::Granted);+ }+ Ok(if self.prompt_for_trust()? {+ PermissionState::Granted+ } else {+ PermissionState::NotRequested+ })+ }+fn list_targets(&self) -> Result<Vec<RawTarget>, DesktopError> {self.enumerate()}diff --git a/crates/host-core/src/computer/tests.rs b/crates/host-core/src/computer/tests.rsindex 161323ffb..37f92a516 100644--- a/crates/host-core/src/computer/tests.rs+++ b/crates/host-core/src/computer/tests.rs@@ -627,6 +627,7 @@ fn an_unsupported_platform_refuses_every_operation() {"refusing is the safe default");assert_eq!(desktop.capabilities().fidelity, Fidelity::None);+ assert_eq!(desktop.request_permission(), Err(DesktopError::Unsupported));assert_eq!(policy::list_targets(&desktop, &Denylist::default()).expect_err("targets"),Refusal::PlatformUnsupporteddiff --git a/crates/host-core/src/rpc/computer_rpc.rs b/crates/host-core/src/rpc/computer_rpc.rsindex 73b8e0fb1..a530d8809 100644--- a/crates/host-core/src/rpc/computer_rpc.rs+++ b/crates/host-core/src/rpc/computer_rpc.rs@@ -88,6 +88,27 @@ pub(crate) async fn handle("computer.capabilities" => Ok(serde_json::to_value(desktop.capabilities()).map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?),+ // The settings row asks the OS on the user's click. It stays readable+ // while the feature is off: the grant is what makes computer use usable+ // at all, and asking for it must not require turning the feature on+ // first — that would make the toggle look broken on a fresh install.+ "computer.requestPermission" => {+ let accessibility = desktop+ .request_permission()+ .map_err(|error| refusal_err(error.into()))?;+ let st = state.lock().await;+ audit_computer(+ &st,+ "computer.permission.requested",+ None,+ json!({ "accessibility": accessibility }),+ );+ let mut capabilities = desktop.capabilities();+ capabilities.accessibility = accessibility;+ Ok(serde_json::to_value(capabilities)+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?)+ }+"computer.listTargets" => {if !settings_enabled(&state).await {return Err(refusal_err(Refusal::Disabled));diff --git a/docs/spec/03-runtime/05-host-core-rust.md b/docs/spec/03-runtime/05-host-core-rust.mdindex f6c19074f..fa95ffd60 100644--- a/docs/spec/03-runtime/05-host-core-rust.md+++ b/docs/spec/03-runtime/05-host-core-rust.md@@ -94,7 +94,7 @@ Domains:- `settings.*` (adapter level)- `secrets.*`- `audit.*`-- `computer.*` (scope grants, accessibility inspection, synthesis, capture)+- `computer.*` (scope grants, accessibility inspection, synthesis, capture, OS permission request)Example:diff --git a/docs/spec/03-runtime/computer-use.md b/docs/spec/03-runtime/computer-use.mdindex bdbe8d41a..74a686f6e 100644--- a/docs/spec/03-runtime/computer-use.md+++ b/docs/spec/03-runtime/computer-use.md@@ -128,6 +128,7 @@ Underneath, main drives these host operations. They are not agent-facing.| Host operation | Risk | Behavior ||---|---|---|| `computer.capabilities` | low | Backend identity, fidelity, per-platform OS permission state, session type |+| `computer.requestPermission` | low | Ask the OS for Accessibility from the trusted Settings window; returns capabilities, never a scope grant; unsupported backends refuse || `computer.listTargets` | low | Pickable windows for the picker only; refused targets are listed with their reason, never silently dropped || `computer.grantCreate` / `grantRevoke` / `grantDescribe` | low | Mint, revoke, and read the single active grant; minting requires the user's picker choice || `computer.inspect` | low | Structured accessibility tree of the scope: role, name, value presence, enabled, focused, bounds, per-grant opaque `uid`, declared fidelity |@@ -252,6 +253,21 @@ never a no-op reported as success.capture, accessibility bus, session type) and distinguishes "not requested","denied", and "unsupported on this platform". A denied TCC grant must not bepresented as a broken feature.+- On macOS, missing Accessibility is a keyboard-accessible button in Settings,+ available even while Computer Use is off. Only clicking it invokes+ `pi-desktop/computer/permission/request` → `computer.requestPermission` →+ `AXIsProcessTrustedWithOptions` with the OS prompt option. If still untrusted,+ main opens the fixed Accessibility pane in System Settings; the user must+ enable the switch. This never grants trust automatically or hands over a+ target. macOS cannot distinguish an unrequested grant from a denied grant+ through its trust query, so both report `not-requested` until granted.+- Requests show busy/disabled feedback and cannot run twice concurrently.+ Failures, including failure to open System Settings, are visible with an error+ code and may be retried. Returning focus or making the page visible rechecks+ capabilities without prompting. Stale reads cannot overwrite a request result;+ unmount removes listeners and discards pending results. Granted and unsupported+ permission states remain labels, not request buttons. The request IPC rejects+ non-main-window senders, and no `host.proxy` allowlist entry is added.- The target picker is host-driven and shows the display list only while it isopen. It is the only way to choose a target.- The grant indicator is visible for the whole life of a grant, names thediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a7725ac10..f2fe7d69a 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -19662,11 +19662,34 @@ their separate platform acceptance.script exists.## Computer use (ADR 0342)-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.+Native-control scenarios remain landing gates for+[03-runtime/computer-use](../03-runtime/computer-use.md). Their underlying+refusals are unit-covered, but driving real applications remains `NOT RUN`.+The permission-request UI below has isolated fixture automation.++### E2E-COMPUTER-USE-request-accessibility-from-settings++- **Preconditions**: Isolated Electron fixture profile; OS calls mocked at IPC+ and Electron boundaries; computer use disabled; no provider or real OS prompt.+- **Steps**: Open Settings with missing Accessibility; focus and click its status+ button twice. Complete the request while permission remains missing. Grant it+ externally and return focus. Exercise denied permission, a failed request and+ retry, a stale capabilities read, focus during a pending request, unsupported+ platform, and unmount during a request.+- **Expected**: Opening Settings or toggling the feature never requests OS+ permission. Explicit click alone sends `computer.requestPermission`; while+ pending, the button is busy/disabled and duplicate clicks are ignored. Missing+ trust opens only the fixed macOS Accessibility pane and explains that the user+ must enable it. Errors are visible and retryable. Focus/visibility refreshes+ without prompting; stale results and unmounted listeners cannot update UI.+ Granted/unsupported states are labels. Non-main senders are rejected before+ OS calls; opening failure propagates; no grant, capture, or input is dispatched.+- **Automation**: `node --test apps/desktop/test/computer-use-permission-user-path.test.mjs+ apps/desktop/test/computer-use-permission-ipc.test.mjs`; shared capability+ selection tests and host-core unsupported-backend tests cover platform gating.+- **Specs**: [Computer Use](../03-runtime/computer-use.md), Settings and UX surface.+- **Status**: Fixture automation PASS; actual macOS TCC prompt/switch NOT RUN.+ Native OS approval remains a manual system decision.### E2E-COMPUTER-USE-grant-is-user-minted-and-revocablediff --git a/docs/zh-CN/spec/03-runtime/05-host-core-rust.md b/docs/zh-CN/spec/03-runtime/05-host-core-rust.mdindex 6d8b5de24..e2d7e6fe6 100644--- a/docs/zh-CN/spec/03-runtime/05-host-core-rust.md+++ b/docs/zh-CN/spec/03-runtime/05-host-core-rust.md@@ -94,7 +94,7 @@ EOF 或不可恢复的管道错误。无法创建任一控制线程- `settings.*`(适配器级别)- `secrets.*`- `audit.*`-- `computer.*`(作用域授权、无障碍检查、合成、截取)+- `computer.*`(作用域授权、无障碍检查、合成、截取、操作系统权限申请)示例:diff --git a/docs/zh-CN/spec/03-runtime/computer-use.md b/docs/zh-CN/spec/03-runtime/computer-use.mdindex 607a562e6..afa8f7d40 100644--- a/docs/zh-CN/spec/03-runtime/computer-use.md+++ b/docs/zh-CN/spec/03-runtime/computer-use.md@@ -75,6 +75,7 @@ Agent 以一条自然语言 `instruction` 加可选 `maxSteps` 调用它;`obse| 宿主操作 | 风险 | 行为 ||---|---|---|| `computer.capabilities` | low | 后端身份、保真度、各平台操作系统权限状态、会话类型 |+| `computer.requestPermission` | low | 由可信设置窗口向系统申请辅助功能权限;返回能力状态,不创建作用域授权;不支持的后端拒绝 || `computer.listTargets` | low | 仅供挑选器使用的可选窗口;被拒绝的目标连同原因一起列出,绝不静默丢弃 || `computer.grantCreate` / `grantRevoke` / `grantDescribe` | low | 签发、撤销与读取唯一的活动授权;签发必须基于用户在挑选器中的选择 || `computer.inspect` | low | 作用域的结构化无障碍树:role、name、是否有值、是否可用、是否聚焦、bounds、按授权生成的不透明 `uid`、声明的保真度 |@@ -143,6 +144,8 @@ Agent 以一条自然语言 `instruction` 加可选 `maxSteps` 调用它;`obse- 电脑操作默认关闭。打开开关不会创建授权、申请操作系统权限、截取画面或枚举窗口。- 模型绑定是显式的。设置里提供用户已配置的 Provider 行;功能已开启但没有绑定是一个可见的未配置状态,而不是静默回退到对话模型。- 体检视图按平台报告操作系统权限状态(无障碍、截取、无障碍总线、会话类型),并区分"未申请"、"已拒绝"与"本平台不支持"。被拒绝的 TCC 授权不得呈现为功能损坏。+- macOS 上,缺少辅助功能权限时,设置中的状态是可用键盘访问的申请按钮,功能关闭时也可点击。仅点击才调用 `pi-desktop/computer/permission/request` → `computer.requestPermission` → 带系统提示选项的 `AXIsProcessTrustedWithOptions`。仍未授权时,Main 打开固定的系统设置辅助功能页面,由用户手动开启开关;不会自动获得权限或交接目标。macOS 的可信查询无法区分未申请与已拒绝,两者均在获准前显示 `not-requested`。+- 请求期间显示忙碌并禁用按钮,重复点击不会重复申请。申请失败或系统设置打开失败会显示错误码并允许重试。返回应用或页面再次可见时仅重新查询能力,不再次弹授权提示。过期查询不得覆盖申请结果;卸载页面清理监听并丢弃未完成结果。已授权与不支持状态仅显示标签。申请 IPC 拒绝非主窗口来源,不新增 `host.proxy` 白名单入口。- 目标挑选器由宿主驱动,仅在打开期间展示列表。它是选择目标的唯一方式。- 授权指示器在授权存续期间始终可见,标明目标、剩余预算与截取模式,并带有"停止"。应用退到后台时它仍然可见。- 授权卡片在批准之前说明正在批准哪种截取模式,并说明 `a11y-and-pixels` 意味着目标的截图可能进入会话转录。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.mdindex f09b498e7..86d716c2e 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,18 @@ PluginPack 产物的解包目录,仅用于开发验证。验收 #1711 前需## 电脑操作(ADR 0342)-每一条都是 [03-runtime/computer-use](/zh-CN/spec/03-runtime/computer-use)-所述能力的落地闸门。阶段 1 已实现,因此每条场景依赖的拒绝逻辑都有单测覆盖;-场景本身需要驱动真实应用,状态仍全部为 `NOT RUN`。已有的自动化按场景列出。+原生应用操作仍以 [03-runtime/computer-use](/zh-CN/spec/03-runtime/computer-use)+为落地闸门;拒绝逻辑有单测覆盖,真实应用操作仍为 `NOT RUN`。+下述权限申请界面已有隔离 fixture 自动化。++### E2E-COMPUTER-USE-request-accessibility-from-settings++- **前置条件**:隔离 Electron profile;在 IPC 与 Electron 边界模拟系统调用;功能关闭,不调用 Provider 或真实系统权限提示。+- **步骤**:打开设置,键盘聚焦并连续点击未授权状态;完成申请但保持未授权。在外部开启权限后返回应用。覆盖权限拒绝、申请失败及重试、过期查询、申请中返回焦点、不支持平台与申请中卸载页面。+- **预期**:打开设置或开启功能不会申请系统权限。只有显式点击发送 `computer.requestPermission`;等待中禁用按钮并显示忙碌,重复点击不重复申请。未授权时仅打开固定的 macOS 辅助功能设置页,并提示用户开启权限。错误可见且可重试。焦点/可见性恢复只刷新状态,不再次提示;过期结果和卸载后的监听不得更新界面。已授权或不支持状态仅显示标签。非主窗口来源在系统调用前被拒绝,系统设置打开失败传回;不会交接窗口、截屏或派发输入。+- **自动化**:`node --test apps/desktop/test/computer-use-permission-user-path.test.mjs apps/desktop/test/computer-use-permission-ipc.test.mjs`;shared 能力筛选测试与 host-core 不支持后端测试覆盖平台门禁。+- **规格**:[Computer Use](/zh-CN/spec/03-runtime/computer-use) 的设置与 UX 界面。+- **状态**:fixture 自动化 PASS;真实 macOS TCC 提示/开关 NOT RUN。系统权限仍由用户手动确认。### E2E-COMPUTER-USE-grant-is-user-minted-and-revocablediff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex a0784acef..eb8ee16db 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2919,6 +2919,10 @@ sklm: {platform: "This platform",platformUnsupported: "No backend on this platform",platformUnknown: "Checking this platform…",+ requestPermission: "Zugriff auf Bedienungshilfen anfordern",+ requestingPermission: "Zugriff wird angefordert…",+ permissionPending: "Aktiviere PI-Desktop unter Bedienungshilfen in den Systemeinstellungen. Kehre dann zurück, um den Status zu aktualisieren.",+ permissionRequestFailed: "Bedienungshilfen konnten nicht angefordert oder Systemeinstellungen nicht geöffnet werden. Versuche es erneut. ({{code}})",permission: {granted: "Accessibility granted",denied: "Accessibility denied",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 4d6592314..739c2d695 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2967,6 +2967,10 @@ importConfirm: "Imported extensions run inside the agent process with the same aplatform: "This platform",platformUnsupported: "No backend on this platform",platformUnknown: "Checking this platform…",+ requestPermission: "Request Accessibility permission",+ requestingPermission: "Requesting Accessibility…",+ permissionPending: "Enable Accessibility for PI-Desktop in System Settings, then return here to refresh the status.",+ permissionRequestFailed: "Could not request Accessibility or open System Settings. Try again. ({{code}})",permission: {granted: "Accessibility granted",denied: "Accessibility denied",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 1f3ae2ae8..3f13ecabe 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2919,6 +2919,10 @@ sklm: {platform: "This platform",platformUnsupported: "No backend on this platform",platformUnknown: "Checking this platform…",+ requestPermission: "Solicitar permiso de accesibilidad",+ requestingPermission: "Solicitando accesibilidad…",+ permissionPending: "Activa la accesibilidad para PI-Desktop en Ajustes del Sistema y vuelve aquí para actualizar el estado.",+ permissionRequestFailed: "No se pudo solicitar accesibilidad o abrir Ajustes del Sistema. Inténtalo de nuevo. ({{code}})",permission: {granted: "Accessibility granted",denied: "Accessibility denied",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 88337d086..5194a7fc3 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2919,6 +2919,10 @@ sklm: {platform: "This platform",platformUnsupported: "No backend on this platform",platformUnknown: "Checking this platform…",+ requestPermission: "Demander l’autorisation d’accessibilité",+ requestingPermission: "Demande d’accessibilité en cours…",+ permissionPending: "Activez l’accessibilité pour PI-Desktop dans Réglages Système, puis revenez ici pour actualiser l’état.",+ permissionRequestFailed: "Impossible de demander l’accessibilité ou d’ouvrir Réglages Système. Réessayez. ({{code}})",permission: {granted: "Accessibility granted",denied: "Accessibility denied",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 3176d6fbd..ec1a0ae23 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2958,6 +2958,10 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이platform: "This platform",platformUnsupported: "No backend on this platform",platformUnknown: "Checking this platform…",+ requestPermission: "손쉬운 사용 권한 요청",+ requestingPermission: "손쉬운 사용 권한 요청 중…",+ permissionPending: "시스템 설정에서 PI-Desktop의 손쉬운 사용 권한을 켠 다음 돌아오면 상태가 갱신됩니다.",+ permissionRequestFailed: "손쉬운 사용 권한을 요청하거나 시스템 설정을 열 수 없습니다. 다시 시도하세요. ({{code}})",permission: {granted: "Accessibility granted",denied: "Accessibility denied",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex eb30a8b65..a1303207e 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2889,6 +2889,10 @@ export const ptBR = {platform: "This platform",platformUnsupported: "No backend on this platform",platformUnknown: "Checking this platform…",+ requestPermission: "Solicitar permissão de acessibilidade",+ requestingPermission: "Solicitando acessibilidade…",+ permissionPending: "Ative a acessibilidade para o PI-Desktop nos Ajustes do Sistema e volte aqui para atualizar o status.",+ permissionRequestFailed: "Não foi possível solicitar acessibilidade ou abrir os Ajustes do Sistema. Tente novamente. ({{code}})",permission: {granted: "Accessibility granted",denied: "Accessibility denied",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 6437d1237..7824e7071 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2951,6 +2951,10 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçplatform: "This platform",platformUnsupported: "No backend on this platform",platformUnknown: "Checking this platform…",+ requestPermission: "Erişilebilirlik izni iste",+ requestingPermission: "Erişilebilirlik izni isteniyor…",+ permissionPending: "Sistem Ayarları’nda PI-Desktop için erişilebilirliği etkinleştirin, ardından durumu yenilemek için buraya dönün.",+ permissionRequestFailed: "Erişilebilirlik izni istenemedi veya Sistem Ayarları açılamadı. Tekrar deneyin. ({{code}})",permission: {granted: "Accessibility granted",denied: "Accessibility denied",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 3aae96107..c2772df8f 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2916,6 +2916,10 @@ sklm: {platform: "当前平台",platformUnsupported: "本平台暂无后端",platformUnknown: "正在检查当前平台……",+ requestPermission: "申请辅助功能权限",+ requestingPermission: "正在申请辅助功能权限……",+ permissionPending: "请在系统设置中开启 PI-Desktop 的辅助功能权限,返回此处后会自动刷新状态。",+ permissionRequestFailed: "申请辅助功能权限或打开系统设置失败,请重试。({{code}})",permission: {granted: "已获得辅助功能权限",denied: "辅助功能权限被拒绝",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex e2cdfd526..65430f2db 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2914,6 +2914,10 @@ sklm: {platform: "目前平台",platformUnsupported: "本平台暫無後端",platformUnknown: "正在检查目前平台……",+ requestPermission: "申請輔助使用權限",+ requestingPermission: "正在申請輔助使用權限……",+ permissionPending: "請在系統設定中開啟 PI-Desktop 的輔助使用權限,返回此處後會自動更新狀態。",+ permissionRequestFailed: "申請輔助使用權限或開啟系統設定失敗,請重試。({{code}})",permission: {granted: "已取得輔助使用權限",denied: "輔助使用權限被拒絕",diff --git a/packages/shared/src/computer-use.test.ts b/packages/shared/src/computer-use.test.tsindex 676466b89..2770cd0e8 100644--- a/packages/shared/src/computer-use.test.ts+++ b/packages/shared/src/computer-use.test.ts@@ -2,6 +2,8 @@ import { expect, it } from "vitest";import {COMPUTER_ACTION_BUDGET_LIMIT,COMPUTER_MAX_STEPS_LIMIT,+ needsAccessibilityRequest,+ type ComputerCapabilities,validateComputerToolArgs,validateComputerUseSettings,} from "./computer-use.js";@@ -79,3 +81,17 @@ it("Computer tool args refuse addressing, targets, and runaway step counts", ()expect(() => validateComputerToolArgs(value), `accepted ${JSON.stringify(value)}`).toThrow(/Computer/);}});++it("OS permission requests are offered only for missing macOS Accessibility", () => {+ const capabilities: ComputerCapabilities = {+ platform: "darwin", backend: "macos-ax", fidelity: "full",+ accessibility: "not-requested", capture: "not-requested",+ };+ expect(needsAccessibilityRequest(capabilities)).toBe(true);+ expect(needsAccessibilityRequest({ ...capabilities, accessibility: "denied" })).toBe(true);+ expect(needsAccessibilityRequest({ ...capabilities, accessibility: "granted" })).toBe(false);+ expect(needsAccessibilityRequest({ ...capabilities, accessibility: "unsupported" })).toBe(false);+ for (const platform of ["linux", "win32", "other"] as const) {+ expect(needsAccessibilityRequest({ ...capabilities, platform, backend: "unsupported" })).toBe(false);+ }+});diff --git a/packages/shared/src/computer-use.ts b/packages/shared/src/computer-use.tsindex 5d231c113..2d4dcdf3c 100644--- a/packages/shared/src/computer-use.ts+++ b/packages/shared/src/computer-use.ts@@ -183,6 +183,13 @@ export type ComputerCapabilities = {inputUnsupportedReason?: string;};+/** Only the macOS backend currently implements an explicit OS trust request. */+export function needsAccessibilityRequest(capabilities: ComputerCapabilities): boolean {+ return capabilities.platform === "darwin"+ && capabilities.backend === "macos-ax"+ && (capabilities.accessibility === "not-requested" || capabilities.accessibility === "denied");+}+export type ComputerGrantView = {grantId: string;/** Bumped whenever the measured target geometry or identity changes. */diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex cf4844098..9732fe996 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -141,6 +141,8 @@ export const IPC = {* handler.*/computerCapabilities: "pi-desktop/computer/capabilities",+ /** Ask the OS for the grant the platform needs; the user's click starts it. */+ computerRequestPermission: "pi-desktop/computer/permission/request",computerListTargets: "pi-desktop/computer/listTargets",computerGrantCreate: "pi-desktop/computer/grant/create",computerGrantRevoke: "pi-desktop/computer/grant/revoke",