A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): the desktop window's files panel can show a file in its folder (#733)
Yaowei Zheng77c746954f92
diff --git a/changelog/unreleased/2026-09-15-reveal-in-folder.md b/changelog/unreleased/2026-09-15-reveal-in-folder.mdnew file mode 100644index 00000000..15eb223d--- /dev/null+++ b/changelog/unreleased/2026-09-15-reveal-in-folder.md@@ -0,0 +1,33 @@+# Show in folder, from the desktop app's own window++- **Date:** 2026-09-15+- **Type:** feature+- **Scope:** `server`, `web`, `docs`++[中文版](2026-09-15-reveal-in-folder.zh.md)++The Files panel's preview header gained a **Show in folder** button beside Download: it opens the+previewed file's directory in the machine's own file manager, which is where a file goes on being+worked on once the Agent has written it.++## What changed++- The button is drawn only when the page IS the desktop app's own window — the server was spawned+ by the shell, and this session was established through the shell's one-shot token. A browser+ signed into the same server does not get it even when it runs on that very machine: the server+ cannot tell that browser from one on the other side of a network, and a folder springing open+ beside the server means nothing to whoever is actually looking at the page. The same two fields+ are enforced on the server — no desktop mode is a 404, a browser session in desktop mode a 403+ `desktop_shell_only` — so the control and the endpoint agree on who may ask.+- macOS and Windows select the file itself (`open -R`, `explorer.exe /select,`); a Linux desktop+ opens the containing directory with `xdg-open`, which is the part of the request that can be+ asked for portably there.+- `POST /api/sessions/:sessionId/files/reveal?path=` is the new endpoint, taking the+ Workspace-relative path the way `GET /files/content` does and answering 204. The path goes+ through the read path's own resolution before it reaches the OS, so a `..` and a symlink+ pointing out of the Workspace are refused exactly as they are for a read, and a path that is not+ there is a 404 rather than a path the file manager is asked to find. A command that cannot be+ started at all — a headless box with no `xdg-open` — comes back as 502 `reveal_failed` and the+ panel says so.+- The reveal never waits for the file manager to exit: the child is detached and unref'd, and only+ its start is awaited.diff --git a/changelog/unreleased/2026-09-15-reveal-in-folder.zh.md b/changelog/unreleased/2026-09-15-reveal-in-folder.zh.mdnew file mode 100644index 00000000..2614b44e--- /dev/null+++ b/changelog/unreleased/2026-09-15-reveal-in-folder.zh.md@@ -0,0 +1,25 @@+# 桌面端自己的窗口里可以「在文件夹中显示」++- **Date:** 2026-09-15+- **Type:** feature+- **Scope:** `server`, `web`, `docs`++[English](2026-09-15-reveal-in-folder.md)++文件面板的预览标题行在「下载」旁多了一枚**在文件夹中显示**按钮:它在本机的系统文件管理器里打开所预览文件+所在的目录——Agent 写完之后,文件接下来往往就是在那里被继续处理的。++## 变更内容++- 只有页面本身就是桌面端自己的窗口时才画出这枚按钮——服务端由桌面 shell 启动,且本会话经 shell 的一次性+ 令牌建立。用浏览器登录同一台服务端的会话拿不到它,哪怕浏览器就开在这台机器上:服务端分不清它与网络另一+ 端的浏览器,而在服务端所在机器上弹出一个目录,对正在看页面的人毫无意义。服务端按同样这两个字段把关——+ 非桌面模式返回 404,桌面模式下的浏览器会话返回 403 `desktop_shell_only`——控件与接口对「谁可以问」的+ 判断因而一致。+- macOS 与 Windows 会选中文件本身(`open -R`、`explorer.exe /select,`);Linux 桌面以 `xdg-open` 打开+ 所在目录,那是在那里能够可移植地提出的部分。+- 新接口为 `POST /api/sessions/:sessionId/files/reveal?path=`,与 `GET /files/content` 一样接收+ Workspace 相对路径,成功返回 204。路径在交给操作系统之前先走文件读取的同一道解析:`..` 与指向 Workspace+ 之外的符号链接与读取时一样被拒绝,不存在的路径返回 404,而不是把一个找不到的路径丢给文件管理器。命令根本+ 起不来时(例如无 `xdg-open` 的无头机器)返回 502 `reveal_failed`,面板据此报错。+- 打开之后不等文件管理器退出:子进程 detached 并 unref,只等它启动这一步。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 8b7e9120..322555a9 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -348,6 +348,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| PUT | /files/content?path= | Upload a file: `{dataBase64}`, capped at 14MB || POST | /files/move | Move or rename one Workspace file: `{from, to, ifVersion?}` → 204. **Files only** — a directory carries no single version marker, so the precondition that protects the operation cannot be expressed for one, and it is a 400. `to`'s parent directory is created when missing. 404 `path_not_found` when `from` is gone, 409 `file_changed` when `ifVersion` no longer matches it (a source that vanished under a marker counts as changed), 409 `target_exists` when something already sits at `to` — the destination was never read, so it is refused rather than overwritten — and 400 for a move onto the file's own path || DELETE | /files/content?path=&ifVersion= | Delete one Workspace file: 204. Files only (a directory is a 400); 404 `path_not_found`, and 409 `file_changed` when `ifVersion` no longer matches. The marker is optional on the wire — without it the delete is unconditional — and the Files panel always sends the one its read returned |+| POST | /files/reveal?path= | Show the file in the machine's own file manager (macOS and Windows select it, a Linux desktop opens its directory) → 204. Only the desktop shell's own window may ask: 404 `not_found` when the server was not spawned by a shell, 403 `desktop_shell_only` for a browser session against a desktop-mode server — it cannot be told apart from a remote one, and a folder opening on the server's machine helps nobody there. The path is confined the way a read is (400 out of bounds, 404 `path_not_found`); a file manager that will not start is 502 `reveal_failed` || GET | /files/search?q= | Search the whole Workspace by entry **name** (case-insensitive substring; the path is not matched) → `{hits: [{path, kind, sizeBytes, mtime}], truncated}`, each hit carrying what a directory listing's entry carries. Breadth-first from the root, so hits come shallowest-first and a capped result is the most relevant ones rather than whatever the first directory held; `truncated` says a cap stopped the walk — 200 hits, or 20000 directory entries visited. An empty `q`, or one over 100 characters, is a 400 || GET | /traces | List this Session's Trace files || GET | /traces/:index | Read Trace events (paginated) |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex cd70bd82..4fb54756 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -348,6 +348,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| PUT | /files/content?path= | 上传文件:`{dataBase64}`,上限 14MB || POST | /files/move | 移动或重命名单个 Workspace 文件:`{from, to, ifVersion?}` → 204。**仅限文件**——目录没有单一的版本标记,无法为其表达保护该操作的前置条件,因此返回 400。`to` 的父目录缺失时自动创建。`from` 不存在时 404 `path_not_found`;`ifVersion` 与文件不再匹配时 409 `file_changed`(带标记时源文件消失同样算作已变化);`to` 已被占用时 409 `target_exists`——目的地从未被读取过,因此只拒绝、不覆盖;移动到文件自身路径返回 400 || DELETE | /files/content?path=&ifVersion= | 删除单个 Workspace 文件:204。仅限文件(目录返回 400);文件不存在时 404 `path_not_found`,`ifVersion` 不再匹配时 409 `file_changed`。该标记在协议上可选——不带即为无条件删除——而 Files 面板总是回传其读取时拿到的那一枚 |+| POST | /files/reveal?path= | 在本机的系统文件管理器里显示该文件(macOS 与 Windows 选中文件,Linux 桌面打开其所在目录)→ 204。仅桌面端自己的窗口可以请求:服务端非由 shell 启动时 404 `not_found`,桌面模式下的浏览器会话 403 `desktop_shell_only`——服务端分不清它与远程浏览器,而在服务端所在机器上弹出目录对那边的用户毫无用处。路径按读取的同一道规则限域(越界 400,不存在 404 `path_not_found`);文件管理器起不来时 502 `reveal_failed` || GET | /files/search?q= | 按条目**名称**搜索整个 Workspace(大小写不敏感的子串匹配,不匹配路径)→ `{hits: [{path, kind, sizeBytes, mtime}], truncated}`,每条命中携带的字段与目录列表中的条目一致。自根目录广度优先遍历,因此命中按层级由浅至深排列,被截断时留下的是最相关的命中,而不是最先遍历到的那个目录里的内容;`truncated` 表示遍历触及上限——200 条命中,或访问 20000 个目录条目。`q` 为空或超过 100 字符返回 400 || GET | /traces | 本 Session 的 Trace 文件列表 || GET | /traces/:index | 读取 Trace 事件(分页) |diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 9da38a63..7b5d4e83 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -94,7 +94,7 @@ Whenever no side panel is on screen — the right panel closed on a desktop-widtThe files panel shows the Workspace as a directory tree on the left and a preview of the selected file on the right. A directory lists its contents the first time it is opened; the tree takes the arrow keys (up/down move, right opens a directory or steps into it, left closes it or steps out), the selected file is highlighted, and the breadcrumbs above read out the current directory — a path, not a row of links, since the tree beside them is what navigates; when the path outgrows the toolbar its leading segments collapse into a single `…`, keeping the current directory visible and Refresh and Upload on the same row; the root segment reads `.`, and the Workspace's absolute path lives in the Session details card rather than on this toolbar. A search box above the tree filters what the tree holds: matching is on the entry's name, a match keeps its parent directories visible and open, and a directory whose own name matches is shown with its contents. The tree is lazy, so the search reaches only the directories that have been opened at least once — when nothing in them matches it says so rather than looking empty; Esc clears the box. Opening or closing a directory grows its subtree out of its row, or shrinks it back into it, over about 200ms — the rows stay on screen until the collapse finishes; with reduced motion the change is immediate. A toolbar toggle hides or shows the tree (shown by default; the choice is remembered in the browser) and slides out of and back into the panel's left edge over about 200ms, the motion the docks themselves expand and collapse with; the divider between the two panes drags to set the tree's width (arrow keys nudge it while it has focus, and the width is remembered too), and a panel too narrow for both panes falls back to one column — the tree until a file is chosen, then the preview with a Back button. Markdown and HTML preview rendered with a Source toggle, text files inline with highlighting, images inline (click to zoom), PDF embedded; anything else is offered as a download. A file whose extension says nothing about its type (a `Makefile`, a `LICENSE`) is read as text when its bytes look like text.-Text files can be edited in place: **Edit** replaces the preview with a plain monospace text box — no rich editor — and **Save** (also Ctrl+S / Cmd+S) writes the file back through the same content endpoint uploads use, after the usual save confirmation; Cancel returns to the preview. A **Wrap** toggle sits beside them: off by default, so long lines scroll sideways as they would in a code editor, and the choice carries to the next file you edit. The panel asks before unsaved changes would be lost — switching to another file, closing the panel's tab, leaving the page. Collapsing or hiding the dock loses nothing: the panel stays exactly as it was, preview, tree and draft included, and comes back untouched without asking. A draft survives a Session switch too: opening the same file again reopens the editor on it. A file larger than the 256KB preview cap is shown truncated and stays read-only (saving a partial text would overwrite the whole file), and a save over the 14MB write limit is refused with a message.+Text files can be edited in place: **Edit** replaces the preview with a plain monospace text box — no rich editor — and **Save** (also Ctrl+S / Cmd+S) writes the file back through the same content endpoint uploads use, after the usual save confirmation; Cancel returns to the preview. A **Wrap** toggle sits beside them: off by default, so long lines scroll sideways as they would in a code editor, and the choice carries to the next file you edit. The panel asks before unsaved changes would be lost — switching to another file, closing the panel's tab, leaving the page. Collapsing or hiding the dock loses nothing: the panel stays exactly as it was, preview, tree and draft included, and comes back untouched without asking. A draft survives a Session switch too: opening the same file again reopens the editor on it. A file larger than the 256KB preview cap is shown truncated and stays read-only (saving a partial text would overwrite the whole file), and a save over the 14MB write limit is refused with a message. In the desktop app's own window a **Show in folder** button sits beside Download and opens the file's directory in the system file manager — Finder and Explorer select the file, a Linux desktop opens the directory; a browser signed into the same server, even on this machine, does not get the button, because the server cannot tell it from a remote one.Because the Agent writes to the same Workspace, a file can change while you are editing it. It is checked whenever a turn finishes — your text is never replaced, but the editor header says **Changed on disk** as soon as it has — and a save that would land on a changed file is refused before anything is written: the panel asks whether to **Overwrite** it with your version or keep editing, and your text is kept either way.diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 96b9e9e2..7135d1a6 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -93,7 +93,7 @@ penguin web文件面板左侧是 Workspace 的目录树,右侧是所选文件的预览。目录在首次展开时才加载内容;目录树支持方向键(上下移动、右键展开目录或进入其中、左键收起或回到上级),选中的文件高亮,工具栏的面包屑只读出当前目录的路径、不再可点——旁边就是目录树,导航交给它;路径长到工具栏放不下时,前导段折叠成一个「…」,当前目录始终可见,刷新 / 上传也不会被挤到第二行;根目录在面包屑里写作 `.`,Workspace 的绝对路径在会话详情卡片里,不在这条工具栏上。目录树上方的搜索框按条目名称过滤:命中项的上级目录一并保留并展开,名称本身命中的目录连同其内容一起显示。目录树是懒加载的,搜索只能覆盖至少展开过一次的目录——都不匹配时会明说,而不是显示成空树;按 Esc 清空搜索框。展开 / 折叠时子树以高度过渡动画展开或收起(约 200ms,折叠期间行仍可见直至收起完成;系统设为减少动态时即时)。工具栏按钮可隐藏或显示目录树(默认显示,选择记在浏览器本地),显隐时目录树以约 200ms 的宽度过渡滑出或滑入,与停靠面板展开 / 收起同款;两栏之间的分隔条可拖动调整目录树宽度(获得焦点后可用左右方向键微调,宽度同样记住);面板宽度容不下两栏时退化为单栏——先显示目录树,选中文件后换成带「返回列表」按钮的预览。Markdown 与 HTML 以渲染视图预览并可切换源码,文本文件内联高亮显示,图片内联显示(点击放大),PDF 内嵌;其余类型提示下载。扩展名看不出类型的文件(`Makefile`、`LICENSE` 之类)在内容看起来是文本时按文本处理。-文本文件可以就地编辑:**编辑**把预览换成纯文本的等宽文本框——没有富文本编辑器——**保存**(也可按 Ctrl+S / Cmd+S)经上传所用的同一内容写接口写回文件,保存前先弹统一的确认框;取消则回到预览。旁边还有**自动换行**开关:缺省关闭,长行像代码编辑器那样横向滚动,选择会带到下一个编辑的文件。未保存的修改在可能丢失之前都会先询问——切换到别的文件、关闭该面板的标签页、离开页面。折叠或隐藏停靠面板不会丢失任何东西:面板连同预览、目录树状态与编辑草稿原样留着,重新展开即回到原处,也不会询问。切换 Session 时草稿也会保留:再次打开同一文件即回到编辑状态。超过 256KB 预览上限的文件以截断方式显示且保持只读(把不完整的文本存回去会覆盖整个文件);超过 14MB 写入上限的保存会被拒绝并给出提示。+文本文件可以就地编辑:**编辑**把预览换成纯文本的等宽文本框——没有富文本编辑器——**保存**(也可按 Ctrl+S / Cmd+S)经上传所用的同一内容写接口写回文件,保存前先弹统一的确认框;取消则回到预览。旁边还有**自动换行**开关:缺省关闭,长行像代码编辑器那样横向滚动,选择会带到下一个编辑的文件。未保存的修改在可能丢失之前都会先询问——切换到别的文件、关闭该面板的标签页、离开页面。折叠或隐藏停靠面板不会丢失任何东西:面板连同预览、目录树状态与编辑草稿原样留着,重新展开即回到原处,也不会询问。切换 Session 时草稿也会保留:再次打开同一文件即回到编辑状态。超过 256KB 预览上限的文件以截断方式显示且保持只读(把不完整的文本存回去会覆盖整个文件);超过 14MB 写入上限的保存会被拒绝并给出提示。在桌面端自己的窗口里,「下载」旁多一枚**在文件夹中显示**按钮,会在系统文件管理器里打开该文件所在目录——Finder 与资源管理器会选中该文件,Linux 桌面打开目录;用浏览器登录同一台服务端的会话——哪怕就在本机——不显示这枚按钮,服务端分不清它与远程浏览器。Agent 写的是同一个 Workspace,你编辑期间文件可能被改动。每轮 Task 结束时都会检查一次——你的文本不会被替换,但编辑器标题栏会立即标出**磁盘上已变更**;若保存会落在已变更的文件上,写入前即被拒绝:面板会询问是用你的版本**仍然覆盖**,还是继续编辑,两种选择都保留你的文本。diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 38f81b8b..8f9c5518 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -86,6 +86,10 @@ export interface SessionsRouteDeps {sessionsRepo: SessionIndex;traceService: Traces;workspaceFiles: WorkspaceFiles;+ /** Whether this server was spawned by the desktop shell — half of the reveal route's gate. */+ desktopMode: boolean;+ /** Opens a Workspace file's directory in the machine's file manager (the reveal route). */+ fileReveal: FileReveal;}import { MAX_UPLOAD_BYTES } from "../../services/workspace-files-service.js";import {@@ -104,7 +108,7 @@ import {import type { AttachmentLimits } from "../../services/attachment-limits.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";-import { Channels, Config } from "../../hmr/capabilities.js";+import { Channels, Config, Desktop } from "../../hmr/capabilities.js";import { Sessions as ManagerIface, SessionServiceIface } from "../../runtime/session-manager.js";import { Messaging } from "../../runtime/messaging/bridge.js";@@ -121,7 +125,7 @@ import type { Access, ModelOAuth, ProjectConfigStore } from "../../mechanisms/primport type { Schedules, SessionIndex, SessionOrigins } from "../../mechanisms/sessions.js";import type { ErrorLog, UsageQueries } from "../../mechanisms/observability.js";import type { TraceIndex, Traces } from "../../mechanisms/traces.js";-import type { WorkspaceFiles } from "../../mechanisms/workspace.js";+import type { FileReveal, WorkspaceFiles } from "../../mechanisms/workspace.js";import type { Machines } from "../../machines/service.js";import type { AgentConfig, AgentLifecycle } from "../../mechanisms/agents.js";import type { Settings } from "../../mechanisms/settings.js";@@ -1343,6 +1347,43 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {});});+ /**+ * Shows a Workspace file in the machine's own file manager.+ *+ * Gated on the same two fields the desktop routes use, and for the same reason: outside+ * desktop mode there is no window on this machine to open anything beside, and inside it a+ * browser session is refused because the server cannot tell one signed in from this machine+ * from one signed in from another — a folder springing open on the server's machine means+ * nothing to a user who is somewhere else.+ *+ * The path is resolved the way a read resolves it (`..` and symlink escapes refused, a+ * missing path a 404) before it is handed to the OS, and the answer comes back as soon as+ * the file manager has started: nothing here waits for the window to be closed.+ */+ app.post("/:sessionId/files/reveal", async (c) => {+ const row = resolveSession(c);+ const rel = c.req.query("path") ?? "";+ if (!deps.desktopMode) throw new HttpError(404, "not_found", "Desktop mode is not enabled.");+ if (c.var.sessionVia !== "desktop") {+ throw new HttpError(+ 403,+ "desktop_shell_only",+ "Showing a file in its folder is available from the desktop app's own window.",+ );+ }+ const file = await deps.workspaceFiles.resolvePath(row.workspace, rel);+ try {+ await deps.fileReveal.reveal(file);+ } catch (err) {+ throw new HttpError(+ 502,+ "reveal_failed",+ err instanceof Error ? err.message : "The file manager could not be opened.",+ );+ }+ return c.body(null, 204);+ });+// "Open in a new tab" for Workspace HTML: mints a token and redirects to the separate// preview origin.//@@ -1616,6 +1657,8 @@ export class SessionApiRoutes {@Use() private readonly traceIndex!: TraceIndex;@Use() private readonly traces!: Traces;@Use() private readonly workspaceFiles!: WorkspaceFiles;+ @Use() private readonly fileReveal!: FileReveal;+ @Use() private readonly desktop!: Desktop;@Use() private readonly previewTokens!: PreviewTokens;@Use() private readonly settings!: Settings;@Use() private readonly sessionsRepo!: SessionIndex;@@ -1656,6 +1699,10 @@ export class SessionApiRoutes {sessionsRepo,traceService: this.traces,workspaceFiles: this.workspaceFiles,+ // Read once per generation, as the desktop routes read it: the shell either spawned+ // this process or it did not, and that cannot change under a running server.+ desktopMode: this.desktop.current() !== null,+ fileReveal: this.fileReveal,};const modelOAuthDeps = {config: this.config,diff --git a/packages/server/src/mechanisms/workspace.ts b/packages/server/src/mechanisms/workspace.tsindex ab4a8a3d..741ce6ab 100644--- a/packages/server/src/mechanisms/workspace.ts+++ b/packages/server/src/mechanisms/workspace.ts@@ -28,4 +28,10 @@ export abstract class WorkspaceFiles extends Interface<{move(workspace: string, from: string, to: string, ifVersion?: string): Promise<void>;remove(workspace: string, rel: string, ifVersion?: string): Promise<void>;search(workspace: string, q: string): Promise<WorkspaceSearchResponse>;+ resolvePath(workspace: string, rel: string): Promise<string>;+}>() {}++/** FileReveal: opening a path in the machine's file manager, as RevealService implements it. */+export abstract class FileReveal extends Interface<{+ reveal(filePath: string): Promise<void>;}>() {}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex fc99eef5..67aa2866 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -82,6 +82,7 @@ import { ModelOAuthService } from "./services/model-oauth-service.js";import { TraceIndexService } from "./services/trace-index.js";import { TraceService } from "./services/trace-service.js";import { WorkspaceFilesService } from "./services/workspace-files-service.js";+import { RevealService } from "./services/reveal-path.js";import { ProjectAccess } from "./services/project-access.js";import { ProjectService, ProjectRuns } from "./services/project-service.js";import { AuthService, InitialProjectProvisioner } from "./auth/service.js";@@ -131,7 +132,7 @@ import {} from "./mechanisms/observability.js";import { TraceIndex, TraceIndexStore, Traces } from "./mechanisms/traces.js";import { AgentConfig, AgentLifecycle, Benchmarks, Memory, Snapshots } from "./mechanisms/agents.js";-import { WorkspaceFiles } from "./mechanisms/workspace.js";+import { FileReveal, WorkspaceFiles } from "./mechanisms/workspace.js";import { Settings, UiPrefsStore } from "./mechanisms/settings.js";import { MessagingBindings } from "./mechanisms/messaging.js";import { OrgCache } from "./mechanisms/organization.js";@@ -329,8 +330,8 @@ export class TracesModule {}export class AgentsModule {}@Module({- children: [WorkspaceFilesService, PreviewModule],- exports: [WorkspaceFiles, PreviewTokens],+ children: [WorkspaceFilesService, RevealService, PreviewModule],+ exports: [WorkspaceFiles, FileReveal, PreviewTokens],})export class WorkspaceModule {}diff --git a/packages/server/src/services/reveal-path.ts b/packages/server/src/services/reveal-path.tsnew file mode 100644index 00000000..26b5aa81--- /dev/null+++ b/packages/server/src/services/reveal-path.ts@@ -0,0 +1,62 @@+/**+ * Showing a file in the machine's own file manager — what the Files panel's "Show in folder"+ * asks for, and only ever on the machine this server runs on.+ *+ * Two of the three platforms can point at the file itself: Finder takes `-R`, Explorer takes+ * `/select,`. A Linux desktop has no portable way to ask for a selection, so it gets the+ * containing directory, which is the part of the request that always holds.+ *+ * Nothing here waits for the file manager — it outlives the request that opened it, so the+ * child is detached, given no stdio and unref'd. What IS awaited is the spawn itself: a+ * command that is not on the machine at all (a headless box has no `xdg-open`) has to reach+ * the caller as a failure rather than as a window that never appeared.+ */+import { spawn } from "node:child_process";+import path from "node:path";+import { Component } from "@prismshadow/penguin-core/kernel";+import type { FileReveal } from "../mechanisms/workspace.js";++/** The command that reveals `filePath` on `platform`. Pure; exported for unit tests. */+export function revealCommand(+ platform: string,+ filePath: string,+): { command: string; args: string[] } {+ if (platform === "darwin") return { command: "open", args: ["-R", filePath] };+ // `explorer.exe /select,<path>` is the documented form, and the comma belongs to the switch:+ // the switch and the path have to arrive as two separate arguments for the file to be+ // selected — joined into one, Explorer opens the user's home directory instead.+ if (platform === "win32") return { command: "explorer.exe", args: ["/select,", filePath] };+ return { command: "xdg-open", args: [path.dirname(filePath)] };+}++/**+ * Opens `filePath`'s directory in the file manager, selecting the file where the platform+ * allows. Resolves as soon as the process has started; rejects when it cannot be started at+ * all. `platform` and `spawnImpl` exist for the unit test — production passes neither.+ */+export function revealInFileManager(+ filePath: string,+ opts?: { platform?: string; spawnImpl?: typeof spawn },+): Promise<void> {+ const { command, args } = revealCommand(opts?.platform ?? process.platform, filePath);+ const spawnChild = opts?.spawnImpl ?? spawn;+ return new Promise<void>((resolve, reject) => {+ const child = spawnChild(command, args, { detached: true, stdio: "ignore" });+ child.on("spawn", () => {+ child.unref();+ resolve();+ });+ child.on("error", reject);+ });+}++/** The reveal as a node, so a test stands in for the spawn rather than opening a window. */+@Component()+export class RevealService implements FileReveal {+ /** The opener a reveal goes through; a replacement supplies its own. */+ private readonly opener: (filePath: string) => Promise<void> = revealInFileManager;++ reveal(filePath: string): Promise<void> {+ return this.opener(filePath);+ }+}diff --git a/packages/server/src/services/workspace-files-service.ts b/packages/server/src/services/workspace-files-service.tsindex 9c6457d2..0574d6a4 100644--- a/packages/server/src/services/workspace-files-service.ts+++ b/packages/server/src/services/workspace-files-service.ts@@ -405,6 +405,17 @@ export class WorkspaceFilesService implements WorkspaceFiles {return { path: rel, entries };}+ /**+ * The canonical absolute path of an existing entry, for the caller that hands the path to+ * something other than this process's own IO (the desktop "show in folder", which passes it+ * to the machine's file manager). Resolution is the read path's, so a `..` and a symlink+ * pointing out of the Workspace are refused here exactly as they are for a read, and a path+ * that is not there at all is a 404 rather than a path the OS is asked to open.+ */+ async resolvePath(workspace: string, rel: string): Promise<string> {+ return await this.resolveRead(workspace, rel);+ }+/*** Read a file (preview/download): IO on the canonical path (resolveRead has already* eliminated symlink escapes).diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex b2a0d48f..ade55952 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -62,6 +62,7 @@ import { hashPassword, ScryptHasher } from "../src/auth/password.js";import { CoreSessionLoaders, DefaultTitleGenerators } from "../src/runtime/session-manager.js";import type { TitleNotifier } from "../src/runtime/title-generator.js";import { UpdateCheckService } from "../src/services/update-check-service.js";+import { RevealService } from "../src/services/reveal-path.js";import { DefaultMessagingTuning } from "../src/runtime/messaging/bridge.js";import { FeishuSdkProvider } from "../src/runtime/messaging/feishu-connector.js";import type { FeishuSdk } from "../src/runtime/messaging/feishu-sdk.js";@@ -264,6 +265,8 @@ export interface TestAppOptions {machines?: MachinesService;/** Test double: company mode's organization service, for the route suite (its semantics have their own suites). */orgService?: OrganizationService;+ /** Test double: the desktop reveal, so a test never opens a file manager. */+ reveal?: (filePath: string) => Promise<void>;/** Test double: the password work factor (scrypt at full strength is seconds per hash). */passwordHashCost?: number;log?: (line: string) => void;@@ -302,6 +305,7 @@ export function replacementsFor(o: TestAppOptions): Replacements {out.push([DefaultTitleGenerators, { create: () => titles }]);}if (o.updateCheck) out.push([UpdateCheckService, o.updateCheck]);+ if (o.reveal) out.push([RevealService, { reveal: o.reveal }]);if (o.feishuSdk) out.push([FeishuSdkProvider, { feishuSdk: { sdk: o.feishuSdk } }]);if (o.telegramTransport)out.push([@@ -399,8 +403,11 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestAexport const TEST_DESKTOP_TOKEN = "test-desktop-token";/** A test app running in desktop mode (desktop.test.ts, desktop-update.test.ts). */-export function createDesktopApp(): Promise<TestApp> {- return createTestApp({ config: { desktopToken: TEST_DESKTOP_TOKEN } });+export function createDesktopApp(options: TestAppOptions = {}): Promise<TestApp> {+ return createTestApp({+ ...options,+ config: { desktopToken: TEST_DESKTOP_TOKEN, ...options.config },+ });}/** Redeems the shell's one-shot token for a `sessionVia: "desktop"` cookie. */diff --git a/packages/server/test/reveal-path.test.ts b/packages/server/test/reveal-path.test.tsnew file mode 100644index 00000000..8a64f6da--- /dev/null+++ b/packages/server/test/reveal-path.test.ts@@ -0,0 +1,75 @@+/**+ * The desktop "show in folder" opener: the per-platform command, and the spawn it waits on+ * (start, not exit). Nothing here starts a real process.+ */+import { EventEmitter } from "node:events";+import type { spawn } from "node:child_process";+import { describe, expect, it } from "vitest";+import { revealCommand, revealInFileManager } from "../src/services/reveal-path.js";++/**+ * A spawn that records its call and then behaves like a child that either started or could+ * not. The event is emitted on the next tick because a real one is: emitting it inside the+ * call would fire before the opener has attached its listeners.+ */+function fakeSpawn(outcome: "spawn" | "error") {+ const calls: Array<{ command: string; args: readonly string[]; options: unknown }> = [];+ let unrefs = 0;+ const impl = ((command: string, args: string[], options: unknown) => {+ calls.push({ command, args, options });+ const child = new EventEmitter() as EventEmitter & { unref: () => void };+ child.unref = () => {+ unrefs += 1;+ };+ setImmediate(() => {+ if (outcome === "spawn") child.emit("spawn");+ else child.emit("error", new Error("spawn xdg-open ENOENT"));+ });+ return child;+ }) as unknown as typeof spawn;+ return { impl, calls, unrefCount: () => unrefs };+}++describe("revealCommand", () => {+ it("selects the file on macOS and Windows, and opens the directory everywhere else", () => {+ expect(revealCommand("darwin", "/Users/ada/ws/report.md")).toEqual({+ command: "open",+ args: ["-R", "/Users/ada/ws/report.md"],+ });+ // The switch and the path are two arguments: joined into one, Explorer ignores the file.+ expect(revealCommand("win32", "C:\\ws\\report.md")).toEqual({+ command: "explorer.exe",+ args: ["/select,", "C:\\ws\\report.md"],+ });+ expect(revealCommand("linux", "/home/ada/ws/report.md")).toEqual({+ command: "xdg-open",+ args: ["/home/ada/ws"],+ });+ });+});++describe("revealInFileManager", () => {+ it("resolves once the child has started, detached and unref'd, without waiting for it to exit", async () => {+ const fake = fakeSpawn("spawn");+ await expect(+ revealInFileManager("/ws/report.md", { platform: "darwin", spawnImpl: fake.impl }),+ ).resolves.toBeUndefined();+ expect(fake.calls).toEqual([+ {+ command: "open",+ args: ["-R", "/ws/report.md"],+ options: { detached: true, stdio: "ignore" },+ },+ ]);+ // The fake never ends its child: resolving at all is what proves nothing awaits the exit.+ expect(fake.unrefCount()).toBe(1);+ });++ it("rejects with the spawn error when the command is not on the machine", async () => {+ const fake = fakeSpawn("error");+ await expect(+ revealInFileManager("/ws/report.md", { platform: "linux", spawnImpl: fake.impl }),+ ).rejects.toThrow(/ENOENT/);+ expect(fake.unrefCount()).toBe(0);+ });+});diff --git a/packages/server/test/workspace-files.test.ts b/packages/server/test/workspace-files.test.tsindex 1de812c7..6261ccc2 100644--- a/packages/server/test/workspace-files.test.ts+++ b/packages/server/test/workspace-files.test.ts@@ -1,8 +1,9 @@/*** Unit tests for the Workspace files service: directory-listing order, read/write,* move / delete / search, path confinement (`..` traversal and symlink escape), size-limit- * protection, batch existence checks (files/stat); and the Agent delete route (default_agent- * cannot be deleted, owner-only, directory and index cleanup).+ * protection, batch existence checks (files/stat); the desktop-only files/reveal route; and+ * the Agent delete route (default_agent cannot be deleted, owner-only, directory and index+ * cleanup).*/import fs from "node:fs/promises";import path from "node:path";@@ -14,11 +15,20 @@ import {} from "../src/services/workspace-files-service.js";import type {AgentCreateResponse,+ ErrorBody,ProjectCreateResponse,SessionCreateResponse,WorkspaceSearchResponse,} from "../src/api/types.js";-import { apiClient, createTestApp, makeTempRoot, provisionUser } from "./helpers.js";+import {+ apiClient,+ createDesktopApp,+ createTestApp,+ desktopLoginCookie,+ loginAdmin,+ makeTempRoot,+ provisionUser,+} from "./helpers.js";import type { TestApp } from "./helpers.js";describe("workspace-files-service", () => {@@ -739,3 +749,127 @@ describe("agent delete route", () => {expect(def.status).toBe(409);});});++describe("files/reveal route (the desktop shell's own window)", () => {+ /** The admin's Session in default_project, with one file sitting in its Workspace. */+ async function seedSession(+ t: TestApp,+ ): Promise<{ cookie: string; sessionId: string; workspace: string }> {+ const admin = await loginAdmin(t.app);+ const api = apiClient(t.app, admin.cookie);+ await api.put("/api/projects/default_project/models", {+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],+ });+ const created = await api.post(+ "/api/projects/default_project/agents/default_agent/sessions",+ {},+ );+ expect(created.status).toBe(201);+ const { session } = (await created.json()) as SessionCreateResponse;+ await fs.writeFile(path.join(session.workspace, "a.txt"), "A");+ return { cookie: admin.cookie, sessionId: session.sessionId, workspace: session.workspace };+ }++ it("opens the file for the shell's own window: 204, and the opener is handed the canonical path", async () => {+ const revealed: string[] = [];+ const t = await createDesktopApp({+ reveal: async (filePath) => {+ revealed.push(filePath);+ },+ });+ try {+ const { sessionId, workspace } = await seedSession(t);+ const shell = apiClient(t.app, await desktopLoginCookie(t.app));+ const res = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=a.txt`);+ expect(res.status).toBe(204);+ expect(await res.text()).toBe("");+ // The absolute path the OS can act on, with every symlink already resolved away.+ expect(revealed).toEqual([await fs.realpath(path.join(workspace, "a.txt"))]);+ } finally {+ await t.cleanup();+ }+ });++ it("refuses a browser session on the same desktop-mode server with desktop_shell_only", async () => {+ const revealed: string[] = [];+ const t = await createDesktopApp({+ reveal: async (filePath) => {+ revealed.push(filePath);+ },+ });+ try {+ const { cookie, sessionId } = await seedSession(t);+ // The seeded admin signed in through the login form: the same user, the same machine+ // for all the server knows, and still not the window the shell is drawing.+ const res = await apiClient(t.app, cookie).post(+ `/api/sessions/${sessionId}/files/reveal?path=a.txt`,+ );+ expect(res.status).toBe(403);+ expect(((await res.json()) as ErrorBody).error.code).toBe("desktop_shell_only");+ expect(revealed).toEqual([]);+ } finally {+ await t.cleanup();+ }+ });++ it("does not exist outside desktop mode", async () => {+ const revealed: string[] = [];+ const t = await createTestApp({+ reveal: async (filePath) => {+ revealed.push(filePath);+ },+ });+ try {+ const { cookie, sessionId } = await seedSession(t);+ const res = await apiClient(t.app, cookie).post(+ `/api/sessions/${sessionId}/files/reveal?path=a.txt`,+ );+ expect(res.status).toBe(404);+ expect(((await res.json()) as ErrorBody).error.code).toBe("not_found");+ expect(revealed).toEqual([]);+ } finally {+ await t.cleanup();+ }+ });++ it("resolves the path as a read does: `..` is a 400 and a missing file a 404, with nothing opened", async () => {+ const revealed: string[] = [];+ const t = await createDesktopApp({+ reveal: async (filePath) => {+ revealed.push(filePath);+ },+ });+ try {+ const { sessionId } = await seedSession(t);+ const shell = apiClient(t.app, await desktopLoginCookie(t.app));+ const escape = await shell.post(+ `/api/sessions/${sessionId}/files/reveal?path=${encodeURIComponent("../secret.txt")}`,+ );+ expect(escape.status).toBe(400);+ const missing = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=nope.txt`);+ expect(missing.status).toBe(404);+ expect(((await missing.json()) as ErrorBody).error.code).toBe("path_not_found");+ expect(revealed).toEqual([]);+ } finally {+ await t.cleanup();+ }+ });++ it("reports an opener that cannot start as 502 reveal_failed", async () => {+ const t = await createDesktopApp({+ reveal: () => Promise.reject(new Error("spawn xdg-open ENOENT")),+ });+ try {+ const { sessionId } = await seedSession(t);+ const shell = apiClient(t.app, await desktopLoginCookie(t.app));+ const res = await shell.post(`/api/sessions/${sessionId}/files/reveal?path=a.txt`);+ expect(res.status).toBe(502);+ const body = (await res.json()) as ErrorBody;+ expect(body.error.code).toBe("reveal_failed");+ expect(body.error.message).toContain("ENOENT");+ } finally {+ await t.cleanup();+ }+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex af34bc76..2114d563 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -1085,6 +1085,15 @@ export const workspaceFileUrl = (sessionId: string, path: string, download = falexport const workspaceFilePreviewUrl = (sessionId: string, path: string): string =>`/api/sessions/${sessionId}/files/preview-redirect?path=${encodeURIComponent(path)}`;+/**+ * Opens the file's directory in the machine's own file manager, selecting the file where the+ * platform allows. Only the desktop shell's own window may ask: the server answers 404 when it+ * was not spawned by a shell and 403 `desktop_shell_only` for a browser session beside one,+ * since it cannot tell that browser from a remote one (see lib/account-menu.ts).+ */+export const revealWorkspaceFile = (sessionId: string, path: string) =>+ apiFetch<void>(`/api/sessions/${sessionId}/files/reveal`, { method: "POST", query: { path } });+/*** Writes a Workspace file whole. `ifVersion` is the marker a previous read returned in its* `ETag`: pass it and the write is refused with 409 `file_changed` unless the file is stilldiff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex 804b7c37..e7da8975 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -54,6 +54,7 @@ import { ApiError } from "../../api/client";import { useAuth } from "../../state/auth";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";+import { isDesktopShellWindow } from "../../lib/account-menu";import { joinWorkspacePath } from "../../lib/file-path";import { dropRegionAction, isFileDrag } from "../../lib/file-drop";import type { DragSignal } from "../../lib/file-drop";@@ -109,6 +110,7 @@ import {import { Dropdown } from "../../components/ui/dropdown";import { EmptyState } from "../../components/ui/empty-state";import { GlyphIcon } from "../../components/ui/glyph-icon";+import { FOLDER_OPEN_ICON } from "../../components/ui/group-list";import { HiddenFileInput } from "../../components/ui/hidden-file-input";import {CloseIcon,@@ -508,7 +510,11 @@ export function WorkspaceBrowser({// rendered view and "open in new tab" through the preview origin; false downgrades// the new tab to the same-origin sandbox (which the link flags rather than failing// silently in the page) and the in-app rendered view to the srcDoc fallback.- const { previewIsolated } = useAuth();+ const { previewIsolated, desktopMode, sessionVia } = useAuth();+ // The desktop app's own window is the one page whose machine IS the server's, so it is the+ // only one offered "show in folder" — see lib/account-menu.ts for why a browser signed into+ // the same server, even on this machine, must not be.+ const isShellWindow = isDesktopShellWindow({ desktopMode, sessionVia });const previewIsolatedRef = useRef(previewIsolated);previewIsolatedRef.current = previewIsolated;const sessionId = session.sessionId;@@ -1496,6 +1502,20 @@ export function WorkspaceBrowser({if (files.length > 0) void stageUpload(files, menuUploadDir.current);};+ /**+ * Asks the server to show the file in the machine's file manager. Only the shell's own+ * window offers this, so a refusal here is a real failure — no file manager on the box, or+ * a command that would not start — and it is reported rather than swallowed. Nothing on+ * screen changes either way: the window that opens is not this one.+ */+ const revealInFolder = async (filePath: string): Promise<void> => {+ try {+ await api.revealWorkspaceFile(sessionId, filePath);+ } catch (err) {+ toastError(apiErrorText(err));+ }+ };+// ------------------------------------------------------------------------ context menusconst copyPath = (target: FileMenuTarget): void => {@@ -2387,6 +2407,18 @@ export function WorkspaceBrowser({<GlyphIcon d={DOWNLOAD_ICON} size={ICON_SIZE.iconButton} /></a></Tooltip>+ {isShellWindow && (+ <Tooltip label={S.files.revealInFolder} placement="bottom" className="shrink-0">+ <button+ type="button"+ aria-label={S.files.revealInFolder}+ onClick={() => void revealInFolder(preview.path)}+ className={iconActionClass}+ >+ <GlyphIcon d={FOLDER_OPEN_ICON} size={ICON_SIZE.iconButton} />+ </button>+ </Tooltip>+ )}</>));diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex d9275b48..4f947caf 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -2729,6 +2729,8 @@ Scenarios:title: "Files",upload: "Upload",download: "Download",+ /** Desktop shell's own window only: opens the previewed file's directory in the OS file manager. */+ revealInFolder: "Show in folder",/** Row / preview context menu: the two entries both kinds carry, then the kind-specific one. */copyPath: "Copy relative path",addToChat: "Add to conversation",@@ -4107,6 +4109,7 @@ Scenarios:dir_not_found: "That directory does not exist or is inaccessible.",not_a_dir: "That path is not a directory.",path_not_found: "That path does not exist.",+ reveal_failed: "Could not open the folder.",workspace_missing: "This Session's Workspace no longer exists.",workspace_not_found: "That Workspace does not exist, or is not a directory.",session_not_found: "This Session no longer exists, or you do not have access.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 84c13e3c..58f1e4c7 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -2716,6 +2716,8 @@ Benchmark:title: "文件",upload: "上传",download: "下载",+ /** Desktop shell's own window only: opens the previewed file's directory in the OS file manager. */+ revealInFolder: "在文件夹中显示",/** Row / preview context menu: the two entries both kinds carry, then the kind-specific one. */copyPath: "复制相对路径",addToChat: "添加到对话",@@ -4068,6 +4070,7 @@ Benchmark:dir_not_found: "该目录不存在或不可访问。",not_a_dir: "该路径不是目录。",path_not_found: "该路径不存在。",+ reveal_failed: "无法打开文件夹。",workspace_missing: "该 Session 的 Workspace 已不存在。",workspace_not_found: "该 Workspace 不存在或不是目录。",session_not_found: "该 Session 已不存在,或你没有访问权限。",