A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): 工作区选择器随被浏览的机器适配(移植上游 #962)
lmlihengab6aa82724ac
diff --git a/FORK-PROGRESS.md b/FORK-PROGRESS.mdindex 8b70ab58..b7ccd2e0 100644--- a/FORK-PROGRESS.md+++ b/FORK-PROGRESS.md@@ -203,11 +203,19 @@- [x] **5.1 工位 @ 合并成一个工作轮**(上游 `feat/org-trigger-coalesce` / `c41fa086`)——本轮做完,见下。这是四处里唯一一条直接压公司模式那笔钱的:会话数才是费用变量,而忙工位过去会攒下几十个各带一份频道上下文的工作轮。-- [ ] 5.2 **插件库「自带 demo」+ 商店条目模型**(上游 `c6a7b6ee` `#726`、`feat/plugin-store`)——+- [x] **5.2 插件库「自带 demo」+ 商店条目模型**(上游 `c6a7b6ee` `#726`、`feat/plugin-store`)——正对插件市场 v1 的货架、一键安装与更新提示;上游把索引条目、桶、demo 快速开始都试过了。-- [ ] 5.3 **跨机 agents**(`feat/agents-across-machines`、`feat/machine-*`、`feat/port-forwarding`、- `feat/company-remote-machines`、`feat/agent-state-handover`)——**先调研再投资**。价值最大:- 公司跑在 Windows(RTX 5060)那台,现在两台机器之间靠人搬。+ **2026-10-07 核实:这件事已经做完了**,由另外的巡台会话在 2026-10-06 提交:`2a8f56e7`+ 「插件市场给每个自带插件包一条条目」(core/server/web/docs)、`fcc78f93`「插件市场的卡片加每 Agent+ 状态与一键安装/更新」——`packages/web/src/features/plugins/plugins-page.tsx` 里+ `marketState` 的 not installed / installed / updatable 三态、`availablePluginRows`、筛选与一键+ 安装/更新都在,两条提交就在本文件的 HEAD 历史里。**本条没有留下需要做的活**(`/root/evolution/PLAN.md`+ 里「插件市场 v1」标的 ⏳ 已过时,那份计划不归本台账管,未改)。+- [~] 5.3 **跨机 agents**(`feat/agents-across-machines`、`feat/machine-*`、`feat/port-forwarding`、+ `feat/company-remote-machines`、`feat/agent-state-handover`)——**调研已做完(见文件末尾「跨机评估」+ 一节),落地只做了「跟上游学之二」那一条**。结论:我们自己的跨机子系统已经不小,缺的不是地基而是+ 上游那批修复与「公司模式跑在别的机器上」;而**「这台 Linux 指挥 Windows 生成台」在今天的两侧代码里+ 都还不可能**(Windows 机器连不上,见评估)。价值仍在,但要按评估里的顺序走。- [ ] 5.4 **沙箱体系**(上游已进 main:Landlock 让默认 Ubuntu 可用 `234183f5`、权限菜单命名预设`9b170c61`、`sandbox-dsh` 在 Windows 走 pwsh `c03e58c4`、建沙箱前先建 scratchpad `cba091e3`、后端拆成 npm 包 `1ba104c9`)。我们有四个后端,缺的是「体系」:公司模式下一群 agent 在跑命令。@@ -1949,3 +1957,125 @@ README 的环境表跟上了。这一轮没碰它,它属 2.2c 的文档尾巴- `pnpm lint` 0 警告 0 错误(2052 文件);`pnpm format:check` 干净;`packages/server` 的`tsc --noEmit` 过,`ifaces.json` 重新生成(它是生成物、`.gitignore` 里,不进提交)。- 没有起的服务、没有动的端口;`/root/adelie-fork` 工作树在本轮开始与结束时都只有本轮的文件。++## 跟上游学之二:工作区选择器随被浏览的机器适配(#962,2026-10-07)++用户说「继续」,承接上一条(5.1)往下走。5.2 核实为**已经做完**(见待办 5.2),于是本轮做 5.3 里+唯一一件「已经在 main 里、规模可控、对 Windows 那台直接有用」的事:上游 `b5a0ae8f`+(`The Workspace finder adapts to the machine it browses`,#962,17 文件 +1777)。++### 为什么要做++公司跑在 Windows(RTX 5060)那台。在那台机上选工作区时,选择器的左栏过去只会按 Linux 的方式想事情:+`C:\` 被当成相对路径、盘符要点地址栏手打、`AppData` 与旧式目录链接(点进去只有「拒绝访问」)照列。+#962 让**被浏览的机器**用自己的规则回答左栏:Windows 给盘符(带卷标与类型)、macOS 给 `/Volumes`、+Linux 给根与挂载点;标准文件夹按那台机自己的规则找(OneDrive 接管的桌面、中文桌面的 `~/桌面`);+Windows 上按隐藏属性过滤,并可只输入 `D:` 打开该盘。++### 做了什么(照上游移植,不是合分支)++- **新服务** `packages/server/src/services/dir-places.ts`(829 行):Windows 走 PowerShell 报盘符,+ macOS 读 `/Volumes`,Linux 读 `/proc/mounts` 与 XDG 用户目录。所有平台调用都过 `PlaceEffects`+ 接口,所以每个平台的分支都能在任何机器上跑单测;真机走 `systemEffects`。枚举在子进程里做并限时+ (PowerShell 5s、cmd 3s),结果缓存 15s(失败也缓存),因为一台断开的网络盘会把 libuv 的线程按+ 几十秒。+- **路由** `GET /api/projects/:p/dirs`:主目录请求带 `places=1` 时返回 `standardFolders` 与+ `locations`;Windows 上每条列表标出 `hidden`;`D:` / `d:` 归一成 `D:\`(`normalizeRequestedDir`,+ 纯函数、导出给单测)。旧的 `roots` 字段去掉。+- **前端**:左栏这一节在 Windows 上仍叫「此电脑」,别处叫「位置」;地址栏根部多一个 `切换位置` 下拉,+ 一次换盘(窄屏左栏收成抽屉时尤其有用);非 Mac 上 Ctrl+L / Alt+D / F4 编辑地址、F5 刷新当前目录+ (过去是刷新整个应用);标准文件夹优先用机器自己给的答案,机器没给才回落到按英文名找。+- **图标**:finder 里那枚 `DRIVE_ICON` 搬进注册表(`hardDrive`,与上游同一段 path),另加 `plug` 给+ 可移动盘;`packages/web/test/icon-registry.test.ts` 里该文件的白名单从 11 收紧到 10。+- 变更日志中英双份 `changelog/unreleased/2026-10-07-workspace-finder-per-platform{,zh}.md`(日期与+ 文件名按本仓习惯改成落地日,正文里写明来源是上游 #962 / `b5a0ae8f`);`packages/docs` 的+ `server-api.{en,zh}.md` 的 `/dirs` 一节跟着改;画廊 mock 补上 `places=1` 的答案,好在本地看到这一节。++### 怎么移植的++`upstream` 这个 remote 还指向已被删掉的 `/root/penguin-harness`(`git fetch upstream` 直接失败),+本轮**没有改仓库配置**,只用一次性 URL 抓 `main` 进对象库:+`git fetch --no-tags https://github.com/Prism-Shadow/penguin-harness.git main:refs/remotes/gh/main`+(2 秒,绝大部分对象已在库里),然后 `git apply -3 /tmp/dirplaces.diff` 走三方合并。17 个文件里 12 个+自动落地(含两个新文件与全部文案、文档、画廊 mock),5 个留冲突:`dirs.ts`、`dirs.test.ts`、+`workspace-finder-model.ts`、`workspace-finder.tsx`、`web/test/workspace-finder.test.ts`,共 9 处。+逐处看下来,冲突全是**我们自己的分叉**,不是上游的设计分歧:文件头注释(本仓多了 POST/DELETE/+access 那几段)、包名(`@lmliheng/` vs 上游的 `@prismshadow/`)、列表样式(本仓 `space-y-0.5`,+上游 `flex flex-col gap-1`)、图标常量(本仓仍留 10 枚字面量 path)。一律「上游的逻辑 + 本仓的样式」。++### 验证(都实跑过)++- 测试:server **182 文件 / 2625 通过 · 4 跳过 · 0 失败**(新增 `dir-places.test.ts` 11 条与+ `dirs.test.ts` 的 places/裸盘符用例);web **236 / 2899 通过 · 2 跳过**;ui 1003;docs 62;+ core 1359 · 5 跳过;cli 506;ui-gallery 131;**0 失败**。+- 门禁:`pnpm lint` 0 警告 0 错误(2054 文件);`pnpm format:check` 干净;server 与 web 的+ `tsc --noEmit` 过。+- **真机器**:`dirs.test.ts` 里那条「主请求带 `places=1`,不带就不给」走的是真 HTTP 与真文件系统+ (返回 `locations[0] = {path:"/", kind:"root"}`、`standardFolders` 是对象;Windows 那两条按平台+ 跳过)。另外直接把 `discoverLocalPlaces()` 跑了一遍:11ms 出结果、第二次调用拿到**缓存里的同一个+ 对象**、非 Windows 上 `windowsHiddenNames` 返回空集合而不是抛错。+- **真浏览器**:`pnpm dev:gallery`(7372,是我自己起的、看完就停了)配 Playwright + 本地 chromium,+ 打开 `/app.html?route=/chat/new&lang=zh` 再点开 finder:左栏依次是「常用 / 位置(文件系统、data)/+ 最近使用 / 机器」,地址栏那颗 `切换位置` 的下拉列出「文件系统、data」,console 无 error。截图+ `/tmp/finder-open.png`、`/tmp/finder-menu.png`。+- **没验的**:Windows 与 macOS 两条分支只有单测(这台机器是 Linux);跨机那条路+ (`/api/projects/:p/machines/:id/dirs`)本轮没跑,它按设计也不带 places。+- `pnpm -r test` 里 `packages/desktop` 有 2 条红:`installer-assets.test.ts` 比对+ `packages/desktop/dist/install.{sh,ps1}`(构建产物、`.gitignore` 里)与仓库根的安装脚本,前者是+ 2026-10-06 早些时候的旧构建(提示里还写着 4000),后者已被 `3835c0e8` 改成新端口。**与本轮无关**,+ 是本地陈旧产物;CI 上 `dist/` 不存在,那条测试自己跳过。++## 跨机评估(2026-10-07,条目 5.3)++### 我们已经有什么(都是本仓文件级证据)++- 服务端 `packages/server/src/machines/`:17 个文件 + `transport/`(`service`、`proxy`、`transport`、+ `terminal-relay`、`remote-token`、`install-server`、`ssh-config`、`server-control`、`server-state`、+ `plugins-sync`、`models-sync`、`upgrade`、`detect`、`layout`、`answer`、`machine-api`)。+- 路由 `packages/server/src/http/routes/machines.ts` **13 个端点**:ssh-hosts 增删查改、probe、+ install、connect、dirs、release、restart、disconnect、use / stop-using。+- 库表:`machine`(本机身份)、`machines`、`machine_project`(迁移 4、12)。+- 前端 `packages/web/src/features/machines/*`(机器页、机器选择器、ssh 主机对话框、probe 排期、+ 匹配规则)。+- 模型:一台机器归一个 Project;本服务器用 SSH 把**本构建**装到对端,命令走 stdin、TCP 走 SOCKS,+ 请求经 `/server/<machineId>/api/…` 同源转发;`sessions` 表**没有**机器列 —— 机器是 Project 级、+ 前端按前缀改指。+- 测试:`packages/server/test/machines-*.test.ts` 10 个文件、**186 条全过**(含对真起服务的+ `syncModelsToMachine`)。++### 缺口(对着上游核过)++- 上游 `main` 里我们还缺的跨机提交只有两条:`dd1b931f`(CI 上把 machine 测试也跑到 Windows,#973,+ 3 文件)与本轮移植的 `b5a0ae8f`(#962)。+- 其余跨机工作**全在分支上、没进 main**:22 个带 machine 字样的 head —— `feat/agents-across-machines`、+ `feat/company-remote-machines`、`feat/benchmarks-across-machines`、`feat/machines-simplified`、+ `feat/machine-transport-ssh-config-io`、`feat/machine-connection-stage-timings`、+ `feat/workspace-machine-identity`、`feat/plugin-machines`、`fix/machine-events-redial-a-failed-dial`、+ `fix/machine-events-attach-a-machine-connected-later`、`fix/machine-hop-answers-in-time`、+ `fix/machine-linked-stopped`、`fix/machines-adopted-table`、`fix/machine-server-own-session`、+ `fix/model-switch-on-its-machine` 等。**规模没法从 API 量**:GitHub 的 compare 只给前 300 个文件,+ 而且这些分支相对 main 报 94~569 个提交(是血缘分叉,不是它们各自的工作量)。要量得逐个 fetch 下来+ diff,所以对它们的态度应当是「按需挑补丁」,不是「整体合」。+- 我们自己的差距不在「有没有跨机」,而在:没有第二台机器做端到端;以及公司模式还不会把活儿派到别的+ 机器上(那需要上游那批分支)。++### 关键限制:Windows 那台今天连不上(两侧代码都拦着)++- `http/routes/machines.ts` 的 connect 明确拒绝 Windows:+ 「A Windows machine cannot be connected yet: its sshd hands commands to cmd.exe, and there is no+ shell to hold a session on.」——**上游 main 里是同一句话**(`git show gh/main:…/machines.ts` 核过)。+- 跨机的目录列举 `machines/commands.ts` 的 `listDirsCommand` 是纯 POSIX 的(`$HOME`、`ls -1p`、+ `sed`、`grep`),一行 Windows 分支都没有。+- 结论:「这台 Linux 指挥 Windows 生成台」在两侧都还不成立,能跨的是 Linux/macOS 之间。Windows 那台+ 今天的用法只能是它自己起服务、自己开界面 —— 这也正是本轮 #962 对它直接有用的原因(选工作区时能看到+ 盘符、`此电脑`、`D:` 与隐藏项)。要真做到「Linux 指挥 Windows」,先得有「Windows 上也能维持一条+ 会话」这件事(上游拿那 22 个分支在试,没进 main),而且没有第二台机器就无法端到端验证。++### 建议的落地顺序++1. `fix/machine-*` 那批小修复:逐个看补丁,能上就上(我们已有 186 条跨机测试兜底),优先+ `fix/machine-server-own-session`、`fix/machine-events-redial-a-failed-dial`、+ `fix/machine-hop-answers-in-time` 这类「不修就会挂」的。+2. 有第二台 Linux 机器时,把「安装 → 使用 → 跨机建会话 → 插件/模型同步」端到端跑一次。+3. Windows 侧要么等上游把「Windows 上的会话」做进 main,要么自己评估成本(比前两项都大)。+4. 公司模式跑在别的机器上(`feat/company-remote-machines`)放在最后:它建立在上面这些之上。diff --git a/changelog/unreleased/2026-10-07-workspace-finder-per-platform.md b/changelog/unreleased/2026-10-07-workspace-finder-per-platform.mdnew file mode 100644index 00000000..0cca8873--- /dev/null+++ b/changelog/unreleased/2026-10-07-workspace-finder-per-platform.md@@ -0,0 +1,39 @@+# The Workspace finder adapts to the machine it browses++- **Date:** 2026-10-07+- **Type:** feature+- **Scope:** `web`, `server`, `docs`++[中文版](2026-10-07-workspace-finder-per-platform.zh.md)++The Workspace finder's sidebar now shows what the browsed machine's own file manager would:+Windows drives with their names, macOS volumes, the Linux root and its mounts, and standard+folders found by that machine's own rules. Drive switching is one click from the address bar, and+a drive can be typed as `D:`. Ported from upstream PenguinHarness (#962, commit `b5a0ae8f`),+which the fork did not carry.++## Details++- **Locations.** The section after Quick access is **This PC** on Windows and **Locations** on+ macOS and Linux. Windows drives are named as Explorer names them — `Windows (C:)`, or by type+ when the volume has no label (Local Disk, USB Drive, Network Drive, CD Drive), and an unnamed+ network drive by its share (`\\nas\media (Z:)`). macOS lists the volumes under `/Volumes`, the+ startup disk first. Linux lists **File System** (`/`) and the mounts under `/media`,+ `/run/media` and `/mnt`; under WSL that is where the Windows drives are, named `C:` and so on.+- **The address bar** has a drop-down beside its root (`C:`, `/`) listing the same locations, so+ switching drives takes one click even on a narrow window where the sidebar is a drawer. Typing a+ bare drive (`d:`) opens that drive's root.+- **Standard folders** come from the machine: Windows' known folders (a Desktop or Documents moved+ into OneDrive is found), Linux's XDG user directories (`~/桌面`, `~/文档` on a Chinese desktop),+ macOS's fixed names. A machine browsed over ssh is still matched by English names.+- **Freshness and time limits.** Places are fetched again on every open, so a USB drive plugged in+ meanwhile appears. Discovery runs with a time limit and a short cache; a disconnected network+ drive no longer holds the dialog, and the folder list never waits for it.+- **Hidden items on Windows.** Entries with the hidden attribute are left out, as in Explorer:+ `AppData`, `NTUSER.DAT`, `$Recycle.Bin` and the legacy profile links such as `Application Data`,+ which refused to open when clicked.+- **Keys.** Off the Mac, Ctrl+L, Alt+D and F4 edit the address, as in Explorer and the Linux file+ managers. F5 refreshes the folder instead of reloading the app.+- **API.** `GET /api/projects/:p/dirs` drops `roots`; the home request with `places=1` returns+ `standardFolders` and `locations`, and Windows listings mark `hidden` entries. The Server API+ docs describe the new fields.diff --git a/changelog/unreleased/2026-10-07-workspace-finder-per-platform.zh.md b/changelog/unreleased/2026-10-07-workspace-finder-per-platform.zh.mdnew file mode 100644index 00000000..4fc65a73--- /dev/null+++ b/changelog/unreleased/2026-10-07-workspace-finder-per-platform.zh.md@@ -0,0 +1,19 @@+# Workspace 选择器随被浏览机器的系统适配++- **Date:** 2026-10-07+- **Type:** feature+- **Scope:** `web`, `server`, `docs`++[English](2026-10-07-workspace-finder-per-platform.md)++Workspace 选择器的左栏现在显示被浏览机器自己的文件管理器会显示的内容:带名称的 Windows 盘符、macOS 的各卷、Linux 的根目录与挂载点,以及按该机器自己的规则找到的标准文件夹。从地址栏一次点击即可切换盘符,也可以直接输入 `D:`。本次从上游 PenguinHarness 移植(#962,提交 `b5a0ae8f`),此前本 fork 没有这一条。++## 细节++- **存储位置。** 常用之后的一节在 Windows 上叫**此电脑**,在 macOS 与 Linux 上叫**位置**。Windows 盘符按资源管理器的写法命名:`Windows (C:)`;卷没有标签时按类型命名(本地磁盘、U 盘、网络驱动器、CD 驱动器),未命名的网络驱动器显示其共享路径(`\\nas\media (Z:)`)。macOS 列出 `/Volumes` 下的各卷,启动盘排第一。Linux 列出**文件系统**(`/`)以及 `/media`、`/run/media`、`/mnt` 下的挂载点;WSL 下 Windows 各盘就在这里,以 `C:` 等命名。+- **地址栏**根部(`C:`、`/`)旁新增下拉箭头,列出同样的各位置;窄屏下左栏收成抽屉时,换盘同样只需一次点击。只输入盘符(`d:`)即打开该盘根目录。+- **标准文件夹**由机器自己给出:Windows 读已知文件夹(被 OneDrive 接管的桌面、文档也能找到),Linux 读 XDG 用户目录(中文桌面的 `~/桌面`、`~/文档`),macOS 用固定名称。经 ssh 浏览的机器仍按英文名查找。+- **刷新与时限。** 每次打开都会重新获取存储位置,期间插上的 U 盘随之出现。查找有时限并短暂缓存:断开的网络驱动器不再拖住弹窗,目录列表也从不等它。+- **Windows 上的隐藏项。** 带隐藏属性的条目像资源管理器一样不再列出:`AppData`、`NTUSER.DAT`、`$Recycle.Bin`,以及 `Application Data` 这类旧式目录链接(以前点进去只会报拒绝访问)。+- **按键。** 非 Mac 上 Ctrl+L、Alt+D 与 F4 进入地址编辑,与资源管理器和 Linux 文件管理器一致;F5 刷新当前目录,不再重新加载整个应用。+- **API。** `GET /api/projects/:p/dirs` 去掉 `roots`;请求主目录并带 `places=1` 时返回 `standardFolders` 与 `locations`,Windows 的列表为隐藏条目标 `hidden`。Server API 文档已写明新字段。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 46b3c52c..ca522dd4 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -632,7 +632,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, 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 /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 an entry the system hides (the hidden attribute: `AppData`, `NTUSER.DAT`) carries `hidden: true`. A bare drive such as `D:` is taken as its root `D:\`. The home request with `places=1` adds what the picker's sidebar shows: `standardFolders` (Desktop, Documents, Downloads and Pictures as the machine resolves them — Windows known folders, Linux XDG user directories — omitted when they could not be read) and `locations` (Windows drives, macOS volumes, the Linux root and its mounts under `/media`, `/run/media` and `/mnt`, each with its `kind` and, when it has one, its `label`). A directory the server may not read answers `403 dir_permission_denied` rather than an empty list — on macOS that is usually a Files and Folders permission the user has not granted.- `POST /dirs/access` is the Workspace picker's **Allow access** in the desktop app. macOS asks about Desktop, Documents and Downloads only on behalf of the app it holds responsible for the read, so the desktop shell's main process reads the absolute `path` once, and the answer waits for the user. `granted` says whether the read succeeded (always `true` off macOS, where nothing is read). `packaged` is `false` for a development instance started from a terminal, whose reads macOS charges to that terminal. The route returns `400` `dir_not_absolute` for a path that is not absolute, `503` `shell_unreachable` when the server has no desktop shell to ask, and `504` `timeout` when the shell has not answered within 120 seconds. Only the desktop app's own window may call it; any other session gets `403` `desktop_shell_only`.- `GET /dir-skills` reads only `<path>/.agents/skills` and `<path>/.claude/skills` of an absolute `path`, and answers `{path, skills}`. A directory without Skills answers with an empty list. See `POST /agents` under [Agents](#agents).- `/workspace-files` runs the operations of [Workspace files](#workspace-files) on a directory named by its absolute path in `workspace`, for the pages that have no Session yet: the new-chat page's chosen folder, and a sidebar Workspace group's **Browse files**. The answers are the Session routes' own. The caller needs access to the Project, the same access that lets it create a Session in that directory, and `workspace` must be an existing directory, as when a Session is created there (400 `workspace_not_found` otherwise). Every `path` is confined to it as for a Session. There is no preview redirect, because preview tokens name a Session: HTML from a directory previews with `preview=1` in the same-origin sandbox. A directory on another machine is reached through that machine's `/server/<machineId>` proxy.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex dc55721c..fc9a7da1 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -632,7 +632,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, platform}`:每个条目带 `kind`(`dir` 或 `file`)与 `mtime`;在 Windows 上,请求主目录时另带 `roots`,即实际存在的各盘符根目录。服务无权读取的目录返回 `403 dir_permission_denied`,不再按空列表返回;在 macOS 上这通常是用户尚未授予的「文件与文件夹」权限。+- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries, platform}`:每个条目带 `kind`(`dir` 或 `file`)与 `mtime`;在 Windows 上,系统隐藏的条目(带隐藏属性,如 `AppData`、`NTUSER.DAT`)另带 `hidden: true`,只写盘符如 `D:` 即视为其根目录 `D:\`。请求主目录并带 `places=1` 时,另附选择器左栏所需的两项:`standardFolders`(桌面、文档、下载、图片,按该机器自己的规则取得——Windows 的已知文件夹、Linux 的 XDG 用户目录;读取失败时省略)与 `locations`(Windows 的各盘符、macOS 的各卷、Linux 的根目录及 `/media`、`/run/media`、`/mnt` 下的挂载点,各带 `kind`,有名称时带 `label`)。服务无权读取的目录返回 `403 dir_permission_denied`,不再按空列表返回;在 macOS 上这通常是用户尚未授予的「文件与文件夹」权限。- `POST /dirs/access` 是桌面端 Workspace 选择器里的**允许访问**。macOS 只替它认定为读取责任方的应用询问桌面、文稿与下载的访问权限,因此由桌面 shell 的主进程把绝对路径 `path` 读一次,响应要等用户作答后才返回。`granted` 表示这次读取是否成功(非 macOS 平台不读取,恒为 `true`)。`packaged` 为 `false` 表示这是从终端启动的开发实例,macOS 把它的读取记在该终端名下。`path` 不是绝对路径时返回 `400` `dir_not_absolute`;服务器没有可询问的桌面 shell 时返回 `503` `shell_unreachable`;shell 在 120 秒内没有应答时返回 `504` `timeout`。只有桌面应用自己的窗口可以调用,其他会话返回 `403` `desktop_shell_only`。- `GET /dir-skills` 只读取绝对路径下的 `<path>/.agents/skills` 和 `<path>/.claude/skills`,响应为 `{path, skills}`。没有 Skill 的目录返回空列表。参见 [Agent](#agent) 一节中的 `POST /agents`。- `/workspace-files` 对 `workspace` 里以绝对路径指定的目录执行 [Workspace 文件](#workspace-文件)中的那组操作,供还没有 Session 的页面使用:新建对话页选定的文件夹,以及侧栏 Workspace 分组的**打开文件浏览**。响应与 Session 路由完全相同。调用方需要有该 Project 的访问权——也就是能在该目录下创建 Session 的同一种权限;`workspace` 必须是已存在的目录,校验口径与在该目录创建 Session 时相同(否则返回 400 `workspace_not_found`)。每个 `path` 都像对 Session 一样被限制在该目录内。这里没有预览跳转,因为预览令牌绑定 Session:目录里的 HTML 以 `preview=1` 在同源沙箱中预览。其他机器上的目录经该机器的 `/server/<machineId>` 代理访问。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex d66a3260..547a575e 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1682,6 +1682,23 @@ export interface DirEntryInfo {kind?: "dir" | "file";/** Last modification, epoch milliseconds; absent when unknown (listings over ssh, an entry stat could not reach). */mtime?: number;+ /** Hidden by the machine's own rules beyond the dot-name convention (Windows hidden/system attribute). */+ hidden?: true;+}+/** A storage location the machine offers beside its folders: a Windows drive, a macOS volume, a Linux root or mount. */+export interface DirLocation {+ /** Absolute path it opens (`C:\`, `/`, `/Volumes/USB`, `/media/me/USB`, `/mnt/c`). */+ path: string;+ kind: "drive" | "removable" | "network" | "optical" | "volume" | "root";+ /** The machine's own name for it (volume label, volume name, share `\\nas\media`, WSL `C:`); absent when none. */+ label?: string;+}+/** The platform's standard folders as that machine resolves them; only those that exist. */+export interface DirStandardFolders {+ desktop?: string;+ documents?: string;+ downloads?: string;+ pictures?: string;}export interface DirListResponse {/** Absolute path of the current directory (realpath). */@@ -1692,8 +1709,10 @@ export interface DirListResponse {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[];+ /** Home request with `places=1` only. */+ standardFolders?: DirStandardFolders;+ /** Home request with `places=1` only, in the order the sidebar lists them. */+ locations?: DirLocation[];}/** The answer to making one folder: its absolute path, for the picker to reveal and select. */export interface DirCreateResponse {diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.tsindex ffc76a0d..95b5b755 100644--- a/packages/server/src/http/routes/dirs.ts+++ b/packages/server/src/http/routes/dirs.ts@@ -15,6 +15,20 @@* (Desktop, Documents, Downloads) looks exactly like that, and an empty list sent people* looking for files that were there all along.*+ * The home request (no `path`) with `places=1` also answers what the picker's sidebar needs+ * and only this machine knows: the standard folders as this machine resolves them (a Desktop+ * redirected into OneDrive, a localized `~/桌面`) and its storage locations — Windows drives+ * with labels and kinds, macOS volumes, the Linux root and its mounts. Discovery is the+ * dir-places service's: time-boxed and cached, so a disconnected network drive never holds a+ * listing. The picker asks for places on the request that builds its sidebar and leaves the+ * flag off the one that fills its list, so the list never waits on discovery either.+ *+ * On Windows every listing marks the entries Explorer hides (`hidden: true`): the hidden+ * attribute is what keeps `AppData`, `NTUSER.DAT` and the legacy profile junctions — which+ * are also access-denied, so a click on one only fails — out of the way, and no Node API reads+ * it. A bare drive `D:` is accepted there as `D:\`, as Explorer's address bar does; to Node a+ * bare drive is drive-relative and would otherwise be refused as not absolute.+ ** POST /api/projects/:p/dirs makes one folder inside the folder being browsed, which is the* picker's "New folder": see the route for what it refuses.*@@ -46,6 +60,7 @@ import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";import { directorySkillsRoutes } from "./directory-skills.js";import type { Desktop, DesktopApi, Paths } from "../../hmr/capabilities.js";import type { Access } from "../../mechanisms/projects.js";+import { discoverLocalPlaces, windowsHiddenNames } from "../../services/dir-places.js";/** What this route group reaches — bound by its module (src/modules). */export interface DirsRouteDeps {@@ -68,8 +83,11 @@ 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 requested = raw?.trim() ?? "";+ const requested = normalizeRequestedDir(raw?.trim() ?? "", process.platform);const home = requested === "";+ // Places answer the home request alone: that is the one the picker makes to build its+ // sidebar, and discovering drives on every folder change would be waste.+ const places = home && c.req.query("places") === "1";const real = await resolveBrowsableDir(home ? os.homedir() : requested);let dirents: import("node:fs").Dirent[];@@ -78,9 +96,20 @@ export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {} catch (err) {throw dirReadError(err, real);}- const entries = (await describeEntries(real, dirents)).sort((a, b) =>- a.name.localeCompare(b.name),- );+ // The attribute pass and the discovery run beside the per-entry stats, not after them.+ const [described, hidden, found] = await Promise.all([+ describeEntries(real, dirents),+ process.platform === "win32"+ ? windowsHiddenNames(+ real,+ dirents.map((d) => d.name),+ )+ : null,+ places ? discoverLocalPlaces() : null,+ ]);+ const entries = described+ .map((e): DirEntryInfo => (hidden?.has(e.name) ? { ...e, hidden: true } : e))+ .sort((a, b) => a.name.localeCompare(b.name));const parent = path.dirname(real);return c.json({@@ -88,9 +117,9 @@ export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {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() } : {}),+ // `standardFolders` stays absent when discovery could not ask the machine, so the+ // picker finds them by name; present and empty means there are none.+ ...(found !== null ? found : {}),} satisfies DirListResponse);});@@ -418,18 +447,13 @@ async function describeEntries();}-/** 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);+/**+ * A bare drive (`D:`, `d:`) typed on Windows means that drive's root, as it does in Explorer's+ * address bar. To Node it is drive-relative — `path.isAbsolute("D:")` is false — so without+ * this it would be refused as not absolute. Pure; exported for the unit test.+ */+export function normalizeRequestedDir(requested: string, platform: string): string {+ return platform === "win32" && /^[A-Za-z]:$/.test(requested) ? `${requested}\\` : requested;}/** The Project-scoped directory routes; the repos and the access check are components of their own. */diff --git a/packages/server/src/services/dir-places.ts b/packages/server/src/services/dir-places.tsnew file mode 100644index 00000000..b91b64e0--- /dev/null+++ b/packages/server/src/services/dir-places.ts@@ -0,0 +1,829 @@+/**+ * Where a machine keeps its things, as the Workspace picker's sidebar wants them: the+ * platform's standard folders as THIS machine resolves them (a Desktop redirected into+ * OneDrive, a `~/桌面` on a Chinese Linux desktop), and the storage locations it offers beside+ * its folders — Windows drives with their labels and kinds, macOS volumes, the Linux root and+ * its mounts. Also the Windows hidden attribute, which no Node API exposes and which Explorer+ * uses to keep `AppData`, `NTUSER.DAT` and the legacy profile junctions out of sight.+ *+ * Everything that touches the platform goes through {@link PlaceEffects}, so the parsers and+ * the decisions run under test on any platform; {@link systemEffects} is the real machine.+ *+ * Two constraints shape every shell-out here. First, a disconnected network drive makes any+ * filesystem call on it block for the redirector's timeout (tens of seconds), and a blocked+ * `fs` call pins one of libuv's four threadpool threads for that long — the whole server's+ * file I/O queues behind it, and a probe "raced against a timeout" still pins the thread after+ * its caller moved on. So nothing in this file touches a drive from this process: enumeration+ * runs in a child (spawning uses no threadpool thread), the child is time-boxed and killed, and+ * whatever it printed before the deadline is kept. Second, the picker's home request waits for+ * this answer, so the whole discovery is cached for a short while, a failure included, and two+ * concurrent requests share one run.+ */+import { spawn, type ChildProcess } from "node:child_process";+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { DirLocation, DirStandardFolders } from "../api/types.js";++/** What the home request carries with `places=1`. */+export interface DirPlaces {+ /**+ * Absent when the machine could not be asked (the Windows report ended before it got to+ * the folders), so the picker falls back to matching names in the home listing. Present and+ * empty means the machine was asked and has none of them, and the picker shows none.+ */+ standardFolders?: DirStandardFolders;+ locations: DirLocation[];+}++/** One child process run to completion or to its deadline. */+export interface ExecOutcome {+ /** What the child wrote before it exited or was killed — bytes, because `cmd /u` writes UTF-16LE. */+ stdout: Buffer;+ /** The exit code; null when the child was killed or never started. */+ code: number | null;+ /** True when the child outlived its budget and was killed; `stdout` is what it had printed by then. */+ timedOut: boolean;+ /** Set when the child could not be started at all (the command is not on the machine). */+ failed?: string;+}++/** A directory entry as `readdir` records it, without a stat: the two kinds this file asks about. */+export interface PlaceDirent {+ name: string;+ isDirectory(): boolean;+ isSymbolicLink(): boolean;+}++/** The machine as discovery sees it; tests inject one, production uses {@link systemEffects}. */+export interface PlaceEffects {+ platform: string;+ homedir: string;+ env: Record<string, string | undefined>;+ readFile(file: string): Promise<string>;+ readdir(dir: string): Promise<PlaceDirent[]>;+ readlink(file: string): Promise<string>;+ /** False for anything that is not a directory, a missing path included. */+ isDirectory(file: string): Promise<boolean>;+ /**+ * Runs a child without a shell and without the threadpool, killing it at `timeoutMs`.+ * `verbatim` hands the arguments to Windows unquoted, for a `cmd.exe` command line whose+ * quoting this file controls itself.+ */+ exec(+ file: string,+ args: string[],+ opts: { timeoutMs: number; verbatim?: boolean },+ ): Promise<ExecOutcome>;+}++/**+ * The discovery's shelf life. Long enough that reopening the picker, or two of its requests+ * landing together, never spawn PowerShell twice; short enough that a USB drive plugged in+ * shows up on the next open.+ */+export const PLACES_CACHE_TTL_MS = 15_000;+/**+ * PowerShell's budget. A cold `powershell.exe` takes one to three seconds on a slow laptop or+ * a CI runner; a budget it routinely blew would make the fallback the normal path. The script+ * prints one JSON line per fact, so a run that hits the deadline still yields everything it+ * had said by then.+ */+export const POWERSHELL_TIMEOUT_MS = 5_000;+/** `cmd.exe` budgets: the drive-letter probe and the hidden-attribute listing. */+export const CMD_TIMEOUT_MS = 3_000;+/** More than any directory listing or drive report; past it the child is killed and ignored. */+const OUTPUT_CAP_BYTES = 16 * 1024 * 1024;++export function systemEffects(): PlaceEffects {+ return {+ platform: process.platform,+ homedir: os.homedir(),+ env: process.env,+ readFile: (file) => fs.readFile(file, "utf8"),+ readdir: (dir) => fs.readdir(dir, { withFileTypes: true }),+ readlink: (file) => fs.readlink(file),+ isDirectory: (file) =>+ fs.stat(file).then(+ (st) => st.isDirectory(),+ () => false,+ ),+ exec: runChild,+ };+}++/**+ * Collects a child's stdout until it exits or runs out of time. stdin and stderr are not even+ * opened: nothing here reads a diagnostic (`dir`'s "File Not Found" is localized), and a pipe+ * nobody drains could block the child. On the deadline the child is killed and the promise+ * settles on `close`, or one second later if a grandchild inherited the pipe and keeps it open.+ */+function runChild(+ file: string,+ args: string[],+ opts: { timeoutMs: number; verbatim?: boolean },+): Promise<ExecOutcome> {+ return new Promise((resolve) => {+ const chunks: Buffer[] = [];+ let size = 0;+ let timedOut = false;+ let settled = false;+ let timer: NodeJS.Timeout | undefined;+ let backstop: NodeJS.Timeout | undefined;+ const settle = (code: number | null, failed?: string) => {+ if (settled) return;+ settled = true;+ if (timer !== undefined) clearTimeout(timer);+ if (backstop !== undefined) clearTimeout(backstop);+ resolve({+ stdout: Buffer.concat(chunks),+ code,+ timedOut,+ ...(failed !== undefined ? { failed } : {}),+ });+ };+ let child: ChildProcess;+ try {+ child = spawn(file, args, {+ stdio: ["ignore", "pipe", "ignore"],+ windowsHide: true,+ windowsVerbatimArguments: opts.verbatim === true,+ });+ } catch (err) {+ settle(null, (err as Error).message);+ return;+ }+ const kill = () => {+ try {+ child.kill();+ } catch {+ // Already gone.+ }+ };+ timer = setTimeout(() => {+ timedOut = true;+ kill();+ backstop = setTimeout(() => settle(null), 1_000);+ }, opts.timeoutMs);+ child.stdout?.on("data", (chunk: Buffer) => {+ size += chunk.length;+ if (size > OUTPUT_CAP_BYTES) {+ kill();+ settle(null, "output too large");+ return;+ }+ chunks.push(chunk);+ });+ child.on("error", (err) => settle(null, err.message));+ child.on("close", (code) => settle(code));+ });+}++// ---------------------------------------------------------------------------------------------+// The cached discovery++/** Place discovery with its cache; one per machine, built once for the server by {@link discoverLocalPlaces}. */+export function createPlaceDiscovery(+ effects: PlaceEffects,+ opts: { ttlMs?: number; now?: () => number } = {},+): { discover(): Promise<DirPlaces> } {+ const ttl = opts.ttlMs ?? PLACES_CACHE_TTL_MS;+ const now = opts.now ?? Date.now;+ let cached: { at: number; value: DirPlaces } | null = null;+ let inFlight: Promise<DirPlaces> | null = null;+ return {+ discover() {+ if (cached !== null && now() - cached.at < ttl) return Promise.resolve(cached.value);+ if (inFlight !== null) return inFlight;+ inFlight = discoverPlaces(effects)+ .then((value) => {+ cached = { at: now(), value };+ return value;+ })+ .finally(() => {+ inFlight = null;+ });+ return inFlight;+ },+ };+}++let local: { discover(): Promise<DirPlaces> } | null = null;++/** The places of the machine this server runs on, cached. Never rejects. */+export function discoverLocalPlaces(): Promise<DirPlaces> {+ local ??= createPlaceDiscovery(systemEffects());+ return local.discover();+}++/**+ * One uncached discovery. Never rejects: a platform whose every source failed still answers+ * with the root (or the system drive), and leaves the folders unanswered for the picker to+ * find by name, which is what it showed before places existed.+ */+export async function discoverPlaces(effects: PlaceEffects): Promise<DirPlaces> {+ try {+ if (effects.platform === "win32") return await windowsPlaces(effects);+ if (effects.platform === "darwin") return await darwinPlaces(effects);+ if (effects.platform === "linux") return await linuxPlaces(effects);+ } catch {+ // Fall through to the bare answer.+ }+ return {+ locations:+ effects.platform === "win32" ? knownWindowsDrives(effects) : [{ path: "/", kind: "root" }],+ };+}++// ---------------------------------------------------------------------------------------------+// Standard folders by their English names (macOS, and the fallback everywhere)++const FIXED_FOLDERS: ReadonlyArray<[keyof DirStandardFolders, string]> = [+ ["desktop", "Desktop"],+ ["documents", "Documents"],+ ["downloads", "Downloads"],+ ["pictures", "Pictures"],+];++/** `~/Desktop` and friends, those that exist. The path flavour follows the DESCRIBED platform, not the host's. */+async function fixedStandardFolders(effects: PlaceEffects): Promise<DirStandardFolders> {+ const flavour = effects.platform === "win32" ? path.win32 : path.posix;+ const found: DirStandardFolders = {};+ await Promise.all(+ FIXED_FOLDERS.map(async ([key, name]) => {+ const full = flavour.join(effects.homedir, name);+ if (await effects.isDirectory(full)) found[key] = full;+ }),+ );+ return found;+}++// ---------------------------------------------------------------------------------------------+// Linux++const NETWORK_FSTYPES = new Set([+ "nfs",+ "nfs4",+ "cifs",+ "smb3",+ "smbfs",+ "sshfs",+ "fuse.sshfs",+ "fuse.rclone",+ "davfs",+ "fuse.davfs2",+ "afs",+ "ceph",+ "fuse.ceph",+ "glusterfs",+ "fuse.glusterfs",+ "ncpfs",+ "coda",+ "afp",+ "fuse.afpfs",+]);++/** Kernel bookkeeping that happens to be mounted under a user prefix (WSL puts a tmpfs at /mnt/wsl). */+const PSEUDO_FSTYPES = new Set([+ "tmpfs",+ "devtmpfs",+ "proc",+ "sysfs",+ "cgroup",+ "cgroup2",+ "binfmt_misc",+ "debugfs",+ "tracefs",+ "securityfs",+ "pstore",+ "bpf",+ "configfs",+ "fusectl",+ "mqueue",+ "hugetlbfs",+ "devpts",+ "nsfs",+ "rpc_pipefs",+]);++/** The filesystems WSL mounts a Windows drive with: WSL1 `drvfs`, WSL2 `9p`, and their newer spellings. */+const WSL_DRIVE_FSTYPES = new Set(["9p", "drvfs", "v9fs", "virtiofs"]);++/** Where Linux desktops and admins mount things a person would browse to. */+const MOUNT_PREFIXES = ["/media/", "/run/media/", "/mnt/"];++/** `/proc/mounts` escapes a space as `\040`, a tab `\011`, a newline `\012` and a backslash `\134`. */+function unescapeMountField(field: string): string {+ return field.replace(/\\([0-7]{3})/g, (_, oct: string) => String.fromCharCode(parseInt(oct, 8)));+}++/**+ * The browsable mounts in a `/proc/self/mounts` text, in path order: those under+ * {@link MOUNT_PREFIXES}, minus WSL's own plumbing (`/mnt/wsl*`, `/mnt/wslg`), pseudo+ * filesystems, and a mount nested under another listed one (a bind mount inside a disk is the+ * disk's business). The same mount point listed twice keeps the later row: a systemd automount+ * shows its `autofs` trigger and, once mounted, the real filesystem at the same path.+ */+export function parseMounts(text: string): DirLocation[] {+ const byPath = new Map<string, { fstype: string }>();+ for (const line of text.split("\n")) {+ const fields = line.trim().split(/\s+/);+ if (fields.length < 3) continue;+ const mountPoint = unescapeMountField(fields[1] ?? "");+ const fstype = fields[2] ?? "";+ if (!MOUNT_PREFIXES.some((prefix) => mountPoint.startsWith(prefix))) continue;+ if (/^\/mnt\/wslg?(\/|$)/.test(mountPoint)) continue;+ if (PSEUDO_FSTYPES.has(fstype)) continue;+ byPath.set(mountPoint, { fstype });+ }+ // Code-unit order, so a mount point always precedes anything nested under it.+ const sorted = [...byPath.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ const kept: DirLocation[] = [];+ for (const [mountPoint, { fstype }] of sorted) {+ if (kept.some((k) => mountPoint.startsWith(`${k.path}/`))) continue;+ kept.push(mountLocation(mountPoint, fstype));+ }+ return kept;+}++function mountLocation(mountPoint: string, fstype: string): DirLocation {+ const name = path.posix.basename(mountPoint);+ if (NETWORK_FSTYPES.has(fstype)) return { path: mountPoint, kind: "network", label: name };+ const wslDrive = /^\/mnt\/([A-Za-z])$/.exec(mountPoint);+ if (wslDrive !== null && WSL_DRIVE_FSTYPES.has(fstype)) {+ return { path: mountPoint, kind: "drive", label: `${wslDrive[1]?.toUpperCase()}:` };+ }+ if (mountPoint.startsWith("/media/") || mountPoint.startsWith("/run/media/")) {+ return { path: mountPoint, kind: "removable", label: name };+ }+ return { path: mountPoint, kind: "volume", label: name };+}++const XDG_KEYS: ReadonlyArray<[keyof DirStandardFolders, string]> = [+ ["desktop", "XDG_DESKTOP_DIR"],+ ["documents", "XDG_DOCUMENTS_DIR"],+ ["downloads", "XDG_DOWNLOAD_DIR"],+ ["pictures", "XDG_PICTURES_DIR"],+];++/**+ * The four folders as `user-dirs.dirs` configures them: `XDG_DESKTOP_DIR="$HOME/桌面"` lines,+ * `$HOME` expanded. A value that is the home directory itself is how the spec says "this+ * folder is disabled", and comes back as null; a key the file does not mention is absent.+ */+export function parseUserDirs(+ text: string,+ home: string,+): Partial<Record<keyof DirStandardFolders, string | null>> {+ const found: Partial<Record<keyof DirStandardFolders, string | null>> = {};+ const homeNorm = home.replace(/\/+$/, "") || "/";+ for (const line of text.split("\n")) {+ const match = /^\s*(XDG_[A-Z]+_DIR)\s*=\s*"?([^"\n]*)"?\s*$/.exec(line);+ if (match === null) continue;+ const key = XDG_KEYS.find(([, name]) => name === match[1])?.[0];+ if (key === undefined) continue;+ const value = (match[2] ?? "").replace(/^\$\{?HOME\}?/, homeNorm).replace(/\/+$/, "") || "/";+ found[key] = value === homeNorm ? null : value;+ }+ return found;+}++/**+ * Linux standard folders: what `user-dirs.dirs` names, where it exists; the English name where+ * the file says nothing; nothing where the file disables the folder.+ */+async function linuxStandardFolders(effects: PlaceEffects): Promise<DirStandardFolders> {+ const configHome = effects.env.XDG_CONFIG_HOME || path.posix.join(effects.homedir, ".config");+ let configured: Partial<Record<keyof DirStandardFolders, string | null>> = {};+ try {+ configured = parseUserDirs(+ await effects.readFile(path.posix.join(configHome, "user-dirs.dirs")),+ effects.homedir,+ );+ } catch {+ // No file: the English names below.+ }+ const found: DirStandardFolders = {};+ await Promise.all(+ FIXED_FOLDERS.map(async ([key, name]) => {+ const chosen = key in configured ? configured[key] : path.posix.join(effects.homedir, name);+ if (chosen !== null && chosen !== undefined && (await effects.isDirectory(chosen))) {+ found[key] = chosen;+ }+ }),+ );+ return found;+}++async function linuxPlaces(effects: PlaceEffects): Promise<DirPlaces> {+ let mounts: DirLocation[] = [];+ try {+ mounts = parseMounts(await effects.readFile("/proc/self/mounts"));+ } catch {+ // A sandbox without /proc still has a root to offer.+ }+ return {+ standardFolders: await linuxStandardFolders(effects),+ locations: [{ path: "/", kind: "root" }, ...mounts],+ };+}++// ---------------------------------------------------------------------------------------------+// macOS++/**+ * The volumes under `/Volumes`, the startup disk first. Since Catalina the startup disk is a+ * symlink there (`/Volumes/Macintosh HD -> /`), which is how it gets its name; `/` leads even+ * when no entry links to it, so the picker's root always has a target. Only the directory+ * listing and the link targets are read — a network volume whose server is gone is a plain+ * directory entry of `/Volumes` until something touches it. Dot-names and Time Machine's+ * `com.apple.TimeMachine.localsnapshots` are not volumes a person would pick.+ */+export async function darwinLocations(effects: PlaceEffects): Promise<DirLocation[]> {+ let startup: DirLocation = { path: "/", kind: "volume" };+ const others: DirLocation[] = [];+ let entries: PlaceDirent[] = [];+ try {+ entries = await effects.readdir("/Volumes");+ } catch {+ // No /Volumes at all: the root alone.+ }+ for (const entry of entries) {+ if (entry.name.startsWith(".") || entry.name.startsWith("com.apple.")) continue;+ const full = `/Volumes/${entry.name}`;+ if (entry.isSymbolicLink()) {+ let target: string;+ try {+ target = path.posix.resolve("/Volumes", await effects.readlink(full));+ } catch {+ continue;+ }+ if (target === "/") startup = { path: "/", kind: "volume", label: entry.name };+ continue;+ }+ if (entry.isDirectory()) others.push({ path: full, kind: "volume", label: entry.name });+ }+ others.sort((a, b) => (a.label ?? "").localeCompare(b.label ?? ""));+ return [startup, ...others];+}++async function darwinPlaces(effects: PlaceEffects): Promise<DirPlaces> {+ const [locations, standardFolders] = await Promise.all([+ darwinLocations(effects),+ fixedStandardFolders(effects),+ ]);+ return { standardFolders, locations };+}++// ---------------------------------------------------------------------------------------------+// Windows++/**+ * The drive and known-folder report, one JSON object per line, written as raw UTF-8 bytes.+ *+ * Raw bytes because Windows PowerShell's redirected output otherwise uses the OEM code page,+ * and its `ConvertTo-Json` leaves non-ASCII as is — a volume labelled 「U 盘」 would arrive+ * garbled. One object per line because the parser then keeps whatever arrived before the+ * deadline, and because `ConvertTo-Json` on a collection of one yields an object, not an array.+ *+ * Drives are enumerated with `GetLogicalDrives` (a bitmask) and `DriveInfo.DriveType` (the DOS+ * device table) rather than `Win32_LogicalDisk`: WMI reads size and free space from every+ * disk, which on a disconnected mapped drive is the redirector round-trip this whole file+ * avoids, and a cold WMI call also starts its provider host. A label is read only from a local+ * drive that says it is ready (an empty card reader throws); a network drive is named by its+ * share, from the persistent mappings in the registry and then the redirector's own list, and+ * never by a volume label that would have to come from the server. Constrained Language Mode+ * forbids `New-Object` on .NET types, so that branch falls back to WMI without network drives.+ *+ * Folders come last: `Test-Path` on a Documents folder redirected to a dead share blocks, and+ * put last it costs the folders alone. Downloads has no `SpecialFolder` member; its known+ * folder id is read from the shell's registry key.+ */+const WINDOWS_REPORT_SCRIPT =+ String.raw`+$ErrorActionPreference = 'SilentlyContinue'+$stdout = [Console]::OpenStandardOutput()+function Emit($value) {+ $bytes = [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $value -Compress -Depth 3) + "` ++ "`n" ++ String.raw`")+ $stdout.Write($bytes, 0, $bytes.Length)+ $stdout.Flush()+}+$network = @()+try {+ foreach ($root in [IO.Directory]::GetLogicalDrives()) {+ try {+ $drive = New-Object -TypeName IO.DriveInfo -ArgumentList $root+ $type = [int]$drive.DriveType+ if ($type -eq 4) { $network += $root; continue }+ $label = $null+ try { if ($drive.IsReady) { $label = $drive.VolumeLabel } } catch {}+ Emit @{ drive = $root; type = $type; label = $label }+ } catch {}+ }+} catch {+ try {+ foreach ($disk in @(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType <> 4' -ErrorAction Stop)) {+ Emit @{ drive = ($disk.DeviceID + '\'); type = [int]$disk.DriveType; label = $disk.VolumeName }+ }+ } catch {}+ try { $network = @(Get-ChildItem -LiteralPath 'HKCU:\Network' -ErrorAction Stop | ForEach-Object { $_.PSChildName + ':\' }) } catch {}+}+foreach ($root in $network) {+ $letter = $root.Substring(0, 1)+ $share = $null+ try { $share = (Get-ItemProperty -LiteralPath "HKCU:\Network\$letter" -ErrorAction Stop).RemotePath } catch {}+ if (-not $share) {+ try {+ $drives = (New-Object -ComObject WScript.Network).EnumNetworkDrives()+ for ($i = 0; $i -lt $drives.Count; $i += 2) {+ if ($drives.Item($i) -ieq ($letter + ':')) { $share = $drives.Item($i + 1) }+ }+ } catch {}+ }+ Emit @{ drive = $root; type = 4; share = $share }+}+$folders = @{}+foreach ($pair in @(@('desktop', 'Desktop'), @('documents', 'MyDocuments'), @('pictures', 'MyPictures'))) {+ try {+ $dir = [Environment]::GetFolderPath($pair[1])+ if ($dir -and (Test-Path -LiteralPath $dir -PathType Container)) { $folders[$pair[0]] = $dir }+ } catch {}+}+try {+ $shell = Get-ItemProperty -LiteralPath 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' -ErrorAction Stop+ $downloads = $shell.'{374DE290-123F-4565-9164-39C4925E467B}'+ if (-not $downloads) { $downloads = Join-Path $env:USERPROFILE 'Downloads' }+ $downloads = [Environment]::ExpandEnvironmentVariables($downloads)+ if (Test-Path -LiteralPath $downloads -PathType Container) { $folders['downloads'] = $downloads }+} catch {}+Emit @{ folders = $folders }+`;++/**+ * The script travels base64-encoded (UTF-16LE, what `-EncodedCommand` takes), so no character+ * in it meets the command line's quoting rules. Exported for the test that pins the arguments.+ */+export const POWERSHELL_ARGS: readonly string[] = [+ "-NoProfile",+ "-NonInteractive",+ "-NoLogo",+ "-ExecutionPolicy",+ "Bypass",+ "-EncodedCommand",+ Buffer.from(WINDOWS_REPORT_SCRIPT, "utf16le").toString("base64"),+];++/** Resolved from the system root so the desktop app's PATH, which users do break, is not relied on. */+function powershellPath(env: PlaceEffects["env"]): string {+ const root = env.SystemRoot ?? env.windir;+ return root+ ? path.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")+ : "powershell.exe";+}++function cmdPath(env: PlaceEffects["env"]): string {+ return env.ComSpec ?? "cmd.exe";+}++/** One drive line of the report, after normalization. */+export interface WindowsDrive {+ /** `C:\` */+ root: string;+ /** `System.IO.DriveType` and `Win32_LogicalDisk.DriveType` share the numbering: 2 removable, 3 fixed, 4 network, 5 CD-ROM, 6 RAM. */+ type: number;+ label?: string;+ /** A network drive's `\\server\share`. */+ share?: string;+}++export interface WindowsReport {+ /** Null until the report's folders line arrived: the script prints it last, after the drives. */+ folders: DirStandardFolders | null;+ drives: WindowsDrive[];+}++/** `C:`, `c:\`, `C:\Users` → `C:\`; null for anything that does not start with a drive letter. */+function driveRoot(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const match = /^([A-Za-z]):/.exec(value);+ return match === null ? null : `${match[1]?.toUpperCase()}:\\`;+}++function nonEmpty(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;+}++/**+ * The report's lines, each a JSON object (or an array of them), everything else skipped: a+ * line PowerShell's host printed on its own, or one cut short by the deadline.+ */+export function parseWindowsReport(text: string): WindowsReport {+ const report: WindowsReport = { folders: null, drives: [] };+ for (const line of text.split(/\r?\n/)) {+ const trimmed = line.trim();+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) continue;+ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ continue;+ }+ for (const item of Array.isArray(parsed) ? parsed : [parsed]) absorbReportItem(report, item);+ }+ return report;+}++function absorbReportItem(report: WindowsReport, item: unknown): void {+ if (typeof item !== "object" || item === null) return;+ const record = item as Record<string, unknown>;+ const folders = record.folders;+ if (typeof folders === "object" && folders !== null) {+ const found: DirStandardFolders = report.folders ?? {};+ for (const [key] of FIXED_FOLDERS) {+ const value = nonEmpty((folders as Record<string, unknown>)[key]);+ if (value !== undefined) found[key] = value;+ }+ report.folders = found;+ }+ const root = driveRoot(record.drive);+ if (root === null) return;+ const type = typeof record.type === "number" ? record.type : Number(record.type);+ const label = nonEmpty(record.label);+ const share = nonEmpty(record.share);+ report.drives.push({+ root,+ type: Number.isFinite(type) ? type : 0,+ ...(label !== undefined ? { label } : {}),+ ...(share !== undefined ? { share } : {}),+ });+}++function driveKind(type: number): DirLocation["kind"] {+ if (type === 2) return "removable";+ if (type === 4) return "network";+ if (type === 5) return "optical";+ return "drive";+}++/**+ * The drives as This PC lists them: local drives by letter, then network drives by letter. A+ * drive is named by its volume label when it has one; a network drive otherwise by its share —+ * Explorer shows `media (\\nas)`, and the server behind a dead mapping is never asked for a+ * label, so the share is what a network drive normally carries.+ */+export function windowsLocations(drives: readonly WindowsDrive[]): DirLocation[] {+ const unique = [...new Map(drives.map((d): [string, WindowsDrive] => [d.root, d])).values()];+ const byLetter = (a: WindowsDrive, b: WindowsDrive) => a.root.localeCompare(b.root);+ const locals = unique.filter((d) => d.type !== 4).sort(byLetter);+ const networks = unique.filter((d) => d.type === 4).sort(byLetter);+ return [...locals, ...networks].map((d) => {+ const label = d.label ?? d.share;+ return { path: d.root, kind: driveKind(d.type), ...(label !== undefined ? { label } : {}) };+ });+}++/** `cmd /u` writes UTF-16LE without a BOM; a child killed mid-character leaves an odd byte to drop. */+export function decodeCmdOutput(stdout: Buffer): string {+ return stdout.subarray(0, stdout.length - (stdout.length % 2)).toString("utf16le");+}++const DRIVE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");++/**+ * Drive letters without PowerShell: `if exist X:\` for each letter, inside a `cmd.exe` we can+ * kill. A dead network mapping blocks the loop at its letter; the letters printed before the+ * deadline are kept, and the probe pins a thread of the child's, not one of ours.+ */+async function probeDriveLetters(effects: PlaceEffects): Promise<DirLocation[]> {+ const probe = await effects.exec(+ cmdPath(effects.env),+ ["/d", "/u", "/c", `for %d in (${DRIVE_LETTERS.join(" ")}) do @if exist %d:\\ echo %d:`],+ { timeoutMs: CMD_TIMEOUT_MS, verbatim: true },+ );+ const roots = new Set<string>();+ for (const line of decodeCmdOutput(probe.stdout).split(/\r?\n/)) {+ const root = /^[A-Za-z]:$/.test(line.trim()) ? driveRoot(line.trim()) : null;+ if (root !== null) roots.add(root);+ }+ return [...roots].sort().map((root): DirLocation => ({ path: root, kind: "drive" }));+}++/** What is known without asking anything: the system drive and the one holding the home directory. */+function knownWindowsDrives(effects: PlaceEffects): DirLocation[] {+ const roots = new Set<string>();+ for (const candidate of [effects.env.SystemDrive, effects.homedir]) {+ const root = driveRoot(candidate);+ if (root !== null) roots.add(root);+ }+ return [...roots].sort().map((root): DirLocation => ({ path: root, kind: "drive" }));+}++async function windowsPlaces(effects: PlaceEffects): Promise<DirPlaces> {+ const run = await effects.exec(powershellPath(effects.env), [...POWERSHELL_ARGS], {+ timeoutMs: POWERSHELL_TIMEOUT_MS,+ });+ const report = parseWindowsReport(run.stdout.toString("utf8"));+ let locations = windowsLocations(report.drives);+ if (locations.length === 0) locations = await probeDriveLetters(effects);+ if (locations.length === 0) locations = knownWindowsDrives(effects);+ // A report cut short before its folders line leaves the folders unanswered rather than+ // guessed: the picker then finds them by name, as it did before.+ return {+ locations,+ ...(report.folders !== null ? { standardFolders: report.folders } : {}),+ };+}++// ---------------------------------------------------------------------------------------------+// The Windows hidden attribute++/**+ * Names Explorer hides in a profile or a drive root, for a listing whose attributes could not be+ * read: the profile's own files, the legacy junctions (hidden and access-denied, so a click on+ * one only fails), and the system's root-level folders.+ */+const HIDDEN_BY_CONVENTION = new Set(+ [+ "AppData",+ "Application Data",+ "Cookies",+ "Local Settings",+ "My Documents",+ "NetHood",+ "PrintHood",+ "Recent",+ "SendTo",+ "Start Menu",+ "Templates",+ "ntuser.ini",+ "desktop.ini",+ "Thumbs.db",+ "Documents and Settings",+ "System Volume Information",+ "pagefile.sys",+ "hiberfil.sys",+ "swapfile.sys",+ "DumpStack.log.tmp",+ "bootmgr",+ "BOOTNXT",+ "Config.Msi",+ ].map((n) => n.toLowerCase()),+);++/** The curated fallback: finding-7 names anywhere, `ntuser.dat*`, and `$`-prefixed names in a drive root. */+export function conventionallyHiddenNames(dir: string, names: readonly string[]): Set<string> {+ const atRoot = /^[A-Za-z]:\\?$/.test(dir);+ return new Set(+ names.filter((name) => {+ const lower = name.toLowerCase();+ return (+ HIDDEN_BY_CONVENTION.has(lower) ||+ lower.startsWith("ntuser.dat") ||+ (atRoot && name.startsWith("$"))+ );+ }),+ );+}++/**+ * Which of `names` in `dir` carry the hidden attribute, as `dir /a:h /b` reports them — the+ * attribute Explorer's default view hides (system-only items it shows, and every item Explorer+ * hides in a profile is hidden, so one attribute and one process suffice). `/u` makes the+ * output UTF-16LE whatever the console code page, `/d` keeps AutoRun commands out of it.+ *+ * The directory is an argument rather than the child's working directory because a mapped+ * drive's realpath is a UNC path, and cmd.exe started in a UNC directory warns and silently+ * runs in the Windows directory instead — wrong names with a clean exit. A path can hold no+ * `"`, so the quoting is safe; a segment spelled `%NAME%` after a variable that exists is the+ * one shape cmd mangles, and that folder's entries come back unmarked.+ *+ * `dir` exits 1 when nothing matched ("File Not Found", localized, on the stderr nobody reads),+ * so exit 1 with nothing printed means no hidden entries. Anything else — no cmd.exe, a+ * deadline, an unexpected exit — falls back to {@link conventionallyHiddenNames}.+ */+export async function windowsHiddenNames(+ dir: string,+ names: readonly string[],+ effects: PlaceEffects = systemEffects(),+): Promise<Set<string>> {+ if (names.length === 0) return new Set();+ const run = await effects.exec(+ cmdPath(effects.env),+ ["/d", "/u", "/c", "dir", "/a:h", "/b", `"${dir}"`],+ { timeoutMs: CMD_TIMEOUT_MS, verbatim: true },+ );+ const usable =+ run.failed === undefined &&+ !run.timedOut &&+ (run.code === 0 || (run.code === 1 && run.stdout.length === 0));+ if (!usable) return conventionallyHiddenNames(dir, names);+ const listed = new Set(+ decodeCmdOutput(run.stdout)+ .split(/\r?\n/)+ .map((line) => line.replace(/^\uFEFF/, ""))+ .filter((line) => line !== ""),+ );+ return new Set(names.filter((name) => listed.has(name)));+}diff --git a/packages/server/test/dir-places.test.ts b/packages/server/test/dir-places.test.tsnew file mode 100644index 00000000..84b6a12a--- /dev/null+++ b/packages/server/test/dir-places.test.ts@@ -0,0 +1,321 @@+/**+ * Place discovery for the Workspace picker's sidebar: the parsers for what each platform+ * reports, the decisions they feed, and the fallbacks when a report never comes. Every+ * platform call goes through a fake effects object, so each case runs wherever this suite+ * runs; the real machine is asked through the dirs route in dirs.test.ts.+ */+import path from "node:path";+import { describe, expect, it } from "vitest";+import {+ POWERSHELL_ARGS,+ conventionallyHiddenNames,+ createPlaceDiscovery,+ darwinLocations,+ discoverPlaces,+ parseMounts,+ parseWindowsReport,+ systemEffects,+ windowsHiddenNames,+ windowsLocations,+ type ExecOutcome,+ type PlaceDirent,+ type PlaceEffects,+} from "../src/services/dir-places.js";++const errno = (code: string) => Object.assign(new Error(code), { code });++/** A machine with nothing on it; each case overrides the calls it is about. */+function fakeEffects(over: Partial<PlaceEffects> & Pick<PlaceEffects, "platform">): PlaceEffects {+ return {+ homedir: "/home/me",+ env: {},+ readFile: async () => {+ throw errno("ENOENT");+ },+ readdir: async () => [],+ readlink: async () => {+ throw errno("EINVAL");+ },+ isDirectory: async () => false,+ exec: async () => ({+ stdout: Buffer.alloc(0),+ code: null,+ timedOut: false,+ failed: "not on this machine",+ }),+ ...over,+ };+}++const exited = (stdout: Buffer, code = 0): ExecOutcome => ({ stdout, code, timedOut: false });+const killed = (stdout: Buffer): ExecOutcome => ({ stdout, code: null, timedOut: true });+/** What `cmd /u` writes: UTF-16LE, CRLF, no BOM. */+const cmdOutput = (text: string) => Buffer.from(text, "utf16le");+const dirent = (name: string, kind: "dir" | "link"): PlaceDirent => ({+ name,+ isDirectory: () => kind === "dir",+ isSymbolicLink: () => kind === "link",+});++describe("parseMounts", () => {+ it("keeps the browsable mounts, decoded and in order, and none of the plumbing", () => {+ const text = [+ "sysfs /sys sysfs rw 0 0",+ "/dev/sda1 / ext4 rw 0 0",+ "/dev/sdb1 /media/me/My\\040USB vfat rw 0 0",+ "C:\\134 /mnt/c 9p rw,aname=drvfs 0 0",+ "D: /mnt/d drvfs rw 0 0",+ "//nas/media /mnt/nas cifs rw 0 0",+ "/dev/sdc1 /mnt/data ext4 rw 0 0",+ "/dev/sdc2 /mnt/data/sub ext4 rw 0 0",+ "tmpfs /mnt/wsl tmpfs rw 0 0",+ "none /mnt/wslg tmpfs rw 0 0",+ "/dev/sdd1 /mnt/wsl/docker-desktop ext4 rw 0 0",+ "tmpfs /run/media tmpfs rw 0 0",+ "/dev/sde1 /home/me/mnt ext4 rw 0 0",+ // A systemd automount: the trigger, then the real filesystem at the same point.+ "systemd-1 /mnt/auto autofs rw 0 0",+ "//nas/share /mnt/auto nfs4 rw 0 0",+ ].join("\n");+ expect(parseMounts(text)).toEqual([+ { path: "/media/me/My USB", kind: "removable", label: "My USB" },+ { path: "/mnt/auto", kind: "network", label: "auto" },+ { path: "/mnt/c", kind: "drive", label: "C:" },+ { path: "/mnt/d", kind: "drive", label: "D:" },+ { path: "/mnt/data", kind: "volume", label: "data" },+ { path: "/mnt/nas", kind: "network", label: "nas" },+ ]);+ });+});++describe("Linux standard folders", () => {+ it("follows user-dirs.dirs: localized names, $HOME expanded, the home value disabling a folder", async () => {+ const existing = new Set([+ "/home/me/桌面",+ "/home/me/下载",+ "/home/me/Pictures",+ "/home/me/Documents",+ ]);+ const effects = fakeEffects({+ platform: "linux",+ env: { XDG_CONFIG_HOME: "/home/me/.cfg" },+ readFile: async (file) => {+ if (file === "/proc/self/mounts") return "/dev/sda1 / ext4 rw 0 0\n";+ expect(file).toBe("/home/me/.cfg/user-dirs.dirs");+ return [+ "# This file is written by xdg-user-dirs-update",+ 'XDG_DESKTOP_DIR="$HOME/桌面"',+ 'XDG_DOWNLOAD_DIR="$HOME/下载"',+ 'XDG_DOCUMENTS_DIR="$HOME/"',+ 'XDG_PICTURES_DIR="$HOME/图片"',+ 'XDG_MUSIC_DIR="$HOME/音乐"',+ ].join("\n");+ },+ isDirectory: async (file) => existing.has(file),+ });+ const places = await discoverPlaces(effects);+ // Documents is disabled although ~/Documents exists; Pictures is configured to a folder+ // that does not exist, and the configured value wins over the English one that does.+ expect(places.standardFolders).toEqual({+ desktop: "/home/me/桌面",+ downloads: "/home/me/下载",+ });+ expect(places.locations[0]).toEqual({ path: "/", kind: "root" });+ });++ it("falls back to the English names that exist when there is no file", async () => {+ const effects = fakeEffects({+ platform: "linux",+ isDirectory: async (file) => file === "/home/me/Downloads",+ });+ expect((await discoverPlaces(effects)).standardFolders).toEqual({+ downloads: "/home/me/Downloads",+ });+ });+});++describe("Windows drive report", () => {+ it("maps each JSON line, or an array of them, to a location and skips what is not the report", () => {+ const text = [+ "Windows PowerShell wrote this line itself",+ '{"drive":"C:\\\\","type":3,"label":"Windows"}',+ '{"drive":"D:\\\\","type":3,"label":null}',+ '[{"drive":"E:\\\\","type":2,"label":"U 盘"},{"drive":"F:\\\\","type":5,"label":null}]',+ '{"drive":"Z:\\\\","type":4,"share":"\\\\\\\\nas\\\\media"}',+ '{"drive":"C:\\\\","type":3,"label":"Windows"}',+ '{"folders":{"desktop":"C:\\\\Users\\\\me\\\\OneDrive\\\\Desktop","pictures":""}}',+ '{"drive":"G:\\\\","type":3,"la',+ ].join("\r\n");+ const report = parseWindowsReport(text);+ expect(report.folders).toEqual({ desktop: "C:\\Users\\me\\OneDrive\\Desktop" });+ expect(windowsLocations(report.drives)).toEqual([+ { path: "C:\\", kind: "drive", label: "Windows" },+ { path: "D:\\", kind: "drive" },+ { path: "E:\\", kind: "removable", label: "U 盘" },+ { path: "F:\\", kind: "optical" },+ { path: "Z:\\", kind: "network", label: "\\\\nas\\media" },+ ]);+ });++ it("keeps what PowerShell printed before its deadline", async () => {+ const effects = fakeEffects({+ platform: "win32",+ homedir: "C:\\Users\\me",+ exec: async (file) => {+ expect(file).toBe("powershell.exe");+ return killed(+ Buffer.from('{"drive":"C:\\\\","type":3,"label":"Windows"}\n{"drive":"D:\\\\","ty'),+ );+ },+ });+ const places = await discoverPlaces(effects);+ expect(places.locations).toEqual([{ path: "C:\\", kind: "drive", label: "Windows" }]);+ // The folders line never came: unanswered, not "none", so the picker may find them by name.+ expect(places.standardFolders).toBeUndefined();+ });++ it("probes the letters through cmd when PowerShell said nothing, and knows the system drive when even that fails", async () => {+ const calls: string[] = [];+ const probing = fakeEffects({+ platform: "win32",+ homedir: "C:\\Users\\me",+ env: { ComSpec: "C:\\Windows\\system32\\cmd.exe", SystemRoot: "C:\\Windows" },+ exec: async (file, args) => {+ calls.push(file);+ if (file.endsWith("powershell.exe")) {+ return { stdout: Buffer.alloc(0), code: null, timedOut: false, failed: "spawn ENOENT" };+ }+ expect(args[3]).toMatch(/^for %d in \(A B C .* Z\) do @if exist %d:\\ echo %d:$/);+ // Killed while a dead mapping held the loop at E: the letters before it stand.+ return killed(cmdOutput("C:\r\nD:\r\nE"));+ },+ });+ expect((await discoverPlaces(probing)).locations).toEqual([+ { path: "C:\\", kind: "drive" },+ { path: "D:\\", kind: "drive" },+ ]);+ expect(calls).toEqual([+ "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",+ "C:\\Windows\\system32\\cmd.exe",+ ]);++ const blind = fakeEffects({+ platform: "win32",+ homedir: "D:\\Users\\me",+ env: { SystemDrive: "C:" },+ });+ expect((await discoverPlaces(blind)).locations).toEqual([+ { path: "C:\\", kind: "drive" },+ { path: "D:\\", kind: "drive" },+ ]);+ });+});++describe("windowsHiddenNames", () => {+ it("reads dir /a:h /b as UTF-16LE, the directory quoted on the command line", async () => {+ const calls: string[][] = [];+ const effects = fakeEffects({+ platform: "win32",+ exec: async (file, args, opts) => {+ calls.push([file, ...args]);+ expect(opts.verbatim).toBe(true);+ return exited(cmdOutput("AppData\r\n桌面\r\nNTUSER.DAT\r\n"));+ },+ });+ const names = ["AppData", "桌面", "Documents", "NTUSER.DAT"];+ const hidden = await windowsHiddenNames("C:\\Users\\我", names, effects);+ expect([...hidden].sort()).toEqual(["AppData", "NTUSER.DAT", "桌面"]);+ expect(calls).toEqual([["cmd.exe", "/d", "/u", "/c", "dir", "/a:h", "/b", '"C:\\Users\\我"']]);+ });++ it("treats exit 1 with nothing printed as no hidden entries, and anything worse as unknown", async () => {+ const none = fakeEffects({ platform: "win32", exec: async () => exited(Buffer.alloc(0), 1) });+ expect(await windowsHiddenNames("C:\\ws", ["AppData", "src"], none)).toEqual(new Set());++ const late = fakeEffects({ platform: "win32", exec: async () => killed(Buffer.alloc(0)) });+ expect(+ await windowsHiddenNames("C:\\", ["$Recycle.Bin", "Users", "pagefile.sys"], late),+ ).toEqual(new Set(["$Recycle.Bin", "pagefile.sys"]));+ // The `$` rule holds in a drive root only; elsewhere the curated names alone apply.+ expect(+ conventionallyHiddenNames("C:\\Users\\me", ["$money", "ntuser.dat.LOG1", "AppData", "src"]),+ ).toEqual(new Set(["ntuser.dat.LOG1", "AppData"]));+ });+});++describe("darwinLocations", () => {+ it("lists the startup disk first by its link, then the other volumes, and nothing hidden", async () => {+ const effects = fakeEffects({+ platform: "darwin",+ readdir: async (dir) => {+ expect(dir).toBe("/Volumes");+ return [+ dirent("USB", "dir"),+ dirent("Macintosh HD", "link"),+ dirent(".timemachine", "dir"),+ dirent("com.apple.TimeMachine.localsnapshots", "dir"),+ dirent("Backup", "link"),+ dirent("NAS", "dir"),+ ];+ },+ readlink: async (file) =>+ file === "/Volumes/Macintosh HD" ? "/" : "/System/Volumes/Data/Backups",+ });+ expect(await darwinLocations(effects)).toEqual([+ { path: "/", kind: "volume", label: "Macintosh HD" },+ { path: "/Volumes/NAS", kind: "volume", label: "NAS" },+ { path: "/Volumes/USB", kind: "volume", label: "USB" },+ ]);+ // Without the link the root still leads, unnamed.+ expect(await darwinLocations(fakeEffects({ platform: "darwin" }))).toEqual([+ { path: "/", kind: "volume" },+ ]);+ });+});++describe("createPlaceDiscovery", () => {+ it("shares one run between concurrent callers and keeps it until the TTL passes", async () => {+ let runs = 0;+ let clock = 1_000;+ const effects = fakeEffects({+ platform: "linux",+ readFile: async (file) => {+ if (file !== "/proc/self/mounts") throw errno("ENOENT");+ runs += 1;+ return "/dev/sda1 / ext4 rw 0 0\n";+ },+ });+ const discovery = createPlaceDiscovery(effects, { ttlMs: 100, now: () => clock });+ const [a, b] = await Promise.all([discovery.discover(), discovery.discover()]);+ expect(a).toBe(b);+ expect(runs).toBe(1);+ clock += 50;+ expect(await discovery.discover()).toBe(a);+ clock += 60;+ expect(await discovery.discover()).not.toBe(a);+ expect(runs).toBe(2);+ });+});++/**+ * The one place the Windows report script itself runs. Everything above feeds the parser text;+ * a script that fails on a real PowerShell would fall back to the letter probe without a word,+ * and the drive labels and the redirected folders would simply never show. The budget is the+ * test's own, generous for a cold runner, not the route's.+ */+it.runIf(process.platform === "win32")(+ "the Windows report script runs and reports the system drive and the folders line",+ async () => {+ const systemRoot = process.env.SystemRoot ?? "C:\\Windows";+ const out = await systemEffects().exec(+ path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),+ [...POWERSHELL_ARGS],+ { timeoutMs: 60_000 },+ );+ const report = parseWindowsReport(out.stdout.toString("utf8"));+ const systemDrive = `${(process.env.SystemDrive ?? "C:").toUpperCase()}\\`;+ expect(report.drives.find((d) => d.root === systemDrive)?.type).toBe(3);+ expect(report.folders).not.toBeNull();+ },+ 90_000,+);diff --git a/packages/server/test/dirs.test.ts b/packages/server/test/dirs.test.tsindex c4fa831e..3a8f311c 100644--- a/packages/server/test/dirs.test.ts+++ b/packages/server/test/dirs.test.ts@@ -2,8 +2,12 @@* 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.+ * like that, and an empty list hid it. The home request with `places=1` adds this machine's+ * own locations and standard folders; on Windows a listing marks what Explorer hides and a+ * bare drive letter opens that drive. Those cases ask the real machine, which is the only+ * exercise the Windows and macOS branches get before a release.*/+import { execFileSync } from "node:child_process";import fs from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -14,12 +18,20 @@ import type {DirListResponse,ProjectCreateResponse,} from "../src/api/types.js";-import { dirReadError, isSameOrAbove } from "../src/http/routes/dirs.js";+import { dirReadError, isSameOrAbove, normalizeRequestedDir } from "../src/http/routes/dirs.js";import { apiClient, canCreateSymlink, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";const errno = (code: string) => Object.assign(new Error(code), { code });+describe("normalizeRequestedDir", () => {+ it("reads a bare drive as its root on Windows and leaves everything else alone", () => {+ expect(normalizeRequestedDir("d:", "win32")).toBe("d:\\");+ expect(normalizeRequestedDir("D:\\work", "win32")).toBe("D:\\work");+ expect(normalizeRequestedDir("d:", "linux")).toBe("d:");+ });+});+describe("dirReadError", () => {it("gives a refusal its own code, whichever errno the OS used for it", () => {for (const code of ["EACCES", "EPERM"]) {@@ -77,6 +89,48 @@ describe("dirs api", () => {expect(body.entries.every((e) => typeof e.mtime === "number")).toBe(true);});+ it("answers the home request's places only when asked, starting at this machine's root", async () => {+ const plain = (await (await owner.get(listUrl(""))).json()) as DirListResponse;+ expect(plain.locations).toBeUndefined();+ expect(plain.standardFolders).toBeUndefined();++ const res = await owner.get(`${listUrl("")}&places=1`);+ expect(res.status).toBe(200);+ const body = (await res.json()) as DirListResponse;+ expect(body.path).toBe(await fs.realpath(os.homedir()));+ if (process.platform === "win32") {+ // The folders are not asserted here: a PowerShell past its budget on a loaded runner+ // leaves them unanswered by design, and the drives come from the probe regardless.+ const system = `${process.env.SystemDrive ?? "C:"}\\`;+ expect(body.locations?.find((l) => l.path === system)?.kind).toBe("drive");+ } else {+ expect(typeof body.standardFolders).toBe("object");+ expect(body.locations?.[0]).toMatchObject({+ path: "/",+ kind: process.platform === "darwin" ? "volume" : "root",+ });+ }+ });++ it.runIf(process.platform === "win32")(+ "opens a bare drive letter as its root and marks what Explorer hides",+ async () => {+ const drive = process.env.SystemDrive ?? "C:";+ const root = (await (await owner.get(listUrl(drive))).json()) as DirListResponse;+ expect(root.path).toBe(`${drive}\\`);+ expect(root.parent).toBeNull();++ await fs.writeFile(path.join(dir, "shown.txt"), "x");+ await fs.writeFile(path.join(dir, "secret.txt"), "x");+ execFileSync("attrib", ["+h", path.join(dir, "secret.txt")]);+ const body = (await (await owner.get(listUrl(dir))).json()) as DirListResponse;+ expect(body.entries.map((e) => [e.name, e.hidden])).toEqual([+ ["secret.txt", true],+ ["shown.txt", undefined],+ ]);+ },+ );+// 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",diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.tsindex 84982517..df6972bc 100644--- a/packages/ui-gallery/src/app/mock/fixtures.ts+++ b/packages/ui-gallery/src/app/mock/fixtures.ts@@ -1320,6 +1320,11 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {],},"/home": { path: "/home", parent: "/", entries: [{ name: "demo", path: "/home/demo" }] },+ "/mnt/data": {+ path: "/mnt/data",+ parent: "/mnt",+ entries: [{ name: "datasets", path: "/mnt/data/datasets" }],+ },"/": { path: "/", parent: null, entries: [{ name: "home", path: "/home" }] },};diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex 2704fa8b..d9b31954 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -826,7 +826,19 @@ router}).get("/api/projects/:projectId/dirs", ({ store, query }): DirListResponse => {const path = query.get("path") || "/home/demo";- return store.f.dirs[path] ?? { path, parent: "/home/demo", entries: [] };+ const listing = store.f.dirs[path] ?? { path, parent: "/home/demo", entries: [] };+ // The home request that builds the finder's sidebar also carries the machine's own places,+ // as the server's does: a Linux machine's root and one mounted disk.+ if (query.get("path") || query.get("places") !== "1") return listing;+ return {+ ...listing,+ platform: "linux",+ standardFolders: {},+ locations: [+ { path: "/", kind: "root" },+ { path: "/mnt/data", kind: "volume", label: "data" },+ ],+ };}).get("/api/projects/:projectId/machines/:machineId/dirs", ({ store, query }): DirListResponse => {const path = query.get("path") || "/home/demo";diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.tsindex 72274bca..b590c837 100644--- a/packages/ui/src/components/icons/icons.ts+++ b/packages/ui/src/components/icons/icons.ts@@ -71,6 +71,13 @@ export const ICONS = {chip: "M5 5h14v14H5zM9 9h6v6H9zM7.5 5V2.4M12 5V2.4M16.5 5V2.4M7.5 19v2.6M12 19v2.6M16.5 19v2.6M5 7.5H2.4M5 12H2.4M5 16.5H2.4M19 7.5h2.6M19 12h2.6M19 16.5h2.6",/** Two stacked server units, each with its own status lamp. */server: "M4 4h16v6H4zM4 14h16v6H4zM7 7h.01M7 17h.01",+ /**+ * A drive: the box with its lamp, and a platter drawn as the lid's slope. The Workspace+ * finder's one storage drawing — a fixed disk, a volume and a Linux root all take it.+ */+ hardDrive: "M3 13h18v6H3zM5 13l2-8h10l2 8M17 16h.01",+ /** A plug: two prongs, the body and its cord trailing below (what is plugged in). */+ plug: "M9 2v4M15 2v4M6 6h12v4a6 6 0 0 1-12 0V6zM12 16v6",/** A trophy: cup, two handles and a base. */trophy: "M7 4h10v5a5 5 0 0 1-10 0V4zM7 5H4v1a3 3 0 0 0 3 3m10-4h3v1a3 3 0 0 1-3 3M12 14v4m-4 0h8",/** A `>_` prompt in a window frame. */diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 72b069f5..809997ad 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -752,15 +752,26 @@ export const listSessions = (* Browses directories. With no machine, this server's own filesystem; with one, THAT* machine's — listed by this server over ssh, so picking a workspace on another machine* needs no second login to that machine's own server.+ *+ * `places` asks a home request (empty `path`) for the machine's standard folders and its+ * locations (drives, volumes, mounts) as well. Only this server discovers them, so the flag+ * goes on the local route alone; a machine reached over ssh answers with its folders only.*/-export const listDirs = (projectId: string, path = "", machineId?: string | null) =>- machineId === undefined || machineId === null+export const listDirs = (+ projectId: string,+ path = "",+ machineId?: string | null,+ opts?: { places?: boolean },+) => {+ const places = opts?.places === true ? "&places=1" : "";+ return machineId === undefined || machineId === null? apiFetch<DirListResponse>(- `/api/projects/${encodeURIComponent(projectId)}/dirs?path=${encodeURIComponent(path)}`,+ `/api/projects/${encodeURIComponent(projectId)}/dirs?path=${encodeURIComponent(path)}${places}`,): apiFetch<DirListResponse>(`/api/projects/${encodeURIComponent(projectId)}/machines/${encodeURIComponent(machineId)}/dirs?path=${encodeURIComponent(path)}`,);+};/*** Makes one folder inside `parent` (the picker's "New folder"). `name` is a single segment, notdiff --git a/packages/web/src/features/chat/workspace-finder-model.ts b/packages/web/src/features/chat/workspace-finder-model.tsindex c03ceb5f..54dc59c9 100644--- a/packages/web/src/features/chat/workspace-finder-model.ts+++ b/packages/web/src/features/chat/workspace-finder-model.ts@@ -2,17 +2,20 @@* 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, the keyboard map, what the box for a folder the- * server may not read offers, and the footer's no-folder button.+ * removals, and the machine's locations — drives, volumes, mounts — with their names), the+ * context menu's items, the keyboard map, what the box for a folder the server may not read+ * offers, and the footer's no-folder button.** 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.+ * have to split correctly in the same tab. The keyboard map alone is told the user's own+ * platform: keys follow where the user sits, not the machine being browsed.*/import type {DesktopPrivacyPane,DirEntryInfo,DirListResponse,+ DirLocation,} from "@lmliheng/penguin-server/api";import {TEMP_WORKSPACE_GROUP_KEY,@@ -117,12 +120,14 @@ 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.+ * substring), folders first and then by name. Hidden is a dot-name everywhere, plus whatever+ * the machine itself marks hidden: a Windows profile holds `AppData`, `desktop.ini` and the old+ * junctions that refuse to be opened, none of which its own Explorer shows.*/export function visibleEntries(entries: readonly DirEntryInfo[], filter: string): DirEntryInfo[] {const q = filter.trim().toLowerCase();return entries- .filter((e) => !e.name.startsWith("."))+ .filter((e) => !e.name.startsWith(".") && e.hidden !== true).filter((e) => q === "" || e.name.toLowerCase().includes(q)).sort((a, b) => {const fa = isFolder(a);@@ -162,11 +167,18 @@ export function stepSelection(/** A standard folder that a platform's own file manager lists in its sidebar. */export type StandardFolder = "desktop" | "documents" | "downloads" | "pictures";+/** What kind of storage a location is: a Windows drive by its type, a volume, a Linux root. */+export type LocationKind = DirLocation["kind"];+/** 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";+ key: "home" | StandardFolder | LocationKind | "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. */+ /**+ * The label for places named by their path: home by its folder name, an added folder by its+ * name. A location's is the machine's own name for it, empty when it has none; locationName+ * builds what the row shows from it.+ */label: string;}@@ -212,36 +224,80 @@ const STANDARD_FOLDERS: Record<};/**- * 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.+ * Quick access as the machine offers it before the user changes anything: home itself, then+ * the platform's standard folders that exist there. Where the machine resolved them itself+ * (`standardFolders`) its answer is taken whole, since only it knows that Windows moved+ * Documents into OneDrive or that a Linux desktop set up in another language names its folders+ * in that language. Otherwise — a machine reached over ssh — they are found by their English+ * names in the home listing, rather than guessed, because only that listing says 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. Either way the platform's own order is kept,+ * and a folder that turns out to be home, or another place already listed, is not listed twice.*/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) }];+ const resolved = home.standardFolders;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 });+ const path =+ resolved !== undefined+ ? resolved[key]+ : home.entries.find(+ (e) =>+ isFolder(e) &&+ (platform === "win32"+ ? e.name.toLowerCase() === name.toLowerCase()+ : e.name === name),+ )?.path;+ if (path !== undefined && path !== "" && !places.some((p) => p.path === path)) {+ places.push({ key, path, label: baseName(path) });+ }}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(/\\$/, ""),+/**+ * The machine's locations — Windows' drives, a Mac's volumes, a Linux root and its mounts — in+ * the order the machine gave them, for the sidebar section after Quick access and the address+ * bar's root menu. Nothing for a machine that reported none (one reached over ssh).+ */+export function locationPlaces(home: DirListResponse | null): Place[] {+ return (home?.locations ?? []).map((loc) => ({+ key: loc.kind,+ path: loc.path,+ label: loc.label ?? "",}));}+/** The words a location's name is built from, in the reader's language (the finder's strings). */+export interface LocationNames {+ /** A Windows drive with no label of its own, by its type, as Explorer names it. */+ drives: Record<"drive" | "removable" | "network" | "optical", string>;+ /** A Linux machine's file-system root. */+ fileSystem: string;+}++/**+ * What a location's row says. A Windows drive is named as Explorer names it — its label, or+ * the name of its type when it has none, then the letter: `Windows (C:)`, `USB Drive (E:)`,+ * and for a network drive whose share stands in for the label, `\\nas\media (Z:)`. A Linux+ * root is the file system, as its file managers call it; anything else (a Mac volume, a+ * mount, a WSL drive under `/mnt`) goes by its own name, or by its folder's when it has none.+ */+export function locationName(place: Place, names: LocationNames): string {+ const letter = /^([A-Za-z]:)\\?$/.exec(place.path)?.[1];+ if (letter !== undefined) {+ const kind =+ place.key === "removable" || place.key === "network" || place.key === "optical"+ ? place.key+ : "drive";+ return `${place.label !== "" ? place.label : names.drives[kind]} (${letter.toUpperCase()})`;+ }+ if (place.key === "root") return names.fileSystem;+ return place.label !== "" ? place.label : baseName(place.path);+}+/** What the user changed in one machine's Quick access. */export interface QuickAccessEdits {/** Folders the user added, oldest first. */@@ -422,11 +478,14 @@ export function recentWorkspaces(/*** "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+ * when it is known (the dirs API takes absolute paths only), and a bare drive (`d:`) is that+ * drive's root, as Explorer's address bar takes it — to Windows itself `D:` is wherever that+ * drive's current directory is, which a server has no use for. Anything else is sent as typed* and the server decides.*/export function resolveGoTo(input: string, home: string | null): string {const p = input.trim();+ if (/^[A-Za-z]:$/.test(p)) return `${p.toUpperCase()}\\`;if (home === null) return p;if (p === "~") return home;const m = /^~[\\/](.*)$/.exec(p);@@ -437,7 +496,17 @@ export function resolveGoTo(input: string, home: string | null): string {/** What a key press asks the finder to do. */export type FinderAction =- "up" | "down" | "first" | "last" | "open" | "parent" | "back" | "forward" | "goto" | "choose";+ | "up"+ | "down"+ | "first"+ | "last"+ | "open"+ | "parent"+ | "back"+ | "forward"+ | "goto"+ | "choose"+ | "refresh";/** The keyboard-event fields the map reads (a subset of KeyboardEvent, for tests). */export type FinderKey = Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">;@@ -445,10 +514,13 @@ export type FinderKey = Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "alt/*** 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).+ * bar) read the same on every platform; off the Mac, Explorer's own keys work too — Alt+arrows+ * for back, forward and up, and Ctrl+L, Alt+D and F4 for the address bar (Ctrl+L is also the+ * Linux file managers'). F5 refreshes everywhere, as it does in Explorer and in a browser,+ * where it would otherwise reload the whole app out from under the dialog; with a modifier it+ * is left to the browser's own hard reload. 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,@@ -457,6 +529,7 @@ export function finderKeyAction(): FinderAction | null {const mod = isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;const bare = !e.metaKey && !e.ctrlKey && !e.altKey;+ if (bare && !e.shiftKey && e.key === "F5") return "refresh";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";@@ -464,13 +537,16 @@ export function finderKeyAction(if (e.key === "[") return "back";if (e.key === "]") return "forward";if (e.key === "Enter") return "choose";+ if (!isMac && (e.key === "l" || e.key === "L")) return "goto";}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 (e.key === "d" || e.key === "D") return "goto";}if (!bare || e.shiftKey) return null;+ if (!isMac && e.key === "F4") return "goto";if (e.key === "ArrowDown") return "down";if (e.key === "ArrowUp") return "up";if (!inList) return null;diff --git a/packages/web/src/features/chat/workspace-finder.tsx b/packages/web/src/features/chat/workspace-finder.tsxindex e8c57cf6..e7217e16 100644--- a/packages/web/src/features/chat/workspace-finder.tsx+++ b/packages/web/src/features/chat/workspace-finder.tsx@@ -7,6 +7,17 @@* 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.*+ * What the sidebar offers is the browsed machine's own answer, not this browser's: its+ * standard folders as it resolves them, and its locations — Windows' drives under This PC, a+ * Mac's volumes, a Linux root and its mounts under Locations — named the way that platform's+ * file manager names them. The same locations hang off a caret at the head of the address bar,+ * so another drive is one click away even where the sidebar is a drawer. They are asked for+ * again on every open, beside the folder rather than ahead of it (a drive plugged in since+ * shows up; a slow drive never holds the list), and the previous answer stays up until the new+ * one lands. Keys follow the platform the user sits at, not the one being browsed: Explorer's+ * Ctrl+L, Alt+D and F4 edit the address off the Mac, and F5 refreshes everywhere instead of+ * reloading the app.+ ** 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@@ -32,6 +43,7 @@ import type {import type { DesktopPrivacyPane, DirListResponse } from "@lmliheng/penguin-server/api";import {Button,+ ChevronDown,CloseIcon,ConfirmModal,Dropdown,@@ -71,7 +83,6 @@ import {clearButton,defaultPlaces,deniedBox,- drivePlaces,finderKeyAction,finderMenuItems,historyStep,@@ -80,6 +91,8 @@ import {isFolder,isTypeSelectKey,loadQuickAccess,+ locationName,+ locationPlaces,parentOf,quickAccessPlaces,recentWorkspaces,@@ -104,7 +117,6 @@ 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";@@ -113,13 +125,23 @@ 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";+/**+ * The registry has one storage drawing, the drive, so a fixed disk, a volume and a Linux root+ * all take it; the other kinds borrow the nearest thing the registry draws — a plug for what+ * is plugged in, the network for a share, a disc for an optical drive.+ */const PLACE_ICON: Record<Place["key"], string> = {home: HOME_ICON,desktop: DESKTOP_ICON,documents: ICONS.file,downloads: ICONS.download,pictures: PICTURES_ICON,- drive: DRIVE_ICON,+ drive: ICONS.hardDrive,+ volume: ICONS.hardDrive,+ root: ICONS.hardDrive,+ removable: ICONS.plug,+ network: ICONS.network,+ optical: ICONS.target,folder: ICONS.folder,};@@ -211,7 +233,10 @@ export function WorkspaceFinder({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. */+ /**+ * The browsed machine's home listing, asked for with its places: Quick access, the locations,+ * and the platform the pane's copy depends on.+ */const [home, setHome] = useState<{ machine: string | null; listing: DirListResponse } | null>(null,);@@ -241,6 +266,8 @@ export function WorkspaceFinder({/** 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("");+ /** The address bar's root menu: the machine's locations, from the caret before the path. */+ const [rootMenuOpen, setRootMenuOpen] = useState(false);const [sidebarOpen, setSidebarOpen] = useState(false);const [listFocused, setListFocused] = useState(false);const typed = useRef({ text: "", at: 0 });@@ -315,12 +342,22 @@ export function WorkspaceFinder({});};+ /** Monotonic id of the newest home request: an older answer landing late never replaces it. */+ const homeSeq = useRef(0);++ /**+ * Asks machine `m` for its home listing with its places — every time, not once per machine:+ * a drive plugged in, or a folder moved, since the last ask has to show up, and the server+ * keeps a repeat cheap. It is a request of its own beside the folder's, so the list never+ * waits on the places being found. Whatever the sidebar shows stays up until the answer+ * lands (or for good, if it fails), rather than emptying for the length of a request.+ */const loadHome = (m: string | null) => {- if (home?.machine === m) return;+ const seq = ++homeSeq.current;api- .listDirs(projectId, "", m)+ .listDirs(projectId, "", m, { places: true }).then((listing) => {- if (machineRef.current === m) setHome({ machine: m, listing });+ if (seq === homeSeq.current && machineRef.current === m) setHome({ machine: m, listing });}).catch(() => undefined);};@@ -338,7 +375,12 @@ export function WorkspaceFinder({// 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;+ if (!open) {+ // The root menu's state outlives its panel, which unmounts with the finder: left set, the+ // next open would pop the menu up again and pull focus into it.+ setRootMenuOpen(false);+ return;+ }setAddressEditing(false);setSidebarOpen(false);const ws = workspace.trim();@@ -419,7 +461,7 @@ export function WorkspaceFinder({);const homeListing = home?.machine === machine ? home.listing : null;const defaults = useMemo(() => defaultPlaces(homeListing), [homeListing]);- const drives = useMemo(() => drivePlaces(homeListing), [homeListing]);+ const locations = useMemo(() => locationPlaces(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)),@@ -630,6 +672,17 @@ export function WorkspaceFinder({const editAddress = () => {setAddressDraft(view.listing?.path ?? view.path);setAddressEditing(true);+ // The field replaces the segments and the caret before them, menu and all.+ setRootMenuOpen(false);+ };++ /** A location from the address bar's root menu: opened like a sidebar place, as a visit. */+ const openLocation = (path: string) => {+ setRootMenuOpen(false);+ setSidebarOpen(false);+ load(path);+ // The panel is gone and took focus with it; the list is where the keyboard picks up.+ listRef.current?.focus();};/** Leaves the field as it was: Escape, or focus moving elsewhere, as in Explorer. */@@ -865,6 +918,9 @@ export function WorkspaceFinder({case "choose":choose();return;+ case "refresh":+ refresh();+ return;}};@@ -884,20 +940,29 @@ export function WorkspaceFinder({*/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 action = finderKeyAction(e, isMac, inList);+ // F5 is the finder's wherever focus is in it — a typed path and a menu portaled out of it+ // included: let through, it reloads the whole app and the dialog with it.+ if (action === "refresh") {+ e.preventDefault();+ e.stopPropagation();+ run(action);+ return;+ }+ // A menu portaled to body is still a React child of the band that opened it (the address+ // bar's root menu is the toolbar's), so its keys bubble through here: its arrows and Enter+ // are the menu's, not the list's.+ if (!e.currentTarget.contains(target)) return;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.+ // The address field is a path being typed: only its own chords (which close it) apply.const inAddress = target === addressRef.current;- const action = finderKeyAction(e, isMac, inList);if (action === null) {if (inList && isTypeSelectKey(e)) {e.preventDefault();@@ -1000,10 +1065,21 @@ export function WorkspaceFinder({);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];+ switch (place.key) {+ case "home":+ case "folder":+ return place.label;+ case "desktop":+ case "documents":+ case "downloads":+ case "pictures":+ // Finder's Chinese word for Documents is not Explorer's or Files': each machine's own.+ return place.key === "documents" && platform === "darwin"+ ? f.documentsMac+ : f.places[place.key];+ default:+ return locationName(place, f);+ }};const currentFolder = view.listing?.path ?? null;@@ -1048,16 +1124,18 @@ export function WorkspaceFinder({</ul></>)}- {/* Windows' drives, where Explorer keeps them: under This PC, apart from Quick access. */}- {drives.length > 0 && (+ {/* The machine's locations, apart from Quick access as every file manager keeps them:+ Windows' drives under This PC, a Mac's volumes or a Linux root and its mounts under+ Locations. */}+ {locations.length > 0 && (<>- {sideHeading(f.thisPc)}+ {sideHeading(homeListing?.platform === "win32" ? f.thisPc : f.locations)}<ul className="space-y-0.5">- {drives.map((place) =>+ {locations.map((place) =>sideRow({- key: `drive:${place.path}`,+ key: `location:${place.path}`,icon: PLACE_ICON[place.key],- label: place.label,+ label: placeLabel(place),title: place.path,active: view.path === place.path,onClick: () => load(place.path),@@ -1135,7 +1213,9 @@ export function WorkspaceFinder({* 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.+ * leaving the field puts the segments back. Where the machine reported its locations, a caret+ * between the folder mark and the path opens them as a menu; the field replaces it along with+ * the segments.*/const addressBar = (<div@@ -1181,6 +1261,44 @@ export function WorkspaceFinder({><GlyphIcon d={ICONS.folder} size={ICON_SIZE.inlineGlyph} /></button>+ {/* The machine's locations, one click from any folder, the way Explorer's address bar+ drops its root list from the arrow at its head. It sits before the path rather+ than in it: the path scrolls to its end, so a root segment can be out of sight —+ on a phone above all, where the sidebar that also lists them is a drawer. */}+ {locations.length > 0 && (+ <Dropdown+ open={rootMenuOpen}+ setOpen={setRootMenuOpen}+ portal={{ direction: "down", align: "left" }}+ className="flex h-full shrink-0 items-center"+ menuClass="w-max min-w-40 max-w-[calc(100vw-2rem)]"+ button={+ <button+ type="button"+ aria-label={f.switchLocation}+ aria-haspopup="menu"+ aria-expanded={rootMenuOpen}+ // Its hint would only cover the menu it names while that is open.+ {...(rootMenuOpen ? {} : { "data-tooltip": f.switchLocation })}+ onClick={() => setRootMenuOpen((v) => !v)}+ className="flex h-full items-center px-1.5 text-fg-subtle transition-colors duration-150 hover:text-fg"+ >+ <ChevronDown size={ICON_SIZE.caret} />+ </button>+ }+ >+ <Menu density="sm" label={f.switchLocation}>+ {locations.map((place) => (+ <MenuItem+ key={place.path}+ glyph={PLACE_ICON[place.key]}+ label={placeLabel(place)}+ onSelect={() => openLocation(place.path)}+ />+ ))}+ </Menu>+ </Dropdown>+ )}<navref={crumbsRef}aria-label={f.path}@@ -1533,8 +1651,10 @@ export function WorkspaceFinder({machine,});+ // The key map reaches the footer's buttons too, so F5 from Choose refreshes rather than+ // reloading the app; `contents` keeps the wrapper out of the footer's own row layout.const footer = (- <>+ <div className="contents" onKeyDown={onKeyDown}>{/* The host's "no folder" choice: a plain text button whatever is chosen now; the folder atemporary Workspace would get is its tooltip. */}{clear !== null && (@@ -1561,7 +1681,7 @@ export function WorkspaceFinder({>{f.choose}</Button>- </>+ </div>);return (diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 52af8c72..09625656 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -2546,6 +2546,15 @@ export const en: Strings = {hideSidebar: "Hide sidebar",quickAccess: "Quick access",thisPc: "This PC",+ locations: "Locations",+ drives: {+ drive: "Local Disk",+ removable: "USB Drive",+ network: "Network Drive",+ optical: "CD Drive",+ },+ fileSystem: "File System",+ switchLocation: "Switch location",recent: "Recent",machines: "Machines",places: {diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 4c5232b0..2f94fe8a 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -2584,6 +2584,19 @@ export const zh = {quickAccess: "常用",/** Windows only: the section listing the drives. */thisPc: "此电脑",+ /** The same section on a Mac (its volumes) or a Linux machine (the root and the mounted devices). */+ locations: "位置",+ /** A Windows drive with no label of its own, by its type, as Explorer names it; the letter follows. */+ drives: {+ drive: "本地磁盘",+ removable: "U 盘",+ network: "网络驱动器",+ optical: "CD 驱动器",+ },+ /** A Linux machine's root directory, as its file managers name it. */+ fileSystem: "文件系统",+ /** The caret before the path that lists the machine's drives or volumes: its accessible name and hint. */+ switchLocation: "切换位置",recent: "最近使用",machines: "机器",places: {diff --git a/packages/web/test/icon-registry.test.ts b/packages/web/test/icon-registry.test.tsindex 91a0deec..bd3a3bd1 100644--- a/packages/web/test/icon-registry.test.ts+++ b/packages/web/test/icon-registry.test.ts@@ -34,7 +34,7 @@ const ALLOWLIST: Readonly<Record<string, readonly [number, string]>> = {"features/chat/subagents-view.tsx": [1, "W6"],"features/chat/task-stats-line.tsx": [1, "W6"],"features/chat/workspace-browser.tsx": [1, "W7"],- "features/chat/workspace-finder.tsx": [11, "W10"],+ "features/chat/workspace-finder.tsx": [10, "W10"],"features/company/channel-header.tsx": [4, "W6"],"features/company/channel-sidebar.tsx": [2, "W4"],"features/company/channel-view.tsx": [1, "W6"],diff --git a/packages/web/test/workspace-finder.test.ts b/packages/web/test/workspace-finder.test.tsindex fad7ec3e..e847e0a1 100644--- a/packages/web/test/workspace-finder.test.ts+++ b/packages/web/test/workspace-finder.test.ts@@ -5,19 +5,23 @@* - Breadcrumbs split a posix path from the root and keep a drive root whole.* - History goes back and forward, a new visit drops what was ahead, and reloading the folder* shown records nothing.- * - The list hides hidden entries and puts folders first; type-to-select finds a folder by- * prefix and arrow keys skip files, stopping at the ends.+ * - The list hides dot-names and what the machine marks hidden, and puts folders first;+ * type-to-select finds a folder by prefix and arrow keys skip files, stopping at the ends.* - The keyboard map reads the Finder chords with ⌘ on a Mac and Ctrl elsewhere, leaving Enter- * and Home/End to a text field.- * - Quick access offers each platform's standard folders that exist there (Windows names- * ignoring case), keeps Windows drives apart, takes the user's additions and removals (a+ * and Home/End to a text field; Explorer's address keys work off the Mac, and F5 refreshes+ * everywhere.+ * - Quick access takes the standard folders the machine resolved itself, or else finds each+ * platform's by name (Windows ignoring case), takes the user's additions and removals (a* default included), and stores them per machine, reading anything unreadable as none.+ * - Locations keep the machine's order and are named the way its file manager names them: a+ * Windows drive by its label or its type and then its letter, a Linux root as the file+ * system, anything else by its own name.* - The context menu offers open, choose, Delete, Quick access and copy on a folder, copy only* on a file, and acts on the open folder (with New folder, Delete and Refresh) from the* list's empty space — while a target on another machine carries neither of the two rows that* would change that machine's filesystem.* - Recent folds the newest Session per Workspace across Agents, leaving temporary ones out;- * "go to" resolves ~ against the machine's home.+ * "go to" resolves ~ against the machine's home, and a bare drive to its root.* - A folder the server may not read gets a box of its own: the desktop app's access request* only on a Mac, in the shell, browsing its own server, and never Retry alone where there is* something better to do.@@ -27,7 +31,7 @@* layout.*/import { describe, expect, it } from "vitest";-import type { DirEntryInfo, DirListResponse } from "@lmliheng/penguin-server/api";+import type { DirEntryInfo, DirListResponse, DirLocation } from "@lmliheng/penguin-server/api";import {EMPTY_HISTORY,NO_EDITS,@@ -37,12 +41,13 @@ import {clearButton,defaultPlaces,deniedBox,- drivePlaces,finderKeyAction,finderMenuItems,historyStep,historyVisit,loadQuickAccess,+ locationName,+ locationPlaces,parentOf,quickAccessKey,quickAccessPlaces,@@ -108,11 +113,18 @@ describe("history", () => {describe("the list", () => {const entries = visibleEntries(- [dir("zeta"), dir("notes.txt", "file"), dir(".git"), dir("Alpha"), dir("beta")],+ [+ dir("zeta"),+ dir("notes.txt", "file"),+ dir(".git"),+ { ...dir("AppData"), hidden: true },+ dir("Alpha"),+ dir("beta"),+ ],"",);- it("drops hidden entries and puts folders first", () => {+ it("drops dot-names and what the machine marks hidden, 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"]);});@@ -156,6 +168,18 @@ describe("keyboard map", () => {expect(finderKeyAction(key("Home"), false, false)).toBeNull();expect(finderKeyAction(key("ArrowDown"), false, false)).toBe("down");});++ it("takes Explorer's address keys off the Mac, and F5 everywhere", () => {+ for (const k of [key("l", { ctrl: true }), key("D", { alt: true }), key("F4")]) {+ expect(finderKeyAction(k, false, false), k.key).toBe("goto");+ expect(finderKeyAction(k, true, false), k.key).toBeNull();+ }+ expect(finderKeyAction(key("F5"), true, false)).toBe("refresh");+ expect(finderKeyAction(key("F5"), false, true)).toBe("refresh");+ // A modified F5 is the browser's hard reload, and Ctrl+Shift+L is not Ctrl+L.+ expect(finderKeyAction(key("F5", { ctrl: true }), false, true)).toBeNull();+ expect(finderKeyAction(key("L", { ctrl: true, shift: true }), false, true)).toBeNull();+ });});describe("quick access", () => {@@ -202,7 +226,44 @@ describe("quick access", () => {]);});- it("lists only folders that exist there, and matches Windows names ignoring case", () => {+ it("takes the folders the machine resolved itself, whole, in its file manager's order", () => {+ // Windows moved Desktop and Documents into OneDrive, leaving stale English-named folders+ // behind; a German Linux desktop names its XDG folders in German.+ const win = defaultPlaces(+ home({+ path: "C:\\Users\\me",+ platform: "win32",+ entries: folders("C:\\Users\\me", std, "\\"),+ standardFolders: {+ documents: "C:\\Users\\me\\OneDrive\\Documents",+ desktop: "C:\\Users\\me\\OneDrive\\Desktop",+ },+ }),+ );+ expect(win.map((p) => [p.key, p.path])).toEqual([+ ["home", "C:\\Users\\me"],+ ["desktop", "C:\\Users\\me\\OneDrive\\Desktop"],+ ["documents", "C:\\Users\\me\\OneDrive\\Documents"],+ ]);+ const linux = defaultPlaces(+ home({+ platform: "linux",+ standardFolders: {+ downloads: "/home/me/Downloads",+ desktop: "/home/me/Schreibtisch",+ // A folder that is home itself is not listed a second time.+ documents: "/home/me",+ },+ }),+ );+ expect(linux.map((p) => [p.key, p.path])).toEqual([+ ["home", "/home/me"],+ ["desktop", "/home/me/Schreibtisch"],+ ["downloads", "/home/me/Downloads"],+ ]);+ });++ it("finds them by name where the machine did not resolve them, Windows' ignoring case", () => {const linux = defaultPlaces(home({platform: "linux",@@ -220,7 +281,6 @@ describe("quick access", () => {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([@@ -229,16 +289,6 @@ describe("quick access", () => {]);});- 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);@@ -275,6 +325,68 @@ describe("quick access", () => {});});+describe("locations", () => {+ const names = {+ drives: {+ drive: "Local Disk",+ removable: "USB Drive",+ network: "Network Drive",+ optical: "CD Drive",+ },+ fileSystem: "File System",+ };+ const named = (locations: DirLocation[]) =>+ locationPlaces({ path: "/", parent: null, entries: [], locations }).map((p) => [+ p.key,+ locationName(p, names),+ ]);++ it("names a Windows drive as Explorer does: its label or its type, then its letter", () => {+ expect(+ named([+ { path: "C:\\", kind: "drive", label: "Windows" },+ { path: "D:\\", kind: "drive" },+ { path: "E:\\", kind: "removable" },+ { path: "F:\\", kind: "optical" },+ { path: "Z:\\", kind: "network", label: "\\\\nas\\media" },+ { path: "Y:\\", kind: "network" },+ ]),+ ).toEqual([+ ["drive", "Windows (C:)"],+ ["drive", "Local Disk (D:)"],+ ["removable", "USB Drive (E:)"],+ ["optical", "CD Drive (F:)"],+ ["network", "\\\\nas\\media (Z:)"],+ ["network", "Network Drive (Y:)"],+ ]);+ });++ it("names a Linux root as the file system, and anything else by its own name or its folder's", () => {+ expect(+ named([+ { path: "/", kind: "root" },+ { path: "/media/me/STICK", kind: "removable" },+ { path: "/mnt/c", kind: "drive", label: "C:" },+ ]),+ ).toEqual([+ ["root", "File System"],+ ["removable", "STICK"],+ ["drive", "C:"],+ ]);+ expect(+ named([+ { path: "/", kind: "volume", label: "Macintosh HD" },+ { path: "/Volumes/Backup", kind: "volume" },+ ]),+ ).toEqual([+ ["volume", "Macintosh HD"],+ ["volume", "Backup"],+ ]);+ // A machine reached over ssh reports none.+ expect(locationPlaces({ path: "/home/me", parent: "/home", entries: [] })).toEqual([]);+ });+});+describe("the context menu", () => {it("offers a folder open, choose, Delete, Quick access and copy; a file only copy", () => {const folder = { kind: "folder" as const, path: "/p/a", machine: null };@@ -360,10 +472,13 @@ describe("recent and go to folder", () => {]);});- it("resolves ~ against the machine's home", () => {+ it("resolves ~ against the machine's home, and a bare drive to its root", () => {expect(resolveGoTo("~/work", "/home/me")).toBe("/home/me/work");expect(resolveGoTo("~", "C:\\Users\\me")).toBe("C:\\Users\\me");expect(resolveGoTo(" /srv ", null)).toBe("/srv");+ expect(resolveGoTo("d:", null)).toBe("D:\\");+ expect(resolveGoTo(" D: ", "C:\\Users\\me")).toBe("D:\\");+ expect(resolveGoTo("D:\\work", null)).toBe("D:\\work");});});