Skip to content

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

feat(web,server): the Workspace picker is a file-browser dialog with Explorer's habits (#858)

Yaowei Zhengad4c72a8b445
diff --git a/changelog/unreleased/2026-09-24-workspace-finder-modal.md b/changelog/unreleased/2026-09-24-workspace-finder-modal.md
new file mode 100644
index 00000000..0ddf264e
--- /dev/null
+++ b/changelog/unreleased/2026-09-24-workspace-finder-modal.md
@@ -0,0 +1,27 @@
+# Workspace picker opens a file-browser modal
+
+- **Date:** 2026-09-24
+- **Type:** feature
+- **Scope:** `web`, `server`, `docs`
+- **PR:** [#858](https://github.com/Prism-Shadow/penguin-harness/pull/858)
+
+[中文版](2026-09-24-workspace-finder-modal.zh.md)
+
+Every Workspace picker (the chat draft's pill, the form fields in Project settings, schedules, the company dialogs and the Agent create dialog, and the sidebar's new-workspace button) now opens a file-browser modal instead of a dropdown. It follows the habits of the platform file managers, Windows Explorer's in particular. The triggers look the same, and hosts still receive the chosen folder and its machine.
+
+## The finder
+
+- The sidebar starts with **Quick access**: home plus the standard folders of the browsed machine's own platform, where they exist there. That is Desktop, Downloads, Documents and Pictures on Windows; Desktop, Documents and Downloads on macOS; and Desktop, Documents, Downloads and Pictures on Linux. Windows lists its drives under **This PC**. **Recent** (Workspaces of this Project's newest Sessions) and, where the picker offers machines, **Machines** follow; choosing a machine browses from its home.
+- Quick access is editable. The **+** beside its heading adds the folder on screen, the context menu adds any folder, and a hover **×** or the context menu removes an entry, default ones included. The changes are kept per machine in this browser.
+- The toolbar holds back, forward, up and refresh as plain icons, then an **address bar** that looks like a text field. Clicking a path segment opens that folder; clicking elsewhere in the bar (or ⌘⇧G on macOS, Ctrl+Shift+G elsewhere) turns it into an editable path. Enter goes there and Esc puts the segments back; a path that does not exist still shows a toast and keeps the current folder. A filter box sits at the right.
+- The current folder is a list with folders first, name and modification time. Each folder row ends in an enter arrow, as well as opening on double-click or Enter. Files are shown dimmed and cannot be chosen, and hidden entries stay hidden.
+- **Right-click** (press-and-hold on touch, Shift+F10 on the keyboard) opens a menu. A folder gets Open, Choose this folder, Add to / Remove from Quick access, and Copy path; a file gets Copy path. The list's empty space acts on the folder on screen and adds Refresh. Sidebar entries have the same menu.
+- **Choose** takes the selected folder, or the current one when nothing is selected. The temporary-workspace link stays in the footer where the picker offered it.
+- Keyboard: ↑/↓ move, Enter or ⌘↓ opens, ⌘↑ goes to the parent, ⌘[ and ⌘] go back and forward, ⌘Enter chooses, typing a name prefix selects, Esc cancels (Ctrl in place of ⌘ off macOS). The finder opens with the current Workspace selected in its parent folder.
+- On a phone the modal fills the screen and the sidebar sits behind a toggle.
+
+## Unreadable folders
+
+- The directory API answers a folder the server may not read with `403 dir_permission_denied` instead of an empty listing, for this machine and for machines browsed over ssh.
+- The finder says so in the folder pane. When the server runs on macOS, it points to System Settings → Privacy & Security → Files and Folders.
+- Directory listings now include files, each entry's kind and modification time, the server's platform, and the drive roots on Windows.
diff --git a/changelog/unreleased/2026-09-24-workspace-finder-modal.zh.md b/changelog/unreleased/2026-09-24-workspace-finder-modal.zh.md
new file mode 100644
index 00000000..1ba25731
--- /dev/null
+++ b/changelog/unreleased/2026-09-24-workspace-finder-modal.zh.md
@@ -0,0 +1,27 @@
+# Workspace 选择器改为文件浏览弹窗
+
+- **Date:** 2026-09-24
+- **Type:** feature
+- **Scope:** `web`, `server`, `docs`
+- **PR:** [#858](https://github.com/Prism-Shadow/penguin-harness/pull/858)
+
+[English](2026-09-24-workspace-finder-modal.md)
+
+所有 Workspace 选择器(对话草稿页的胶囊按钮,Project 设置、定时任务、公司弹窗与新建智能体弹窗中的表单字段,以及侧边栏的新建工作区按钮)改为打开文件浏览弹窗,不再是下拉菜单。交互沿用各平台文件管理器的习惯,尤其是 Windows 资源管理器。触发按钮外观不变,宿主收到的仍是所选文件夹及其所在机器。
+
+## 弹窗
+
+- 侧边栏以**常用**开头:家目录,加上被浏览机器所在平台的标准文件夹中该机器上实际存在的那些——Windows 为桌面、下载、文档、图片,macOS 为桌面、文稿、下载,Linux 为桌面、文档、下载、图片;Windows 另在**此电脑**下列出各盘符。其后是**最近使用**(本 Project 最近 Session 所在的 Workspace),选择器提供机器选择时另列**机器**;选择机器即从该机器的家目录开始浏览。
+- 常用可以编辑:标题旁的 **+** 把当前文件夹加入常用,右键菜单可加入任意文件夹;悬停时出现的 **×** 或右键菜单可移除任一项,默认项也可移除。改动按机器保存在当前浏览器中。
+- 工具栏左侧是后退、前进、上一级与刷新四枚图标按钮,右侧是外观如输入框的**地址栏**:点击路径中的某一段即打开该文件夹,点击地址栏其余位置(或按 ⌘⇧G,其他平台为 Ctrl+Shift+G)即变为可编辑的路径,Enter 前往、Esc 恢复原状;路径不存在时仍弹出提示并停留在当前文件夹。最右侧为筛选框。
+- 当前文件夹以列表展示,文件夹在前,显示名称与修改时间;除双击或 Enter 外,每个文件夹行末尾另有一个进入箭头。文件以灰色显示、不可选择;隐藏条目仍不显示。
+- **右键**(触屏长按、键盘 Shift+F10)弹出菜单:文件夹为打开、选择此文件夹、添加到常用或从常用中移除、复制路径,文件只有复制路径;列表空白处针对当前文件夹,另有刷新。侧边栏条目同样支持右键菜单。
+- **选择**取选中的文件夹,未选中时取当前文件夹。原选择器提供的「改用临时工作区」链接保留在底栏。
+- 键盘:↑/↓ 移动,Enter 或 ⌘↓ 打开,⌘↑ 回到上级,⌘[ / ⌘] 后退 / 前进,⌘Enter 选择,输入名称前缀即选中,Esc 取消(非 macOS 平台以 Ctrl 代替 ⌘)。打开时在上级文件夹中选中当前 Workspace。
+- 手机上弹窗铺满全屏,侧边栏收进切换按钮。
+
+## 无法读取的文件夹
+
+- 目录 API 对服务无权读取的文件夹返回 `403 dir_permission_denied`,不再返回空列表;本机与通过 ssh 浏览的机器均如此。
+- 弹窗在文件夹区域说明无法读取;服务运行在 macOS 上时,提示前往「系统设置 → 隐私与安全性 → 文件与文件夹」允许访问。
+- 目录列表现在包含文件、每个条目的类型与修改时间、服务器的平台,Windows 上另含各盘符根目录。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 7144357e..233431a5 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -192,7 +192,7 @@ These routes are admin only on a personal server as much as on a multi-user one:
- `POST …/connect` holds an `ssh -T -D` session that never times out when idle, reconnects on its own if it drops, and is restored after a restart or a hot push. A Windows machine returns `409` `connect_unsupported`, because there is no shell to hold a session on.
- `POST …/disconnect` leaves the remote server running because it belongs to that machine, and other people may be using it.
- `POST …/restart` exists as its own action because a machine's files can be updated while it runs, and only a restart makes the process match them.
-- `GET …/dirs` addresses the machine by its own id, like the API proxy below. It returns `404` when the machine is not connected, because a read never opens ssh by itself.
+- `GET …/dirs` addresses the machine by its own id, like the API proxy below. It returns `404` when the machine is not connected, because a read never opens ssh by itself, and `403 dir_permission_denied` for a directory that machine refuses to list. Its entries are folders only, without `kind` or `mtime`.
### Machine fields
@@ -624,7 +624,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
- An explicit `workspace` must be an existing directory; it is never created. When omitted, the Workspace is a temporary one created automatically. The approval mode defaults to `allow-all`.
- `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}` with the subdirectories only, and an unreadable directory lists as empty so the user can still go back up.
+- `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.
- `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)
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 67b61a1d..422e3bb8 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -192,7 +192,7 @@ PUT 时,请求省略的字段保持原值,`null` 或 `""` 清除该字段,
- `POST …/connect` 维持一条 `ssh -T -D` 会话:空闲时永不超时,断开后自动重连,服务器重启或热推送后也会自动恢复。Windows 机器返回 `409` `connect_unsupported`,因为没有 shell 可以维持会话。
- `POST …/disconnect` 断开后远端服务器继续运行:它属于那台机器,其他人可能还在使用。
- `POST …/restart` 之所以是独立操作,是因为机器上的文件可以在运行期间更新,只有重启才能让进程与文件保持一致。
-- `GET …/dirs` 与下文的 API 代理一样,用机器自身的 id 寻址。机器未连接时返回 `404`,因为读取操作绝不会自行建立 ssh 连接。
+- `GET …/dirs` 与下文的 API 代理一样,用机器自身的 id 寻址。机器未连接时返回 `404`,因为读取操作绝不会自行建立 ssh 连接;那台机器拒绝列出的目录返回 `403 dir_permission_denied`。其条目只有文件夹,不带 `kind` 与 `mtime`。
### 机器字段
@@ -624,7 +624,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
- 显式传入的 `workspace` 必须是已存在的目录,永远不会自动创建。省略时自动创建一个临时 Workspace。审批模式默认 `allow-all`。
- `client` 是记录在数据行上的来源提示:CLI 发起的请求为 `"cli"`,默认 `"web"`。组织的工位会话和工单会话由服务器自己写入 `"org"`,客户端不能发送这个值。只有 `excludeOrg` 会把它当作过滤条件,而且只用来剔除这些行。
- `source` 只接受 `"benchmark"`,用于 Benchmark 评估或优化创建的 Session。`subagent` 和 `schedule` 由服务器自己设置。
-- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries}`,只包含子目录;读不了的目录按空列表返回,用户仍然可以向上返回。
+- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries, platform}`:每个条目带 `kind`(`dir` 或 `file`)与 `mtime`;在 Windows 上,请求主目录时另带 `roots`,即实际存在的各盘符根目录。服务无权读取的目录返回 `403 dir_permission_denied`,不再按空列表返回;在 macOS 上这通常是用户尚未授予的「文件与文件夹」权限。
- `GET /dir-skills` 只读取绝对路径下的 `<path>/.agents/skills` 和 `<path>/.claude/skills`,响应为 `{path, skills}`。没有 Skill 的目录返回空列表。参见 [Agent](#agent) 一节中的 `POST /agents`。
## 用量与 Trace(Agent 级别)
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index d5c30e52..ccf68e68 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1541,19 +1541,30 @@ export interface SessionsResponse {
workspaceLatest?: Record<string, string>;
}
-/** Server directory browsing (advanced new-Workspace picker): starts from the home directory by default, can navigate up to the root. */
+/** Server directory browsing (the Workspace picker): starts from the home directory by default, can navigate up to the root. */
export interface DirEntryInfo {
name: string;
- /** Absolute path of this subdirectory (can be submitted directly as a Workspace). */
+ /** Absolute path of this entry (a folder's can be submitted directly as a Workspace). */
path: string;
+ /**
+ * `file` for anything that is not a folder (a symlink counts as what it points to). Absent
+ * means a folder: a machine listed over ssh reports folders only.
+ */
+ kind?: "dir" | "file";
+ /** Last modification, epoch milliseconds; absent when unknown (listings over ssh, an entry stat could not reach). */
+ mtime?: number;
}
export interface DirListResponse {
/** Absolute path of the current directory (realpath). */
path: string;
/** Absolute path of the parent directory; null when already at the root. */
parent: string | null;
- /** Subdirectory list (sorted by name, files excluded). */
+ /** Entries sorted by name, hidden ones included (the picker drops them). */
entries: DirEntryInfo[];
+ /** The listed machine's `process.platform`; absent for a machine listed over ssh. */
+ platform?: string;
+ /** Windows only, on the home request (no `path`): the drive roots that exist. */
+ roots?: string[];
}
/** One Skill found in a picked directory: metadata plus which of the two layouts it came from. */
diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.ts
index 14722fd5..70c5d446 100644
--- a/packages/server/src/http/routes/dirs.ts
+++ b/packages/server/src/http/routes/dirs.ts
@@ -2,11 +2,18 @@
* Server directory browsing:
* GET /api/projects/:p/dirs?path=<absolute>.
*
- * Lets the user interactively pick a Workspace directory when creating a Session via
- * advanced mode. Defaults to the home directory of the account running the service, and
- * can be browsed all the way up to the root `/` — reachability is governed by OS file
- * permissions; the server no longer restricts browsing to within the Project directory
- * tree (same convention as workspace-guard). Lists subdirectories only, not files.
+ * Lets the user interactively pick a Workspace directory (the Workspace picker). Defaults to
+ * the home directory of the account running the service, and can be browsed all the way up
+ * to the root `/` — reachability is governed by OS file permissions; the server does not
+ * restrict browsing to within the Project directory tree (same convention as
+ * workspace-guard). Lists folders and files alike, each with its kind and modification time:
+ * the picker shows files dimmed so a folder reads as what it holds, and only folders can be
+ * picked.
+ *
+ * A folder the service account may not read is an error with its own code
+ * (`dir_permission_denied`), never an empty listing: on macOS an unanswered privacy prompt
+ * (Desktop, Documents, Downloads) looks exactly like that, and an empty list sent people
+ * looking for files that were there all along.
*
* `projectId` remains the authorization anchor: the caller must have access to that Project.
*/
@@ -14,9 +21,10 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { Hono } from "hono";
-import type { DirListResponse } from "../../api/types.js";
+import type { DirEntryInfo, DirListResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import { requireProjectDir, requireValidId } from "../validate.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 { Access } from "../../mechanisms/projects.js";
@@ -35,31 +43,131 @@ export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {
// Default starting point: home directory; an explicit path must be absolute (the frontend always sends back the realpath result).
const raw = c.req.query("path");
- const real = await requireProjectDir(raw && raw.trim() ? raw.trim() : os.homedir());
+ const requested = raw?.trim() ?? "";
+ const home = requested === "";
+ const real = await resolveBrowsableDir(home ? os.homedir() : requested);
- let dirents: import("node:fs").Dirent[] = [];
+ let dirents: import("node:fs").Dirent[];
try {
dirents = await fs.readdir(real, { withFileTypes: true });
- } catch {
- // No read permission: return an empty list instead of an error, so the user can still navigate back up.
- dirents = [];
+ } catch (err) {
+ throw dirReadError(err, real);
}
- const entries = dirents
- .filter((d) => d.isDirectory())
- .map((d) => ({ name: d.name, path: path.join(real, d.name) }))
- .sort((a, b) => a.name.localeCompare(b.name));
+ const entries = (await describeEntries(real, dirents)).sort((a, b) =>
+ a.name.localeCompare(b.name),
+ );
const parent = path.dirname(real);
return c.json({
path: real,
parent: parent === real ? null : parent,
entries,
+ platform: process.platform,
+ // Drive roots only answer the home request: that is the one the picker makes to build
+ // its sidebar, and probing 26 letters on every folder change would be waste.
+ ...(home && process.platform === "win32" ? { roots: await driveRoots() } : {}),
} satisfies DirListResponse);
});
return app;
}
+/**
+ * The HTTP answer for a filesystem call that failed on `dir`. A refusal (EACCES, or EPERM —
+ * what macOS privacy protection returns for a folder the user has not allowed) gets its own
+ * code so the picker can say so and name where to allow it; a missing path stays the 404 it
+ * always was.
+ */
+export function dirReadError(err: unknown, dir: string): HttpError {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code === "EACCES" || code === "EPERM") {
+ return new HttpError(
+ 403,
+ "dir_permission_denied",
+ `The server is not allowed to read this directory: ${dir}.`,
+ );
+ }
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP") {
+ return new HttpError(404, "dir_not_found", `Directory does not exist: ${dir}.`);
+ }
+ return new HttpError(500, "dir_read_failed", `Could not read this directory: ${dir}.`);
+}
+
+/**
+ * `requireProjectDir` with the refusal told apart from absence. That helper folds every
+ * failure into "does not exist or is inaccessible", which is the right answer where a path is
+ * being validated; here it is the question being asked.
+ */
+async function resolveBrowsableDir(target: string): Promise<string> {
+ if (!path.isAbsolute(target)) {
+ throw new HttpError(400, "dir_not_absolute", "Directory must be an absolute path.");
+ }
+ let real: string;
+ let isDir: boolean;
+ try {
+ real = await fs.realpath(target);
+ isDir = (await fs.stat(real)).isDirectory();
+ } catch (err) {
+ throw dirReadError(err, target);
+ }
+ if (!isDir) throw new HttpError(400, "not_a_dir", "Not a directory.");
+ return real;
+}
+
+/**
+ * Past this many entries only the dirent is read: a stat per entry is what gives a symlink
+ * its target's kind and every row its time, and a folder of tens of thousands of files would
+ * otherwise hold the listing for seconds. Beyond it, a symlink to a folder reads as a file.
+ */
+const STAT_LIMIT = 5000;
+
+/**
+ * Kind and modification time for each entry. stat follows symlinks, so a link to a folder is
+ * browsable like one; an entry stat cannot reach (a dangling link, a refused one) keeps the
+ * dirent's kind and no time rather than failing the whole folder.
+ */
+async function describeEntries(
+ dir: string,
+ dirents: import("node:fs").Dirent[],
+): Promise<DirEntryInfo[]> {
+ return Promise.all(
+ dirents.map(async (d, index): Promise<DirEntryInfo> => {
+ const full = path.join(dir, d.name);
+ let isDir = d.isDirectory();
+ let mtime: number | undefined;
+ if (index < STAT_LIMIT) {
+ try {
+ const st = await fs.stat(full);
+ isDir = st.isDirectory();
+ mtime = Math.round(st.mtimeMs);
+ } catch {
+ // Keep the dirent's answer.
+ }
+ }
+ return {
+ name: d.name,
+ path: full,
+ kind: isDir ? "dir" : "file",
+ ...(mtime !== undefined ? { mtime } : {}),
+ };
+ }),
+ );
+}
+
+/** The drive roots that exist on a Windows host (`C:\`, …), for the picker's sidebar. */
+async function driveRoots(): Promise<string[]> {
+ const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
+ const found = await Promise.all(
+ letters.map((letter) =>
+ fs.access(`${letter}:\\`).then(
+ () => `${letter}:\\`,
+ () => null,
+ ),
+ ),
+ );
+ return found.filter((root): root is string => root !== null);
+}
+
/** The Project-scoped directory routes; the repos and the access check are components of their own. */
@Component({
contributes: {
diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.ts
index 705eb353..8598bd4a 100644
--- a/packages/server/src/http/routes/machines.ts
+++ b/packages/server/src/http/routes/machines.ts
@@ -269,6 +269,13 @@ export function machinesRoutes(deps: MachinesRouteDeps): Hono<AppEnv> {
c.req.param("machineId"),
c.req.query("path") ?? "",
);
+ if (listing === "denied") {
+ throw new HttpError(
+ 403,
+ "dir_permission_denied",
+ "That machine does not allow reading this directory.",
+ );
+ }
if (listing === null) {
throw new HttpError(
404,
diff --git a/packages/server/src/machines/commands.ts b/packages/server/src/machines/commands.ts
index e20d4209..41cb3fa3 100644
--- a/packages/server/src/machines/commands.ts
+++ b/packages/server/src/machines/commands.ts
@@ -271,14 +271,21 @@ export const DIR_LIST_MARK = "---penguin-dirs---";
*
* Hidden directories are dropped, matching what the local browser shows, and everything is
* quoted for the remote shell by the caller's quoting rules.
+ *
+ * Exit 3 means there is no such directory; exit 4 means there is one and it may not be read
+ * (a folder without the search bit, or one macOS privacy protection holds back — `ls` fails
+ * there while `[ -r ]` still says yes, so the listing itself is what is tested). The listing
+ * is taken before anything is printed, so a refusal leaves no half-written answer behind.
*/
export function listDirsCommand(dir: string): string {
const target = dir === "" ? '"$HOME"' : shQuote(dir);
return [
- `cd ${target} 2>/dev/null || exit 3`,
+ `[ -d ${target} ] || exit 3`,
+ `cd ${target} 2>/dev/null || exit 4`,
+ `listing=$(ls -1p 2>/dev/null) || exit 4`,
`pwd -P`,
`echo ${DIR_LIST_MARK}`,
// -1 one per line, trailing slash marks directories, then keep only those.
- `ls -1p 2>/dev/null | grep '/$' | sed 's:/$::' | grep -v '^\\.' || true`,
+ `printf '%s\\n' "$listing" | grep '/$' | sed 's:/$::' | grep -v '^\\.' || true`,
].join("; ");
}
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
index fddf4fc5..e70ab2d7 100644
--- a/packages/server/src/machines/service.ts
+++ b/packages/server/src/machines/service.ts
@@ -464,20 +464,27 @@ export class MachinesService {
* The subdirectories of `dir` on a machine, over the HELD connection — so picking a
* workspace on it costs one command and no round trip to its API. Null when the machine is
* not connected: a read must not open ssh on its own, or a disconnected machine would be
- * reconnected by whoever browsed it.
+ * reconnected by whoever browsed it. `"denied"` when the directory is there and may not be
+ * read — told apart from absence so the picker can say which it is.
*/
async listDirs(
machineId: string,
dir: string,
- ): Promise<{
- path: string;
- parent: string | null;
- entries: { name: string; path: string }[];
- } | null> {
+ ): Promise<
+ | {
+ path: string;
+ parent: string | null;
+ entries: { name: string; path: string }[];
+ }
+ | "denied"
+ | null
+ > {
const row = this.#rowFor(machineId);
if (row === null || this.#liveSession(row.address) === null) return null;
const target = this.#targetOf(row.address.slice("ssh:".length));
const result = await this.#effects.runOn(target, listDirsCommand(dir));
+ // listDirsCommand's exit 4: the directory exists and refused the listing.
+ if (result.code === 4) return "denied";
if (result.code !== 0) return null;
const [head, rest] = result.stdout.split(DIR_LIST_MARK);
const path = (head ?? "").trim().split("\n").pop()?.trim() ?? "";
diff --git a/packages/server/test/dirs.test.ts b/packages/server/test/dirs.test.ts
new file mode 100644
index 00000000..cc96717a
--- /dev/null
+++ b/packages/server/test/dirs.test.ts
@@ -0,0 +1,90 @@
+/**
+ * The directory browser behind the Workspace picker: folders and files come back with their
+ * kind and modification time, and a folder the service may not read is a distinguishable
+ * error rather than an empty listing — on macOS an unanswered privacy prompt looks exactly
+ * like that, and an empty list hid it.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { DirListResponse, ProjectCreateResponse } from "../src/api/types.js";
+import { dirReadError } from "../src/http/routes/dirs.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const errno = (code: string) => Object.assign(new Error(code), { code });
+
+describe("dirReadError", () => {
+ it("gives a refusal its own code, whichever errno the OS used for it", () => {
+ for (const code of ["EACCES", "EPERM"]) {
+ const err = dirReadError(errno(code), "/Users/me/Downloads/x");
+ expect([err.status, err.code]).toEqual([403, "dir_permission_denied"]);
+ }
+ });
+
+ it("keeps absence a 404", () => {
+ const err = dirReadError(errno("ENOENT"), "/gone");
+ expect([err.status, err.code]).toEqual([404, "dir_not_found"]);
+ });
+});
+
+describe("dirs api", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let dir: string;
+
+ const listUrl = (p: string) => `/api/projects/${projectId}/dirs?path=${encodeURIComponent(p)}`;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_dirs");
+ owner = apiClient(t.app, a.cookie);
+ const created = (await (
+ await owner.post("/api/projects", { projectId: "owner_dirs-browse", name: "dirs project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "penguin-dirs-")));
+ });
+
+ afterEach(async () => {
+ try {
+ await fs.chmod(path.join(dir, "locked"), 0o755).catch(() => undefined);
+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("lists folders and files with their kind and modification time", async () => {
+ await fs.mkdir(path.join(dir, "src"));
+ await fs.writeFile(path.join(dir, "notes.txt"), "x");
+ const res = await owner.get(listUrl(dir));
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as DirListResponse;
+ expect(body.path).toBe(dir);
+ expect(body.platform).toBe(process.platform);
+ expect(body.entries.map((e) => [e.name, e.kind])).toEqual([
+ ["notes.txt", "file"],
+ ["src", "dir"],
+ ]);
+ expect(body.entries.every((e) => typeof e.mtime === "number")).toBe(true);
+ });
+
+ // POSIX permission bits: meaningless on win32, and root reads through them.
+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
+ "answers a folder it may not read with dir_permission_denied, not an empty list",
+ async () => {
+ const locked = path.join(dir, "locked");
+ await fs.mkdir(locked);
+ await fs.writeFile(path.join(locked, "inside.txt"), "x");
+ await fs.chmod(locked, 0o000);
+ const res = await owner.get(listUrl(locked));
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "dir_permission_denied",
+ );
+ },
+ );
+});
diff --git a/packages/server/test/machines-api.test.ts b/packages/server/test/machines-api.test.ts
index 736f75a6..f2653c3f 100644
--- a/packages/server/test/machines-api.test.ts
+++ b/packages/server/test/machines-api.test.ts
@@ -1216,6 +1216,21 @@ describe("machines API", () => {
expect(res.status).toBe(404);
});
+ it("403s a directory the machine has but refuses to list, with its own code", async () => {
+ await boot({
+ runOn: async (_t, command) =>
+ command.includes("---penguin-dirs---")
+ ? { code: 4, stdout: "", stderr: "", timedOut: false }
+ : { code: 0, stdout: "", stderr: "", timedOut: false },
+ });
+ connectedMachine();
+ const res = await admin.get(`/api/projects/${PROJECT}/machines/${ID}/dirs?path=/root`);
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "dir_permission_denied",
+ );
+ });
+
it("404s a machine that is not connected, and asks it nothing — a read never opens ssh", async () => {
const asked: string[] = [];
await boot({
diff --git a/packages/web/e2e/draft.spec.mjs b/packages/web/e2e/draft.spec.mjs
index 38ea10ee..bb997260 100644
--- a/packages/web/e2e/draft.spec.mjs
+++ b/packages/web/e2e/draft.spec.mjs
@@ -210,18 +210,16 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
// Regression (review): the route-state prefill applies once per navigation only — after the
// user picks a different directory and reloads, the restored cached choice must win; the
// prefill must NOT re-apply (location.state survives a reload inside history.state, so the
- // consumed marker lives in sessionStorage rather than a ref). Browse one level up and select
- // it; the path row mirrors the loaded directory, which orders the two clicks deterministically.
+ // consumed marker lives in sessionStorage rather than a ref). The finder opens revealing the
+ // current Workspace, selected, in its parent; climb one level and choose that parent.
await page.getByRole("button", { name: "Workspace", exact: true }).click();
- // Match by trailing basename: the server realpaths the browsed directory, so the prefix may differ from the raw mkdtemp path.
- await expect(page.getByRole("textbox", { name: "Workspace" })).toHaveValue(
- new RegExp(`${wsLabel}$`),
- );
- // Regression (workspace picker race): while a /dirs request is in flight the picker's rows
- // are disabled, so a rapid double-click on "parent dir" must issue exactly ONE request and
- // ascend exactly one level — previously both clicks fired an un-sequenced load and could
- // relocate the browsing position. The response is gated on an explicit release (not a
- // timeout) so the second click deterministically lands inside the loading window.
+ const finder = page.getByRole("dialog", { name: "Workspace" });
+ await expect(finder.getByRole("option", { name: wsLabel, selected: true })).toBeVisible();
+ // Regression (workspace picker race): a relative move waits for the folder on screen to be
+ // the loaded one, so a rapid double "parent" (⌘↑ / Ctrl+↑) must issue exactly ONE request and
+ // climb exactly one level — two un-sequenced loads from the same position used to resend the
+ // same parent. The response is gated on an explicit release (not a timeout) so the second
+ // press deterministically lands inside the loading window.
let releaseDirs;
const dirsGate = new Promise((resolve) => {
releaseDirs = resolve;
@@ -234,22 +232,17 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses
await route.continue();
};
await page.route(dirsRoute, gateDirs);
- const upRow = page.getByRole("button", { name: "上级目录" });
- await upRow.click();
- // force: the row is disabled while loading, and a plain click would stall on Playwright's
- // actionability wait instead of exercising the double-click; the disabled button swallows it.
- await upRow.click({ force: true });
+ await finder.getByRole("listbox").focus();
+ await page.keyboard.press("ControlOrMeta+ArrowUp");
+ await page.keyboard.press("ControlOrMeta+ArrowUp");
releaseDirs();
+ // Climbing selects the folder it came from, so one level up shows the parent selected.
const parentLabel = basename(dirname(namedWs));
- await expect(page.getByRole("textbox", { name: "Workspace" })).toHaveValue(
- new RegExp(`${parentLabel}$`),
- );
- await expect(page.getByRole("textbox", { name: "Workspace" })).not.toHaveValue(
- new RegExp(`${wsLabel}$`),
- );
- expect(dirsRequests, "double-click while loading fires a single /dirs request").toBe(1);
+ await expect(finder.getByRole("option", { name: parentLabel, selected: true })).toBeVisible();
+ expect(dirsRequests, "double parent while loading fires a single /dirs request").toBe(1);
await page.unroute(dirsRoute, gateDirs);
- await page.getByRole("button", { name: "使用此目录" }).click();
+ await finder.getByRole("button", { name: "选择", exact: true }).click();
+ await expect(finder).toBeHidden();
await expect(page.getByLabel("Workspace")).toContainText(parentLabel);
await page.reload();
await expect(page.getByLabel("Workspace")).toContainText(parentLabel);
diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsx
index 079e19c0..b1933b5e 100644
--- a/packages/web/src/components/layout/project-dialogs.tsx
+++ b/packages/web/src/components/layout/project-dialogs.tsx
@@ -539,9 +539,9 @@ function MembersSection({ projectId, isOwner }: { projectId: string; isOwner: bo
* delete zone): the `[default_chat]` block (Agent / Workspace / approval mode / thinking
* level) plus the Project's default model, laid out as a compact responsive two-column
* grid. Workspace and model reuse the chat draft's own pickers — WorkspaceSelect (the
- * dir browser) and ModelSelect (the composer's model picker) — with their `form`
- * trigger variant, so the controls line up with the dialog's Input/Select while what they
- * open stays exactly the composer's (the directory menu, the model-picker dialog).
+ * folder finder, a modal stacked on this one) and ModelSelect (the composer's model
+ * picker, a dialog too) — with their `form` trigger variant, so the controls line up with
+ * the dialog's Input/Select while what they open stays exactly the composer's.
* The model default is SINGLE-SOURCED with the models page — the picker renders and writes
* the same top-level `default_model` (via the narrow PUT /models/default route), never a
* second key; changing it also releases the draft-cached model pin exactly as the models
@@ -756,8 +756,8 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwne
</div>
<div className="sm:col-span-2">
<FieldLabel>{S.chat.workspace}</FieldLabel>
- {/* The draft page's dir-browser pill: browse server directories, edit the path
- inline, or clear back to a temporary workspace. */}
+ {/* The draft page's folder finder: browse server directories, go to a typed
+ path, or clear back to a temporary workspace. */}
<WorkspaceSelect
projectId={projectId}
workspace={workspace}
diff --git a/packages/web/src/components/ui/form-picker.tsx b/packages/web/src/components/ui/form-picker.tsx
index 60cd678a..e0bf1276 100644
--- a/packages/web/src/components/ui/form-picker.tsx
+++ b/packages/web/src/components/ui/form-picker.tsx
@@ -4,11 +4,12 @@
* chevron) with a portaled dropdown hanging under its left edge. It is the single source of the
* "form-variant" look shared by the model picker, the workspace picker and the schedule's
* session picker, so the three read identically and none re-hand-rolls the trigger. The model
- * picker opens a dialog instead of a menu, so it takes the trigger alone (FormPickerTrigger).
+ * and workspace pickers open a dialog instead of a menu, so they take the trigger alone
+ * (FormPickerTrigger).
*
* It owns only the trigger + Dropdown wiring; the menu body is the caller's `children`
- * (a searchable list, a directory browser, …), and open/close state stays with the caller
- * (the pickers drive it and close on pick).
+ * (a searchable list, …), and open/close state stays with the caller (the pickers drive it
+ * and close on pick).
*/
import type { ReactNode } from "react";
import { Dropdown } from "./dropdown";
@@ -40,8 +41,8 @@ export interface FormPickerTriggerProps {
/**
* The form-variant trigger on its own, for a picker that opens a dialog rather than a hanging
- * menu (the model picker): the same button FormPicker draws, so both kinds of picker read
- * identically in a form.
+ * menu (the model picker, the workspace finder): the same button FormPicker draws, so both
+ * kinds of picker read identically in a form.
*/
export function FormPickerTrigger({
leading,
diff --git a/packages/web/src/components/ui/modal.tsx b/packages/web/src/components/ui/modal.tsx
index e88c2163..0a513ae1 100644
--- a/packages/web/src/components/ui/modal.tsx
+++ b/packages/web/src/components/ui/modal.tsx
@@ -34,6 +34,13 @@ export interface ModalProps {
headerless?: boolean;
/** Render children full-bleed: no built-in padding or 70vh scroller. For dialogs that own their inner layout and scroll regions (PagedDialog); the caller then also owns a close control. */
bare?: boolean;
+ /**
+ * Fill the whole screen on a phone instead of rising as a bottom sheet, and lay the panel out
+ * as a column so a `bare` body can take the height between header and footer. For dialogs
+ * that are a workspace of their own (the Workspace finder) rather than a question; pair it
+ * with an `sm:` height in `widthClass`, since above the breakpoint the panel is a card again.
+ */
+ fullScreenOnPhone?: boolean;
}
/**
@@ -187,6 +194,7 @@ export function Modal({
widthClass,
headerless,
bare,
+ fullScreenOnPhone,
}: ModalProps) {
const titleId = useId();
const panelRef = useRef<HTMLDivElement>(null);
@@ -209,7 +217,11 @@ export function Modal({
{...(headerless ? { "aria-label": title } : { "aria-labelledby": titleId })}
tabIndex={-1}
onKeyDown={onPanelKeyDown}
- className={`anim-pop w-full ${widthClass ?? "sm:max-w-md"} rounded-t-lg border border-gray-200 bg-white pb-[env(safe-area-inset-bottom)] shadow-xl sm:rounded-lg sm:pb-0 dark:border-gray-800 dark:bg-gray-900`}
+ className={`anim-pop w-full ${widthClass ?? "sm:max-w-md"} ${
+ fullScreenOnPhone
+ ? "flex h-[100dvh] flex-col pt-[env(safe-area-inset-top)] sm:pt-0"
+ : "rounded-t-lg"
+ } border border-gray-200 bg-white pb-[env(safe-area-inset-bottom)] shadow-xl sm:rounded-lg sm:pb-0 dark:border-gray-800 dark:bg-gray-900`}
>
{!headerless && (
<div className="flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-800">
diff --git a/packages/web/src/features/chat/workspace-finder-model.ts b/packages/web/src/features/chat/workspace-finder-model.ts
new file mode 100644
index 00000000..0e5856a8
--- /dev/null
+++ b/packages/web/src/features/chat/workspace-finder-model.ts
@@ -0,0 +1,464 @@
+/**
+ * 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.
+ *
+ * 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 {
+ TEMP_WORKSPACE_GROUP_KEY,
+ isTempWorkspace,
+ workspaceGroupMachine,
+ workspaceGroupPath,
+} from "../../lib/session-grouping";
+
+/** A path the dirs API accepts as-is: posix absolute, a drive path, or a UNC share. */
+export function isAbsoluteDirPath(path: string): boolean {
+ return /^\//.test(path) || /^[A-Za-z]:[\\/]/.test(path) || /^\\\\[^\\]/.test(path);
+}
+
+/** One clickable breadcrumb: the label shown, and the absolute path it opens. */
+export interface Crumb {
+ label: string;
+ path: string;
+}
+
+/**
+ * The segments of an absolute path, root first, each carrying the path up to and including
+ * it. The root keeps its own spelling (`/`, `C:\`, `\\server\share\`) because every other
+ * segment is joined onto it with the separator that root implies.
+ */
+export function splitBreadcrumbs(path: string): Crumb[] {
+ const p = path.trim();
+ if (p === "") return [];
+ let root: string;
+ let rest: string;
+ let sep: string;
+ const unc = /^(\\\\[^\\]+\\[^\\]+)\\?(.*)$/.exec(p);
+ const drive = /^([A-Za-z]:)[\\/]?(.*)$/.exec(p);
+ if (unc) {
+ root = `${unc[1]}\\`;
+ rest = unc[2] ?? "";
+ sep = "\\";
+ } else if (drive) {
+ root = `${drive[1]}\\`;
+ rest = drive[2] ?? "";
+ sep = "\\";
+ } else {
+ root = "/";
+ rest = p.replace(/^\/+/, "");
+ sep = "/";
+ }
+ const crumbs: Crumb[] = [{ label: root === "/" ? "/" : root.replace(/\\$/, ""), path: root }];
+ let acc = root;
+ for (const part of rest.split(/[\\/]+/).filter(Boolean)) {
+ acc = acc.endsWith(sep) ? `${acc}${part}` : `${acc}${sep}${part}`;
+ crumbs.push({ label: part, path: acc });
+ }
+ return crumbs;
+}
+
+/** The folder above `path`, or null at a root — for a folder that failed to load, whose listing (and its `parent`) never arrived. */
+export function parentOf(path: string): string | null {
+ const crumbs = splitBreadcrumbs(path);
+ return crumbs.length > 1 ? (crumbs[crumbs.length - 2]?.path ?? null) : null;
+}
+
+/** The last segment of a path, for a label and for picking a folder out of its parent. */
+export function baseName(path: string): string {
+ const crumbs = splitBreadcrumbs(path);
+ return crumbs[crumbs.length - 1]?.label ?? path;
+}
+
+/** Back/forward history: the visited folders and where in them the finder stands. */
+export interface NavHistory {
+ entries: string[];
+ index: number;
+}
+
+export const EMPTY_HISTORY: NavHistory = { entries: [], index: -1 };
+
+/**
+ * Visiting a folder: anything ahead of the current position is dropped, as in a browser. A
+ * reload of the folder already shown is not a visit, or Back would have to be pressed twice.
+ */
+export function historyVisit(h: NavHistory, path: string): NavHistory {
+ if (h.entries[h.index] === path) return h;
+ const entries = [...h.entries.slice(0, h.index + 1), path];
+ return { entries, index: entries.length - 1 };
+}
+
+/** One step back or forward; the same history when there is nowhere to go. */
+export function historyStep(h: NavHistory, delta: -1 | 1): NavHistory {
+ const index = h.index + delta;
+ if (index < 0 || index >= h.entries.length) return h;
+ return { entries: h.entries, index };
+}
+
+export const canGoBack = (h: NavHistory): boolean => h.index > 0;
+export const canGoForward = (h: NavHistory): boolean => h.index < h.entries.length - 1;
+
+/** Whether an entry is a folder: an entry with no kind came from a listing that reports folders only. */
+export const isFolder = (entry: DirEntryInfo): boolean => entry.kind !== "file";
+
+/**
+ * What the list shows: hidden entries dropped, the filter applied (case-insensitive
+ * substring), folders first and then by name.
+ */
+export function visibleEntries(entries: readonly DirEntryInfo[], filter: string): DirEntryInfo[] {
+ const q = filter.trim().toLowerCase();
+ return entries
+ .filter((e) => !e.name.startsWith("."))
+ .filter((e) => q === "" || e.name.toLowerCase().includes(q))
+ .sort((a, b) => {
+ const fa = isFolder(a);
+ if (fa !== isFolder(b)) return fa ? -1 : 1;
+ return a.name.localeCompare(b.name);
+ });
+}
+
+/**
+ * Type-to-select: the first selectable entry whose name starts with what has been typed,
+ * ignoring case. Only folders can be selected, so a file never catches the prefix. -1 when
+ * nothing matches, so the selection stays where it was.
+ */
+export function typeSelectIndex(entries: readonly DirEntryInfo[], typed: string): number {
+ const q = typed.toLowerCase();
+ if (q === "") return -1;
+ return entries.findIndex((e) => isFolder(e) && e.name.toLowerCase().startsWith(q));
+}
+
+/**
+ * The next selectable row from `from` in direction `delta`, skipping files; -1 when there is
+ * none. From no selection (-1), Down lands on the first folder and Up on the last.
+ */
+export function stepSelection(
+ entries: readonly DirEntryInfo[],
+ from: number,
+ delta: -1 | 1,
+): number {
+ let i = from === -1 ? (delta === 1 ? 0 : entries.length - 1) : from + delta;
+ for (; i >= 0 && i < entries.length; i += delta) {
+ const entry = entries[i];
+ if (entry !== undefined && isFolder(entry)) return i;
+ }
+ return from;
+}
+
+/** A standard folder that a platform's own file manager lists in its sidebar. */
+export type StandardFolder = "desktop" | "documents" | "downloads" | "pictures";
+
+/** A sidebar place. `key` picks its icon (and a standard folder's label); `path` is what clicking it opens. */
+export interface Place {
+ key: "home" | StandardFolder | "drive" | "folder";
+ path: string;
+ /** The label for places named by their path: home by its folder name, a drive by its letter, an added folder by its name. */
+ label: string;
+}
+
+/** The three families of Quick access defaults. */
+export type QuickAccessPlatform = "win32" | "darwin" | "linux";
+
+/**
+ * Anything other than Windows and macOS reads as Linux — including a machine browsed over ssh,
+ * which reports no platform at all and is nearly always a Linux server.
+ */
+export function quickAccessPlatform(platform: string | undefined): QuickAccessPlatform {
+ return platform === "win32" || platform === "darwin" ? platform : "linux";
+}
+
+/**
+ * Each platform's standard folders, in the order its own file manager lists them: Explorer's
+ * Quick access pins Desktop, Downloads, Documents and Pictures; Finder's Favourites list
+ * Desktop, Documents and Downloads; a Linux desktop's Files shows the XDG folders Desktop,
+ * Documents, Downloads and Pictures. Media-only folders (Music, Videos) and Applications are
+ * left out — none of them is somewhere a Workspace lives.
+ */
+const STANDARD_FOLDERS: Record<
+ QuickAccessPlatform,
+ ReadonlyArray<readonly [StandardFolder, string]>
+> = {
+ win32: [
+ ["desktop", "Desktop"],
+ ["downloads", "Downloads"],
+ ["documents", "Documents"],
+ ["pictures", "Pictures"],
+ ],
+ darwin: [
+ ["desktop", "Desktop"],
+ ["documents", "Documents"],
+ ["downloads", "Downloads"],
+ ],
+ linux: [
+ ["desktop", "Desktop"],
+ ["documents", "Documents"],
+ ["downloads", "Downloads"],
+ ["pictures", "Pictures"],
+ ],
+};
+
+/**
+ * Quick access as the machine offers it before the user changes anything, from that machine's
+ * own home listing: home itself, then the platform's standard folders that exist there. The
+ * home listing is the source rather than a guessed path because only that machine knows
+ * whether the folder is there (a Linux server without a desktop has none of them). Windows
+ * matches the names ignoring case, as its filesystem does.
+ */
+export function defaultPlaces(home: DirListResponse | null): Place[] {
+ if (home === null) return [];
+ const platform = quickAccessPlatform(home.platform);
+ const places: Place[] = [{ key: "home", path: home.path, label: baseName(home.path) }];
+ for (const [key, name] of STANDARD_FOLDERS[platform]) {
+ const found = home.entries.find(
+ (e) =>
+ isFolder(e) &&
+ (platform === "win32" ? e.name.toLowerCase() === name.toLowerCase() : e.name === name),
+ );
+ if (found !== undefined) places.push({ key, path: found.path, label: found.name });
+ }
+ return places;
+}
+
+/** Windows' drive roots, for the This PC section; nothing on other platforms. */
+export function drivePlaces(home: DirListResponse | null): Place[] {
+ return (home?.roots ?? []).map((root) => ({
+ key: "drive",
+ path: root,
+ label: root.replace(/\\$/, ""),
+ }));
+}
+
+/** What the user changed in one machine's Quick access. */
+export interface QuickAccessEdits {
+ /** Folders the user added, oldest first. */
+ added: string[];
+ /** Default places the user removed. */
+ removed: string[];
+}
+
+export const NO_EDITS: QuickAccessEdits = { added: [], removed: [] };
+
+/**
+ * Quick access as shown: the defaults the user kept, in their own order, then the folders the
+ * user added. Kept as edits against the defaults rather than as a stored list, so a standard
+ * folder that appears on the machine later still turns up unless it was removed.
+ */
+export function quickAccessPlaces(defaults: readonly Place[], edits: QuickAccessEdits): Place[] {
+ const shown = defaults.filter((p) => !edits.removed.includes(p.path));
+ for (const path of edits.added) {
+ if (!shown.some((p) => p.path === path))
+ shown.push({ key: "folder", path, label: baseName(path) });
+ }
+ return shown;
+}
+
+/** Adds a folder: a removed default comes back in its own place; anything else joins the end. */
+export function addToQuickAccess(
+ edits: QuickAccessEdits,
+ defaults: readonly Place[],
+ path: string,
+): QuickAccessEdits {
+ if (defaults.some((p) => p.path === path)) {
+ return edits.removed.includes(path)
+ ? { ...edits, removed: edits.removed.filter((p) => p !== path) }
+ : edits;
+ }
+ return edits.added.includes(path) ? edits : { ...edits, added: [...edits.added, path] };
+}
+
+/** Removes a folder: an added one is forgotten, a default one is remembered as removed. */
+export function removeFromQuickAccess(
+ edits: QuickAccessEdits,
+ defaults: readonly Place[],
+ path: string,
+): QuickAccessEdits {
+ const added = edits.added.filter((p) => p !== path);
+ const hide = defaults.some((p) => p.path === path) && !edits.removed.includes(path);
+ if (added.length === edits.added.length && !hide) return edits;
+ return { added, removed: hide ? [...edits.removed, path] : edits.removed };
+}
+
+/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory one. */
+export interface QuickAccessStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+}
+
+/**
+ * Storage key of one machine's Quick access edits. Per machine because a path means something
+ * only on the machine it is on; `local` is the server serving this page, whose paths no other
+ * machine shares.
+ */
+export const quickAccessKey = (machineId: string | null): string =>
+ `penguin.finderQuickAccess.${machineId ?? "local"}`;
+
+/** One machine's edits; nothing stored, or anything unreadable, is no edits at all. */
+export function loadQuickAccess(
+ machineId: string | null,
+ storage?: QuickAccessStorage,
+): QuickAccessEdits {
+ try {
+ // Resolved inside the try: touching localStorage throws when site data is blocked.
+ const raw: unknown = JSON.parse(
+ (storage ?? localStorage).getItem(quickAccessKey(machineId)) ?? "null",
+ );
+ if (typeof raw !== "object" || raw === null) return NO_EDITS;
+ const paths = (v: unknown): string[] =>
+ Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && x !== "") : [];
+ const record = raw as Record<string, unknown>;
+ return { added: paths(record.added), removed: paths(record.removed) };
+ } catch {
+ return NO_EDITS;
+ }
+}
+
+/** Writes one machine's edits (best-effort: quota limits and blocked storage fail silently). */
+export function saveQuickAccess(
+ machineId: string | null,
+ edits: QuickAccessEdits,
+ storage?: QuickAccessStorage,
+): void {
+ try {
+ (storage ?? localStorage).setItem(quickAccessKey(machineId), JSON.stringify(edits));
+ } catch {
+ /* best-effort persistence */
+ }
+}
+
+/**
+ * What a secondary click landed on: a folder (a list row or a sidebar place), a file row, or
+ * the list's empty space, which stands for the folder on screen.
+ */
+export interface FinderMenuTarget {
+ kind: "folder" | "file" | "here";
+ path: string;
+ /** The machine the path is on (null: this server) — a Recent entry may be on another one. */
+ machine: string | null;
+}
+
+export type FinderMenuItem =
+ "open" | "choose" | "addToQuickAccess" | "removeFromQuickAccess" | "copyPath" | "refresh";
+
+/**
+ * The context menu's rows, the way Explorer orders them: what opening the thing does first,
+ * then choosing it, then Quick access, then copying its path. A file row only copies (files
+ * are listed for context and cannot be picked); the empty space acts on the open folder, and
+ * adds Refresh as Explorer's background menu does.
+ */
+export function finderMenuItems(
+ target: FinderMenuTarget,
+ inQuickAccess: boolean,
+): FinderMenuItem[] {
+ if (target.kind === "file") return ["copyPath"];
+ const quick = inQuickAccess ? "removeFromQuickAccess" : "addToQuickAccess";
+ return target.kind === "here"
+ ? ["choose", quick, "copyPath", "refresh"]
+ : ["open", "choose", quick, "copyPath"];
+}
+
+/** A Workspace recently used in this Project, and the machine it is on (null: this server). */
+export interface RecentWorkspace {
+ path: string;
+ machineId: string | null;
+ /** Newest Session's createdAt there — what orders the list. */
+ at: string;
+}
+
+/**
+ * Recent Workspaces, newest first: the Sessions list already reports, per Agent, each
+ * Workspace's newest Session (keyed by machine and path), so this folds those stamps across
+ * Agents. Temporary Workspaces are left out — they are made per conversation and are never
+ * worth picking again. `machines` restricts the list to the machines the finder may browse.
+ */
+export function recentWorkspaces(
+ latestByAgent: ReadonlyMap<string, Readonly<Record<string, string>>>,
+ machines: (machineId: string | null) => boolean,
+ limit = 6,
+): RecentWorkspace[] {
+ const newest = new Map<string, RecentWorkspace>();
+ for (const byGroup of latestByAgent.values()) {
+ for (const [groupKey, at] of Object.entries(byGroup)) {
+ const path = workspaceGroupPath(groupKey);
+ if (path === TEMP_WORKSPACE_GROUP_KEY || isTempWorkspace(path)) continue;
+ const machineId = workspaceGroupMachine(groupKey);
+ if (!machines(machineId)) continue;
+ const held = newest.get(groupKey);
+ if (held === undefined || held.at < at) newest.set(groupKey, { path, machineId, at });
+ }
+ }
+ return [...newest.values()]
+ .sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0))
+ .slice(0, limit);
+}
+
+/**
+ * "Go to folder" input → the path to load: `~` and `~/…` resolve against the machine's home
+ * when it is known (the dirs API takes absolute paths only); anything else is sent as typed
+ * and the server decides.
+ */
+export function resolveGoTo(input: string, home: string | null): string {
+ const p = input.trim();
+ if (home === null) return p;
+ if (p === "~") return home;
+ const m = /^~[\\/](.*)$/.exec(p);
+ if (m === null) return p;
+ const sep = /^[A-Za-z]:|^\\\\/.test(home) ? "\\" : "/";
+ return home.endsWith(sep) ? `${home}${m[1]}` : `${home}${sep}${m[1]}`;
+}
+
+/** What a key press asks the finder to do. */
+export type FinderAction =
+ "up" | "down" | "first" | "last" | "open" | "parent" | "back" | "forward" | "goto" | "choose";
+
+/** The keyboard-event fields the map reads (a subset of KeyboardEvent, for tests). */
+export type FinderKey = Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">;
+
+/**
+ * The finder's keyboard map. The modifier is ⌘ on a Mac and Ctrl elsewhere, so the Finder
+ * chords (⌘↑ parent, ⌘↓ open, ⌘[ / ⌘] back and forward, ⌘⇧G type a path into the address
+ * bar) read the same on every platform; Alt+arrows are accepted too off the Mac, where
+ * Explorer and the browsers taught them. Plain arrows, Home/End and Enter are list keys — `inList` is false
+ * for a text field, where they belong to the field (Up/Down excepted: the filter box steers
+ * the list the way a combobox does).
+ */
+export function finderKeyAction(
+ e: FinderKey,
+ isMac: boolean,
+ inList: boolean,
+): FinderAction | null {
+ const mod = isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
+ const bare = !e.metaKey && !e.ctrlKey && !e.altKey;
+ if (mod && e.shiftKey && !e.altKey && (e.key === "g" || e.key === "G")) return "goto";
+ if (mod && !e.shiftKey && !e.altKey) {
+ if (e.key === "ArrowUp") return "parent";
+ if (e.key === "ArrowDown") return "open";
+ if (e.key === "[") return "back";
+ if (e.key === "]") return "forward";
+ if (e.key === "Enter") return "choose";
+ }
+ if (!isMac && e.altKey && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
+ if (e.key === "ArrowLeft") return "back";
+ if (e.key === "ArrowRight") return "forward";
+ if (e.key === "ArrowUp") return "parent";
+ }
+ if (!bare || e.shiftKey) return null;
+ if (e.key === "ArrowDown") return "down";
+ if (e.key === "ArrowUp") return "up";
+ if (!inList) return null;
+ if (e.key === "Home") return "first";
+ if (e.key === "End") return "last";
+ if (e.key === "Enter") return "open";
+ return null;
+}
+
+/** Whether a key press is a character to feed type-to-select: one printable character, no modifier. */
+export function isTypeSelectKey(e: FinderKey): boolean {
+ return e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey;
+}
+
+/** How long type-to-select keeps adding to what was typed before starting over. */
+export const TYPE_SELECT_RESET_MS = 900;
diff --git a/packages/web/src/features/chat/workspace-finder.tsx b/packages/web/src/features/chat/workspace-finder.tsx
new file mode 100644
index 00000000..e0833c67
--- /dev/null
+++ b/packages/web/src/features/chat/workspace-finder.tsx
@@ -0,0 +1,1327 @@
+/**
+ * The Workspace finder: the modal every Workspace picker opens (workspace-select.tsx keeps the
+ * triggers). It browses one machine's folders the way a desktop file manager's open dialog
+ * does — places on the left, the current folder as a list, navigation buttons and an address
+ * bar above it, Choose below — and hands back a folder and the machine it is on. Where the
+ * platforms' file managers differ it takes Explorer's habits: the address bar turns into a
+ * path field when clicked, a secondary click opens a context menu, and Quick access is the
+ * user's to edit, starting from the standard folders of the browsed machine's own platform.
+ *
+ * It is a Modal like any other dialog, so it stacks on the dialogs that host the form variant
+ * without anything of its own: Modal portals to body (a later modal sits above an earlier one in
+ * DOM order) and joins the shared Escape stack, so one Escape closes the finder and leaves the
+ * host dialog open, and closing hands focus back to the trigger.
+ *
+ * The component stays mounted while closed, so it reopens where it was browsing when the host
+ * has no Workspace set yet (the sidebar's new-workspace button picks one after another from the
+ * same place); with one set, it reopens revealing that folder in its parent.
+ */
+import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
+import type {
+ KeyboardEvent as ReactKeyboardEvent,
+ MouseEvent as ReactMouseEvent,
+ PointerEvent as ReactPointerEvent,
+ ReactNode,
+} from "react";
+import type { 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 { formatDateTime } from "../../lib/format";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { STAT_ICONS } from "../../lib/stat-icons";
+import { toneStrip } from "../../lib/tone";
+import { machineLabel, nameOnMachine, workspaceMachines } from "../../lib/workspace-machines";
+import type { WorkspaceMachine } from "../../lib/workspace-machines";
+import { useSessions } from "../../state/sessions";
+import { Modal } from "../../components/ui/modal";
+import { Button } from "../../components/ui/button";
+import { useRowContextMenu } from "../../components/ui/context-menu";
+import { writeClipboard } from "../../components/ui/copy-button";
+import { Dropdown } from "../../components/ui/dropdown";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CLOCK_ICON, FOLDER_ICON, FOLDER_OPEN_ICON } from "../../components/ui/group-list";
+import {
+ ARROW_BACK_ICON,
+ ARROW_FORWARD_ICON,
+ CloseIcon,
+ DOWNLOAD_ICON,
+ FILE_ICON,
+ REFRESH_ICON,
+} from "../../components/ui/icons";
+import { noAutofill } from "../../components/ui/input";
+import {
+ PIN_ICON,
+ overflowMenuGlyph,
+ overflowMenuRowClass,
+} from "../../components/ui/session-row-menu";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import {
+ EMPTY_HISTORY,
+ TYPE_SELECT_RESET_MS,
+ addToQuickAccess,
+ baseName,
+ canGoBack,
+ canGoForward,
+ defaultPlaces,
+ drivePlaces,
+ finderKeyAction,
+ finderMenuItems,
+ historyStep,
+ historyVisit,
+ isAbsoluteDirPath,
+ isFolder,
+ isTypeSelectKey,
+ loadQuickAccess,
+ parentOf,
+ quickAccessPlaces,
+ recentWorkspaces,
+ removeFromQuickAccess,
+ resolveGoTo,
+ saveQuickAccess,
+ splitBreadcrumbs,
+ stepSelection,
+ typeSelectIndex,
+ visibleEntries,
+} from "./workspace-finder-model";
+import type {
+ FinderAction,
+ FinderMenuItem,
+ FinderMenuTarget,
+ NavHistory,
+ Place,
+} from "./workspace-finder-model";
+
+const UP_ICON = "M12 19V5m-6 6 6-6 6 6";
+const HOME_ICON = "M3 11l9-8 9 8M5 10v10h14V10";
+const DESKTOP_ICON = "M3 4h18v12H3zM8 20h8M12 16v4";
+const PICTURES_ICON = "M4 5h16v14H4zM4 16l5-5 4 4 3-3 4 4M15 9.5h.01";
+const DRIVE_ICON = "M3 13h18v6H3zM5 13l2-8h10l2 8M17 16h.01";
+const MACHINE_ICON = "M4 4h16v6H4zM4 14h16v6H4zM8 7h.01M8 17h.01";
+const SIDEBAR_ICON = "M4 5h16v14H4zM10 5v14";
+const FILTER_ICON = "M21 21l-4.35-4.35M17 11a6 6 0 1 1-12 0 6 6 0 0 1 12 0z";
+const PLUS_ICON = "M12 5v14M5 12h14";
+const CHECK_ICON = "M5 12.5l4.5 4.5L19 7.5";
+/** A folder row's way in besides a double click: the drill-down chevron list rows use for "go into". */
+const ENTER_ICON = "M9 18l6-6-6-6";
+
+const PLACE_ICON: Record<Place["key"], string> = {
+ home: HOME_ICON,
+ desktop: DESKTOP_ICON,
+ documents: FILE_ICON,
+ downloads: DOWNLOAD_ICON,
+ pictures: PICTURES_ICON,
+ drive: DRIVE_ICON,
+ folder: FOLDER_ICON,
+};
+
+const MENU_ICON: Record<FinderMenuItem, string> = {
+ open: FOLDER_OPEN_ICON,
+ choose: CHECK_ICON,
+ addToQuickAccess: PIN_ICON,
+ removeFromQuickAccess: PIN_ICON,
+ copyPath: STAT_ICONS.copy,
+ refresh: REFRESH_ICON,
+};
+
+function isMacPlatform(): boolean {
+ if (typeof navigator === "undefined") return false;
+ return /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);
+}
+
+/** A touch screen has no double-click to open with, so a tap opens a folder there. */
+function isCoarsePointer(): boolean {
+ return typeof window !== "undefined" && window.matchMedia?.("(pointer: coarse)").matches === true;
+}
+
+/** What the pane shows: the folder asked for, its listing when it came back, or why it did not. */
+interface View {
+ path: string;
+ listing: DirListResponse | null;
+ error: unknown;
+}
+
+/**
+ * The toolbar's navigation buttons: bare glyphs, no box and no hover fill. The address bar
+ * beside them is the toolbar's one boxed control, so a button can never be read as a segment
+ * of the path or the path as a row of buttons.
+ */
+const navButtonClass =
+ "shrink-0 rounded-md p-1.5 text-gray-500 transition-colors duration-150 hover:text-gray-900 disabled:cursor-default disabled:opacity-35 disabled:hover:text-gray-500 dark:text-gray-400 dark:hover:text-gray-100 dark:disabled:hover:text-gray-400";
+
+export function WorkspaceFinder({
+ open,
+ onClose,
+ onChoose,
+ onClear,
+ projectId,
+ workspace,
+ machineId,
+ chooseMachine,
+ title,
+ hint,
+ clearLabel,
+}: {
+ open: boolean;
+ onClose: () => void;
+ /** The chosen folder and the machine it is on (null: this server). */
+ onChoose: (path: string, machineId: string | null) => void;
+ /** Present when the host offers going back to "no folder" (a temporary Workspace, or the host's own default). */
+ onClear?: (machineId: string | null) => void;
+ projectId: string;
+ /** The host's current value; revealed in its parent on open. */
+ workspace: string;
+ /** The machine to browse first; null or omitted is this server. */
+ machineId?: string | null;
+ /** Offer the Machines section. */
+ chooseMachine?: boolean;
+ title: string;
+ hint: string;
+ clearLabel: string;
+}) {
+ const f = S.chat.finder;
+ const isMac = useMemo(isMacPlatform, []);
+ const listId = useId();
+ const listRef = useRef<HTMLDivElement>(null);
+ const filterRef = useRef<HTMLInputElement>(null);
+ const addressRef = useRef<HTMLInputElement>(null);
+ const crumbsRef = useRef<HTMLElement>(null);
+
+ /**
+ * The machine being browsed. Its own state rather than the prop: choosing a machine re-roots
+ * the browser without touching the window's active server — a workspace on another machine
+ * is chosen from here, not by going there.
+ */
+ const [machine, setMachine] = useState<string | null>(machineId ?? null);
+ const machineRef = useRef(machine);
+ machineRef.current = machine;
+ const [machines, setMachines] = useState<WorkspaceMachine[]>([]);
+ /** The browsed machine's home listing: the Favourites, and the platform the pane's copy depends on. */
+ const [home, setHome] = useState<{ machine: string | null; listing: DirListResponse } | null>(
+ null,
+ );
+ const [view, setView] = useState<View>({ path: "", listing: null, error: null });
+ const [loading, setLoading] = useState(false);
+ const [history, setHistory] = useState<NavHistory>(EMPTY_HISTORY);
+ /** The selected row, by path — survives a reload and a filter that keeps it. */
+ const [selected, setSelected] = useState<string | null>(null);
+ const [filter, setFilter] = useState("");
+ /** The address bar is a path field (clicked, or ⌘⇧G) rather than breadcrumbs; the draft is what it holds. */
+ const [addressEditing, setAddressEditing] = useState(false);
+ const [addressDraft, setAddressDraft] = useState("");
+ const [sidebarOpen, setSidebarOpen] = useState(false);
+ const [listFocused, setListFocused] = useState(false);
+ const typed = useRef({ text: "", at: 0 });
+ /** Bumped by every Quick access edit, so the stored edits are read again. */
+ const [quickAccessVersion, setQuickAccessVersion] = useState(0);
+ /**
+ * One context menu for the whole finder, like the Files panel's tree: a hook per row would
+ * be a hold timer per row. The row, place or empty space a gesture landed on is resolved
+ * from the event, and held here while its menu is up.
+ */
+ const menu = useRowContextMenu();
+ const [menuTarget, setMenuTarget] = useState<FinderMenuTarget | null>(null);
+
+ /**
+ * 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
+ * relocate the finder after a newer one.
+ */
+ const loadSeq = useRef(0);
+
+ const load = (
+ target: string,
+ opts: {
+ machine?: string | null;
+ record?: boolean;
+ select?: string | null;
+ /** Handles a failure instead of the pane; true when it did. */
+ onError?: (err: unknown) => boolean;
+ } = {},
+ ) => {
+ const m = opts.machine === undefined ? machine : opts.machine;
+ const seq = ++loadSeq.current;
+ setLoading(true);
+ api
+ .listDirs(projectId, target, m)
+ .then((res) => {
+ if (seq !== loadSeq.current) return;
+ setView({ path: res.path, listing: res, error: null });
+ setSelected(opts.select ?? null);
+ setFilter("");
+ if (opts.record !== false) setHistory((h) => historyVisit(h, res.path));
+ })
+ .catch((err: unknown) => {
+ if (seq !== loadSeq.current) return;
+ if (opts.onError?.(err) === true) return;
+ // The folder that failed is where the finder now stands: its breadcrumbs lead back
+ // up, and Back returns to where it came from.
+ setView({ path: target, listing: null, error: err });
+ setSelected(null);
+ setFilter("");
+ if (opts.record !== false && target !== "") setHistory((h) => historyVisit(h, target));
+ })
+ .finally(() => {
+ if (seq === loadSeq.current) setLoading(false);
+ });
+ };
+
+ const loadHome = (m: string | null) => {
+ if (home?.machine === m) return;
+ api
+ .listDirs(projectId, "", m)
+ .then((listing) => {
+ if (machineRef.current === m) setHome({ machine: m, listing });
+ })
+ .catch(() => undefined);
+ };
+
+ /** Re-roots the finder on another machine: its home (or `target` there), a fresh history. */
+ const switchMachine = (next: string | null, target = "") => {
+ setMachine(next);
+ machineRef.current = next;
+ setHome(null);
+ setHistory(EMPTY_HISTORY);
+ load(target, { machine: next });
+ loadHome(next);
+ };
+
+ // Each open: reveal the host's folder in its parent (on the host's machine), otherwise pick
+ // up where the finder was — refreshed, since the disk may have moved on while it was closed.
+ useEffect(() => {
+ if (!open) return;
+ setAddressEditing(false);
+ setSidebarOpen(false);
+ const ws = workspace.trim();
+ if (ws !== "" && isAbsoluteDirPath(ws)) {
+ const m = machineId ?? null;
+ if (m !== machine) {
+ setMachine(m);
+ machineRef.current = m;
+ setHome(null);
+ }
+ setHistory(EMPTY_HISTORY);
+ const parent = parentOf(ws);
+ load(parent ?? ws, { machine: m, select: parent === null ? null : ws });
+ loadHome(m);
+ } else if (view.listing === null && view.error === null) {
+ load("");
+ loadHome(machine);
+ } else {
+ load(view.path, { record: false, select: selected });
+ loadHome(machine);
+ }
+ // Keyed on `open` alone: this is what opening does, not a reaction to the props moving
+ // while the finder is up.
+ }, [open]);
+
+ // Focus lands in the list on open. Modal has already focused its first control by now
+ // (children's effects run first), so this moves it on.
+ useEffect(() => {
+ if (open) listRef.current?.focus();
+ }, [open]);
+
+ // The machines a workspace can live on: this Project's, from the local server — the list
+ // is its own, whichever server the rest of the window is using.
+ useEffect(() => {
+ if (!open || chooseMachine !== true) return;
+ let cancelled = false;
+ void api
+ .getMachines(projectId)
+ .then((res) => {
+ if (!cancelled) setMachines(workspaceMachines(res));
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [open, chooseMachine, projectId]);
+
+ const { workspaceLatestByAgent } = useSessions();
+ const recents = useMemo(
+ () =>
+ recentWorkspaces(workspaceLatestByAgent, (id) =>
+ chooseMachine === true
+ ? id === null || machines.some((m) => m.selectable && m.id === id)
+ : id === machine,
+ ),
+ [workspaceLatestByAgent, chooseMachine, machines, machine],
+ );
+ const homeListing = home?.machine === machine ? home.listing : null;
+ const defaults = useMemo(() => defaultPlaces(homeListing), [homeListing]);
+ const drives = useMemo(() => drivePlaces(homeListing), [homeListing]);
+ // Re-read on every edit (the version) and on switching machines: each machine keeps its own.
+ const quickAccess = useMemo(
+ () => quickAccessPlaces(defaults, loadQuickAccess(machine)),
+ [defaults, machine, quickAccessVersion],
+ );
+ /**
+ * The Machines section shows whenever this surface offers machines at all, not only when
+ * more than one is reachable: a control that disappears when the answer is "just this one"
+ * reads as a missing feature.
+ */
+ const machineSection = chooseMachine === true && machines.length > 0;
+
+ const entries = useMemo(
+ () => visibleEntries(view.listing?.entries ?? [], filter),
+ [view.listing, filter],
+ );
+ const selIndex = selected === null ? -1 : entries.findIndex((e) => e.path === selected);
+ const selectedEntry = selIndex === -1 ? null : (entries[selIndex] ?? null);
+ const chooseTarget = selectedEntry?.path ?? view.listing?.path ?? null;
+ const platform = view.listing?.platform ?? homeListing?.platform;
+ const crumbs = splitBreadcrumbs(view.path);
+
+ // Keep the selected row in sight as the keyboard moves it.
+ useEffect(() => {
+ if (selIndex === -1) return;
+ document.getElementById(`${listId}-${selIndex}`)?.scrollIntoView({ block: "nearest" });
+ }, [selIndex, listId, open]);
+
+ // A long path scrolls its breadcrumbs to the end, where the current folder is.
+ useLayoutEffect(() => {
+ const el = crumbsRef.current;
+ if (el) el.scrollLeft = el.scrollWidth;
+ }, [view.path, open]);
+
+ // Closed, render nothing: the finder stays mounted to keep its place, and every picker's
+ // copy re-renders with the Sessions list, which changes far more often than it is opened.
+ // Unmounting Modal is itself a close path (Escape layer popped, focus handed back).
+ if (!open) return null;
+
+ /*
+ * Relative moves (back, forward, parent, open) wait for the folder on screen to be the one
+ * loaded: they are computed from it, so a second press while the first is in flight would
+ * resend the same target — two presses of "parent" climbing one level. Absolute ones (a
+ * place, a breadcrumb, a typed path) name their target outright and may supersede a load.
+ */
+ const step = (delta: -1 | 1) => {
+ if (loading) return;
+ const next = historyStep(history, delta);
+ const target = next.entries[next.index];
+ if (next === history || target === undefined) return;
+ setHistory(next);
+ // Back from a subfolder selects it, the way Finder does.
+ load(target, { record: false, select: view.path });
+ };
+
+ const goParent = () => {
+ if (loading) return;
+ const parent = view.listing?.parent ?? parentOf(view.path);
+ if (parent !== null) load(parent, { select: view.path });
+ };
+
+ const openEntry = (path: string) => {
+ if (!loading) load(path);
+ };
+
+ const choose = () => {
+ if (chooseTarget === null || loading) return;
+ onChoose(chooseTarget, machine);
+ };
+
+ /** Re-reads the folder on screen, keeping the selection; not a visit, so history stays put. */
+ const refresh = () => {
+ const path = view.listing?.path ?? view.path;
+ if (path !== "") load(path, { record: false, select: selected });
+ };
+
+ /** 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);
+ setAddressEditing(true);
+ };
+
+ /** Leaves the field as it was: Escape, or focus moving elsewhere, as in Explorer. */
+ const cancelAddress = () => {
+ setAddressEditing(false);
+ };
+
+ const commitAddress = () => {
+ const target = resolveGoTo(addressDraft, homeListing?.path ?? null);
+ setAddressEditing(false);
+ listRef.current?.focus();
+ if (target === "" || target === view.listing?.path) return;
+ load(target, {
+ // A path that is not there (or not a path) keeps the finder where it was; a folder that
+ // is there and refuses to be read is somewhere, and the pane says why it shows nothing.
+ onError: (err) => {
+ if (err instanceof ApiError && err.code === "dir_permission_denied") return false;
+ toastError(S.chat.workspaceDirInvalid);
+ return true;
+ },
+ });
+ };
+
+ /**
+ * Whether `path` on machine `m` is in that machine's Quick access. For the machine being
+ * browsed that is the list the sidebar shows; another machine's defaults are unknown from
+ * here (its home is not listed), so only the folders added there count.
+ */
+ const inQuickAccess = (path: string, m: string | null): boolean =>
+ (m === machine ? quickAccess : quickAccessPlaces([], loadQuickAccess(m))).some(
+ (p) => p.path === path,
+ );
+
+ const editQuickAccess = (path: string, m: string | null, add: boolean) => {
+ const base = m === machine ? defaults : [];
+ const current = loadQuickAccess(m);
+ const next = add
+ ? addToQuickAccess(current, base, path)
+ : removeFromQuickAccess(current, base, path);
+ if (next === current) return;
+ saveQuickAccess(m, next);
+ setQuickAccessVersion((v) => v + 1);
+ };
+
+ const closeMenu = () => {
+ menu.close();
+ setMenuTarget(null);
+ };
+
+ const runMenuItem = (item: FinderMenuItem, target: FinderMenuTarget) => {
+ closeMenu();
+ switch (item) {
+ case "open":
+ if (target.machine === machine) load(target.path);
+ else switchMachine(target.machine, target.path);
+ break;
+ case "choose":
+ onChoose(target.path, target.machine);
+ return;
+ case "addToQuickAccess":
+ case "removeFromQuickAccess":
+ editQuickAccess(target.path, target.machine, item === "addToQuickAccess");
+ break;
+ case "copyPath":
+ // A menu row cannot show the copy button's own feedback — the panel closes out from
+ // under it — so a toast confirms, as the Files panel's copy-path row does.
+ writeClipboard(target.path);
+ toastSuccess(S.common.copied);
+ break;
+ case "refresh":
+ refresh();
+ break;
+ }
+ // The panel is gone and took focus with it; the list is where the keyboard picks up.
+ listRef.current?.focus();
+ };
+
+ const menuLabel = (item: FinderMenuItem, target: FinderMenuTarget): string => {
+ switch (item) {
+ case "open":
+ return f.open;
+ case "choose":
+ return target.kind === "here" ? f.chooseCurrent : f.chooseThis;
+ case "addToQuickAccess":
+ return f.addToQuickAccess;
+ case "removeFromQuickAccess":
+ return f.removeFromQuickAccess;
+ case "copyPath":
+ return f.copyPath;
+ case "refresh":
+ return f.refresh;
+ }
+ };
+
+ /**
+ * What a gesture landed on, read from the data attributes the rows, places and the list
+ * itself carry. The list's own empty space stands for the folder on screen; anything else
+ * (the text fields, the toolbar) resolves to nothing, so its native menu — paste, for a
+ * path — is left alone.
+ */
+ const menuTargetAt = (
+ at: EventTarget | null,
+ ): { target: FinderMenuTarget; el: HTMLElement } | null => {
+ const el =
+ at instanceof Element
+ ? at.closest<HTMLElement>("[data-finder-path], [data-finder-here]")
+ : null;
+ if (el === null) return null;
+ const path = el.dataset.finderPath;
+ if (path === undefined) {
+ const here = view.listing?.path;
+ return here === undefined ? null : { target: { kind: "here", path: here, machine }, el };
+ }
+ const on = el.dataset.finderMachine;
+ return {
+ target: {
+ kind: el.dataset.finderKind === "file" ? "file" : "folder",
+ path,
+ machine: on === undefined ? machine : on === "" ? null : on,
+ },
+ el,
+ };
+ };
+
+ /** Secondary click, touch press-and-hold and the replayed click after it, for the whole finder. */
+ const menuProps = {
+ onContextMenu: (e: ReactMouseEvent) => {
+ const hit = menuTargetAt(e.target);
+ if (hit === null) return;
+ // A list row the menu opens on becomes the selection, as in Explorer — so Choose in the
+ // footer and the menu's own rows agree about which folder is meant.
+ if (hit.target.kind === "folder" && hit.el.getAttribute("role") === "option") {
+ setSelected(hit.target.path);
+ }
+ // Before the hook reads it: a keyboard-synthesized contextmenu is anchored at this box.
+ menu.rowRef(hit.el);
+ setMenuTarget(hit.target);
+ menu.rowProps.onContextMenu(e);
+ },
+ onPointerDown: (e: ReactPointerEvent) => {
+ // Only a press-and-hold opens from here; a mouse arrives through onContextMenu.
+ if (!isLongPressPointer(e.pointerType)) return;
+ const hit = menuTargetAt(e.target);
+ if (hit === null) return;
+ menu.rowRef(hit.el);
+ setMenuTarget(hit.target);
+ menu.rowProps.onPointerDown(e);
+ },
+ onPointerMove: menu.rowProps.onPointerMove,
+ onPointerUp: menu.rowProps.onPointerUp,
+ onPointerCancel: menu.rowProps.onPointerCancel,
+ // A touch screen replays the held press as a click once the finger lifts, and a tap on a
+ // row opens it: swallowed here so opening the menu does not also open the folder.
+ onClickCapture: (e: ReactMouseEvent) => {
+ if (!menu.consumeLongPressClick()) return;
+ e.preventDefault();
+ e.stopPropagation();
+ },
+ };
+
+ /** Shift+F10 / the menu key from the list: the selected row's menu, or the open folder's. */
+ const openMenuFromList = () => {
+ const row = selIndex === -1 ? null : document.getElementById(`${listId}-${selIndex}`);
+ const el = row ?? listRef.current;
+ if (el === null) return;
+ const target: FinderMenuTarget | null =
+ selectedEntry !== null
+ ? { kind: isFolder(selectedEntry) ? "folder" : "file", path: selectedEntry.path, machine }
+ : view.listing !== null
+ ? { kind: "here", path: view.listing.path, machine }
+ : null;
+ if (target === null) return;
+ menu.rowRef(el);
+ setMenuTarget(target);
+ const r = el.getBoundingClientRect();
+ // A row hangs the panel off its own box; the whole list, off its top-left corner.
+ menu.openAt(
+ row !== null
+ ? { top: r.top, bottom: r.bottom, left: r.left + 24, right: r.left + 24 }
+ : { top: r.top + 8, bottom: r.top + 8, left: r.left + 24, right: r.left + 24 },
+ );
+ };
+
+ const run = (action: FinderAction) => {
+ switch (action) {
+ case "down":
+ case "up": {
+ const i = stepSelection(entries, selIndex, action === "down" ? 1 : -1);
+ const entry = entries[i];
+ if (entry !== undefined) setSelected(entry.path);
+ return;
+ }
+ case "first":
+ case "last": {
+ const entry = entries[stepSelection(entries, -1, action === "first" ? 1 : -1)];
+ if (entry !== undefined) setSelected(entry.path);
+ return;
+ }
+ case "open":
+ if (selectedEntry !== null && isFolder(selectedEntry)) openEntry(selectedEntry.path);
+ return;
+ case "parent":
+ goParent();
+ return;
+ case "back":
+ step(-1);
+ return;
+ case "forward":
+ step(1);
+ return;
+ case "goto":
+ if (addressEditing) {
+ cancelAddress();
+ listRef.current?.focus();
+ } else editAddress();
+ return;
+ case "choose":
+ choose();
+ return;
+ }
+ };
+
+ const typeSelect = (ch: string) => {
+ const now = Date.now();
+ const prev = typed.current;
+ const text = now - prev.at > TYPE_SELECT_RESET_MS ? ch : prev.text + ch;
+ typed.current = { text, at: now };
+ const entry = entries[typeSelectIndex(entries, text.trimStart())];
+ if (entry !== undefined) setSelected(entry.path);
+ };
+
+ /**
+ * One key map for the whole finder. The list owns its arrows, Enter and type-to-select; the
+ * filter box steers the list with Up/Down like a combobox; the Finder chords work from
+ * anywhere except that a text field keeps its own ⌘/Ctrl+arrows (they move the caret there).
+ */
+ const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (e.defaultPrevented || e.nativeEvent.isComposing) return;
+ // The context menu is portaled to body but is still a React child of this tree, so its
+ // keys bubble through here: its arrows and Enter are the menu's, not the list's.
+ if (!e.currentTarget.contains(e.target as Node)) return;
+ const target = e.target as HTMLElement;
+ const inList = target === listRef.current;
+ const inFilter = target === filterRef.current;
+ if (inList && isContextMenuKey(e)) {
+ e.preventDefault();
+ openMenuFromList();
+ return;
+ }
+ // The address field is a path being typed: only its own chord (which closes it) applies.
+ const inAddress = target === addressRef.current;
+ const action = finderKeyAction(e, isMac, inList);
+ if (action === null) {
+ if (inList && isTypeSelectKey(e)) {
+ e.preventDefault();
+ typeSelect(e.key);
+ }
+ return;
+ }
+ if (inAddress && action !== "goto") return;
+ const listKey = action === "up" || action === "down" || action === "first" || action === "last";
+ if (listKey && !inList && !inFilter) return;
+ if ((action === "open" || action === "parent") && inFilter) return;
+ e.preventDefault();
+ e.stopPropagation();
+ run(action);
+ };
+
+ const permissionDenied =
+ view.error instanceof ApiError && view.error.code === "dir_permission_denied";
+ const hasRows = view.error === null && entries.length > 0;
+
+ const sideRow = ({
+ key,
+ icon,
+ label,
+ title: fullTitle,
+ active,
+ onClick,
+ extra,
+ disabled = false,
+ folder,
+ onRemove,
+ }: {
+ key: string;
+ icon: string;
+ label: string;
+ title: string;
+ active: boolean;
+ onClick: () => void;
+ extra?: ReactNode;
+ disabled?: boolean;
+ /** The folder the row opens, and its machine: what the context menu acts on. Machine rows have none. */
+ folder?: { path: string; machine: string | null };
+ /** Quick access rows: the hover button that takes the row out. */
+ onRemove?: () => void;
+ }) => (
+ <li
+ key={key}
+ className="group relative"
+ {...(folder !== undefined
+ ? {
+ "data-finder-path": folder.path,
+ "data-finder-kind": "folder",
+ ...(folder.machine !== machine ? { "data-finder-machine": folder.machine ?? "" } : {}),
+ }
+ : {})}
+ >
+ <button
+ type="button"
+ title={fullTitle}
+ disabled={disabled}
+ aria-current={active ? "location" : undefined}
+ data-finder-focus
+ onClick={() => {
+ setSidebarOpen(false);
+ onClick();
+ }}
+ className={`flex w-full items-center ${ICON_GAP.menu} rounded-md px-2 py-1 text-left text-sm transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-50 ${
+ onRemove !== undefined ? "pr-7" : ""
+ } ${
+ active
+ ? "bg-gray-200 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
+ : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800/60"
+ }`}
+ >
+ <GlyphIcon d={icon} size={ICON_SIZE.rowLead} className="shrink-0 text-gray-400" />
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {extra}
+ </button>
+ {/* Revealed on hover and on keyboard focus; a touch screen removes through the row's
+ press-and-hold menu instead, which offers the same action. */}
+ {onRemove !== undefined && (
+ <button
+ type="button"
+ aria-label={f.removeNamed(label)}
+ title={f.removeFromQuickAccess}
+ onClick={onRemove}
+ className="absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-gray-400 opacity-0 transition-opacity duration-150 hover:text-gray-800 focus-visible:opacity-100 group-hover:opacity-100 dark:text-gray-500 dark:hover:text-gray-200"
+ >
+ <CloseIcon size={10} />
+ </button>
+ )}
+ </li>
+ );
+
+ const sideHeading = (text: string, action?: ReactNode) => (
+ <div className="flex items-center justify-between px-2 pb-1 pt-3 first:pt-0">
+ <p className="text-xs font-medium text-gray-400 dark:text-gray-500">{text}</p>
+ {action}
+ </div>
+ );
+
+ const placeLabel = (place: Place): string => {
+ if (place.key === "home" || place.key === "drive" || place.key === "folder") return place.label;
+ // Finder says 文稿 where Explorer and Files say 文档: each machine's own word for it.
+ if (place.key === "documents" && platform === "darwin") return f.documentsMac;
+ return f.places[place.key];
+ };
+
+ const currentFolder = view.listing?.path ?? null;
+ const canAddCurrent = currentFolder !== null && !inQuickAccess(currentFolder, machine);
+
+ const sidebar = (
+ <aside
+ className={`${
+ sidebarOpen ? "absolute inset-y-0 left-0 z-10 flex w-64 shadow-xl" : "hidden"
+ } shrink-0 flex-col overflow-y-auto border-r border-gray-200 bg-gray-50 px-2 py-3 sm:static sm:flex sm:w-48 sm:shadow-none dark:border-gray-800 dark:bg-gray-950`}
+ >
+ {/* Quick access stays up, even emptied, while there is a folder on screen to add back. */}
+ {(quickAccess.length > 0 || currentFolder !== null) && (
+ <>
+ {sideHeading(
+ f.quickAccess,
+ currentFolder !== null && canAddCurrent && (
+ <button
+ type="button"
+ aria-label={f.addCurrentToQuickAccess}
+ title={f.addCurrentToQuickAccess}
+ onClick={() => editQuickAccess(currentFolder, machine, true)}
+ className="rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-800 dark:text-gray-500 dark:hover:text-gray-200"
+ >
+ <GlyphIcon d={PLUS_ICON} size={ICON_SIZE.inlineGlyph} />
+ </button>
+ ),
+ )}
+ <ul className="space-y-0.5">
+ {quickAccess.map((place) =>
+ sideRow({
+ key: `quick:${place.path}`,
+ icon: PLACE_ICON[place.key],
+ label: placeLabel(place),
+ title: place.path,
+ active: view.path === place.path,
+ onClick: () => load(place.path),
+ folder: { path: place.path, machine },
+ onRemove: () => editQuickAccess(place.path, machine, false),
+ }),
+ )}
+ </ul>
+ </>
+ )}
+ {/* Windows' drives, where Explorer keeps them: under This PC, apart from Quick access. */}
+ {drives.length > 0 && (
+ <>
+ {sideHeading(f.thisPc)}
+ <ul className="space-y-0.5">
+ {drives.map((place) =>
+ sideRow({
+ key: `drive:${place.path}`,
+ icon: PLACE_ICON[place.key],
+ label: place.label,
+ title: place.path,
+ active: view.path === place.path,
+ onClick: () => load(place.path),
+ folder: { path: place.path, machine },
+ }),
+ )}
+ </ul>
+ </>
+ )}
+ {recents.length > 0 && (
+ <>
+ {sideHeading(f.recent)}
+ <ul className="space-y-0.5">
+ {recents.map((r) =>
+ sideRow({
+ key: `recent:${r.machineId ?? ""}:${r.path}`,
+ icon: CLOCK_ICON,
+ label: nameOnMachine(
+ baseName(r.path),
+ r.machineId === null ? null : machineLabel(machines, r.machineId),
+ ),
+ title: r.path,
+ active: r.machineId === machine && view.path === r.path,
+ onClick: () =>
+ r.machineId === machine ? load(r.path) : switchMachine(r.machineId, r.path),
+ folder: { path: r.path, machine: r.machineId },
+ }),
+ )}
+ </ul>
+ </>
+ )}
+ {/* Choosing a machine re-roots the finder at that machine's home: a path is only
+ meaningful on the machine it is on, so carrying the current one across would be a
+ path that likely does not exist there. */}
+ {machineSection && (
+ <>
+ {sideHeading(f.machines)}
+ <ul className="space-y-0.5">
+ {machines.map((entry, index) =>
+ sideRow({
+ key: entry.selectable
+ ? `machine:${entry.id ?? "local"}`
+ : `machine-unusable:${index}`,
+ icon: MACHINE_ICON,
+ label: entry.label,
+ title: entry.label,
+ active: entry.selectable && entry.id === machine,
+ onClick: () => {
+ if (entry.id !== machine) switchMachine(entry.id);
+ },
+ extra: entry.local ? (
+ <span className="shrink-0 text-xs text-gray-400">{S.chat.workspaceHere}</span>
+ ) : entry.reason !== undefined ? (
+ // A machine that cannot be browsed says why on its own row, where the
+ // question is asked.
+ <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">
+ {S.chat.workspaceMachineWhy[entry.reason]}
+ </span>
+ ) : undefined,
+ disabled: !entry.selectable,
+ }),
+ )}
+ </ul>
+ </>
+ )}
+ </aside>
+ );
+
+ const shortcut = (mac: string, other: string) => (isMac ? mac : other);
+ const editChord = shortcut("⌘⇧G", "Ctrl+Shift+G");
+ const parentPath = view.listing?.parent ?? parentOf(view.path);
+
+ /**
+ * The address bar: one boxed, input-like control, so it reads as the path and not as more
+ * toolbar. At rest it holds the path as segments — a segment opens that folder — and a click
+ * anywhere else in it (the folder mark, the current folder, the empty stretch after it) turns
+ * it into a text field holding the whole path, as Explorer's does. Enter goes there, Escape or
+ * leaving the field puts the segments back.
+ */
+ const addressBar = (
+ <div
+ className={`flex h-8 min-w-0 flex-1 items-center rounded-md border bg-white transition-colors duration-150 dark:bg-gray-900 ${
+ addressEditing
+ ? "border-gray-400 dark:border-gray-500"
+ : "border-gray-300 hover:border-gray-400 dark:border-gray-700 dark:hover:border-gray-600"
+ }`}
+ >
+ {addressEditing ? (
+ <input
+ ref={addressRef}
+ autoFocus
+ value={addressDraft}
+ aria-label={f.address}
+ placeholder={f.addressPlaceholder}
+ {...noAutofill}
+ onFocus={(e) => e.target.select()}
+ onChange={(e) => setAddressDraft(e.target.value)}
+ onBlur={cancelAddress}
+ onKeyDown={(e) => {
+ if (e.nativeEvent.isComposing) return;
+ if (e.key === "Enter") {
+ e.preventDefault();
+ commitAddress();
+ } else if (e.key === "Escape") {
+ // Puts the segments back; it does not close the finder.
+ e.stopPropagation();
+ cancelAddress();
+ listRef.current?.focus();
+ }
+ }}
+ className="h-full min-w-0 flex-1 rounded-md bg-transparent px-2.5 text-sm text-gray-900 outline-none placeholder:text-gray-400 dark:text-gray-100"
+ />
+ ) : (
+ <>
+ <button
+ type="button"
+ aria-label={f.editPath}
+ title={`${f.editPath} (${editChord})`}
+ onClick={editAddress}
+ className="flex h-full shrink-0 items-center pl-2.5 pr-1 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"
+ >
+ <GlyphIcon d={FOLDER_ICON} size={ICON_SIZE.inlineGlyph} />
+ </button>
+ <nav
+ ref={crumbsRef}
+ aria-label={f.path}
+ className="min-w-0 overflow-x-auto [scrollbar-width:none]"
+ >
+ <ol className="flex items-center whitespace-nowrap text-sm">
+ {crumbs.map((crumb, i) => {
+ const last = i === crumbs.length - 1;
+ return (
+ <li key={crumb.path} className="flex items-center">
+ {i > 0 && crumb.label !== "" && (
+ <span className="px-0.5 text-gray-300 dark:text-gray-600" aria-hidden>
+ ›
+ </span>
+ )}
+ <button
+ type="button"
+ // The folder already on screen has nowhere to go: clicking it edits the
+ // path instead, like the rest of the bar.
+ onClick={last ? editAddress : () => load(crumb.path)}
+ {...(last
+ ? { "aria-current": "page" as const, title: `${f.editPath} (${editChord})` }
+ : {})}
+ className={`rounded px-1 py-0.5 transition-colors duration-150 ${
+ last
+ ? "text-gray-900 dark:text-gray-100"
+ : "text-gray-500 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100"
+ }`}
+ >
+ {crumb.label}
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ </nav>
+ {/* The empty stretch after the path: the widest click target for typing one. A
+ pointer affordance only — the folder mark above is the same action for the
+ keyboard, and ⌘⇧G / Ctrl+Shift+G reaches it from anywhere. */}
+ <div
+ aria-hidden
+ title={`${f.editPath} (${editChord})`}
+ onClick={editAddress}
+ className="h-full min-w-6 flex-1 cursor-text"
+ />
+ </>
+ )}
+ </div>
+ );
+
+ const toolbar = (
+ <div className="flex items-center gap-2 border-b border-gray-200 px-2 py-2 dark:border-gray-800">
+ <div className="flex shrink-0 items-center">
+ <button
+ type="button"
+ className={`${navButtonClass} sm:hidden`}
+ aria-label={sidebarOpen ? f.hideSidebar : f.showSidebar}
+ aria-expanded={sidebarOpen}
+ onClick={() => setSidebarOpen((v) => !v)}
+ >
+ <GlyphIcon d={SIDEBAR_ICON} size={ICON_SIZE.iconButton} />
+ </button>
+ <button
+ type="button"
+ className={navButtonClass}
+ disabled={!canGoBack(history)}
+ title={`${f.back} (${shortcut("⌘[", "Ctrl+[")})`}
+ aria-label={f.back}
+ onClick={() => step(-1)}
+ >
+ <GlyphIcon d={ARROW_BACK_ICON} size={ICON_SIZE.iconButton} />
+ </button>
+ <button
+ type="button"
+ className={navButtonClass}
+ disabled={!canGoForward(history)}
+ title={`${f.forward} (${shortcut("⌘]", "Ctrl+]")})`}
+ aria-label={f.forward}
+ onClick={() => step(1)}
+ >
+ <GlyphIcon d={ARROW_FORWARD_ICON} size={ICON_SIZE.iconButton} />
+ </button>
+ <button
+ type="button"
+ className={navButtonClass}
+ disabled={parentPath === null}
+ title={`${f.up} (${shortcut("⌘↑", "Alt+↑")})`}
+ aria-label={f.up}
+ onClick={goParent}
+ >
+ <GlyphIcon d={UP_ICON} size={ICON_SIZE.iconButton} />
+ </button>
+ {/* Refresh is also on the list's context menu, which is where a phone reaches it. */}
+ <button
+ type="button"
+ className={`${navButtonClass} hidden sm:block`}
+ disabled={currentFolder === null && view.error === null}
+ title={f.refresh}
+ aria-label={f.refresh}
+ onClick={refresh}
+ >
+ <GlyphIcon d={REFRESH_ICON} size={ICON_SIZE.iconButton} />
+ </button>
+ </div>
+ {addressBar}
+ <label className="relative flex shrink-0 items-center">
+ <GlyphIcon
+ d={FILTER_ICON}
+ size={ICON_SIZE.inlineGlyph}
+ className="pointer-events-none absolute left-2 text-gray-400"
+ />
+ <input
+ ref={filterRef}
+ type="search"
+ value={filter}
+ placeholder={f.filter}
+ aria-label={f.filter}
+ aria-controls={listId}
+ {...noAutofill}
+ onChange={(e) => setFilter(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ run("open");
+ } else if (e.key === "Escape" && filter !== "") {
+ // Clear first; only an empty filter lets Escape through to close the finder.
+ e.stopPropagation();
+ setFilter("");
+ }
+ }}
+ className="h-8 w-20 rounded-md border border-gray-300 bg-white pl-7 pr-2 text-sm text-gray-700 placeholder:text-gray-400 focus:border-gray-400 focus:outline-none sm:w-40 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200"
+ />
+ </label>
+ </div>
+ );
+
+ let body: ReactNode;
+ if (view.error !== null) {
+ body = (
+ <div className="p-4">
+ <div
+ className={`rounded-md border px-3 py-2.5 text-sm ${toneStrip[permissionDenied ? "attention" : "danger"]}`}
+ >
+ <p className="font-medium">{permissionDenied ? f.deniedTitle : f.loadFailed}</p>
+ <p className="mt-1 text-xs leading-5">
+ {permissionDenied
+ ? platform === "darwin"
+ ? f.deniedMac
+ : f.denied
+ : 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>
+ </div>
+ );
+ } else if (view.listing === null) {
+ body = <p className="px-4 py-3 text-xs text-gray-400">{S.common.loading}</p>;
+ } else if (entries.length === 0) {
+ body = (
+ <p className="px-4 py-3 text-xs text-gray-400">
+ {filter.trim() !== "" ? f.noMatch(filter.trim()) : f.empty}
+ </p>
+ );
+ } else {
+ body = entries.map((entry, i) => {
+ const folder = isFolder(entry);
+ const isSel = i === selIndex;
+ const accent = isSel && listFocused;
+ return (
+ <div
+ key={entry.path}
+ id={`${listId}-${i}`}
+ role="option"
+ // Named by the folder alone: the date and the enter button are the row's furniture.
+ aria-label={entry.name}
+ aria-selected={isSel}
+ aria-disabled={folder ? undefined : true}
+ title={folder ? entry.path : f.fileNotSelectable}
+ data-finder-path={entry.path}
+ data-finder-kind={folder ? "folder" : "file"}
+ onClick={() => {
+ if (!folder) return;
+ if (isCoarsePointer()) openEntry(entry.path);
+ else setSelected(entry.path);
+ }}
+ onDoubleClick={() => folder && openEntry(entry.path)}
+ className={`flex select-none items-center ${ICON_GAP.menu} py-1 pl-3 pr-2 text-sm ${
+ !folder
+ ? "cursor-default text-gray-400 dark:text-gray-600"
+ : isSel
+ ? listFocused
+ ? "bg-[var(--accent-bg)] text-[var(--accent-fg)]"
+ : "bg-gray-200 text-gray-900 dark:bg-gray-700 dark:text-gray-100"
+ : "cursor-default text-gray-800 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-gray-800/60"
+ }`}
+ >
+ <GlyphIcon
+ d={folder ? FOLDER_ICON : FILE_ICON}
+ size={ICON_SIZE.rowLead}
+ className={`shrink-0 ${accent ? "" : "text-gray-400"}`}
+ />
+ <span className="min-w-0 flex-1 truncate">{entry.name}</span>
+ <span
+ className={`hidden w-36 shrink-0 text-xs tabular-nums sm:block ${accent ? "" : "text-gray-400 dark:text-gray-500"}`}
+ >
+ {entry.mtime !== undefined ? formatDateTime(new Date(entry.mtime).toISOString()) : "—"}
+ </span>
+ {/* A second way into a folder beside the double click — one a touch screen, a
+ trackpad and a first-time user all find. Out of the tab order: the list's own
+ Enter is the keyboard's way in. A file keeps the slot empty so dates line up. */}
+ {folder ? (
+ <button
+ type="button"
+ tabIndex={-1}
+ aria-label={f.openFolder(entry.name)}
+ title={f.open}
+ onClick={(e) => {
+ e.stopPropagation();
+ openEntry(entry.path);
+ }}
+ onDoubleClick={(e) => e.stopPropagation()}
+ className={`flex w-6 shrink-0 justify-center rounded py-0.5 transition-colors duration-150 ${
+ accent
+ ? "text-current"
+ : "text-gray-400 hover:text-gray-900 dark:text-gray-500 dark:hover:text-gray-100"
+ }`}
+ >
+ <GlyphIcon d={ENTER_ICON} size={ICON_SIZE.inlineGlyph} />
+ </button>
+ ) : (
+ <span className="w-6 shrink-0" aria-hidden />
+ )}
+ </div>
+ );
+ });
+ }
+
+ const footer = (
+ <>
+ <div className="mr-auto flex min-w-0 flex-col justify-center gap-0.5 self-center">
+ {onClear !== undefined && workspace.trim() !== "" && (
+ <button
+ type="button"
+ onClick={() => onClear(machine)}
+ className="self-start text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
+ >
+ {clearLabel}
+ </button>
+ )}
+ <p className="line-clamp-2 text-xs leading-5 text-gray-400 dark:text-gray-500">{hint}</p>
+ </div>
+ {/* The buttons keep their width; on a phone the hint beside them wraps instead. */}
+ <Button size="sm" className="shrink-0 self-center whitespace-nowrap" onClick={onClose}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ className="shrink-0 self-center whitespace-nowrap"
+ disabled={chooseTarget === null || loading}
+ title={chooseTarget ?? undefined}
+ onClick={choose}
+ >
+ {f.choose}
+ </Button>
+ </>
+ );
+
+ return (
+ <Modal
+ open={open}
+ title={title}
+ onClose={onClose}
+ bare
+ fullScreenOnPhone
+ widthClass="sm:h-[min(36rem,85vh)] sm:max-w-3xl"
+ footer={footer}
+ >
+ <div className="flex min-h-0 flex-1 flex-col" onKeyDown={onKeyDown} {...menuProps}>
+ {toolbar}
+ <div className="relative flex min-h-0 flex-1">
+ {sidebar}
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex items-center gap-2 border-b border-gray-100 py-1 pl-3 pr-2 text-xs text-gray-400 dark:border-gray-800 dark:text-gray-500">
+ <span className="min-w-0 flex-1 pl-6">{f.columnName}</span>
+ <span className="hidden w-36 shrink-0 sm:block">{f.columnModified}</span>
+ <span className="w-6 shrink-0" aria-hidden />
+ </div>
+ <div
+ ref={listRef}
+ id={listId}
+ // Its empty space is the folder on screen, for the context menu.
+ data-finder-here=""
+ // A listbox only while it holds rows: a message (empty, loading, an error with
+ // its Retry) is not an option, and the pane stays focusable either way so the
+ // keyboard chords keep working from it.
+ role={hasRows ? "listbox" : "region"}
+ tabIndex={0}
+ aria-label={crumbs[crumbs.length - 1]?.label ?? title}
+ aria-busy={loading}
+ {...(selIndex !== -1 ? { "aria-activedescendant": `${listId}-${selIndex}` } : {})}
+ onFocus={() => setListFocused(true)}
+ onBlur={() => setListFocused(false)}
+ className={`min-h-0 flex-1 overflow-y-auto py-1 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/40 ${
+ loading && view.listing !== null ? "opacity-60" : ""
+ }`}
+ >
+ {body}
+ </div>
+ </div>
+ </div>
+ </div>
+ {/* The context menu: `contents` keeps the wrapper out of the layout — the panel is
+ portaled, and it hangs off the point the gesture landed on. */}
+ {menuTarget !== null && (
+ <Dropdown
+ open={menu.open}
+ // The target is cleared where the menu really closes (an item ran): a dismiss is not
+ // always believed — a touch screen replays the held press as an outside click.
+ setOpen={menu.setOpen}
+ portal={{ direction: "down", align: "left" }}
+ anchorRect={menu.anchor}
+ anchorOwner={menu.anchorOwner}
+ // A sidebar place hands Escape back to its own button; a list row, which is no
+ // control of its own, to the list.
+ returnFocus={() =>
+ menu.anchorOwner()?.querySelector<HTMLElement>("[data-finder-focus]") ?? listRef.current
+ }
+ className="contents"
+ menuClass="w-max min-w-40 max-w-[calc(100vw-2rem)]"
+ button={null}
+ >
+ {finderMenuItems(menuTarget, inQuickAccess(menuTarget.path, menuTarget.machine)).map(
+ (item) => (
+ <button
+ key={item}
+ type="button"
+ className={overflowMenuRowClass}
+ onClick={() => runMenuItem(item, menuTarget)}
+ >
+ {overflowMenuGlyph(MENU_ICON[item])}
+ {menuLabel(item, menuTarget)}
+ </button>
+ ),
+ )}
+ </Dropdown>
+ )}
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/chat/workspace-select.tsx b/packages/web/src/features/chat/workspace-select.tsx
index 76739b06..7b7c5cf5 100644
--- a/packages/web/src/features/chat/workspace-select.tsx
+++ b/packages/web/src/features/chat/workspace-select.tsx
@@ -1,34 +1,25 @@
/**
- * Workspace picker: which directory, and — when more than one machine is reachable — which
- * MACHINE it is on. A workspace is a directory on a machine, so choosing one is choosing
- * where the path has to exist; the browser lists that machine's filesystem, over the tunnel
- * when it is not this one. The row only appears when there is a choice to make.
+ * Workspace picker triggers: which directory, and — when machines can be chosen — which
+ * MACHINE it is on. A workspace is a directory on a machine, so choosing one is choosing where
+ * the path has to exist; the finder lists that machine's filesystem, over ssh when it is not
+ * this one.
*
- * Extracted from draft-view.tsx so the Project settings dialog's
- * "new chat defaults" section can offer the same dir-browser popover the chat draft uses.
- * Two trigger variants, one menu:
- * - "pill" (default): the draft page's pill trigger with viewport-docked in-flow menu —
- * moved verbatim, unchanged markup/classes/behavior;
- * - "form": the shared FormPicker (full-width Input/Select-styled trigger, portaled menu) —
- * a dialog's overflow-y-auto content area would clip an in-flow panel, and the portal
- * tier (z-[60]) clears the Modal overlay.
+ * Three trigger shapes open the same Finder-style modal (workspace-finder.tsx):
+ * - "pill" (default): the draft page's compact toolbar pill;
+ * - "form": the shared form-control trigger (FormPickerTrigger), for dialogs — the finder is a
+ * Modal of its own and stacks above the host dialog;
+ * - `trigger`: a caller-rendered button (the sidebar's new-workspace header button).
*/
-import { useCallback, useEffect, useRef, useState } from "react";
-import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";
-import type { DirListResponse } from "@prismshadow/penguin-server/api";
-import * as api from "../../api/endpoints";
+import { useState } from "react";
+import type { ReactNode } from "react";
import { S } from "../../lib/strings";
-import { apiErrorText } from "../../lib/api-error";
import { Chevron } from "../../components/ui/chevron";
-import { Dropdown } from "../../components/ui/dropdown";
-import { FormPicker } from "../../components/ui/form-picker";
-import { noAutofill } from "../../components/ui/input";
-import { toastError } from "../../components/ui/toast";
+import { FormPickerTrigger } from "../../components/ui/form-picker";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { FOLDER_ICON } from "../../components/ui/group-list";
import { ICON_SIZE } from "../../lib/icon-scale";
-import { machineLabel, workspaceMachines } from "../../lib/workspace-machines";
-import type { WorkspaceMachine } from "../../lib/workspace-machines";
+import { WorkspaceFinder } from "./workspace-finder";
+import { baseName } from "./workspace-finder-model";
/** Shared style for pill trigger buttons (ChatGPT project button style: small rounded pill + icon + short name + collapse arrow). */
export const pillClass =
@@ -37,12 +28,9 @@ export const pillClass =
"dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";
/**
- * Workspace selection (pill dropdown): the button shows the selected directory name (empty =
- * a temporary workspace). The menu browses server-side directories: **the current path can be
- * edited directly** at the top (Enter/blur commits it, an invalid directory toasts and reverts
- * to the previous path), the list omits hidden directories, and the hint text sits at the bottom
- * of the menu; only loads on first expand. On narrow screens the menu docks to whichever side
- * of the pill keeps it inside the viewport (measured on open — see menuDock).
+ * Workspace selection: the trigger shows the selected directory's name (empty = a temporary
+ * workspace, or the host's `emptyLabel`) and opens the finder. Callers get `onChange(path,
+ * machineId)` on Choose, and `onChange("", machineId)` from the finder's clear link.
*/
export function WorkspaceSelect({
projectId,
@@ -63,21 +51,20 @@ export function WorkspaceSelect({
onChange: (path: string, machineId?: string | null) => void;
/** The machine to browse first; omitted starts on the window's current server. */
machineId?: string | null;
- /** Offer the machine row. Off where a machine cannot be meaningfully chosen yet. */
+ /** Offer the Machines section. Off where a machine cannot be meaningfully chosen yet. */
chooseMachine?: boolean;
/** Trigger style: the draft page's pill (default), or a dialog form control (see the header comment). */
variant?: "pill" | "form";
/**
- * Caller-rendered trigger (the sidebar's 新建工作区 header button): replaces the pill
- * and switches the panel to the shared body portal — the sidebar's scroller would
- * clip an in-flow panel. The same browse menu, byte for byte.
+ * Caller-rendered trigger (the sidebar's new-workspace header button): replaces the pill. The
+ * same finder opens from it.
*/
trigger?: (open: boolean, toggle: () => void) => ReactNode;
/**
* Copy overrides for a host that browses for a directory which is not going to be a Workspace —
* the Agent create dialog picks one to read Skills out of, where "temporary workspace" would
* describe something this field does not do. `fieldLabel` names the field itself: it is the
- * accessible name of both triggers and of the path input, and the label the tooltip puts in
+ * accessible name of both triggers and the finder's title, and the label the tooltip puts in
* front of the picked path, so a host that overrides the visible copy is not left announcing
* itself as "Workspace".
*/
@@ -89,423 +76,86 @@ export function WorkspaceSelect({
}) {
const fieldName = fieldLabel ?? S.chat.workspace;
const [open, setOpen] = useState(false);
- /**
- * The machine being browsed. Its OWN state rather than a prop: picking a machine re-roots
- * the browser without touching the window's active server, which is the whole point —
- * a workspace on another machine is chosen from here, not by going there.
- *
- * Starts on this machine unless the caller names one — a workspace being edited that
- * already lives elsewhere. The window itself never moves, so "here" is always the honest
- * starting point.
- */
- const [machine, setMachine] = useState<string | null>(machineId ?? null);
- const [machines, setMachines] = useState<WorkspaceMachine[]>([]);
- const [machineOpen, setMachineOpen] = useState(false);
- /**
- * Menu docking, measured on each open: the pill follows the agent pill in a wrapping row, so
- * its left offset varies with the agent's name — a statically left-anchored 20rem panel can
- * cross the viewport's right edge on phones (measured ~143px past a 390px viewport). Keep the
- * desktop left anchoring whenever the panel fits; otherwise dock to whichever side of the
- * pill has more room, capping the width to that room via menuStyle. On desktop the panel
- * always fits, so nothing changes there.
- */
- const [menuDock, setMenuDock] = useState<{ right: boolean; maxWidth?: number }>({
- right: false,
- });
- const browsedRef = useRef(false);
-
- const [dir, setDir] = useState<DirListResponse | null>(null);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- /** Edit draft for the path row: synced with the browsing position, reverts on a failed commit. */
- const [pathDraft, setPathDraft] = useState("");
-
- useEffect(() => {
- setPathDraft(dir?.path ?? "");
- }, [dir]);
-
- /**
- * Monotonic id of the newest loadDir request. Only the newest request may publish its
- * result: navigations race (rows stay visible while a fetch is in flight, and the path row
- * accepts commits at any time), and without the guard a slow older response would overwrite
- * a newer one — silently relocating the browsing position — or clear `loading` while the
- * newer request is still in flight.
- */
- const loadSeq = useRef(0);
-
- /**
- * Browses level by level (clicking a directory/parent); an empty string means the server's
- * home directory (the default starting point). `onError` overrides the default error-row
- * handling (the path-edit commit toasts and reverts instead); it only ever fires for the
- * newest request, like every other outcome.
- */
- const loadDir = useCallback(
- (abs: string, opts?: { onError?: () => void }) => {
- const seq = ++loadSeq.current;
- setLoading(true);
- setError(null);
- api
- .listDirs(projectId, abs, machine)
- .then((res) => {
- if (seq === loadSeq.current) setDir(res);
- })
- .catch((e: unknown) => {
- if (seq !== loadSeq.current) return;
- if (opts?.onError) opts.onError();
- else setError(apiErrorText(e));
- })
- .finally(() => {
- if (seq === loadSeq.current) setLoading(false);
- });
- },
- [projectId, machine],
- );
-
- /**
- * loadDir through a ref: the machine row renders above the browser but has to drive it,
- * and the callback is rebuilt whenever the machine changes — a direct reference captured
- * at render time would browse the machine we just left.
- */
- const loadDirRef = useRef<(machineId: string | null) => void>(() => {});
- loadDirRef.current = (nextMachine: string | null) => {
- const seq = ++loadSeq.current;
- setLoading(true);
- setError(null);
- api
- .listDirs(projectId, "", nextMachine)
- .then((res) => {
- if (seq === loadSeq.current) setDir(res);
- })
- .catch((e: unknown) => {
- if (seq === loadSeq.current) setError(apiErrorText(e));
- })
- .finally(() => {
- if (seq === loadSeq.current) setLoading(false);
- });
- };
-
- // Only loads on first expand: an already-filled absolute path is used as the starting point, otherwise the server falls back to the home directory.
- const loadOnFirstOpen = (next: boolean) => {
- if (next && !browsedRef.current) {
- browsedRef.current = true;
- const ws = workspace.trim();
- loadDir(ws.startsWith("/") ? ws : "");
- }
- };
-
- /** Form-variant open handler (FormPicker owns the trigger): portaled, so no dock measurement — just open + lazy load. */
- const setFormOpen = (next: boolean) => {
- setOpen(next);
- loadOnFirstOpen(next);
- };
-
- /** Pill-variant trigger: measures viewport room to dock the in-flow panel left/right before opening. */
- const toggle = (e: ReactMouseEvent<HTMLButtonElement>) => {
- const next = !open;
- if (next) {
- const r = e.currentTarget.getBoundingClientRect();
- const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
- const margin = 12; // breathing room against the viewport edge
- // The panel's effective width: w-80 capped by its max-w-[calc(100vw-2rem)] class
- // (rem-derived — the root font size is not 16px here).
- const width = Math.min(20 * rem, window.innerWidth - 2 * rem);
- const roomRight = window.innerWidth - margin - r.left; // room for a left-anchored panel
- const roomLeft = r.right - margin; // room for a right-anchored panel
- if (roomRight >= width) setMenuDock({ right: false });
- else if (roomLeft > roomRight)
- setMenuDock({ right: true, ...(roomLeft < width ? { maxWidth: roomLeft } : {}) });
- else setMenuDock({ right: false, maxWidth: roomRight });
- }
- setOpen(next);
- loadOnFirstOpen(next);
- };
-
- /**
- * Commits the edited path: navigates to it if it exists, otherwise toasts and reverts to
- * the current browsing position. Routed through loadDir so the commit shows the loading
- * row and participates in the same request sequencing as row clicks — a raw listDirs here
- * used to race them and could land after (and clobber) a newer navigation.
- */
- const commitPathEdit = () => {
- const p = pathDraft.trim();
- if (!p || p === dir?.path) {
- setPathDraft(dir?.path ?? "");
- return;
- }
- loadDir(p, {
- onError: () => {
- toastError(S.chat.workspaceDirInvalid);
- setPathDraft(dir?.path ?? "");
- },
- });
- };
const trimmed = workspace.trim();
- // Pill short name: the last segment of the directory name (root gives "/"); shows "temporary workspace" when empty.
- const label = trimmed
- ? (trimmed.split("/").filter(Boolean).pop() ?? "/")
- : (emptyLabel ?? S.chat.workspaceAuto);
- const parentPath = dir?.parent ?? null;
- // Hidden directories (starting with .) are excluded from the list.
- const entries = (dir?.entries ?? []).filter((e) => !e.name.startsWith("."));
- // The machines a workspace can live on: this PROJECT's machines, from the LOCAL server —
- // the list is its own, whichever server the rest of the window is using.
- useEffect(() => {
- if (!open || chooseMachine !== true) return;
- let cancelled = false;
- void api
- .getMachines(projectId)
- .then((res) => {
- if (!cancelled) setMachines(workspaceMachines(res));
- })
- .catch(() => undefined);
- return () => {
- cancelled = true;
- };
- }, [open, chooseMachine, projectId]);
+ // Short name: the last segment of the directory (a root keeps its own spelling); "temporary workspace" when empty.
+ const label = trimmed ? baseName(trimmed) : (emptyLabel ?? S.chat.workspaceAuto);
+ const hint = menuHint ?? S.chat.workspaceHint;
+ const title = trimmed ? `${fieldName}:${trimmed}` : hint;
- /**
- * The row is shown whenever this surface offers machines at all — NOT only when more than
- * one is reachable. A control that disappears when the answer is "just this one" reads as
- * a missing feature, and leaves someone with 45 hosts in their ssh config wondering why
- * they cannot pick any of them. Showing it with one entry, plus a line saying how many
- * are a connect away, answers that question where hiding it asked a new one.
- */
- const machineRow = chooseMachine === true && machines.length > 0;
+ const finder = (
+ <WorkspaceFinder
+ open={open}
+ onClose={() => setOpen(false)}
+ onChoose={(path, machine) => {
+ onChange(path, machine);
+ setOpen(false);
+ }}
+ onClear={(machine) => {
+ onChange("", machine);
+ setOpen(false);
+ }}
+ projectId={projectId}
+ workspace={workspace}
+ machineId={machineId}
+ chooseMachine={chooseMachine}
+ title={fieldName}
+ hint={hint}
+ clearLabel={clearLabel ?? S.chat.workspaceClear}
+ />
+ );
- /** Folder glyph shared by both triggers. */
+ /** Folder glyph shared by both built-in triggers. */
const folderIcon = (extraClass: string) => (
<GlyphIcon d={FOLDER_ICON} size={ICON_SIZE.rowLead} className={`text-gray-400 ${extraClass}`} />
);
- const menu = (
- <div className="space-y-1.5 px-2.5 pb-2.5 pt-2">
- {/* Which machine's filesystem is being browsed. Changing it re-roots the browser at
- that machine's home directory — a path is only meaningful on the machine it is on,
- so carrying the current one across would be a path that likely does not exist. */}
- {machineRow && (
- <Dropdown
- open={machineOpen}
- setOpen={setMachineOpen}
- menuClass="left-0 right-0 top-full mt-1 origin-top"
- button={
- <button
- type="button"
- onClick={() => setMachineOpen(!machineOpen)}
- aria-haspopup="listbox"
- aria-expanded={machineOpen}
- className="flex w-full items-center gap-1.5 rounded-md border border-gray-200 px-2 py-1 text-left text-xs text-gray-600 transition-colors hover:bg-gray-50 dark:border-gray-800 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- <span className="min-w-0 flex-1 truncate">
- {machineLabel(machines, machine) ?? S.chat.workspaceMachine}
- </span>
- <Chevron open={machineOpen} />
- </button>
- }
- >
- {machines.map((entry, index) => (
- <button
- key={entry.selectable ? (entry.id ?? "local") : `unusable-${index}`}
- type="button"
- disabled={!entry.selectable}
- onClick={() => {
- setMachineOpen(false);
- if (entry.id === machine) return;
- setMachine(entry.id);
- // Start over at that machine's home directory.
- loadDirRef.current(entry.id);
- }}
- className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:hover:bg-transparent dark:hover:bg-gray-800 dark:disabled:hover:bg-transparent"
- >
- <span
- className={`min-w-0 flex-1 truncate ${entry.selectable ? "" : "text-gray-400 dark:text-gray-500"}`}
- >
- {entry.label}
- </span>
- {entry.local && (
- <span className="shrink-0 text-gray-400">{S.chat.workspaceHere}</span>
- )}
- {/* A machine that cannot be browsed is shown, disabled, saying why — right
- where "why can I not pick that one?" is asked. Leaving it out, or counting
- it in a footnote, answers somewhere the question was not. */}
- {entry.reason !== undefined && (
- <span className="shrink-0 text-gray-400 dark:text-gray-500">
- {S.chat.workspaceMachineWhy[entry.reason]}
- </span>
- )}
- </button>
- ))}
- </Dropdown>
- )}
- <div className="rounded-md border border-gray-200 dark:border-gray-800">
- {/* Current path (editable: Enter/blur commits, Escape discards) + "Use this directory" (closes the menu once selected) */}
- <div className="flex items-center gap-1.5 border-b border-gray-100 px-1.5 py-1 dark:border-gray-800">
- <input
- value={pathDraft}
- placeholder="…"
- aria-label={fieldName}
- {...noAutofill}
- onChange={(e) => setPathDraft(e.target.value)}
- onBlur={commitPathEdit}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.nativeEvent.isComposing) {
- e.preventDefault();
- commitPathEdit();
- } else if (e.key === "Escape") {
- // Discard the edit: only reverts the draft; Escape bubbles up to Dropdown, which closes the menu.
- setPathDraft(dir?.path ?? "");
- }
- }}
- className="min-w-0 flex-1 rounded border border-transparent bg-transparent px-1 py-0.5 font-mono text-xs text-gray-600 focus:border-gray-300 focus:outline-none dark:text-gray-300 dark:focus:border-gray-600"
- />
- <button
- type="button"
- disabled={!dir}
- onClick={() => {
- if (!dir) return;
- onChange(dir.path, machine);
- setOpen(false);
- }}
- className="shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- {S.chat.workspaceUseThis}
- </button>
- </div>
- {/* Directory list (excludes hidden directories) */}
- <ul className="max-h-40 overflow-y-auto py-1">
- {/* Rows are disabled while a load is in flight: they still show the PREVIOUS
- directory until the response lands, so clicks during the window would resend
- stale targets (N clicks on "parent" all resending the same dir.parent). */}
- {parentPath !== null && (
- <li>
- <button
- type="button"
- disabled={loading}
- onClick={() => loadDir(parentPath)}
- className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800"
- >
- ↰ {S.chat.workspaceUp}
- </button>
- </li>
- )}
- {entries.map((entry) => (
- <li key={entry.path}>
- <button
- type="button"
- disabled={loading}
- onClick={() => loadDir(entry.path)}
- className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- <GlyphIcon d={FOLDER_ICON} className="text-gray-400" />
- <span className="min-w-0 flex-1 truncate" title={entry.name}>
- {entry.name}
- </span>
- </button>
- </li>
- ))}
- {dir && entries.length === 0 && (
- <li className="px-2.5 py-1.5 text-xs text-gray-400">{S.chat.workspaceNoSubdirs}</li>
- )}
- {loading && <li className="px-2.5 py-1.5 text-xs text-gray-400">{S.common.loading}</li>}
- {/* Load failure (e.g. the cached starting directory was deleted): provide "retry" to fall back to the home directory, avoiding getting stuck in an error state. */}
- {error && (
- <li className="flex items-center justify-between gap-2 px-2.5 py-1.5 text-xs text-red-500">
- <span className="min-w-0 flex-1 truncate" title={error}>
- {error}
- </span>
- <button
- type="button"
- disabled={loading}
- onClick={() => loadDir("")}
- className="shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- {S.common.retry}
- </button>
- </li>
- )}
- </ul>
- </div>
- {/* When a directory has been specified, offer a one-click way back to a temporary workspace */}
- {trimmed && (
- <button
- type="button"
- onClick={() => {
- onChange("", machine);
- setOpen(false);
- }}
- className="text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
- >
- {clearLabel ?? S.chat.workspaceClear}
- </button>
- )}
- {/* Hint text (bottom of the menu) */}
- <p className="px-0.5 text-xs leading-5 text-gray-400 dark:text-gray-500">
- {menuHint ?? S.chat.workspaceHint}
- </p>
- </div>
- );
- // Custom trigger (sidebar header): portaled panel, right-aligned under the trigger —
- // placement and flipping are the portal's job, so no dock measurement here. w-64
- // (the Dropdown default menu width): the pill/form variants' w-80 overhung the
- // sidebar; long entry names truncate with their full text in the row tooltip.
if (trigger) {
return (
- <Dropdown
- open={open}
- setOpen={setFormOpen}
- portal={{ direction: "down", align: "right" }}
- menuClass="w-64"
- button={trigger(open, () => setFormOpen(!open))}
- >
- {menu}
- </Dropdown>
+ <>
+ {trigger(open, () => setOpen(!open))}
+ {finder}
+ </>
);
}
// Form: the shared full-width trigger (its label goes mono once a real path is set).
if (variant === "form") {
return (
- <FormPicker
- size="sm"
- open={open}
- setOpen={setFormOpen}
- leading={folderIcon("")}
- label={label}
- {...(trimmed ? { labelClassName: "font-mono" } : {})}
- title={trimmed ? `${fieldName}:${trimmed}` : (menuHint ?? S.chat.workspaceHint)}
- ariaLabel={fieldName}
- ariaHaspopup="dialog"
- menuClass="w-80"
- >
- {menu}
- </FormPicker>
+ <>
+ <FormPickerTrigger
+ size="sm"
+ expanded={open}
+ onClick={() => setOpen(!open)}
+ leading={folderIcon("")}
+ label={label}
+ {...(trimmed ? { labelClassName: "font-mono" } : {})}
+ title={title}
+ ariaLabel={fieldName}
+ ariaHaspopup="dialog"
+ />
+ {finder}
+ </>
);
}
- // Pill: the composer's compact toolbar trigger, with the in-flow panel docked left/right by `toggle`'s measurement.
+ // Pill: the composer's compact toolbar trigger.
return (
- <Dropdown
- open={open}
- setOpen={setOpen}
- menuClass={`top-full mt-1 w-80 max-w-[calc(100vw-2rem)] ${
- menuDock.right ? "right-0 origin-top-right" : "left-0 origin-top-left"
- }`}
- {...(menuDock.maxWidth !== undefined ? { menuStyle: { maxWidth: menuDock.maxWidth } } : {})}
- button={
- <button
- type="button"
- title={trimmed ? `${fieldName}:${trimmed}` : (menuHint ?? S.chat.workspaceHint)}
- aria-label={fieldName}
- onClick={toggle}
- className={pillClass}
- >
- {folderIcon("ml-0.5")}
- <span className={`min-w-0 truncate ${trimmed ? "font-mono" : ""}`}>{label}</span>
- <Chevron open={open} size={12} className="shrink-0 text-gray-400" />
- </button>
- }
- >
- {menu}
- </Dropdown>
+ <>
+ <button
+ type="button"
+ title={title}
+ aria-label={fieldName}
+ aria-haspopup="dialog"
+ aria-expanded={open}
+ onClick={() => setOpen(!open)}
+ className={pillClass}
+ >
+ {folderIcon("ml-0.5")}
+ <span className={`min-w-0 truncate ${trimmed ? "font-mono" : ""}`}>{label}</span>
+ <Chevron open={open} size={12} className="shrink-0 text-gray-400" />
+ </button>
+ {finder}
+ </>
);
}
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index 1f905f9e..947b8d87 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -223,6 +223,12 @@ export const KEY_RULES: readonly KeyRule[] = [
scope: "install",
why: "Manually registered Workspace paths per Project; a new root has no such Project.",
},
+ {
+ kind: "family",
+ key: "penguin.finderQuickAccess.",
+ scope: "install",
+ why: "Folders added to and removed from the Workspace finder's Quick access, keyed by machine id and holding paths on the machines of this root — the same kind of state as the registered Workspace paths.",
+ },
{
kind: "family",
key: "penguin.pinnedSessions.",
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 47d5d9ec..bdf56dbe 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2172,19 +2172,62 @@ export const en: Strings = {
`Context compacted; thinking level switched to "${to}".`,
thinkingSwitchCompactFailed:
"The compaction did not finish; the thinking level was switched anyway.",
- /** The machine a workspace lives on; the row only shows when more than one is reachable. */
- workspaceMachine: "Machine",
workspaceHere: "here",
/** Why a listed machine cannot be picked — shown ON its row, where the question is asked. */
workspaceMachineWhy: {
"no-identity": "not identified",
},
- workspaceUseThis: "Use this dir",
- workspaceUp: "Parent dir",
- workspaceNoSubdirs: "No subdirectories",
workspaceAuto: "Temporary workspace",
workspaceClear: "Use a temporary workspace instead",
workspaceDirInvalid: "Directory does not exist or is inaccessible; reverted",
+ /** The Workspace finder: the modal the Workspace pickers open (workspace-finder.tsx). */
+ finder: {
+ choose: "Choose",
+ back: "Back",
+ forward: "Forward",
+ up: "Up",
+ refresh: "Refresh",
+ address: "Path",
+ addressPlaceholder: "An absolute path, or one starting with ~",
+ editPath: "Edit path",
+ filter: "Filter",
+ showSidebar: "Show sidebar",
+ hideSidebar: "Hide sidebar",
+ quickAccess: "Quick access",
+ thisPc: "This PC",
+ recent: "Recent",
+ machines: "Machines",
+ places: {
+ desktop: "Desktop",
+ documents: "Documents",
+ downloads: "Downloads",
+ pictures: "Pictures",
+ },
+ documentsMac: "Documents",
+ addToQuickAccess: "Add to Quick access",
+ removeFromQuickAccess: "Remove from Quick access",
+ addCurrentToQuickAccess: "Add the current folder to Quick access",
+ removeNamed: (name: string): string => `Remove ${name} from Quick access`,
+ open: "Open",
+ openFolder: (name: string): string => `Open ${name}`,
+ chooseThis: "Choose this folder",
+ chooseCurrent: "Choose the current folder",
+ copyPath: "Copy path",
+ /** Accessible name of the breadcrumb trail. */
+ path: "Current path",
+ columnName: "Name",
+ columnModified: "Date modified",
+ /** Tooltip on a file row: files are listed for context but cannot be picked. */
+ fileNotSelectable: "Only folders can be chosen",
+ 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.",
+ loadFailed: "Can't open this folder",
+ },
/** Sidebar conversation-list grouping toggle (workspace is the default) + workspace groups. */
groupByWorkspace: "Group by workspace",
groupByAgent: "Group by agent",
@@ -4589,6 +4632,7 @@ Scenarios:
image_too_large: "The image is too large to send inline.",
dir_not_absolute: "The directory must be an absolute path.",
dir_not_found: "That directory does not exist or is inaccessible.",
+ dir_permission_denied: "Reading that directory is not allowed.",
not_a_dir: "That path is not a directory.",
path_not_found: "That path does not exist.",
reveal_failed: "Could not open the folder.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 20ef9f38..ddc90d15 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2207,19 +2207,70 @@ export const zh = {
thinkingSwitchApplied: (to: string): string => `上下文已压缩,思考等级已切换为「${to}」。`,
/** Compaction ended without completing — the switch still applies, so say both. */
thinkingSwitchCompactFailed: "压缩未成功完成,思考等级已照常切换。",
- /** The machine a workspace lives on; the row only shows when more than one is reachable. */
- workspaceMachine: "机器",
workspaceHere: "本机",
/** Why a listed machine cannot be picked — shown ON its row, where the question is asked. */
workspaceMachineWhy: {
"no-identity": "待识别",
},
- workspaceUseThis: "使用此目录",
- workspaceUp: "上级目录",
- workspaceNoSubdirs: "无子目录",
workspaceAuto: "临时工作区",
workspaceClear: "改用临时工作区",
workspaceDirInvalid: "目录不存在或无法访问,已回退",
+ /** The Workspace finder: the modal the Workspace pickers open (workspace-finder.tsx). */
+ finder: {
+ choose: "选择",
+ back: "后退",
+ forward: "前进",
+ /** Toolbar: the parent folder. */
+ up: "上一级",
+ refresh: "刷新",
+ /** The address bar turned into a text field: its accessible name and placeholder. */
+ address: "路径",
+ addressPlaceholder: "输入绝对路径,或以 ~ 开头",
+ /** What clicking the address bar does (also ⌘⇧G / Ctrl+Shift+G). */
+ editPath: "编辑路径",
+ filter: "筛选",
+ showSidebar: "显示侧边栏",
+ hideSidebar: "隐藏侧边栏",
+ quickAccess: "常用",
+ /** Windows only: the section listing the drives. */
+ thisPc: "此电脑",
+ recent: "最近使用",
+ machines: "机器",
+ places: {
+ desktop: "桌面",
+ documents: "文档",
+ downloads: "下载",
+ pictures: "图片",
+ },
+ /** Finder's own name for Documents, used when the browsed machine is a Mac. */
+ documentsMac: "文稿",
+ addToQuickAccess: "添加到常用",
+ removeFromQuickAccess: "从常用中移除",
+ /** The + beside the Quick access heading. */
+ addCurrentToQuickAccess: "将当前文件夹添加到常用",
+ /** Accessible name of a Quick access row's remove button. */
+ removeNamed: (name: string): string => `从常用中移除「${name}」`,
+ open: "打开",
+ /** Accessible name of the enter button at the end of a folder row. */
+ openFolder: (name: string): string => `打开「${name}」`,
+ chooseThis: "选择此文件夹",
+ chooseCurrent: "选择当前文件夹",
+ copyPath: "复制路径",
+ /** Accessible name of the breadcrumb trail. */
+ path: "当前路径",
+ columnName: "名称",
+ columnModified: "修改日期",
+ /** Tooltip on a file row: files are listed for context but cannot be picked. */
+ fileNotSelectable: "只能选择文件夹",
+ empty: "此文件夹为空",
+ noMatch: (q: string): string => `没有名称包含「${q}」的项目`,
+ deniedTitle: "无法读取此文件夹",
+ /** The server runs on macOS and privacy protection refused the folder. */
+ deniedMac:
+ "macOS 阻止了对此文件夹的访问。请在「系统设置 → 隐私与安全性 → 文件与文件夹」中允许访问后重试。",
+ denied: "运行服务的账户没有读取此文件夹的权限。",
+ loadFailed: "无法打开此文件夹",
+ },
/** Grouping toggle of the sidebar conversation list (workspace grouping is the default) and the workspace groups. */
groupByWorkspace: "按工作区分组",
groupByAgent: "按智能体分组",
@@ -4593,6 +4644,7 @@ Benchmark:
image_too_large: "图片过大,无法随对话发送。",
dir_not_absolute: "目录必须是绝对路径。",
dir_not_found: "该目录不存在或不可访问。",
+ dir_permission_denied: "没有读取该目录的权限。",
not_a_dir: "该路径不是目录。",
path_not_found: "该路径不存在。",
reveal_failed: "无法打开文件夹。",
diff --git a/packages/web/test/workspace-finder.test.ts b/packages/web/test/workspace-finder.test.ts
new file mode 100644
index 00000000..1587ee3c
--- /dev/null
+++ b/packages/web/test/workspace-finder.test.ts
@@ -0,0 +1,346 @@
+/**
+ * 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.
+ */
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+import type { DirEntryInfo, DirListResponse } from "@prismshadow/penguin-server/api";
+import {
+ EMPTY_HISTORY,
+ NO_EDITS,
+ addToQuickAccess,
+ canGoBack,
+ canGoForward,
+ defaultPlaces,
+ drivePlaces,
+ finderKeyAction,
+ finderMenuItems,
+ historyStep,
+ historyVisit,
+ loadQuickAccess,
+ parentOf,
+ quickAccessKey,
+ quickAccessPlaces,
+ recentWorkspaces,
+ removeFromQuickAccess,
+ resolveGoTo,
+ saveQuickAccess,
+ splitBreadcrumbs,
+ stepSelection,
+ typeSelectIndex,
+ visibleEntries,
+} from "../src/features/chat/workspace-finder-model";
+import type { QuickAccessStorage } from "../src/features/chat/workspace-finder-model";
+
+const dir = (name: string, kind: "dir" | "file" = "dir"): DirEntryInfo => ({
+ name,
+ path: `/p/${name}`,
+ kind,
+});
+
+describe("breadcrumbs", () => {
+ it("splits a posix path from the root", () => {
+ expect(splitBreadcrumbs("/Users/me/Downloads")).toEqual([
+ { label: "/", path: "/" },
+ { label: "Users", path: "/Users" },
+ { label: "me", path: "/Users/me" },
+ { label: "Downloads", path: "/Users/me/Downloads" },
+ ]);
+ expect(splitBreadcrumbs("/")).toEqual([{ label: "/", path: "/" }]);
+ });
+
+ it("keeps a drive root whole, so no crumb is drive-relative", () => {
+ expect(splitBreadcrumbs("C:\\Users\\me").map((c) => c.path)).toEqual([
+ "C:\\",
+ "C:\\Users",
+ "C:\\Users\\me",
+ ]);
+ expect(splitBreadcrumbs("C:\\")[0]).toEqual({ label: "C:", path: "C:\\" });
+ expect(parentOf("C:\\Users")).toBe("C:\\");
+ expect(parentOf("/")).toBeNull();
+ });
+});
+
+describe("history", () => {
+ it("goes back and forward, and a new visit drops what was ahead", () => {
+ let h = historyVisit(historyVisit(historyVisit(EMPTY_HISTORY, "/a"), "/a/b"), "/a/b/c");
+ h = historyStep(h, -1);
+ expect(h.entries[h.index]).toBe("/a/b");
+ expect([canGoBack(h), canGoForward(h)]).toEqual([true, true]);
+ h = historyVisit(h, "/x");
+ expect(h.entries).toEqual(["/a", "/a/b", "/x"]);
+ expect(canGoForward(h)).toBe(false);
+ });
+
+ it("does not record a reload of the folder already shown", () => {
+ const h = historyVisit(EMPTY_HISTORY, "/a");
+ expect(historyVisit(h, "/a")).toBe(h);
+ expect(historyStep(h, -1)).toBe(h);
+ });
+});
+
+describe("the list", () => {
+ const entries = visibleEntries(
+ [dir("zeta"), dir("notes.txt", "file"), dir(".git"), dir("Alpha"), dir("beta")],
+ "",
+ );
+
+ it("drops hidden entries and puts folders first", () => {
+ expect(entries.map((e) => e.name)).toEqual(["Alpha", "beta", "zeta", "notes.txt"]);
+ expect(visibleEntries(entries, "ET").map((e) => e.name)).toEqual(["beta", "zeta"]);
+ });
+
+ it("type-to-select finds a folder by prefix, never a file", () => {
+ expect(typeSelectIndex(entries, "b")).toBe(1);
+ expect(typeSelectIndex(entries, "ZE")).toBe(2);
+ expect(typeSelectIndex(entries, "no")).toBe(-1);
+ });
+
+ it("arrow keys skip files and stop at the ends", () => {
+ expect(stepSelection(entries, -1, 1)).toBe(0);
+ expect(stepSelection(entries, 2, 1)).toBe(2);
+ expect(stepSelection(entries, -1, -1)).toBe(2);
+ });
+});
+
+describe("keyboard map", () => {
+ type Mods = Partial<Record<"meta" | "ctrl" | "alt" | "shift", boolean>>;
+ const key = (k: string, mods: Mods = {}) => ({
+ key: k,
+ metaKey: mods.meta ?? false,
+ ctrlKey: mods.ctrl ?? false,
+ altKey: mods.alt ?? false,
+ shiftKey: mods.shift ?? false,
+ });
+
+ it("reads the Finder chords with ⌘ on a Mac and Ctrl elsewhere", () => {
+ expect(finderKeyAction(key("ArrowUp", { meta: true }), true, true)).toBe("parent");
+ expect(finderKeyAction(key("ArrowUp", { ctrl: true }), false, true)).toBe("parent");
+ expect(finderKeyAction(key("ArrowUp", { ctrl: true }), true, true)).toBeNull();
+ expect(finderKeyAction(key("[", { meta: true }), true, true)).toBe("back");
+ expect(finderKeyAction(key("]", { ctrl: true }), false, true)).toBe("forward");
+ expect(finderKeyAction(key("G", { meta: true, shift: true }), true, false)).toBe("goto");
+ expect(finderKeyAction(key("ArrowDown", { meta: true }), true, true)).toBe("open");
+ });
+
+ it("leaves Enter and Home/End to a text field, but lets Up/Down steer the list", () => {
+ expect(finderKeyAction(key("Enter"), false, true)).toBe("open");
+ expect(finderKeyAction(key("Enter"), false, false)).toBeNull();
+ expect(finderKeyAction(key("Home"), false, false)).toBeNull();
+ expect(finderKeyAction(key("ArrowDown"), false, false)).toBe("down");
+ });
+});
+
+describe("quick access", () => {
+ const folders = (base: string, names: string[], sep = "/"): DirEntryInfo[] =>
+ names.map((name) => ({ name, path: `${base}${sep}${name}`, kind: "dir" }));
+ const home = (over: Partial<DirListResponse>): DirListResponse => ({
+ path: "/home/me",
+ parent: "/home",
+ entries: [],
+ ...over,
+ });
+ const std = ["Desktop", "Documents", "Downloads", "Pictures", "Music", "Videos"];
+
+ it("offers each platform's own standard folders, in its file manager's order", () => {
+ const keys = (h: DirListResponse) => defaultPlaces(h).map((p) => p.key);
+ // Explorer: Desktop, Downloads, Documents, Pictures.
+ expect(
+ keys(
+ home({
+ path: "C:\\Users\\me",
+ platform: "win32",
+ entries: folders("C:\\Users\\me", std, "\\"),
+ }),
+ ),
+ ).toEqual(["home", "desktop", "downloads", "documents", "pictures"]);
+ // Finder: Desktop, Documents, Downloads — no Pictures.
+ expect(
+ keys(home({ path: "/Users/me", platform: "darwin", entries: folders("/Users/me", std) })),
+ ).toEqual(["home", "desktop", "documents", "downloads"]);
+ // A Linux desktop's XDG folders; a machine over ssh reports no platform and reads the same.
+ expect(keys(home({ platform: "linux", entries: folders("/home/me", std) }))).toEqual([
+ "home",
+ "desktop",
+ "documents",
+ "downloads",
+ "pictures",
+ ]);
+ expect(keys(home({ entries: folders("/home/me", std) }))).toEqual([
+ "home",
+ "desktop",
+ "documents",
+ "downloads",
+ "pictures",
+ ]);
+ });
+
+ it("lists only folders that exist there, and matches Windows names ignoring case", () => {
+ const linux = defaultPlaces(
+ home({
+ platform: "linux",
+ entries: [
+ { name: "Downloads", path: "/home/me/Downloads", kind: "dir" },
+ { name: "Documents", path: "/home/me/Documents", kind: "file" },
+ ],
+ }),
+ );
+ expect(linux.map((p) => [p.key, p.path])).toEqual([
+ ["home", "/home/me"],
+ ["downloads", "/home/me/Downloads"],
+ ]);
+ const win = defaultPlaces({
+ path: "C:\\Users\\me",
+ parent: "C:\\Users",
+ platform: "win32",
+ roots: ["C:\\", "D:\\"],
+ entries: [{ name: "documents", path: "C:\\Users\\me\\documents", kind: "dir" }],
+ });
+ expect(win.map((p) => [p.key, p.label])).toEqual([
+ ["home", "me"],
+ ["documents", "documents"],
+ ]);
+ });
+
+ it("keeps Windows' drives for This PC, apart from Quick access", () => {
+ const listing = home({ platform: "win32", roots: ["C:\\", "D:\\"] });
+ expect(drivePlaces(listing).map((p) => [p.key, p.label, p.path])).toEqual([
+ ["drive", "C:", "C:\\"],
+ ["drive", "D:", "D:\\"],
+ ]);
+ expect(defaultPlaces(listing).some((p) => p.key === "drive")).toBe(false);
+ expect(drivePlaces(home({ platform: "linux" }))).toEqual([]);
+ });
+
+ it("adds any folder at the end, and removes any entry — a default included", () => {
+ const defaults = defaultPlaces(home({ platform: "linux", entries: folders("/home/me", std) }));
+ const paths = (e: typeof NO_EDITS) => quickAccessPlaces(defaults, e).map((p) => p.path);
+ let edits = addToQuickAccess(NO_EDITS, defaults, "/srv/work");
+ expect(paths(edits).at(-1)).toBe("/srv/work");
+ expect(quickAccessPlaces(defaults, edits).at(-1)).toMatchObject({
+ key: "folder",
+ label: "work",
+ });
+ // Adding what is already there changes nothing.
+ expect(addToQuickAccess(edits, defaults, "/srv/work")).toBe(edits);
+ expect(addToQuickAccess(edits, defaults, "/home/me/Desktop")).toBe(edits);
+ // A removed default is remembered as removed, and adding it back restores it in place.
+ edits = removeFromQuickAccess(edits, defaults, "/home/me/Desktop");
+ expect(paths(edits)).not.toContain("/home/me/Desktop");
+ edits = addToQuickAccess(edits, defaults, "/home/me/Desktop");
+ expect(paths(edits).indexOf("/home/me/Desktop")).toBe(1);
+ // An added folder is simply forgotten.
+ edits = removeFromQuickAccess(edits, defaults, "/srv/work");
+ expect(edits).toEqual(NO_EDITS);
+ });
+
+ it("stores the edits per machine, and reads anything unreadable as none", () => {
+ const store = new Map<string, string>();
+ const storage: QuickAccessStorage = {
+ getItem: (k) => store.get(k) ?? null,
+ setItem: (k, v) => void store.set(k, v),
+ };
+ const edits = { added: ["/srv/work"], removed: ["/home/me/Desktop"] };
+ saveQuickAccess(null, edits, storage);
+ saveQuickAccess("m-1", NO_EDITS, storage);
+ expect(loadQuickAccess(null, storage)).toEqual(edits);
+ expect(loadQuickAccess("m-1", storage)).toEqual(NO_EDITS);
+ expect(quickAccessKey(null)).toBe("penguin.finderQuickAccess.local");
+ expect(quickAccessKey("m-1")).toBe("penguin.finderQuickAccess.m-1");
+ store.set(quickAccessKey("m-2"), "{not json");
+ expect(loadQuickAccess("m-2", storage)).toEqual(NO_EDITS);
+ store.set(quickAccessKey("m-3"), JSON.stringify({ added: ["/a", 3, ""], removed: "x" }));
+ expect(loadQuickAccess("m-3", storage)).toEqual({ added: ["/a"], removed: [] });
+ });
+});
+
+describe("the context menu", () => {
+ it("offers a folder open, choose, Quick access and copy; a file only copy", () => {
+ const folder = { kind: "folder" as const, path: "/p/a", machine: null };
+ expect(finderMenuItems(folder, false)).toEqual([
+ "open",
+ "choose",
+ "addToQuickAccess",
+ "copyPath",
+ ]);
+ expect(finderMenuItems(folder, true)).toContain("removeFromQuickAccess");
+ expect(finderMenuItems({ ...folder, kind: "file" }, false)).toEqual(["copyPath"]);
+ });
+
+ it("acts on the open folder from the list's empty space, with Refresh", () => {
+ expect(finderMenuItems({ kind: "here", path: "/p", machine: null }, false)).toEqual([
+ "choose",
+ "addToQuickAccess",
+ "copyPath",
+ "refresh",
+ ]);
+ });
+});
+
+describe("recent and go to folder", () => {
+ it("folds the newest Session per Workspace across Agents, temporary ones left out", () => {
+ const latest = new Map<string, Record<string, string>>([
+ ["a1", { "/srv/app": "2026-09-01T00:00:00.000Z", "/srv/old": "2026-08-01T00:00:00.000Z" }],
+ [
+ "a2",
+ {
+ "/srv/app": "2026-09-03T00:00:00.000Z",
+ "far\0/srv/app": "2026-09-02T00:00:00.000Z",
+ "\0temp-workspaces": "2026-09-09T00:00:00.000Z",
+ },
+ ],
+ ]);
+ expect(recentWorkspaces(latest, () => true)).toEqual([
+ { path: "/srv/app", machineId: null, at: "2026-09-03T00:00:00.000Z" },
+ { path: "/srv/app", machineId: "far", at: "2026-09-02T00:00:00.000Z" },
+ { path: "/srv/old", machineId: null, at: "2026-08-01T00:00:00.000Z" },
+ ]);
+ expect(recentWorkspaces(latest, (m) => m === null).map((r) => r.machineId)).toEqual([
+ null,
+ null,
+ ]);
+ });
+
+ it("resolves ~ against the machine's home", () => {
+ expect(resolveGoTo("~/work", "/home/me")).toBe("/home/me/work");
+ expect(resolveGoTo("~", "C:\\Users\\me")).toBe("C:\\Users\\me");
+ expect(resolveGoTo(" /srv ", null)).toBe("/srv");
+ });
+});
+
+describe("the modal (source contract)", () => {
+ const read = (rel: string) =>
+ readFileSync(fileURLToPath(new URL(`../src/${rel}`, import.meta.url)), "utf8");
+ const finder = read("features/chat/workspace-finder.tsx");
+ const select = read("features/chat/workspace-select.tsx");
+
+ it("is the shared Modal, so it stacks on a host dialog through the one Escape stack", () => {
+ expect(finder).toContain("<Modal");
+ expect(finder).not.toContain("createPortal");
+ expect(finder).not.toMatch(/fixed inset-0/);
+ expect(select).not.toContain("Dropdown");
+ });
+
+ it("says a refused folder is refused, and names the macOS setting only on darwin", () => {
+ expect(finder).toContain('code === "dir_permission_denied"');
+ expect(finder).toMatch(/platform === "darwin"\s*\?\s*f\.deniedMac/);
+ });
+
+ it("types a path in the address bar itself — no separate Go to row or button", () => {
+ expect(finder).toContain("onClick={editAddress}");
+ expect(finder).not.toMatch(/goToSubmit|gotoRow/);
+ });
+
+ it("gives a folder row an enter button, and one context menu covers the finder", () => {
+ expect(finder).toContain("aria-label={f.openFolder(entry.name)}");
+ expect(finder).toContain("useRowContextMenu()");
+ expect(finder).toContain("anchorRect={menu.anchor}");
+ });
+});