Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(desktop,server,web): macOS asks for Desktop, Documents and Downloads in the app's own name (#846)

Yaowei Zhenge8c0a4ad01e9
diff --git a/changelog/unreleased/2026-09-24-macos-folder-access-prompts.md b/changelog/unreleased/2026-09-24-macos-folder-access-prompts.md
new file mode 100644
index 00000000..29a59125
--- /dev/null
+++ b/changelog/unreleased/2026-09-24-macos-folder-access-prompts.md
@@ -0,0 +1,38 @@
+# macOS asks for Desktop, Documents and Downloads in the app's own name
+
+- **Date:** 2026-09-24
+- **Type:** fix
+- **Scope:** `desktop`, `server`, `web`, `docs`
+- **PR:** [#846](https://github.com/Prism-Shadow/penguin-harness/pull/846)
+
+[中文版](2026-09-24-macos-folder-access-prompts.zh.md)
+
+On macOS, a Workspace chosen under Downloads (or Desktop, Documents, an external or network volume)
+looked empty to every agent, and no permission prompt ever appeared, so PenguinHarness was not
+listed under Files and Folders and there was nothing to allow. The Workspace picker named the
+setting and offered a Retry that could not change anything.
+
+The app now carries a purpose string for each of those locations, and asks for them itself. The
+picker's box for a refused folder offers **Allow access**: the desktop app's main process reads the
+folder once in the app's own name, which is the read macOS answers with its prompt. Once it is
+allowed, the listing reloads, and the app's server and every agent shell it starts can read the
+folder too. If macOS still refuses, the box says what to change and **Open System Settings** goes
+straight to Privacy & Security: Full Disk Access for the packaged app, which can be added there by
+hand when it is not listed under Files and Folders. A development instance started from a terminal
+is told that macOS charges its reads to that terminal, and is sent to Files and Folders to allow
+the terminal. A browser tab has no app to ask, so its box says which process to allow and keeps
+Retry.
+
+## Details
+
+- `POST /api/projects/:projectId/dirs/access` (`{path}` → `{granted, packaged}`) has the desktop
+ shell read one folder in the app's own name, and waits for the user's answer to macOS. Only
+ the desktop app's own window may call it (`403` `desktop_shell_only` otherwise). It returns `503` `shell_unreachable` when the server has no desktop shell to ask, and `504`
+ `timeout` after 120 seconds without an answer.
+- `POST /api/desktop/privacy-settings` (`{pane}`, `files` or `fullDisk`) has the shell open that
+ Privacy & Security pane. Like the other page-facing desktop routes, it answers only the shell's
+ own window.
+- The shell and the server exchange three new frames over the utilityProcess port:
+ `desktop-folder-access`, its reply `desktop-folder-access-result`, and
+ `desktop-open-privacy-settings`. Off macOS the shell reads and opens nothing.
+- The Web App localizes the `shell_unreachable` and `timeout` error codes.
diff --git a/changelog/unreleased/2026-09-24-macos-folder-access-prompts.zh.md b/changelog/unreleased/2026-09-24-macos-folder-access-prompts.zh.md
new file mode 100644
index 00000000..68db9f7a
--- /dev/null
+++ b/changelog/unreleased/2026-09-24-macos-folder-access-prompts.zh.md
@@ -0,0 +1,19 @@
+# macOS 以应用自己的名义询问桌面、文稿与下载的访问权限
+
+- **Date:** 2026-09-24
+- **Type:** fix
+- **Scope:** `desktop`, `server`, `web`, `docs`
+- **PR:** [#846](https://github.com/Prism-Shadow/penguin-harness/pull/846)
+
+[English](2026-09-24-macos-folder-access-prompts.md)
+
+在 macOS 上,把「下载」(或桌面、文稿、外接盘与网络卷)里的文件夹选作 Workspace 后,所有 Agent 看到的都是空目录,而且从不弹出授权询问;「文件与文件夹」里也就没有 PenguinHarness,无从放行。Workspace 选择器只指明了设置的位置,再给一个改变不了任何事情的「重试」。
+
+现在应用为这几类位置都写明了用途,并且由应用自己去申请。选择器里被拒目录的说明框提供**允许访问**:桌面应用的主进程以应用自身的身份把该目录读一次,macOS 正是对这次读取弹出询问。允许之后列表立即重新加载,应用的服务端及其启动的每个 Agent shell 也都能读取该目录。macOS 仍然拒绝时,说明框写明要改什么,**打开系统设置**直达「隐私与安全性」:打包的应用进入「完全磁盘访问权限」,它不在「文件与文件夹」里时可以在那里手动添加。从终端启动的开发实例会被告知 macOS 把它的读取算在该终端名下,并被引到「文件与文件夹」去放行该终端。浏览器标签页没有可代为申请的应用,说明框只写明需要放行哪个进程,并保留「重试」。
+
+## 细节
+
+- `POST /api/projects/:projectId/dirs/access`(`{path}` → `{granted, packaged}`)请桌面 shell 以应用自身的身份读一次该目录,并等待用户对 macOS 询问的回答;只有桌面应用自己的窗口可以调用(否则 `403` `desktop_shell_only`)。服务器没有可询问的桌面 shell 时返回 `503` `shell_unreachable`,120 秒内没有应答时返回 `504` `timeout`。
+- `POST /api/desktop/privacy-settings`(`{pane}`,取 `files` 或 `fullDisk`)请 shell 打开「隐私与安全性」的对应面板。与其他面向页面的桌面路由一样,它只响应 shell 自己的窗口。
+- shell 与服务端经 utilityProcess 端口新增三种帧:`desktop-folder-access`、它的回复 `desktop-folder-access-result`,以及 `desktop-open-privacy-settings`。非 macOS 平台上 shell 不读取也不打开任何东西。
+- Web App 为错误码 `shell_unreachable` 与 `timeout` 提供了本地化文案。
diff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.yml
index 86cad6be..672ccd9e 100644
--- a/packages/desktop/electron-builder.yml
+++ b/packages/desktop/electron-builder.yml
@@ -77,6 +77,17 @@ mac:
entitlements: build/entitlements.mac.plist
entitlementsInherit: build/entitlements.mac.inherit.plist
notarize: true
+ # macOS guards Desktop, Documents, Downloads and removable/network volumes behind TCC, and it
+ # only ASKS the user on behalf of an app that says why it wants them: without these purpose
+ # strings a read is refused silently, so a Workspace chosen under ~/Downloads looks empty to
+ # every agent and nothing ever explains why. The server and the agents' shells run as
+ # descendants of this app, so the one prompt the user answers covers all of them.
+ extendInfo:
+ NSDesktopFolderUsageDescription: PenguinHarness needs access to your Desktop when an agent's workspace is a folder on it.
+ NSDocumentsFolderUsageDescription: PenguinHarness needs access to your Documents when an agent's workspace is a folder in it.
+ NSDownloadsFolderUsageDescription: PenguinHarness needs access to your Downloads when an agent's workspace is a folder in it.
+ NSRemovableVolumesUsageDescription: PenguinHarness needs access to removable volumes when an agent's workspace is on one.
+ NSNetworkVolumesUsageDescription: PenguinHarness needs access to network volumes when an agent's workspace is on one.
# Version-less artifact names, following the CLI bundles (penguin-darwin-arm64.tar.gz):
# the version lives in the Release tag and SHA256SUMS.desktop, so the download page and
# the OSS mirror manifest can address every installer by a stable name — and GitHub's
diff --git a/packages/desktop/src/folder-access.ts b/packages/desktop/src/folder-access.ts
new file mode 100644
index 00000000..c416da09
--- /dev/null
+++ b/packages/desktop/src/folder-access.ts
@@ -0,0 +1,126 @@
+/**
+ * macOS folder access: the shell's half of the Workspace picker's "Allow access" (pure apart
+ * from the injected deps, so it unit-tests without Electron).
+ *
+ * macOS privacy protection (TCC) asks the user about Desktop, Documents, Downloads and
+ * removable or network volumes only on behalf of an app it holds responsible for the read, and
+ * lists under Files and Folders only the apps it has asked about; any other read gets a silent
+ * EPERM, with nothing for the user to allow. A read from the embedded server has been seen to
+ * fail that way without a prompt, so the server relays the page's request here and the main
+ * process reads the folder itself, once, in the app's own name. Once the app is allowed, its
+ * children — the server and the agents' shells — read too. A development instance started from
+ * a terminal is that terminal's responsibility instead, whatever the app declares, so the reply
+ * says whether the app is packaged and the page words its advice accordingly.
+ *
+ * The second request opens the Privacy & Security pane the page names. Mechanism only (see
+ * main.ts's header): what an outcome means for the user is the page's to say.
+ *
+ * The wire is the server's api contract, imported type-only.
+ */
+import path from "node:path";
+import type {
+ DesktopFolderAccessMessage,
+ DesktopFolderAccessResultMessage,
+ DesktopOpenPrivacySettingsMessage,
+ DesktopPrivacyPane,
+} from "@prismshadow/penguin-server/api";
+
+export interface FolderAccessDeps {
+ platform: NodeJS.Platform;
+ /** Electron's `app.isPackaged`: false for a run from a source checkout. */
+ isPackaged: boolean;
+ /**
+ * Reads a directory, asynchronously: on macOS the call holds until the user has answered the
+ * privacy prompt, and the main process must not stop while it waits.
+ */
+ readdir(dir: string): Promise<unknown>;
+ openExternal(url: string): Promise<void>;
+}
+
+/** One folder-access request off the port, validated; null when the frame is not one. */
+export function parseFolderAccessRequest(
+ data: unknown,
+): Pick<DesktopFolderAccessMessage, "id" | "path"> | null {
+ if (typeof data !== "object" || data === null) return null;
+ const msg = data as Partial<DesktopFolderAccessMessage>;
+ if (msg.type !== "desktop-folder-access" || typeof msg.id !== "string") return null;
+ // A request with an id is always answered, so the server never waits out its timeout on a
+ // malformed one: a path that is not a string reads as "", which is refused as not absolute.
+ return { id: msg.id, path: typeof msg.path === "string" ? msg.path : "" };
+}
+
+/** One privacy-settings request off the port: the pane it names, or null when the frame is not one. */
+export function parseOpenPrivacySettingsRequest(data: unknown): DesktopPrivacyPane | null {
+ if (typeof data !== "object" || data === null) return null;
+ const msg = data as Partial<DesktopOpenPrivacySettingsMessage>;
+ if (msg.type !== "desktop-open-privacy-settings") return null;
+ return msg.pane === "files" || msg.pane === "fullDisk" ? msg.pane : null;
+}
+
+/** System Settings › Privacy & Security, opened at the pane named. */
+export function privacySettingsUrl(pane: DesktopPrivacyPane): string {
+ const anchor = pane === "files" ? "Privacy_FilesAndFolders" : "Privacy_AllFiles";
+ return `x-apple.systempreferences:com.apple.preference.security?${anchor}`;
+}
+
+/**
+ * The reply to one folder-access request. Off macOS nothing is read: no other platform asks
+ * the user for a folder, so there is nothing to grant. A failed read reports its errno code.
+ */
+export async function folderAccessReply(
+ request: Pick<DesktopFolderAccessMessage, "id" | "path">,
+ deps: FolderAccessDeps,
+): Promise<DesktopFolderAccessResultMessage> {
+ const answer = (granted: boolean, code?: string): DesktopFolderAccessResultMessage => ({
+ type: "desktop-folder-access-result",
+ id: request.id,
+ granted,
+ ...(code !== undefined ? { code } : {}),
+ packaged: deps.isPackaged,
+ });
+ if (!path.isAbsolute(request.path)) return answer(false, "EINVAL");
+ if (deps.platform !== "darwin") return answer(true);
+ try {
+ await deps.readdir(request.path);
+ return answer(true);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return answer(false, typeof code === "string" ? code : undefined);
+ }
+}
+
+export interface FolderAccessFrameDeps extends FolderAccessDeps {
+ /** Sends the reply to the embedded server; dropped while none is running. */
+ post(reply: DesktopFolderAccessResultMessage): void;
+ log(line: string): void;
+}
+
+/**
+ * Runs one frame from the server if it is either request; false when it is neither. A
+ * folder-access request is always answered; a privacy-settings request has no reply, and off
+ * macOS it opens nothing. Each outcome leaves a line in the log: it is the one record of what
+ * macOS answered.
+ */
+export function handleFolderAccessFrame(message: unknown, deps: FolderAccessFrameDeps): boolean {
+ const request = parseFolderAccessRequest(message);
+ if (request !== null) {
+ void folderAccessReply(request, deps)
+ .then((reply) => {
+ const outcome = reply.granted ? "granted" : `refused (${reply.code ?? "no code"})`;
+ deps.log(`folder access for ${request.path}: ${outcome}`);
+ deps.post(reply);
+ })
+ .catch((err: unknown) => {
+ deps.log(`folder access for ${request.path}: the reply was not sent: ${String(err)}`);
+ });
+ return true;
+ }
+ const pane = parseOpenPrivacySettingsRequest(message);
+ if (pane === null) return false;
+ if (deps.platform === "darwin") {
+ deps.openExternal(privacySettingsUrl(pane)).catch((err: unknown) => {
+ deps.log(`System Settings could not be opened at ${pane}: ${String(err)}`);
+ });
+ }
+ return true;
+}
diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts
index 9e963c4b..90b06d03 100644
--- a/packages/desktop/src/main.ts
+++ b/packages/desktop/src/main.ts
@@ -38,6 +38,12 @@
* tab registry, the page scripts, scan / exec / click, import and history are the server
* platform's, delivered by push like any other product behavior.
*
+ * Folder access (macOS): on the Workspace picker's request, relayed over the same port, the
+ * main process reads a protected folder once and opens System Settings at a privacy pane (see
+ * folder-access.ts). It lives here because it has to: macOS asks about Desktop, Documents and
+ * Downloads only on behalf of the app it holds responsible, and the app is this process. What
+ * to tell the user about the outcome is the Web App's.
+ *
* Dev isolation: the dev profile — an unpackaged run, or any build launched with `--dev`
* — takes a dev-suffixed identity (own userData, and with it the single-instance lock and
* sticky port) and defaults to the ~/.penguin/dev-data root, so it runs beside an
@@ -72,6 +78,8 @@ import { resolveTrayIcon, resolveWindowIcon } from "./app-icon.js";
import { createBuiltinBrowserShell } from "./builtin-browser.js";
import { installCliCommand, ensureCliCommand, currentCliInstallKind } from "./cli-install.js";
import { logLine, logServerOutput, startDesktopLog, stopDesktopLog } from "./desktop-log.js";
+import { handleFolderAccessFrame } from "./folder-access.js";
+import type { FolderAccessFrameDeps } from "./folder-access.js";
import { applyLoginShellEnv } from "./login-shell-env.js";
import { installAppMenu } from "./menu.js";
import { startEmbeddedServer, stopEmbeddedServer } from "./server-process.js";
@@ -140,6 +148,15 @@ const builtinBrowser = createBuiltinBrowserShell({
locale: () => trayLocale,
log: (line) => logLine(`[shell] ${line}`),
});
+/** The Workspace picker's macOS folder access (see the header); replies go to whichever child is live. */
+const folderAccess: FolderAccessFrameDeps = {
+ platform: process.platform,
+ isPackaged: app.isPackaged,
+ readdir: (dir) => fs.promises.readdir(dir),
+ openExternal: (url) => shell.openExternal(url),
+ post: (reply) => relayChild?.postMessage(reply),
+ log: (line) => logLine(`[shell] ${line}`),
+};
/** App origin (embedded or attached); null until boot resolves. */
let appOrigin: string | null = null;
let quitting = false;
@@ -522,15 +539,17 @@ function setTrayLocale(next: TrayLocale): void {
/**
* Shell relay over the utilityProcess port: forward the account-menu row's check/install
- * frames to the updater, the Appearance switch's frames to the tray and the built-in browser's
- * commands to its guests, push every updater status fold back, and push both current states
- * now — the fresh child, restarts included, must not start blind. The subscription dies with
- * the child; the next start wires the next one.
+ * frames to the updater, the Appearance switch's frames to the tray, the built-in browser's
+ * commands to its guests and the Workspace picker's folder-access requests to folder-access.ts,
+ * push every updater status fold back, and push both current states now — the fresh child,
+ * restarts included, must not start blind. The subscription dies with the child; the next
+ * start wires the next one.
*/
function wireShellRelay(child: EmbeddedServer["child"]): void {
relayChild = child;
child.on("message", (message: unknown) => {
if (builtinBrowser.handle(message)) return;
+ if (handleFolderAccessFrame(message, folderAccess)) return;
const action = parseUpdaterCommand(message);
if (action !== null) {
handleUpdaterCommand(action);
diff --git a/packages/desktop/test/folder-access.test.ts b/packages/desktop/test/folder-access.test.ts
new file mode 100644
index 00000000..ada1be35
--- /dev/null
+++ b/packages/desktop/test/folder-access.test.ts
@@ -0,0 +1,237 @@
+/**
+ * The shell's half of the Workspace picker's macOS folder access: the two frames it reads off
+ * the port, the read it makes in the app's own name and the reply that reports it, and the
+ * System Settings panes it opens. Only macOS reads or opens anything; every other platform
+ * answers without touching the disk.
+ */
+import { describe, expect, it, vi } from "vitest";
+import type { DesktopFolderAccessResultMessage } from "@prismshadow/penguin-server/api";
+import {
+ folderAccessReply,
+ handleFolderAccessFrame,
+ parseFolderAccessRequest,
+ parseOpenPrivacySettingsRequest,
+ privacySettingsUrl,
+} from "../src/folder-access.js";
+import type { FolderAccessDeps } from "../src/folder-access.js";
+
+const DOWNLOADS = "/Users/me/Downloads";
+
+/** A read that macOS refuses the way it refuses an app it has not asked about. */
+function refused(code: string | undefined): Error {
+ const err = new Error("operation not permitted") as NodeJS.ErrnoException;
+ if (code !== undefined) err.code = code;
+ return err;
+}
+
+function deps(overrides: Partial<FolderAccessDeps> = {}): FolderAccessDeps {
+ return {
+ platform: "darwin",
+ isPackaged: true,
+ readdir: vi.fn(async () => []),
+ openExternal: vi.fn(async () => {}),
+ ...overrides,
+ };
+}
+
+describe("the frames", () => {
+ it("reads a folder-access request, answering even one whose path is not a string", () => {
+ expect(
+ parseFolderAccessRequest({ type: "desktop-folder-access", id: "a", path: DOWNLOADS }),
+ ).toEqual({ id: "a", path: DOWNLOADS });
+ // An id is enough to be owed a reply: the empty path is then refused as not absolute.
+ expect(parseFolderAccessRequest({ type: "desktop-folder-access", id: "b", path: 7 })).toEqual({
+ id: "b",
+ path: "",
+ });
+ for (const data of [
+ null,
+ "desktop-folder-access",
+ {},
+ { type: "desktop-folder-access", path: DOWNLOADS },
+ { type: "desktop-folder-access", id: 1, path: DOWNLOADS },
+ // The other frames on the same port are not requests for this module.
+ { type: "desktop-updater-command", action: "check" },
+ { type: "desktop-open-privacy-settings", pane: "files" },
+ ]) {
+ expect(parseFolderAccessRequest(data)).toBeNull();
+ }
+ });
+
+ it("reads a privacy-settings request by its pane, and nothing else", () => {
+ expect(
+ parseOpenPrivacySettingsRequest({ type: "desktop-open-privacy-settings", pane: "files" }),
+ ).toBe("files");
+ expect(
+ parseOpenPrivacySettingsRequest({ type: "desktop-open-privacy-settings", pane: "fullDisk" }),
+ ).toBe("fullDisk");
+ for (const data of [
+ null,
+ { type: "desktop-open-privacy-settings" },
+ { type: "desktop-open-privacy-settings", pane: "camera" },
+ { type: "desktop-folder-access", id: "a", path: DOWNLOADS },
+ ]) {
+ expect(parseOpenPrivacySettingsRequest(data)).toBeNull();
+ }
+ });
+
+ it("opens Files and Folders, or Full Disk Access", () => {
+ expect(privacySettingsUrl("files")).toBe(
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_FilesAndFolders",
+ );
+ expect(privacySettingsUrl("fullDisk")).toBe(
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles",
+ );
+ });
+});
+
+describe("the read", () => {
+ it("reads the folder on macOS and reports it granted", async () => {
+ const d = deps();
+ expect(await folderAccessReply({ id: "a", path: DOWNLOADS }, d)).toEqual({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: true,
+ packaged: true,
+ });
+ expect(d.readdir).toHaveBeenCalledWith(DOWNLOADS);
+ });
+
+ it("reports a refused read with its errno code", async () => {
+ for (const code of ["EPERM", "EACCES", "ENOENT"]) {
+ const d = deps({ readdir: vi.fn(async () => Promise.reject(refused(code))) });
+ expect(await folderAccessReply({ id: "a", path: DOWNLOADS }, d)).toEqual({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: false,
+ code,
+ packaged: true,
+ });
+ }
+ // A failure that carries no code is still a refusal.
+ const d = deps({ readdir: vi.fn(async () => Promise.reject(refused(undefined))) });
+ expect(await folderAccessReply({ id: "a", path: DOWNLOADS }, d)).toEqual({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: false,
+ packaged: true,
+ });
+ });
+
+ it("says whether the app is packaged, which decides whose permission it is", async () => {
+ const granted = deps({ isPackaged: false });
+ expect(await folderAccessReply({ id: "a", path: DOWNLOADS }, granted)).toMatchObject({
+ granted: true,
+ packaged: false,
+ });
+ const denied = deps({
+ isPackaged: false,
+ readdir: vi.fn(async () => Promise.reject(refused("EPERM"))),
+ });
+ expect(await folderAccessReply({ id: "a", path: DOWNLOADS }, denied)).toMatchObject({
+ granted: false,
+ code: "EPERM",
+ packaged: false,
+ });
+ });
+
+ it("reads nothing off macOS, where no folder is asked for", async () => {
+ for (const platform of ["linux", "win32"] as const) {
+ const d = deps({ platform });
+ expect(await folderAccessReply({ id: "a", path: DOWNLOADS }, d)).toMatchObject({
+ granted: true,
+ });
+ expect(d.readdir).not.toHaveBeenCalled();
+ }
+ });
+
+ it("refuses a path that is not absolute without reading it, on every platform", async () => {
+ for (const platform of ["darwin", "linux"] as const) {
+ for (const path of ["Downloads", "", "./Downloads"]) {
+ const d = deps({ platform });
+ expect(await folderAccessReply({ id: "a", path }, d)).toEqual({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: false,
+ code: "EINVAL",
+ packaged: true,
+ });
+ expect(d.readdir).not.toHaveBeenCalled();
+ }
+ }
+ });
+});
+
+describe("the frame handler", () => {
+ function frameDeps(overrides: Partial<FolderAccessDeps> = {}) {
+ const posted: DesktopFolderAccessResultMessage[] = [];
+ const logged: string[] = [];
+ return {
+ posted,
+ logged,
+ deps: {
+ ...deps(overrides),
+ post: (reply: DesktopFolderAccessResultMessage) => posted.push(reply),
+ log: (line: string) => logged.push(line),
+ },
+ };
+ }
+
+ it("answers a folder-access request on the port and logs what macOS said", async () => {
+ const f = frameDeps({ readdir: vi.fn(async () => Promise.reject(refused("EPERM"))) });
+ expect(
+ handleFolderAccessFrame({ type: "desktop-folder-access", id: "a", path: DOWNLOADS }, f.deps),
+ ).toBe(true);
+ await vi.waitFor(() => expect(f.posted).toHaveLength(1));
+ expect(f.posted[0]).toEqual({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: false,
+ code: "EPERM",
+ packaged: true,
+ });
+ expect(f.logged).toEqual([`folder access for ${DOWNLOADS}: refused (EPERM)`]);
+ });
+
+ it("opens the pane asked for on macOS, and nothing elsewhere", () => {
+ const mac = frameDeps();
+ expect(
+ handleFolderAccessFrame(
+ { type: "desktop-open-privacy-settings", pane: "fullDisk" },
+ mac.deps,
+ ),
+ ).toBe(true);
+ expect(mac.deps.openExternal).toHaveBeenCalledWith(privacySettingsUrl("fullDisk"));
+ expect(mac.posted).toEqual([]);
+
+ const linux = frameDeps({ platform: "linux" });
+ expect(
+ handleFolderAccessFrame({ type: "desktop-open-privacy-settings", pane: "files" }, linux.deps),
+ ).toBe(true);
+ expect(linux.deps.openExternal).not.toHaveBeenCalled();
+ });
+
+ it("logs a pane that would not open", async () => {
+ const f = frameDeps({
+ openExternal: vi.fn(async () => Promise.reject(new Error("no handler"))),
+ });
+ handleFolderAccessFrame({ type: "desktop-open-privacy-settings", pane: "files" }, f.deps);
+ await vi.waitFor(() => expect(f.logged).toHaveLength(1));
+ expect(f.logged[0]).toContain("System Settings could not be opened at files");
+ });
+
+ it("leaves every other frame to the rest of the relay", () => {
+ const f = frameDeps();
+ for (const data of [
+ { type: "desktop-updater-command", action: "check" },
+ { type: "desktop-tray-command", showTrayIcon: false },
+ { type: "desktop-browser-command", id: "x", command: { op: "hello" } },
+ { type: "desktop-open-privacy-settings", pane: "camera" },
+ null,
+ ]) {
+ expect(handleFolderAccessFrame(data, f.deps)).toBe(false);
+ }
+ expect(f.deps.readdir).not.toHaveBeenCalled();
+ expect(f.deps.openExternal).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/desktop/test/mac-privacy.test.ts b/packages/desktop/test/mac-privacy.test.ts
new file mode 100644
index 00000000..6699b16e
--- /dev/null
+++ b/packages/desktop/test/mac-privacy.test.ts
@@ -0,0 +1,38 @@
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const config = readFileSync(
+ fileURLToPath(new URL("../electron-builder.yml", import.meta.url)),
+ "utf8",
+);
+
+/** The keys under `mac.extendInfo`, read line by line (the block keeps them plain). */
+function macExtendInfoKeys(): string[] {
+ const lines = config.split("\n");
+ const start = lines.findIndex((line) => line === " extendInfo:");
+ if (start === -1) return [];
+ const keys: string[] = [];
+ for (const line of lines.slice(start + 1)) {
+ const m = /^ {4}([A-Za-z]+):\s*\S/.exec(line);
+ if (m === null) break;
+ keys.push(m[1]!);
+ }
+ return keys;
+}
+
+describe("macOS privacy purpose strings", () => {
+ it("declares one for every protected location a Workspace can live in", () => {
+ // Without a purpose string macOS refuses the read silently instead of asking, so a
+ // Workspace under ~/Downloads would look empty to every agent with nothing to explain it.
+ expect(macExtendInfoKeys()).toEqual(
+ expect.arrayContaining([
+ "NSDesktopFolderUsageDescription",
+ "NSDocumentsFolderUsageDescription",
+ "NSDownloadsFolderUsageDescription",
+ "NSRemovableVolumesUsageDescription",
+ "NSNetworkVolumesUsageDescription",
+ ]),
+ );
+ });
+});
diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.md
index bd5222ea..474bd8bf 100644
--- a/packages/docs/content/quickstart-desktop.en.md
+++ b/packages/docs/content/quickstart-desktop.en.md
@@ -60,6 +60,10 @@ For an official provider's model with no stored key, the **Models** page shows t
Tool calls appear inline as cards; open one to inspect its arguments and output. With the **Ask every time** (`always-ask`) approval mode, every file write waits for you to click **Allow**. [Tools & Approval](/tools) describes the four approval modes.
+> [!INFO]- On macOS, the directory browser can't read Desktop, Documents or Downloads
+>
+> macOS protects these folders. Click **Allow access** in the directory browser: the app asks macOS for the folder in its own name, and once you allow it, your agents can read the folder too. If macOS doesn't allow it, **Open System Settings** takes you to Privacy & Security; if PenguinHarness is not listed under **Files and Folders**, add it under **Full Disk Access**. A development build started from a terminal counts as that terminal to macOS, so allow the terminal there instead.
+
## The `penguin` command
The app installs the `penguin` command itself, at every launch, from the CLI bundled inside it. The app and the command always come from the same build, so updating the app updates the command too. No system Node.js is involved: the launcher runs the bundled CLI on the app's own runtime.
diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.md
index b6a44d48..1b472f74 100644
--- a/packages/docs/content/quickstart-desktop.zh.md
+++ b/packages/docs/content/quickstart-desktop.zh.md
@@ -60,6 +60,10 @@ PenguinHarness 不内置任何模型凭据。为要使用的模型配置 API Key
工具调用会以卡片形式显示在消息流里,点开卡片可以查看参数和输出。审批模式为**总是询问**(`always-ask`)时,每次写文件都会等你点击**允许**。四种审批模式的区别见[工具与审批](/tools)。
+> [!INFO]- macOS 上目录浏览器读不到桌面、文稿或下载
+>
+> 这些文件夹受 macOS 保护。在目录浏览器里点击**允许访问**:应用会以自己的名义向 macOS 申请,你允许之后,Agent 也能读取这个文件夹。macOS 没有放行时,**打开系统设置**会进入「隐私与安全性」;若「文件与文件夹」里没有 PenguinHarness,请在「完全磁盘访问权限」里添加它。从终端启动的开发构建在 macOS 看来归该终端所有,这时要放行的是那个终端。
+
## `penguin` 命令
应用每次启动时,都会用自身打包的 CLI 装好 `penguin` 命令。应用和命令始终来自同一次构建,所以更新应用时命令也会随之更新。整个过程不需要系统里的 Node.js:启动器用应用自带的运行时执行打包的 CLI。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 233431a5..6f0dc127 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -616,6 +616,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
| GET | `/agents/:agentId/sessions` | Lists the agent's Sessions with their run state, whichever client created them, unless `excludeOrg=1` asks for the user's own rows only |
| POST | `/agents/:agentId/sessions` | Creates a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201 `{session}` |
| GET | `/dirs?path=` | Server-side directory browser behind the Workspace picker |
+| POST | `/dirs/access` | Desktop app: has the shell read a folder macOS refused, in the app's own name, so that macOS asks the user: `{path}` → `{granted, packaged}` |
| GET | `/dir-skills?path=` | The Skills a directory carries, for importing them into a new agent |
- The Session list accepts optional query parameters. `limit` and `offset` page the list (`offset` requires `limit`). `category` (`active`, `subagent`, `schedule`, `benchmark` or `archived`) filters it before paging, and `workspaceGroup` filters it to one Workspace. `counts=1` adds `counts` (totals per category over the whole list), `workspaceCounts` (the same totals per Workspace path) and `workspaceLatest` (each Workspace's newest Session). Without paging parameters, the full list is returned.
@@ -625,6 +626,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
- `client` is a provenance hint stored on the row: `"cli"` from the CLI, `"web"` by default. The server itself writes `"org"` on an organization's desk and ticket sessions, and a client cannot send that value. Only `excludeOrg` reads it as a filter, and only to drop those rows.
- `source` accepts only `"benchmark"`, for a Session created by a Benchmark evaluation or optimization. The server sets `subagent` and `schedule` itself.
- `GET /dirs` starts at the home directory when `path` is omitted; an explicit `path` must be absolute. It answers `{path, parent, entries, platform}`: every entry carries its `kind` (`dir` or `file`) and `mtime`, and on Windows the home request adds `roots`, the drive roots that exist. A directory the server may not read answers `403 dir_permission_denied` rather than an empty list — on macOS that is usually a Files and Folders permission the user has not granted.
+- `POST /dirs/access` is the Workspace picker's **Allow access** in the desktop app. macOS asks about Desktop, Documents and Downloads only on behalf of the app it holds responsible for the read, so the desktop shell's main process reads the absolute `path` once, and the answer waits for the user. `granted` says whether the read succeeded (always `true` off macOS, where nothing is read). `packaged` is `false` for a development instance started from a terminal, whose reads macOS charges to that terminal. The route returns `400` `dir_not_absolute` for a path that is not absolute, `503` `shell_unreachable` when the server has no desktop shell to ask, and `504` `timeout` when the shell has not answered within 120 seconds. Only the desktop app's own window may call it; any other session gets `403` `desktop_shell_only`.
- `GET /dir-skills` reads only `<path>/.agents/skills` and `<path>/.claude/skills` of an absolute `path`, and answers `{path, skills}`. A directory without Skills answers with an empty list. See `POST /agents` under [Agents](#agents).
## Usage and Traces (Agent Level)
@@ -1029,6 +1031,7 @@ Routes that serve the desktop shell, hot updates and the Web App's own module sy
| GET | `/api/desktop/update` | The desktop app updater's status: `{status}` |
| POST | `/api/desktop/update/check`, `/api/desktop/update/download`, `/api/desktop/update/install` | Relays the command to the desktop shell; 202 |
| GET / PUT | `/api/desktop/tray` | Reads the tray-icon preference: `{status}` / relays a change: `{showTrayIcon?, locale?}` → 202 |
+| POST | `/api/desktop/privacy-settings` | Has the shell open a macOS Privacy & Security pane: `{pane}` (`files` or `fullDisk`) → 202 |
| POST | `/api/hmr/assets/probe` | Hot update: reports which blobs the store lacks |
| PUT | `/api/hmr/blobs/:sha` | Hot update: uploads one blob under its sha256 |
| POST | `/api/hmr/upgrade` | Hot update: moves the platform, CLI and web bundles to a new version together |
@@ -1036,7 +1039,8 @@ Routes that serve the desktop shell, hot updates and the Web App's own module sy
- Outside desktop mode, the desktop routes return `404` `not_found`.
- `POST /api/desktop/shutdown` does not use the cookie session. It authenticates with the desktop shell's own Bearer token (`401` `unauthorized` otherwise), answers first, and starts the graceful shutdown right after.
-- The update and tray routes answer only the desktop shell's own window: any other session gets `403` `desktop_shell_only`. When the shell is not listening, they return `503` `shell_unreachable`. `PUT /api/desktop/tray` returns `400` `invalid_show_tray_icon` for a non-boolean `showTrayIcon`, `400` `invalid_locale` for a `locale` other than `zh` or `en`, and `400` `empty_tray_patch` when neither field is given. The PUT only acknowledges the change; read the result back with GET.
+- The update, tray and privacy-settings routes answer only the desktop shell's own window: any other session gets `403` `desktop_shell_only`. When the shell is not listening, they return `503` `shell_unreachable`. `PUT /api/desktop/tray` returns `400` `invalid_show_tray_icon` for a non-boolean `showTrayIcon`, `400` `invalid_locale` for a `locale` other than `zh` or `en`, and `400` `empty_tray_patch` when neither field is given. The PUT only acknowledges the change; read the result back with GET.
+- `POST /api/desktop/privacy-settings` returns `400` `invalid_privacy_pane` for a `pane` other than `files` (Files and Folders) or `fullDisk` (Full Disk Access). The shell opens the pane on macOS only.
- The `/api/hmr` routes are admin only (`403` `forbidden`). On a non-loopback bind they also require HTTPS and otherwise return `403` `hmr_disabled`. `X-Forwarded-Proto` counts only when `PENGUIN_TRUST_PROXY=1`. A completed upgrade sends `web_updated` to every connected client, so they reload.
## Streaming (SSE)
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 422e3bb8..ad057767 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -616,6 +616,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| GET | `/agents/:agentId/sessions` | 列出 Agent 的 Session 及运行状态,不论由哪个客户端创建;`excludeOrg=1` 则只要用户自己的那些 |
| POST | `/agents/:agentId/sessions` | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201 `{session}` |
| GET | `/dirs?path=` | Workspace 选择器背后的服务器端目录浏览器 |
+| POST | `/dirs/access` | 桌面端:请 shell 以应用自身的身份读一次 macOS 拒绝的目录,让 macOS 询问用户:`{path}` → `{granted, packaged}` |
| GET | `/dir-skills?path=` | 目录所带的 Skill,用于导入到新 Agent |
- Session 列表接受可选查询参数。`limit` 和 `offset` 用于分页(`offset` 必须搭配 `limit`)。`category`(`active`、`subagent`、`schedule`、`benchmark` 或 `archived`)先过滤再分页;`workspaceGroup` 只保留一个 Workspace 的会话。`counts=1` 会在响应里附加 `counts`(整个列表按类别的总数)、`workspaceCounts`(按 Workspace 路径统计的同类总数)和 `workspaceLatest`(每个 Workspace 最新的 Session)。不带分页参数时,返回完整列表。
@@ -625,6 +626,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
- `client` 是记录在数据行上的来源提示:CLI 发起的请求为 `"cli"`,默认 `"web"`。组织的工位会话和工单会话由服务器自己写入 `"org"`,客户端不能发送这个值。只有 `excludeOrg` 会把它当作过滤条件,而且只用来剔除这些行。
- `source` 只接受 `"benchmark"`,用于 Benchmark 评估或优化创建的 Session。`subagent` 和 `schedule` 由服务器自己设置。
- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries, platform}`:每个条目带 `kind`(`dir` 或 `file`)与 `mtime`;在 Windows 上,请求主目录时另带 `roots`,即实际存在的各盘符根目录。服务无权读取的目录返回 `403 dir_permission_denied`,不再按空列表返回;在 macOS 上这通常是用户尚未授予的「文件与文件夹」权限。
+- `POST /dirs/access` 是桌面端 Workspace 选择器里的**允许访问**。macOS 只替它认定为读取责任方的应用询问桌面、文稿与下载的访问权限,因此由桌面 shell 的主进程把绝对路径 `path` 读一次,响应要等用户作答后才返回。`granted` 表示这次读取是否成功(非 macOS 平台不读取,恒为 `true`)。`packaged` 为 `false` 表示这是从终端启动的开发实例,macOS 把它的读取记在该终端名下。`path` 不是绝对路径时返回 `400` `dir_not_absolute`;服务器没有可询问的桌面 shell 时返回 `503` `shell_unreachable`;shell 在 120 秒内没有应答时返回 `504` `timeout`。只有桌面应用自己的窗口可以调用,其他会话返回 `403` `desktop_shell_only`。
- `GET /dir-skills` 只读取绝对路径下的 `<path>/.agents/skills` 和 `<path>/.claude/skills`,响应为 `{path, skills}`。没有 Skill 的目录返回空列表。参见 [Agent](#agent) 一节中的 `POST /agents`。
## 用量与 Trace(Agent 级别)
@@ -1029,6 +1031,7 @@ Telegram 连接时会先清空积压,跳过无连接期间发送的消息。
| GET | `/api/desktop/update` | 桌面应用更新器的状态:`{status}` |
| POST | `/api/desktop/update/check`、`/api/desktop/update/download`、`/api/desktop/update/install` | 把命令转发给桌面 shell;202 |
| GET / PUT | `/api/desktop/tray` | 读取系统托盘图标偏好:`{status}` / 转发更改:`{showTrayIcon?, locale?}` → 202 |
+| POST | `/api/desktop/privacy-settings` | 请 shell 打开 macOS「隐私与安全性」的某个面板:`{pane}`(`files` 或 `fullDisk`)→ 202 |
| POST | `/api/hmr/assets/probe` | 热更新:报告存储缺少哪些 blob |
| PUT | `/api/hmr/blobs/:sha` | 热更新:按 sha256 上传一个 blob |
| POST | `/api/hmr/upgrade` | 热更新:把 platform、CLI 和 web bundle 一并升到新版本 |
@@ -1036,7 +1039,8 @@ Telegram 连接时会先清空积压,跳过无连接期间发送的消息。
- 非桌面模式下,桌面路由返回 `404` `not_found`。
- `POST /api/desktop/shutdown` 不使用 cookie 会话。它用桌面 shell 专有的 Bearer token 认证(否则返回 `401` `unauthorized`),先应答,再立即开始优雅关闭。
-- update 和 tray 路由只响应桌面 shell 自己的窗口:其他任何会话都会得到 `403` `desktop_shell_only`。shell 未监听时,返回 `503` `shell_unreachable`。`showTrayIcon` 不是布尔值时,`PUT /api/desktop/tray` 返回 `400` `invalid_show_tray_icon`;`locale` 不是 `zh` 或 `en` 时返回 `400` `invalid_locale`;两个字段都未提供时返回 `400` `empty_tray_patch`。PUT 只确认收到更改;请用 GET 读回实际结果。
+- update、tray 和 privacy-settings 路由只响应桌面 shell 自己的窗口:其他任何会话都会得到 `403` `desktop_shell_only`。shell 未监听时,返回 `503` `shell_unreachable`。`showTrayIcon` 不是布尔值时,`PUT /api/desktop/tray` 返回 `400` `invalid_show_tray_icon`;`locale` 不是 `zh` 或 `en` 时返回 `400` `invalid_locale`;两个字段都未提供时返回 `400` `empty_tray_patch`。PUT 只确认收到更改;请用 GET 读回实际结果。
+- `pane` 不是 `files`(文件与文件夹)或 `fullDisk`(完全磁盘访问权限)时,`POST /api/desktop/privacy-settings` 返回 `400` `invalid_privacy_pane`。shell 只在 macOS 上打开面板。
- `/api/hmr` 路由仅限管理员(`403` `forbidden`)。绑定在非环回地址上时还要求 HTTPS,否则返回 `403` `hmr_disabled`。只有 `PENGUIN_TRUST_PROXY=1` 时 `X-Forwarded-Proto` 才生效。升级完成后,每个已连接的客户端都会收到 `web_updated` 并重新加载。
## 流式传输(SSE)
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 701bb75e..90cecef1 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3945,6 +3945,62 @@ export interface DesktopTrayCommandMessage {
locale?: DesktopTrayLocale;
}
+// Desktop folder access (desktop mode, macOS)
+//
+// macOS privacy protection (TCC) guards Desktop, Documents, Downloads and removable and network
+// volumes. It asks the user only on behalf of an app it holds responsible for a read, and lists
+// under Files and Folders only the apps it has asked about; any other read gets a silent EPERM.
+// The Workspace picker's "Allow access" therefore goes to the shell, over the same
+// utilityProcess message channel as the updater and tray above: its main process reads the
+// folder once in the app's own name and says whether it could, and once the app is allowed its
+// children (this server, the agents' shells) read too. The page can also have the shell open
+// the Privacy & Security pane to change it. What either outcome means for the user is the
+// page's to say; the shell only reports.
+
+/** What the shell's read of one folder came to. */
+export interface DesktopFolderAccessResult {
+ /** The folder could be read. Always true off macOS, where the shell reads nothing. */
+ granted: boolean;
+ /** The failed read's errno code (`EPERM`, `EACCES`, `ENOENT`, …); `EINVAL` for a path that is not absolute. */
+ code?: string;
+ /**
+ * Whether the app is a packaged build (Electron's `app.isPackaged`). An unpackaged one is a
+ * development instance started from a terminal, and macOS holds that terminal responsible
+ * for its reads rather than the app.
+ */
+ packaged: boolean;
+}
+
+/** Server → shell request over the utilityProcess message channel (relayed from POST /api/projects/:projectId/dirs/access). */
+export interface DesktopFolderAccessMessage {
+ type: "desktop-folder-access";
+ /** Pairs the reply with its request. */
+ id: string;
+ /** The folder to read, as an absolute path. */
+ path: string;
+}
+
+/** Shell → server reply to one {@link DesktopFolderAccessMessage}, carrying its `id`. */
+export interface DesktopFolderAccessResultMessage extends DesktopFolderAccessResult {
+ type: "desktop-folder-access-result";
+ id: string;
+}
+
+/** POST /api/projects/:projectId/dirs/access: the shell's answer, for the picker to act on. */
+export interface DirAccessResponse {
+ granted: boolean;
+ packaged: boolean;
+}
+
+/** The Privacy & Security panes the page may open: Files and Folders, and Full Disk Access. */
+export type DesktopPrivacyPane = "files" | "fullDisk";
+
+/** Server → shell command over the utilityProcess message channel (relayed from POST /api/desktop/privacy-settings). No reply. */
+export interface DesktopOpenPrivacySettingsMessage {
+ type: "desktop-open-privacy-settings";
+ pane: DesktopPrivacyPane;
+}
+
/**
* The outcome of one self-update run (`penguin update --yes` on the server host), carried
* by {@link UpdateJobStatus.result}. `unsupported` covers both a server not launched via
diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.ts
index 40adfa72..d25b3cd1 100644
--- a/packages/server/src/hmr/capabilities.ts
+++ b/packages/server/src/hmr/capabilities.ts
@@ -431,6 +431,10 @@ export type DesktopApi = Pick<
| "setTrayStatus"
| "onTrayCommand"
| "requestTrayCommand"
+ | "onFolderAccessRequest"
+ | "requestFolderAccess"
+ | "onPrivacySettingsCommand"
+ | "requestPrivacySettings"
>;
/** The desktop shell's service, or null when this server is not the shell's child. */
diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.ts
index ba9a1e97..b6b2afe8 100644
--- a/packages/server/src/http/routes/desktop.ts
+++ b/packages/server/src/http/routes/desktop.ts
@@ -1,14 +1,16 @@
/**
* Desktop-mode routes: POST /api/desktop/shutdown, the client-update relay under
- * /api/desktop/update, the tray-icon preference at /api/desktop/tray, plus the shared
- * desktop-mode guard that turns off multi-user surfaces (see rejectInDesktopMode).
+ * /api/desktop/update, the tray-icon preference at /api/desktop/tray, the Privacy & Security
+ * pane at /api/desktop/privacy-settings, plus the shared desktop-mode guard that turns off
+ * multi-user surfaces (see rejectInDesktopMode).
*
* Platform code, all of it: what the shell's window may ask of the shell is policy. The
* shutdown route is authenticated by the shell's Bearer token, not the cookie session (the
* shell holds no cookie), so its group is unauthenticated and checks the token itself; it
* answers 202 first, then triggers the graceful shutdown a beat later so the response is not
- * cut off by the closing listener. The update and tray routes are called by the page, so their
- * groups sit behind the cookie gate and are further restricted to the shell's own window.
+ * cut off by the closing listener. The update, tray and privacy-settings routes are called by
+ * the page, so their groups sit behind the cookie gate and are further restricted to the
+ * shell's own window.
*/
import { Hono } from "hono";
import type { Context, MiddlewareHandler } from "hono";
@@ -70,7 +72,7 @@ export function desktopRoutes(deps: DesktopRouteDeps): Hono {
}
/**
- * The shared gate for the two page-facing desktop surfaces: they exist only in desktop
+ * The shared gate for the page-facing desktop surfaces: they exist only in desktop
* mode, and only for the shell's own window (`sessionVia === "desktop"`, the same
* two-field rule as the change-password gate, inverted). A browser signed into the same
* desktop-mode server must not read the machine's updater state, restart its GUI app, or
@@ -169,6 +171,35 @@ export function desktopTrayRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {
return app;
}
+/**
+ * Opens System Settings at a Privacy & Security pane — Files and Folders, or Full Disk Access —
+ * for the Workspace picker's box about a folder macOS refused. The shell opens it (on macOS
+ * only) and sends nothing back, so the answer is an acknowledgement. Like the relays above, the
+ * member is optional on a layer older than the picker's box.
+ */
+export function desktopPrivacySettingsRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.post("/", async (c) => {
+ const desktop = shellSessionOf(
+ deps,
+ c,
+ "System Settings is opened from the desktop app's own window.",
+ );
+ const body = (await c.req.json().catch(() => null)) as { pane?: unknown } | null;
+ const pane = body?.pane;
+ if (pane !== "files" && pane !== "fullDisk") {
+ throw new HttpError(400, "invalid_privacy_pane", 'pane must be "files" or "fullDisk".');
+ }
+ if (!desktop.requestPrivacySettings?.(pane)) {
+ throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");
+ }
+ return c.body(null, 202);
+ });
+
+ return app;
+}
+
@Component({
contributes: {
"HttpModule.routes": [
@@ -213,3 +244,23 @@ export class DesktopTrayRoutes {
this.routes = desktopTrayRoutes({ desktop: this.desktop.current() });
}
}
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "DesktopPrivacySettingsRoutes.routes",
+ prefix: "/api/desktop/privacy-settings",
+ auth: "user",
+ order: 10,
+ },
+ ],
+ },
+})
+export class DesktopPrivacySettingsRoutes {
+ @Use() private readonly desktop!: Desktop;
+ @Bind("DesktopPrivacySettingsRoutes.routes") routes!: Hono<AppEnv>;
+ setup() {
+ this.routes = desktopPrivacySettingsRoutes({ desktop: this.desktop.current() });
+ }
+}
diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.ts
index 70c5d446..4e5efbc9 100644
--- a/packages/server/src/http/routes/dirs.ts
+++ b/packages/server/src/http/routes/dirs.ts
@@ -15,23 +15,29 @@
* (Desktop, Documents, Downloads) looks exactly like that, and an empty list sent people
* looking for files that were there all along.
*
+ * POST /api/projects/:p/dirs/access is the picker's way out of that refusal in the desktop
+ * app: see the route.
+ *
* `projectId` remains the authorization anchor: the caller must have access to that Project.
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { Hono } from "hono";
-import type { DirEntryInfo, DirListResponse } from "../../api/types.js";
+import type { DirAccessResponse, DirEntryInfo, DirListResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { HttpError } from "../errors.js";
import { requireValidId } from "../validate.js";
import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
import { directorySkillsRoutes } from "./directory-skills.js";
+import type { Desktop, DesktopApi } from "../../hmr/capabilities.js";
import type { Access } from "../../mechanisms/projects.js";
/** What this route group reaches — bound by its module (src/modules). */
export interface DirsRouteDeps {
access: Access;
+ /** The desktop shell's service; null when this server was not started by the desktop shell. */
+ desktop: Pick<DesktopApi, "requestFolderAccess"> | null;
}
export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {
@@ -69,6 +75,46 @@ export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {
} satisfies DirListResponse);
});
+ /**
+ * The picker's "Allow access" for a folder macOS refused: the desktop shell's main process
+ * reads it once in the app's own name, which is what makes macOS ask the user — a read from
+ * this server, the shell's child, has been seen to fail silently instead. Once the app is
+ * allowed, this server reads the folder too. Only this server's own shell can be asked, so
+ * the route has no machine form, and only the desktop app's own window may call it (403
+ * `desktop_shell_only`, like the reveal route): a browser tab on the same server has no shell
+ * of its own to ask on the user's behalf. Without a shell there is nothing to ask (503
+ * `shell_unreachable`); a shell that has not answered within FOLDER_ACCESS_TIMEOUT_MS is a
+ * 504 `timeout`. The member is optional: a layer older than the picker's box has none.
+ */
+ app.post("/access", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
+ if (c.var.sessionVia !== "desktop") {
+ throw new HttpError(
+ 403,
+ "desktop_shell_only",
+ "Asking macOS for a folder is available from the desktop app's own window.",
+ );
+ }
+ const body = (await c.req.json().catch(() => null)) as { path?: unknown } | null;
+ const target = typeof body?.path === "string" ? body.path.trim() : "";
+ if (!path.isAbsolute(target)) {
+ throw new HttpError(400, "dir_not_absolute", "Directory must be an absolute path.");
+ }
+ const asked = deps.desktop?.requestFolderAccess?.(target) ?? null;
+ if (asked === null) {
+ throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");
+ }
+ const result = await asked;
+ if (result === null) {
+ throw new HttpError(504, "timeout", "The desktop shell did not answer in time.");
+ }
+ return c.json({
+ granted: result.granted,
+ packaged: result.packaged,
+ } satisfies DirAccessResponse);
+ });
+
return app;
}
@@ -189,10 +235,11 @@ async function driveRoots(): Promise<string[]> {
})
export class ProjectsRoutes {
@Use() private readonly access!: Access;
+ @Use() private readonly desktop!: Desktop;
@Bind("projects.dirs") dirsRoutes!: Hono<AppEnv>;
@Bind("projects.dir-skills") dirSkillsRoutes!: Hono<AppEnv>;
setup() {
- this.dirsRoutes = dirsRoutes({ access: this.access });
+ this.dirsRoutes = dirsRoutes({ access: this.access, desktop: this.desktop.current() });
this.dirSkillsRoutes = directorySkillsRoutes({ access: this.access });
}
}
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
index 8fae12bd..30219ca3 100644
--- a/packages/server/src/platform.ts
+++ b/packages/server/src/platform.ts
@@ -122,7 +122,12 @@ import { ProjectAdminRoutes } from "./http/routes/projects.js";
import { AdminRoutes } from "./http/routes/admin.js";
import { MeRoutes } from "./http/routes/me.js";
import { AuthRoutes } from "./http/routes/auth.js";
-import { DesktopRoutes, DesktopTrayRoutes, DesktopUpdateRoutes } from "./http/routes/desktop.js";
+import {
+ DesktopPrivacySettingsRoutes,
+ DesktopRoutes,
+ DesktopTrayRoutes,
+ DesktopUpdateRoutes,
+} from "./http/routes/desktop.js";
import { InstallRoutes } from "./http/routes/install.js";
import { HmrRoutes } from "./hmr/routes.js";
import { EventsRoutes } from "./http/routes/events.js";
@@ -435,6 +440,7 @@ export class CompanyModule {}
DesktopRoutes,
DesktopUpdateRoutes,
DesktopTrayRoutes,
+ DesktopPrivacySettingsRoutes,
PluginRoutes,
PluginRegistryRoutes,
InstalledPluginRoutes,
diff --git a/packages/server/src/services/desktop-service.ts b/packages/server/src/services/desktop-service.ts
index d5d3079e..d199b17c 100644
--- a/packages/server/src/services/desktop-service.ts
+++ b/packages/server/src/services/desktop-service.ts
@@ -19,9 +19,15 @@
* GET /api/desktop/update or /api/desktop/tray and writes back a command that is
* forwarded to the shell. The window itself stays a plain browser — every capability
* flows through this HTTP surface, never a renderer IPC bridge.
+ *
+ * The same channel carries the Workspace picker's macOS folder access: a request the shell
+ * answers (its main process reads a folder in the app's own name), and a command that opens
+ * System Settings at a privacy pane.
*/
import { createHash, timingSafeEqual } from "node:crypto";
import type {
+ DesktopFolderAccessResult,
+ DesktopPrivacyPane,
DesktopTrayPatch,
DesktopTrayStatus,
DesktopUpdateStatus,
@@ -121,4 +127,38 @@ export class DesktopService {
this.trayCommandSender(patch);
return true;
}
+
+ // --- macOS folder-access relay ----------------------------------------------
+
+ private folderAccessSender: FolderAccessSender | null = null;
+ private privacySettingsSender: ((pane: DesktopPrivacyPane) => void) | null = null;
+
+ /** index.ts registers the message-port request; absent outside a shell-forked process. */
+ onFolderAccessRequest(sender: FolderAccessSender): void {
+ this.folderAccessSender = sender;
+ }
+
+ /**
+ * Invoked by the dirs access route: has the shell read `path` in the app's own name. Null
+ * when no shell port is wired (tests, plain runs); the promise resolves null when the shell
+ * does not answer in time.
+ */
+ requestFolderAccess(path: string): Promise<DesktopFolderAccessResult | null> | null {
+ return this.folderAccessSender?.(path) ?? null;
+ }
+
+ /** index.ts registers the message-port sender; absent outside a shell-forked process. */
+ onPrivacySettingsCommand(sender: (pane: DesktopPrivacyPane) => void): void {
+ this.privacySettingsSender = sender;
+ }
+
+ /** Invoked by the privacy-settings route; false when no shell port is wired (tests, plain runs). */
+ requestPrivacySettings(pane: DesktopPrivacyPane): boolean {
+ if (!this.privacySettingsSender) return false;
+ this.privacySettingsSender(pane);
+ return true;
+ }
}
+
+/** Asks the shell to read one folder; resolves with its answer, or null when none came in time. */
+export type FolderAccessSender = (path: string) => Promise<DesktopFolderAccessResult | null>;
diff --git a/packages/server/src/services/desktop-update-port.ts b/packages/server/src/services/desktop-update-port.ts
index 814e3469..f6b4a6ea 100644
--- a/packages/server/src/services/desktop-update-port.ts
+++ b/packages/server/src/services/desktop-update-port.ts
@@ -1,17 +1,24 @@
/**
- * Shell↔server message-port relay (desktop mode only): client updates, and the tray icon.
+ * Shell↔server message-port relay (desktop mode only): client updates, the tray icon, and the
+ * Workspace picker's macOS folder access.
*
* Under the desktop shell this server runs as an Electron utilityProcess, which injects
* `process.parentPort` — an EventEmitter-ish port to the shell. The shell pushes its
* updater snapshot and its tray state through it, and the routes forward the page's
- * check/download/install commands and its tray switch back. Under a plain
- * `penguin server|web` run the port does not exist and this module wires nothing; those
- * routes then answer 503 `shell_unreachable`.
+ * check/download/install commands and its tray switch back. Folder access is the one
+ * request that is answered: the shell reads the folder and replies under the request's id.
+ * Under a plain `penguin server|web` run the port does not exist and this module wires
+ * nothing; those routes then answer 503 `shell_unreachable`.
*
- * Wire shapes live in api/types.ts (the two updater messages and the two tray ones) so
- * the shell imports the same contract.
+ * Wire shapes live in api/types.ts (the updater, tray and folder-access messages) so the
+ * shell imports the same contract.
*/
+import { randomUUID } from "node:crypto";
import type {
+ DesktopFolderAccessMessage,
+ DesktopFolderAccessResult,
+ DesktopFolderAccessResultMessage,
+ DesktopOpenPrivacySettingsMessage,
DesktopTrayCommandMessage,
DesktopTrayStatus,
DesktopTrayStatusMessage,
@@ -21,6 +28,12 @@ import type {
} from "../api/types.js";
import type { DesktopService } from "./desktop-service.js";
+/**
+ * How long the shell may take to answer a folder-access request. Generous: its read holds
+ * until the user has answered the macOS prompt, and nothing hurries them.
+ */
+export const FOLDER_ACCESS_TIMEOUT_MS = 120_000;
+
/** The slice of Electron's ParentPort this relay uses (structural: the server must not depend on Electron types). */
export interface ShellPort {
on(event: "message", listener: (e: { data: unknown }) => void): void;
@@ -73,12 +86,32 @@ export function parseTrayStatusMessage(data: unknown): DesktopTrayStatus | null
return { showTrayIcon: status.showTrayIcon, locale };
}
+/** Validates one shell reply to a folder-access request; null when the frame is not one. */
+export function parseFolderAccessResultMessage(
+ data: unknown,
+): DesktopFolderAccessResultMessage | null {
+ if (typeof data !== "object" || data === null) return null;
+ const msg = data as Partial<DesktopFolderAccessResultMessage>;
+ if (msg.type !== "desktop-folder-access-result" || typeof msg.id !== "string") return null;
+ if (typeof msg.granted !== "boolean" || typeof msg.packaged !== "boolean") return null;
+ return {
+ type: "desktop-folder-access-result",
+ id: msg.id,
+ granted: msg.granted,
+ ...(typeof msg.code === "string" ? { code: msg.code } : {}),
+ packaged: msg.packaged,
+ };
+}
+
/**
* Connects the port to the service: stores validated status pushes, registers the command
- * senders. A frame that fails to apply is logged and dropped: an exception escaping a port
- * listener is uncaught, and an uncaught exception ends the server (index.ts).
+ * senders, and pairs each folder-access reply with the request it answers. A frame that fails
+ * to apply is logged and dropped: an exception escaping a port listener is uncaught, and an
+ * uncaught exception ends the server (index.ts).
*/
export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): void {
+ /** Folder-access requests still waiting for the shell, by id. */
+ const awaiting = new Map<string, (reply: DesktopFolderAccessResultMessage) => void>();
port.on("message", (e) => {
try {
const status = parseUpdaterStatusMessage(e.data);
@@ -87,7 +120,13 @@ export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): v
return;
}
const tray = parseTrayStatusMessage(e.data);
- if (tray !== null) desktop.setTrayStatus(tray);
+ if (tray !== null) {
+ desktop.setTrayStatus(tray);
+ return;
+ }
+ // A reply nobody waits for any more (its request timed out) is dropped.
+ const access = parseFolderAccessResultMessage(e.data);
+ if (access !== null) awaiting.get(access.id)?.(access);
} catch (err) {
console.error(`[server] dropped a frame from the desktop shell: ${String(err)}`);
}
@@ -104,4 +143,32 @@ export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): v
...patch,
} satisfies DesktopTrayCommandMessage);
});
+ desktop.onFolderAccessRequest(
+ (path) =>
+ new Promise<DesktopFolderAccessResult | null>((resolve) => {
+ const id = randomUUID();
+ // Posted before anything is registered: a port that refuses the frame rejects this
+ // promise and leaves nothing waiting behind it.
+ port.postMessage({
+ type: "desktop-folder-access",
+ id,
+ path,
+ } satisfies DesktopFolderAccessMessage);
+ const timer = setTimeout(() => {
+ awaiting.delete(id);
+ resolve(null);
+ }, FOLDER_ACCESS_TIMEOUT_MS);
+ awaiting.set(id, ({ granted, code, packaged }) => {
+ clearTimeout(timer);
+ awaiting.delete(id);
+ resolve({ granted, ...(code !== undefined ? { code } : {}), packaged });
+ });
+ }),
+ );
+ desktop.onPrivacySettingsCommand((pane) => {
+ port.postMessage({
+ type: "desktop-open-privacy-settings",
+ pane,
+ } satisfies DesktopOpenPrivacySettingsMessage);
+ });
}
diff --git a/packages/server/test/dirs-access.test.ts b/packages/server/test/dirs-access.test.ts
new file mode 100644
index 00000000..23e9193b
--- /dev/null
+++ b/packages/server/test/dirs-access.test.ts
@@ -0,0 +1,432 @@
+/**
+ * The Workspace picker's macOS folder access, server side. POST /api/projects/:p/dirs/access
+ * relays a refused folder to the desktop shell, whose main process reads it in the app's own
+ * name, and answers what that read came to — 503 `shell_unreachable` when this server has no
+ * shell to ask. POST /api/desktop/privacy-settings has the shell open a Privacy & Security
+ * pane, under the same gate as the other page-facing desktop routes. The port glue pairs each
+ * shell reply with the request it answers, and a reply that comes after its request gave up
+ * is dropped.
+ *
+ * The route tests drive the real port glue against a fake shell on the far side of the port,
+ * so the frames themselves are exercised, not just the service's seam.
+ */
+import { describe, expect, it, vi } from "vitest";
+import type {
+ DesktopFolderAccessResult,
+ DesktopPrivacyPane,
+ DirAccessResponse,
+ ErrorBody,
+} from "../src/api/types.js";
+import { DesktopService } from "../src/services/desktop-service.js";
+import {
+ FOLDER_ACCESS_TIMEOUT_MS,
+ parseFolderAccessResultMessage,
+ wireShellUpdatePort,
+} from "../src/services/desktop-update-port.js";
+import type { ShellPort } from "../src/services/desktop-update-port.js";
+import {
+ apiClient,
+ createDesktopApp,
+ createTestApp,
+ desktopLoginCookie,
+ loginAdmin,
+} from "./helpers.js";
+
+const DOWNLOADS = "/Users/me/Downloads";
+const ACCESS = "/api/projects/default_project/dirs/access";
+const SETTINGS = "/api/desktop/privacy-settings";
+
+/**
+ * A shell on the far side of the port: every folder-access request is answered, a tick later,
+ * the way `answer` says; every frame the server posts is kept.
+ */
+function fakeShell(answer: (path: string) => DesktopFolderAccessResult) {
+ const posted: Record<string, unknown>[] = [];
+ let listener: ((e: { data: unknown }) => void) | undefined;
+ const port: ShellPort = {
+ on: (_event, l) => {
+ listener = l;
+ },
+ postMessage: (message) => {
+ const frame = message as Record<string, unknown>;
+ posted.push(frame);
+ if (frame.type !== "desktop-folder-access") return;
+ setTimeout(() =>
+ listener?.({
+ data: {
+ type: "desktop-folder-access-result",
+ id: frame.id,
+ ...answer(frame.path as string),
+ },
+ }),
+ );
+ },
+ };
+ return { port, posted };
+}
+
+const errorCode = async (res: Response): Promise<string> =>
+ ((await res.json()) as ErrorBody).error.code;
+
+describe("POST /api/projects/:projectId/dirs/access", () => {
+ it("has the shell read the folder and answers what the read came to", async () => {
+ const t = await createDesktopApp();
+ try {
+ const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ let granted = false;
+ const shell = fakeShell(() => ({
+ granted,
+ ...(granted ? {} : { code: "EPERM" }),
+ packaged: true,
+ }));
+ wireShellUpdatePort(t.deps.desktop!, shell.port);
+
+ const refused = await api.post(ACCESS, { path: DOWNLOADS });
+ expect(refused.status).toBe(200);
+ // The errno stays in the shell's log: the page acts on the two booleans alone.
+ expect((await refused.json()) as DirAccessResponse).toEqual({
+ granted: false,
+ packaged: true,
+ });
+ expect(shell.posted).toEqual([
+ { type: "desktop-folder-access", id: expect.any(String), path: DOWNLOADS },
+ ]);
+
+ granted = true;
+ const allowed = await api.post(ACCESS, { path: DOWNLOADS });
+ expect((await allowed.json()) as DirAccessResponse).toEqual({
+ granted: true,
+ packaged: true,
+ });
+ // Every request carries its own id, so a reply can only settle the one it answers.
+ expect(shell.posted[1]!.id).not.toBe(shell.posted[0]!.id);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("reports an unpackaged app, whose reads macOS charges to the terminal", async () => {
+ const t = await createDesktopApp();
+ try {
+ const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ wireShellUpdatePort(
+ t.deps.desktop!,
+ fakeShell(() => ({ granted: false, code: "EPERM", packaged: false })).port,
+ );
+ const res = await api.post(ACCESS, { path: DOWNLOADS });
+ expect((await res.json()) as DirAccessResponse).toEqual({ granted: false, packaged: false });
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("refuses a path that is not absolute before asking the shell", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const asked: string[] = [];
+ t.deps.desktop!.onFolderAccessRequest(async (path) => {
+ asked.push(path);
+ return { granted: true, packaged: true };
+ });
+ for (const body of ['{"path":"Downloads"}', '{"path":""}', '{"path":7}', "{}", "not json"]) {
+ const res = await t.app.request(ACCESS, {
+ method: "POST",
+ headers: { cookie, "content-type": "application/json" },
+ body,
+ });
+ expect(res.status, body).toBe(400);
+ expect(await errorCode(res), body).toBe("dir_not_absolute");
+ }
+ expect(asked).toEqual([]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("is refused to anything but the desktop app's own window", async () => {
+ // A plain server's password session: no window of the shell's at all.
+ const plain = await createTestApp();
+ try {
+ const admin = await loginAdmin(plain.app);
+ const res = await apiClient(plain.app, admin.cookie).post(ACCESS, { path: DOWNLOADS });
+ expect(res.status).toBe(403);
+ expect(await errorCode(res)).toBe("desktop_shell_only");
+ } finally {
+ await plain.cleanup();
+ }
+ // A browser tab signed in with the password on the desktop app's own server.
+ const t = await createDesktopApp();
+ try {
+ let asked = 0;
+ t.deps.desktop!.onFolderAccessRequest(async () => {
+ asked += 1;
+ return { granted: true, packaged: true };
+ });
+ const admin = await loginAdmin(t.app);
+ const res = await apiClient(t.app, admin.cookie).post(ACCESS, { path: DOWNLOADS });
+ expect(res.status).toBe(403);
+ expect(await errorCode(res)).toBe("desktop_shell_only");
+ expect(asked).toBe(0);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("answers 503 shell_unreachable with no shell to ask", async () => {
+ // Desktop mode, but no port wired.
+ const t = await createDesktopApp();
+ try {
+ const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ const res = await api.post(ACCESS, { path: DOWNLOADS });
+ expect(res.status).toBe(503);
+ expect(await errorCode(res)).toBe("shell_unreachable");
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("answers 504 timeout when the shell does not answer in time", async () => {
+ const t = await createDesktopApp();
+ try {
+ const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ t.deps.desktop!.onFolderAccessRequest(async () => null);
+ const res = await api.post(ACCESS, { path: DOWNLOADS });
+ expect(res.status).toBe(504);
+ expect(await errorCode(res)).toBe("timeout");
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("keeps the Project as the authorization anchor", async () => {
+ const t = await createDesktopApp();
+ try {
+ const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ const asked: string[] = [];
+ t.deps.desktop!.onFolderAccessRequest(async (path) => {
+ asked.push(path);
+ return { granted: true, packaged: true };
+ });
+ const res = await api.post("/api/projects/nobody_s_project/dirs/access", {
+ path: DOWNLOADS,
+ });
+ expect(res.status).toBe(404);
+ expect(await errorCode(res)).toBe("project_not_found");
+ expect(asked).toEqual([]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
+
+describe("POST /api/desktop/privacy-settings", () => {
+ it("relays the pane to the shell and answers 202", async () => {
+ const t = await createDesktopApp();
+ try {
+ const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ const shell = fakeShell(() => ({ granted: true, packaged: true }));
+ wireShellUpdatePort(t.deps.desktop!, shell.port);
+ for (const pane of ["files", "fullDisk"] satisfies DesktopPrivacyPane[]) {
+ const res = await api.post(SETTINGS, { pane });
+ expect(res.status, pane).toBe(202);
+ }
+ expect(shell.posted).toEqual([
+ { type: "desktop-open-privacy-settings", pane: "files" },
+ { type: "desktop-open-privacy-settings", pane: "fullDisk" },
+ ]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("refuses a pane it does not know", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const sent: DesktopPrivacyPane[] = [];
+ t.deps.desktop!.onPrivacySettingsCommand((pane) => sent.push(pane));
+ for (const body of ['{"pane":"camera"}', '{"pane":true}', "{}", "not json"]) {
+ const res = await t.app.request(SETTINGS, {
+ method: "POST",
+ headers: { cookie, "content-type": "application/json" },
+ body,
+ });
+ expect(res.status, body).toBe(400);
+ expect(await errorCode(res), body).toBe("invalid_privacy_pane");
+ }
+ expect(sent).toEqual([]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("answers only the shell's own window, like the other desktop routes", async () => {
+ const t = await createDesktopApp();
+ try {
+ const sent: DesktopPrivacyPane[] = [];
+ t.deps.desktop!.onPrivacySettingsCommand((pane) => sent.push(pane));
+ // A password session against the same server may be on another machine: System
+ // Settings springing open on this one means nothing there.
+ const admin = await loginAdmin(t.app);
+ const forbidden = await apiClient(t.app, admin.cookie).post(SETTINGS, { pane: "files" });
+ expect(forbidden.status).toBe(403);
+ expect(await errorCode(forbidden)).toBe("desktop_shell_only");
+ const anonymous = await t.app.request(SETTINGS, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: '{"pane":"files"}',
+ });
+ expect(anonymous.status).toBe(401);
+ expect(sent).toEqual([]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("answers 503 shell_unreachable while no port is wired, and does not exist outside desktop mode", async () => {
+ const t = await createDesktopApp();
+ try {
+ const api = apiClient(t.app, await desktopLoginCookie(t.app));
+ const res = await api.post(SETTINGS, { pane: "files" });
+ expect(res.status).toBe(503);
+ expect(await errorCode(res)).toBe("shell_unreachable");
+ } finally {
+ await t.cleanup();
+ }
+ const plain = await createTestApp();
+ try {
+ const admin = await loginAdmin(plain.app);
+ const res = await apiClient(plain.app, admin.cookie).post(SETTINGS, { pane: "files" });
+ expect(res.status).toBe(404);
+ } finally {
+ await plain.cleanup();
+ }
+ });
+});
+
+describe("the folder-access half of the shell port", () => {
+ it("parses only well-formed replies", () => {
+ expect(
+ parseFolderAccessResultMessage({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: false,
+ code: "EPERM",
+ packaged: true,
+ }),
+ ).toEqual({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: false,
+ code: "EPERM",
+ packaged: true,
+ });
+ // A code that is not a string is left out rather than failing the whole reply.
+ expect(
+ parseFolderAccessResultMessage({
+ type: "desktop-folder-access-result",
+ id: "a",
+ granted: true,
+ code: 1,
+ packaged: false,
+ }),
+ ).toEqual({ type: "desktop-folder-access-result", id: "a", granted: true, packaged: false });
+ for (const data of [
+ null,
+ {},
+ { type: "desktop-folder-access-result", granted: true, packaged: true },
+ { type: "desktop-folder-access-result", id: "a", packaged: true },
+ { type: "desktop-folder-access-result", id: "a", granted: "yes", packaged: true },
+ { type: "desktop-folder-access-result", id: "a", granted: true },
+ // The request's own shape, and the other frames on the same port, are not replies.
+ { type: "desktop-folder-access", id: "a", path: DOWNLOADS },
+ { type: "desktop-tray-status", status: { showTrayIcon: true, locale: "en" } },
+ ]) {
+ expect(parseFolderAccessResultMessage(data)).toBeNull();
+ }
+ });
+
+ it("settles a request only with the reply carrying its id", async () => {
+ const desktop = new DesktopService("t");
+ const posted: Record<string, unknown>[] = [];
+ let onMessage: ((e: { data: unknown }) => void) | undefined;
+ wireShellUpdatePort(desktop, {
+ on: (_event, listener) => {
+ onMessage = listener;
+ },
+ postMessage: (message) => posted.push(message as Record<string, unknown>),
+ });
+ const pending = desktop.requestFolderAccess(DOWNLOADS);
+ expect(pending).not.toBeNull();
+ const id = posted[0]!.id as string;
+ let settled = false;
+ void pending!.then(() => {
+ settled = true;
+ });
+ onMessage!({
+ data: {
+ type: "desktop-folder-access-result",
+ id: `${id}-other`,
+ granted: true,
+ packaged: true,
+ },
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ onMessage!({
+ data: {
+ type: "desktop-folder-access-result",
+ id,
+ granted: false,
+ code: "EPERM",
+ packaged: true,
+ },
+ });
+ await expect(pending).resolves.toEqual({ granted: false, code: "EPERM", packaged: true });
+ });
+
+ it("gives up after the timeout, and drops the reply that comes later", async () => {
+ vi.useFakeTimers();
+ try {
+ const desktop = new DesktopService("t");
+ const posted: Record<string, unknown>[] = [];
+ let onMessage: ((e: { data: unknown }) => void) | undefined;
+ wireShellUpdatePort(desktop, {
+ on: (_event, listener) => {
+ onMessage = listener;
+ },
+ postMessage: (message) => posted.push(message as Record<string, unknown>),
+ });
+ const pending = desktop.requestFolderAccess(DOWNLOADS)!;
+ vi.advanceTimersByTime(FOLDER_ACCESS_TIMEOUT_MS - 1);
+ let settled = false;
+ void pending.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ vi.advanceTimersByTime(1);
+ await expect(pending).resolves.toBeNull();
+ // Nobody waits for it any more: the late reply is dropped without a trace.
+ expect(() =>
+ onMessage!({
+ data: {
+ type: "desktop-folder-access-result",
+ id: posted[0]!.id,
+ granted: true,
+ packaged: true,
+ },
+ }),
+ ).not.toThrow();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("reports no shell before a port is wired", () => {
+ const desktop = new DesktopService("t");
+ expect(desktop.requestFolderAccess(DOWNLOADS)).toBeNull();
+ expect(desktop.requestPrivacySettings("files")).toBe(false);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index d239b2cb..b34394b3 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -36,7 +36,9 @@ import type {
CommandPolicyRuleDto,
DefaultModelResponse,
DefaultModelUpdateRequest,
+ DesktopPrivacyPane,
DesktopUpdateStatusResponse,
+ DirAccessResponse,
DirectorySkillsResponse,
DirListResponse,
EndpointModelListRequest,
@@ -715,6 +717,18 @@ export const listDirs = (projectId: string, path = "", machineId?: string | null
`/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/dirs?path=${encodeURIComponent(path)}`,
);
+/**
+ * Asks the desktop shell to read a folder macOS refused, in the app's own name — what makes
+ * macOS ask the user. Always this server: only the shell that started it can be asked. The
+ * answer waits on the user's reply to that prompt.
+ */
+export const requestDirAccess = (projectId: string, path: string) =>
+ apiFetch<DirAccessResponse>(`/api/projects/${encodeURIComponent(projectId)}/dirs/access`, {
+ method: "POST",
+ body: { path },
+ server: null,
+ });
+
/**
* Skills a directory carries under `.agents/skills` / `.claude/skills`: what picking it at Agent
* creation would offer to install. `path` must be absolute.
@@ -2012,6 +2026,14 @@ export const getDesktopTray = () => apiFetch<DesktopTrayStatusResponse>("/api/de
export const setDesktopTray = (patch: DesktopTrayPatch) =>
apiFetch<void>("/api/desktop/tray", { method: "PUT", body: patch });
+/** Has the desktop shell open System Settings at a Privacy & Security pane (macOS). */
+export const openPrivacySettings = (pane: DesktopPrivacyPane) =>
+ apiFetch<void>("/api/desktop/privacy-settings", {
+ method: "POST",
+ body: { pane },
+ server: null,
+ });
+
// ---- Workflows (an Agent's own extension packages, served as tabs beside the chat) ----
const workflowsBase = (projectId: string, agentId: string) =>
`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/workflows`;
diff --git a/packages/web/src/features/chat/workspace-finder-model.ts b/packages/web/src/features/chat/workspace-finder-model.ts
index 0e5856a8..7d57cf42 100644
--- a/packages/web/src/features/chat/workspace-finder-model.ts
+++ b/packages/web/src/features/chat/workspace-finder-model.ts
@@ -2,13 +2,18 @@
* The Workspace finder's decisions, kept apart from the modal so they are testable without a
* DOM: path breadcrumbs, back/forward history, what the list shows and in which order,
* type-to-select, the sidebar's places (Quick access, with the user's own additions and
- * removals), the context menu's items, and the keyboard map.
+ * removals), the context menu's items, the keyboard map, and what the box for a folder the
+ * server may not read offers.
*
* Paths come from whichever machine is being browsed, so nothing here asks the browser's own
* platform about a path — a Windows server's `C:\Users\me` and a Linux one's `/home/me` both
* have to split correctly in the same tab.
*/
-import type { DirEntryInfo, DirListResponse } from "@prismshadow/penguin-server/api";
+import type {
+ DesktopPrivacyPane,
+ DirEntryInfo,
+ DirListResponse,
+} from "@prismshadow/penguin-server/api";
import {
TEMP_WORKSPACE_GROUP_KEY,
isTempWorkspace,
@@ -462,3 +467,63 @@ export function isTypeSelectKey(e: FinderKey): boolean {
/** How long type-to-select keeps adding to what was typed before starting over. */
export const TYPE_SELECT_RESET_MS = 900;
+
+/**
+ * Where the "Allow access" exchange for a refused folder stands: not asked yet, waiting on the
+ * desktop shell (its read holds until the user answers the macOS prompt), or asked — and the
+ * folder still refused, whether it was the shell's own read or the listing after it. `packaged`
+ * is the shell's word on whose permission it is: the app's, or for a development instance
+ * started from a terminal, that terminal's.
+ */
+export type AccessAsk =
+ { phase: "idle" } | { phase: "asking" } | { phase: "asked"; packaged: boolean };
+
+/** What the box for a refused folder says (a key of the finder's strings), and what it offers. */
+export interface DeniedBox {
+ text: "denied" | "deniedMacServer" | "deniedMacAsk" | "deniedMacRefused" | "deniedMacRefusedDev";
+ /** "Allow access": not offered, ready, or disabled while the shell waits on the user. */
+ allow: "none" | "ready" | "waiting";
+ /** The Privacy & Security pane "Open System Settings" goes to; null when it is not offered. */
+ settings: DesktopPrivacyPane | null;
+ retry: boolean;
+}
+
+/**
+ * The box for a folder the server may not read. Only a Mac has anything to ask for. There, a
+ * page in the desktop shell that is browsing its own server has the shell read the folder in
+ * the app's own name — what makes macOS ask — and, if the folder is still refused, offers
+ * System Settings: Full Disk Access for a packaged app, where it can be added by hand when
+ * macOS never listed it under Files and Folders, and Files and Folders for a development
+ * instance, whose permission is its terminal's. A browser tab has no shell to ask, and a
+ * machine's listing comes from another computer, so both can only say which process has to be
+ * allowed. Retry is offered wherever the user may have changed something outside the app, and
+ * never before the app has asked: it would only repeat the refusal.
+ */
+export function deniedBox(input: {
+ /** The browsed machine's platform, from its listing. */
+ platform: string | undefined;
+ /** The page is drawn by the desktop shell, and the shell answers this server. */
+ desktopShell: boolean;
+ /** The machine being browsed (null: this server). */
+ machine: string | null;
+ ask: AccessAsk;
+}): DeniedBox {
+ if (input.platform !== "darwin") {
+ return { text: "denied", allow: "none", settings: null, retry: true };
+ }
+ if (!input.desktopShell || input.machine !== null) {
+ return { text: "deniedMacServer", allow: "none", settings: null, retry: true };
+ }
+ const { ask } = input;
+ if (ask.phase === "asked") {
+ return ask.packaged
+ ? { text: "deniedMacRefused", allow: "none", settings: "fullDisk", retry: true }
+ : { text: "deniedMacRefusedDev", allow: "none", settings: "files", retry: true };
+ }
+ return {
+ text: "deniedMacAsk",
+ allow: ask.phase === "asking" ? "waiting" : "ready",
+ settings: null,
+ retry: false,
+ };
+}
diff --git a/packages/web/src/features/chat/workspace-finder.tsx b/packages/web/src/features/chat/workspace-finder.tsx
index e0833c67..5a020023 100644
--- a/packages/web/src/features/chat/workspace-finder.tsx
+++ b/packages/web/src/features/chat/workspace-finder.tsx
@@ -23,12 +23,13 @@ import type {
PointerEvent as ReactPointerEvent,
ReactNode,
} from "react";
-import type { DirListResponse } from "@prismshadow/penguin-server/api";
+import type { DesktopPrivacyPane, DirListResponse } from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { isContextMenuKey, isLongPressPointer } from "../../lib/context-menu";
+import { isElectronRenderer } from "../../lib/desktop-renderer";
import { formatDateTime } from "../../lib/format";
import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
import { STAT_ICONS } from "../../lib/stat-icons";
@@ -66,6 +67,7 @@ import {
canGoBack,
canGoForward,
defaultPlaces,
+ deniedBox,
drivePlaces,
finderKeyAction,
finderMenuItems,
@@ -87,6 +89,7 @@ import {
visibleEntries,
} from "./workspace-finder-model";
import type {
+ AccessAsk,
FinderAction,
FinderMenuItem,
FinderMenuTarget,
@@ -224,6 +227,19 @@ export function WorkspaceFinder({
const menu = useRowContextMenu();
const [menuTarget, setMenuTarget] = useState<FinderMenuTarget | null>(null);
+ /** Drawn by the desktop shell, which can ask macOS for a refused folder in the app's own name. */
+ const inShell = useMemo(
+ () => typeof navigator !== "undefined" && isElectronRenderer(navigator.userAgent),
+ [],
+ );
+ /**
+ * The "Allow access" exchange and the folder it is about: the shell answers only once the user
+ * has answered macOS, and the finder may stand somewhere else by then.
+ */
+ const [access, setAccess] = useState<{ path: string; ask: AccessAsk } | null>(null);
+ /** This server has no shell to ask: a desktop window attached to a server started elsewhere. */
+ const [shellUnreachable, setShellUnreachable] = useState(false);
+
/**
* Monotonic id of the newest listing request. Only the newest may publish: navigations race
* (a double-click, then Back before it lands), and a slow older answer would otherwise
@@ -428,6 +444,43 @@ export function WorkspaceFinder({
if (path !== "") load(path, { record: false, select: selected });
};
+ /**
+ * "Allow access": the shell reads the refused folder in the app's own name, which is what
+ * makes macOS ask. Granted, the folder is read again — unless the finder has moved on while
+ * macOS waited for the user. A server with no shell to ask turns the box into the
+ * explanation a browser tab gets.
+ */
+ const askAccess = () => {
+ const target = view.path;
+ const seq = loadSeq.current;
+ /** Records the answer, unless the exchange on record is already another folder's. */
+ const settle = (ask: AccessAsk | null) =>
+ setAccess((cur) => {
+ if (cur?.path !== target) return cur;
+ return ask === null ? null : { path: target, ask };
+ });
+ setAccess({ path: target, ask: { phase: "asking" } });
+ api
+ .requestDirAccess(projectId, target)
+ .then((res) => {
+ settle({ phase: "asked", packaged: res.packaged });
+ if (res.granted && loadSeq.current === seq) load(target, { record: false });
+ })
+ .catch((err: unknown) => {
+ settle(null);
+ if (
+ err instanceof ApiError &&
+ (err.code === "shell_unreachable" || err.code === "desktop_shell_only")
+ )
+ setShellUnreachable(true);
+ else toastError(apiErrorText(err));
+ });
+ };
+
+ const openSystemSettings = (pane: DesktopPrivacyPane) => {
+ void api.openPrivacySettings(pane).catch((err: unknown) => toastError(apiErrorText(err)));
+ };
+
/** The address bar becomes a path field holding the folder on screen, ready to be typed over. */
const editAddress = () => {
setAddressDraft(view.listing?.path ?? view.path);
@@ -1105,28 +1158,53 @@ export function WorkspaceFinder({
let body: ReactNode;
if (view.error !== null) {
+ // A refused folder says whose permission is missing and offers what can get it (see
+ // deniedBox); any other failure names itself and offers Retry.
+ const denied = permissionDenied
+ ? deniedBox({
+ platform,
+ desktopShell: inShell && !shellUnreachable,
+ machine,
+ ask: access?.path === view.path ? access.ask : { phase: "idle" },
+ })
+ : null;
+ const settingsPane = denied?.settings ?? null;
body = (
<div className="p-4">
<div
- className={`rounded-md border px-3 py-2.5 text-sm ${toneStrip[permissionDenied ? "attention" : "danger"]}`}
+ className={`rounded-md border px-3 py-2.5 text-sm ${toneStrip[denied !== null ? "attention" : "danger"]}`}
>
- <p className="font-medium">{permissionDenied ? f.deniedTitle : f.loadFailed}</p>
+ <p className="font-medium">{denied !== null ? f.deniedTitle : f.loadFailed}</p>
<p className="mt-1 text-xs leading-5">
- {permissionDenied
- ? platform === "darwin"
- ? f.deniedMac
- : f.denied
- : apiErrorText(view.error)}
+ {denied !== null ? f[denied.text] : apiErrorText(view.error)}
</p>
<p className="mt-1 break-all font-mono text-xs opacity-80">{view.path}</p>
- <Button
- size="sm"
- className="mt-2"
- disabled={loading}
- onClick={() => load(view.path, { record: false })}
- >
- {S.common.retry}
- </Button>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {denied !== null && denied.allow !== "none" && (
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={denied.allow === "waiting" || loading}
+ onClick={askAccess}
+ >
+ {denied.allow === "waiting" ? f.allowAccessWaiting : f.allowAccess}
+ </Button>
+ )}
+ {settingsPane !== null && (
+ <Button size="sm" variant="primary" onClick={() => openSystemSettings(settingsPane)}>
+ {f.openSystemSettings}
+ </Button>
+ )}
+ {(denied === null || denied.retry) && (
+ <Button
+ size="sm"
+ disabled={loading}
+ onClick={() => load(view.path, { record: false })}
+ >
+ {S.common.retry}
+ </Button>
+ )}
+ </div>
</div>
</div>
);
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 6f12050b..5e88219d 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2283,10 +2283,28 @@ export const en: Strings = {
empty: "This folder is empty",
noMatch: (q: string): string => `Nothing here has "${q}" in its name`,
deniedTitle: "Can't read this folder",
- /** The server runs on macOS and privacy protection refused the folder. */
- deniedMac:
- "macOS is blocking access to this folder. Allow it in System Settings → Privacy & Security → Files and Folders, then retry.",
denied: "The account running the server is not allowed to read this folder.",
+ /**
+ * macOS privacy protection refused the folder and this page cannot ask for it (a browser
+ * tab, or another machine's listing): the process that reads it has to be allowed.
+ */
+ deniedMacServer:
+ "macOS is blocking access to this folder. The process running the server has to be allowed: a server started from a terminal belongs to that terminal, so allow the terminal in System Settings → Privacy & Security → Files and Folders (or give it Full Disk Access), then retry.",
+ /** The desktop app can ask: before it has (see allowAccess). */
+ deniedMacAsk:
+ "macOS is blocking access to this folder. Use “Allow access” to ask macOS for it, and allow it when macOS asks.",
+ /** Asked, and the folder is still refused: a packaged app. */
+ deniedMacRefused:
+ "macOS did not allow it. If PenguinHarness is not listed under Files and Folders, add it under Full Disk Access with +, then retry.",
+ /** Asked, and the folder is still refused: a development instance, whose reads macOS charges to its terminal. */
+ deniedMacRefusedDev:
+ "This is an unpackaged development instance: macOS counts its file access against the terminal that started it. Allow that terminal under Files and Folders (or give it Full Disk Access), then retry.",
+ /** Has the desktop app read the folder in its own name, which is what makes macOS ask. */
+ allowAccess: "Allow access",
+ /** The same button while the app's read waits for the user to answer macOS. */
+ allowAccessWaiting: "Waiting for macOS…",
+ /** Opens System Settings at the Privacy & Security pane the box names. */
+ openSystemSettings: "Open System Settings",
loadFailed: "Can't open this folder",
},
/** Sidebar conversation-list grouping toggle (workspace is the default) + workspace groups. */
@@ -4778,6 +4796,8 @@ Scenarios:
browser_unavailable:
"The built-in browser is unavailable: it needs the PenguinHarness desktop app to be open.",
source_not_found: "That browser profile was not found.",
+ shell_unreachable: "The desktop app could not be reached.",
+ timeout: "That took too long. Try again.",
},
},
};
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 9c046254..040100a4 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2319,10 +2319,28 @@ export const zh = {
empty: "此文件夹为空",
noMatch: (q: string): string => `没有名称包含「${q}」的项目`,
deniedTitle: "无法读取此文件夹",
- /** The server runs on macOS and privacy protection refused the folder. */
- deniedMac:
- "macOS 阻止了对此文件夹的访问。请在「系统设置 → 隐私与安全性 → 文件与文件夹」中允许访问后重试。",
denied: "运行服务的账户没有读取此文件夹的权限。",
+ /**
+ * macOS privacy protection refused the folder and this page cannot ask for it (a browser
+ * tab, or another machine's listing): the process that reads it has to be allowed.
+ */
+ deniedMacServer:
+ "macOS 阻止了对此文件夹的访问。运行服务的进程需要被放行:从终端启动的服务归该终端所有,请在「系统设置 → 隐私与安全性 → 文件与文件夹」里放行该终端(或给它完全磁盘访问权限)后重试。",
+ /** The desktop app can ask: before it has (see allowAccess). */
+ deniedMacAsk:
+ "macOS 阻止了对此文件夹的访问。点「允许访问」向 macOS 申请,macOS 询问时选择允许。",
+ /** Asked, and the folder is still refused: a packaged app. */
+ deniedMacRefused:
+ "系统没有放行。若「文件与文件夹」里没有 PenguinHarness,请在「完全磁盘访问权限」里用 + 添加它,然后再试。",
+ /** Asked, and the folder is still refused: a development instance, whose reads macOS charges to its terminal. */
+ deniedMacRefusedDev:
+ "这是未打包的开发实例:macOS 把它的文件访问算在启动它的终端名下。请在「文件与文件夹」里放行该终端(或给它完全磁盘访问权限),再试。",
+ /** Has the desktop app read the folder in its own name, which is what makes macOS ask. */
+ allowAccess: "允许访问",
+ /** The same button while the app's read waits for the user to answer macOS. */
+ allowAccessWaiting: "等待 macOS 询问…",
+ /** Opens System Settings at the Privacy & Security pane the box names. */
+ openSystemSettings: "打开系统设置",
loadFailed: "无法打开此文件夹",
},
/** Grouping toggle of the sidebar conversation list (workspace grouping is the default) and the workspace groups. */
@@ -4772,6 +4790,8 @@ Benchmark:
handbook_index_required: "手册索引(README.md)不能删除。",
browser_unavailable: "内置浏览器不可用:它需要 PenguinHarness 桌面应用处于打开状态。",
source_not_found: "找不到这个浏览器配置文件。",
+ shell_unreachable: "无法联系桌面应用。",
+ timeout: "操作超时,请重试。",
},
},
};
diff --git a/packages/web/test/api-error-text.test.ts b/packages/web/test/api-error-text.test.ts
index 197b80e7..7c0f556e 100644
--- a/packages/web/test/api-error-text.test.ts
+++ b/packages/web/test/api-error-text.test.ts
@@ -53,6 +53,9 @@ describe("apiErrorText", () => {
"memory_scope_not_found",
"trace_not_found",
"platform_rate_limited",
+ // The Workspace picker's "Allow access" in the desktop app: no shell, or no answer.
+ "shell_unreachable",
+ "timeout",
"internal",
];
for (const code of reachable) {
diff --git a/packages/web/test/workspace-finder.test.ts b/packages/web/test/workspace-finder.test.ts
index 1587ee3c..74c9386f 100644
--- a/packages/web/test/workspace-finder.test.ts
+++ b/packages/web/test/workspace-finder.test.ts
@@ -2,11 +2,11 @@
* The Workspace finder (src/features/chat/workspace-finder*.tsx): the modal every Workspace
* picker opens. Its decisions live in workspace-finder-model.ts and are exercised directly —
* breadcrumbs for both path families, back/forward history, type-to-select, the keyboard map,
- * Quick access per platform with the user's own edits, the context menu's rows, and Recent.
- * The suite has no DOM, so the few JSX facts that fail silently are pinned against the source:
- * the finder is a Modal (no second overlay system), a permission refusal renders its own copy
- * instead of an empty folder, the address bar is the one place a path is typed, and a folder
- * row carries its own way in.
+ * Quick access per platform with the user's own edits, the context menu's rows, Recent, and
+ * what the box for a refused folder offers. The suite has no DOM, so the few JSX facts that
+ * fail silently are pinned against the source: the finder is a Modal (no second overlay
+ * system), a permission refusal renders its own box instead of an empty folder, the address
+ * bar is the one place a path is typed, and a folder row carries its own way in.
*/
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
@@ -19,6 +19,7 @@ import {
canGoBack,
canGoForward,
defaultPlaces,
+ deniedBox,
drivePlaces,
finderKeyAction,
finderMenuItems,
@@ -37,7 +38,11 @@ import {
typeSelectIndex,
visibleEntries,
} from "../src/features/chat/workspace-finder-model";
-import type { QuickAccessStorage } from "../src/features/chat/workspace-finder-model";
+import type {
+ AccessAsk,
+ DeniedBox,
+ QuickAccessStorage,
+} from "../src/features/chat/workspace-finder-model";
const dir = (name: string, kind: "dir" | "file" = "dir"): DirEntryInfo => ({
name,
@@ -315,6 +320,71 @@ describe("recent and go to folder", () => {
});
});
+describe("a folder the server may not read", () => {
+ const idle: AccessAsk = { phase: "idle" };
+ const asking: AccessAsk = { phase: "asking" };
+ const refusedApp: AccessAsk = { phase: "asked", packaged: true };
+ const refusedDev: AccessAsk = { phase: "asked", packaged: false };
+ const plain: DeniedBox = { text: "denied", allow: "none", settings: null, retry: true };
+ const server: DeniedBox = { text: "deniedMacServer", allow: "none", settings: null, retry: true };
+
+ it("offers the desktop app's own request only on a Mac, in the shell, browsing its own server", () => {
+ const table: Array<[string, string | undefined, boolean, string | null, AccessAsk, DeniedBox]> =
+ [
+ // Off macOS nothing asks for a folder: the account simply lacks the permission.
+ ["a Linux server, in the shell", "linux", true, null, idle, plain],
+ ["a Windows server, after an ask", "win32", true, null, refusedApp, plain],
+ ["no listing yet to name the platform", undefined, true, null, idle, plain],
+ // A browser tab has no shell to ask; a machine's listing comes from another computer.
+ ["a browser tab", "darwin", false, null, idle, server],
+ ["a browser tab, whatever is on record", "darwin", false, null, refusedApp, server],
+ ["a Mac machine, from the shell", "darwin", true, "m1", idle, server],
+ [
+ "the shell, before asking: Allow access and nothing else",
+ "darwin",
+ true,
+ null,
+ idle,
+ { text: "deniedMacAsk", allow: "ready", settings: null, retry: false },
+ ],
+ [
+ "the shell, while macOS waits for the user",
+ "darwin",
+ true,
+ null,
+ asking,
+ { text: "deniedMacAsk", allow: "waiting", settings: null, retry: false },
+ ],
+ [
+ "the shell, still refused, packaged: Full Disk Access",
+ "darwin",
+ true,
+ null,
+ refusedApp,
+ { text: "deniedMacRefused", allow: "none", settings: "fullDisk", retry: true },
+ ],
+ [
+ "the shell, still refused, a development instance: its terminal",
+ "darwin",
+ true,
+ null,
+ refusedDev,
+ { text: "deniedMacRefusedDev", allow: "none", settings: "files", retry: true },
+ ],
+ ];
+ for (const [label, platform, desktopShell, machine, ask, expected] of table) {
+ expect(deniedBox({ platform, desktopShell, machine, ask }), label).toEqual(expected);
+ }
+ });
+
+ it("never offers Retry alone where there is something better to do", () => {
+ for (const ask of [idle, asking, refusedApp, refusedDev]) {
+ const box = deniedBox({ platform: "darwin", desktopShell: true, machine: null, ask });
+ expect(box.allow !== "none" || box.settings !== null, ask.phase).toBe(true);
+ }
+ });
+});
+
describe("the modal (source contract)", () => {
const read = (rel: string) =>
readFileSync(fileURLToPath(new URL(`../src/${rel}`, import.meta.url)), "utf8");
@@ -328,9 +398,14 @@ describe("the modal (source contract)", () => {
expect(select).not.toContain("Dropdown");
});
- it("says a refused folder is refused, and names the macOS setting only on darwin", () => {
+ it("says a refused folder is refused, in the box deniedBox decides", () => {
expect(finder).toContain('code === "dir_permission_denied"');
- expect(finder).toMatch(/platform === "darwin"\s*\?\s*f\.deniedMac/);
+ expect(finder).toContain("f[denied.text]");
+ // The one renderer marker (lib/desktop-renderer.ts), not a check of the finder's own.
+ expect(finder).toContain("isElectronRenderer(navigator.userAgent)");
+ expect(finder).toMatch(/api\s*\.requestDirAccess\(projectId, target\)/);
+ // A server with no shell behind it gets the browser tab's explanation, not an error loop.
+ expect(finder).toContain('err.code === "shell_unreachable"');
});
it("types a path in the address bar itself — no separate Go to row or button", () => {