Skip to content

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

feat(web,ui,server): the Files panel makes folders and text files, renames folders, keeps the editor's place, and opens on the new-chat page (#938)

Yaowei Zheng2b4c3704536c
diff --git a/changelog/unreleased/2026-10-01-files-panel-folders.md b/changelog/unreleased/2026-10-01-files-panel-folders.md
new file mode 100644
index 00000000..5fef2186
--- /dev/null
+++ b/changelog/unreleased/2026-10-01-files-panel-folders.md
@@ -0,0 +1,40 @@
+# Files panel: new folders and text files, folder rename, a VS Code-like editor, and the panel on the new-chat page
+
+- **Date:** 2026-10-01
+- **Type:** feature
+- **Scope:** `web`, `ui`, `server`, `docs`
+- **PR:** [#938](https://github.com/Prism-Shadow/penguin-harness/pull/938)
+
+[中文版](2026-10-01-files-panel-folders.zh.md)
+
+The Files panel gained **New text file** and **New folder**, folders can be renamed and moved, the editor keeps its place like a code editor, and the panel opens on the new-chat page for the folder picked there, including from a sidebar Workspace group's new **Browse files**.
+
+## New files and folders
+
+- A **New** menu in the tree pane's header creates in the current directory, a folder's context menu creates inside that folder, and the blank space under the tree creates at the Workspace root.
+- A name dialog follows. A text file starts as `untitled.txt` with `untitled` selected, and a `/` in the name creates the folders in between. Enter creates.
+- A new folder opens in the tree and becomes the current directory. A new text file is empty and opens in the editor, unless the editor holds unsaved changes.
+- A taken name is refused with nothing written, and the dialog stays open on it. The server's `POST files/create` answers 409 `target_exists`, and it does not follow a link at the path.
+
+## Folder rename
+
+- Folders take the same **Rename or move** dialog as files and move whole. An occupied destination and a move into the folder's own subtree are refused.
+- A folder has no version marker, so it moves without one. `POST files/move` accepts a folder and refuses a folder sent with `ifVersion`.
+- The open folders, the current directory and an open file follow the new path. A file's rename now follows it too, instead of leaving the preview waiting on the old path.
+
+## Editing like a code editor
+
+- **Edit** opens the editor where the preview was scrolled, with the cursor at the start of the first line in view.
+- Saving leaves the editor open, with the cursor, the selection and the scroll untouched. `PUT files/content` answers with the version it wrote in `ETag`, and the next save carries it.
+- When a finished turn rewrote the open file and the editor holds no unsaved changes, the editor takes the new text in place, keeping the cursor's line and the scroll. With unsaved changes the text is kept, **Changed on disk** shows, and the save asks as before.
+- **Stop editing** (×, formerly **Cancel**) returns to the preview where the editor was scrolled.
+
+## The Files panel without a Session
+
+- On the new-chat page, a **Files** toggle right of the Workspace pill opens the dock's Files panel on the folder picked there, and picking another folder re-roots it. **Add to conversation** adds to the new chat's composer. With a temporary workspace the toggle is unavailable, and its tooltip says why.
+- A Workspace group's **…** menu in the sidebar offers **Browse files** for any group that is one folder. When the page on screen is already in that folder, the panel opens in place. Otherwise the new-chat page opens on the folder with the panel.
+- The panel addresses such a folder by its path through `/api/projects/:projectId/workspace-files`, the same operations as a Session's file routes, under Project access. HTML there previews in the same-origin sandbox.
+
+## Copies
+
+- The docs state that **Copy relative path** writes the Workspace-relative path to the clipboard of the computer the browser runs on, also over plain HTTP. The fallback for plain HTTP landed in [#523](https://github.com/Prism-Shadow/penguin-harness/pull/523), and a browser test (`files-folders.spec.mjs`) now covers it.
diff --git a/changelog/unreleased/2026-10-01-files-panel-folders.zh.md b/changelog/unreleased/2026-10-01-files-panel-folders.zh.md
new file mode 100644
index 00000000..3bd74f06
--- /dev/null
+++ b/changelog/unreleased/2026-10-01-files-panel-folders.zh.md
@@ -0,0 +1,40 @@
+# 文件浏览面板:新建文件夹与文本文件、文件夹重命名、代码编辑器式的编辑,以及新建对话页上的面板
+
+- **Date:** 2026-10-01
+- **Type:** feature
+- **Scope:** `web`, `ui`, `server`, `docs`
+- **PR:** [#938](https://github.com/Prism-Shadow/penguin-harness/pull/938)
+
+[English](2026-10-01-files-panel-folders.md)
+
+文件浏览面板新增**新建文本文件**和**新建文件夹**,文件夹可以重命名和移动,编辑器像代码编辑器一样停在原处;新建对话页上可以为选定的文件夹打开面板,侧栏 Workspace 分组新增的**打开文件浏览**也会走到这里。
+
+## 新建文件与文件夹
+
+- 目录树顶栏的**新建**菜单建在当前目录,文件夹的右键菜单建在该文件夹内,目录树下方的空白处建在 Workspace 根目录。
+- 随后弹出名称框。文本文件的名称默认是 `untitled.txt` 并选中 `untitled`,名称里的 `/` 会同时建出中间的文件夹;按 Enter 即创建。
+- 新建的文件夹在目录树中展开并成为当前目录。新建的文本文件是空文件,建好后在编辑器中打开;编辑器里有未保存的修改时则只建不开。
+- 名称已被占用时拒绝,不写入任何内容,对话框停在该名称上。服务端 `POST files/create` 返回 409 `target_exists`,且不跟随该路径上的符号链接。
+
+## 文件夹重命名
+
+- 文件夹与文件共用**重命名 / 移动**对话框,整棵移动;目标已存在、或要移入文件夹自身之下时拒绝。
+- 文件夹没有版本标记,因此不带前置条件移动。`POST files/move` 接受文件夹,对带 `ifVersion` 的文件夹返回 400。
+- 展开的文件夹、当前目录和打开中的文件都跟到新路径。文件的重命名同样跟过去,预览不再停在旧路径上等待。
+
+## 代码编辑器式的编辑
+
+- **编辑**打开的编辑器停在预览滚动到的位置,光标位于可见区第一行行首。
+- 保存后编辑器仍然打开,光标、选区和滚动位置都不动。`PUT files/content` 在 `ETag` 里带回写入后的版本,下一次保存带着它。
+- 一轮对话结束后,若打开的文件已被改写而编辑器里没有未保存的修改,编辑器直接换成新内容,保留光标所在行与滚动位置。有未保存的修改时保留文本,标出**磁盘上已变更**,保存时照旧先询问。
+- **退出编辑**(×,原为**取消**)回到预览,预览停在编辑器滚动到的位置。
+
+## 没有 Session 时的文件浏览面板
+
+- 新建对话页工作区胶囊右侧的**文件浏览**开关,为胶囊里选定的文件夹打开停靠栏的文件浏览面板;改选文件夹即换根。**添加到对话**会加到新对话的输入框里。临时工作区下开关不可用,悬停提示说明原因。
+- 侧栏 Workspace 分组的 **…** 菜单为每个指向单一文件夹的分组提供**打开文件浏览**。当前页面已在该文件夹上时在原处打开面板,否则打开该文件夹的新建对话页并打开面板。
+- 面板经 `/api/projects/:projectId/workspace-files` 按路径寻址这样的文件夹:操作与 Session 的文件路由相同,授权落在 Project 访问权上。其中的 HTML 以同源沙箱预览。
+
+## 复制
+
+- 文档写明**复制相对路径**把相对 Workspace 的路径写入浏览器所在电脑的剪贴板,经明文 HTTP 访问时同样如此。明文 HTTP 下的回退由 [#523](https://github.com/Prism-Shadow/penguin-harness/pull/523) 实现,现在有一个浏览器测试(`files-folders.spec.mjs`)覆盖它。
diff --git a/packages/docs/content/chat.en.md b/packages/docs/content/chat.en.md
index 8bede75c..f699684a 100644
--- a/packages/docs/content/chat.en.md
+++ b/packages/docs/content/chat.en.md
@@ -211,7 +211,7 @@ To return to the newest message, select **Jump to latest**. In a longer conversa
## Use side panels
-The chat page has two docks for panels: the right sidebar and the bottom panel. The **Right sidebar** and **Bottom panel** buttons at the top right of the chat toolbar show and hide them. An empty dock offers a list of panels to open; **Add panel** adds another, and a panel can move to the other dock. Panels become available once the conversation has started.
+The chat page has two docks for panels: the right sidebar and the bottom panel. The **Right sidebar** and **Bottom panel** buttons at the top right of the chat toolbar show and hide them. An empty dock offers a list of panels to open; **Add panel** adds another, and a panel can move to the other dock. Panels become available once the conversation has started, except **Files**: on the new-chat page it browses the folder picked for the new conversation, from the **Files** button right of the Workspace pill (see [Files panel](/files#open-the-files-panel)).
| Panel | What it shows |
| --- | --- |
diff --git a/packages/docs/content/chat.zh.md b/packages/docs/content/chat.zh.md
index 8a0fced4..1cc5c4f2 100644
--- a/packages/docs/content/chat.zh.md
+++ b/packages/docs/content/chat.zh.md
@@ -211,7 +211,7 @@ Session 的模型是锁定的,点击模型名称会提示「输入 /model 切
## 使用侧边面板
-对话页有两个放面板的侧栏:右侧栏和下侧栏,用对话工具栏右上角的**右侧栏**和**下侧栏**按钮显示或隐藏。空的侧栏会列出可以打开的面板;用**添加面板**可以再加一个,面板也可以移到另一侧。对话开始后才能使用这些面板。
+对话页有两个放面板的侧栏:右侧栏和下侧栏,用对话工具栏右上角的**右侧栏**和**下侧栏**按钮显示或隐藏。空的侧栏会列出可以打开的面板;用**添加面板**可以再加一个,面板也可以移到另一侧。对话开始后才能使用这些面板,**文件浏览**除外:在新建对话页上,它浏览为新对话选定的文件夹,入口是工作区胶囊右侧的**文件浏览**按钮(见[文件面板](/files#打开文件面板))。
| 面板 | 内容 |
| --- | --- |
diff --git a/packages/docs/content/files.en.md b/packages/docs/content/files.en.md
index d70c304c..581912d9 100644
--- a/packages/docs/content/files.en.md
+++ b/packages/docs/content/files.en.md
@@ -3,12 +3,12 @@ title: Files panel
description: Browse, preview, edit, and manage the files in a conversation's Workspace.
---
-The **Files** panel is one of the chat page's side panels. It shows the Workspace of the open conversation: a directory tree on the left, and a preview of the selected file on the right. Every member of the Project can browse, preview, edit, upload, rename and delete files here.
+The **Files** panel is one of the chat page's side panels. It shows the Workspace of the open conversation, or on the new-chat page the folder picked for the new one: a directory tree on the left, and a preview of the selected file on the right. Every member of the Project can browse, preview, edit, upload and delete files here, and create, rename and move files and folders.
- To get started, see [Open the Files panel](#open-the-files-panel).
- To find a file, see [Search the Workspace](#search-the-workspace).
- To change files, see [Edit a text file](#edit-a-text-file) and [Use the context menu](#use-the-context-menu).
-- To add files, see [Upload files](#upload-files).
+- To add files, see [Create a file or folder](#create-a-file-or-folder) and [Upload files](#upload-files).
## Open the Files panel
@@ -17,14 +17,16 @@ Open the panel from any of these places:
- The top right of the chat toolbar: select **Right sidebar** or **Bottom panel**, then choose **Files**. If the dock already shows other panels, use its **Add panel** menu.
- The **Shortcuts** launcher on the conversation's right edge.
- A message: select a file chip or file card to open the panel at that file. A link in a reply that names a file in the Workspace opens it here too, instead of navigating the browser; whether the file exists is not checked first, so the panel says when it is missing.
+- The new-chat page: select **Files** right of the Workspace pill under the composer. The panel shows the folder picked in the pill, and picking another folder moves it there. **Add to conversation** adds to the new chat's composer.
+- The sidebar: in a Workspace group's **…** menu, select **Browse files**. When the page on screen is already in that folder, the panel opens there. Otherwise a new chat opens on that folder, with the panel.
-The panel is available once the conversation has started. See [Use side panels](/chat#use-side-panels).
+On the new-chat page the panel needs a folder. A temporary workspace is created with the first message, so until then **Files** is unavailable, and its tooltip says why. When the first message is sent, the panel carries on with the new conversation's Workspace. See [Use side panels](/chat#use-side-panels).
## Browse the file tree
The tree lists the contents of a directory the first time you open it. File rows show the file size after the name. Point at a row to see its path, size, and modified time.
-The tree pane's header holds the search box, **Refresh** and **Upload**.
+The tree pane's header holds the search box, **New**, **Refresh** and **Upload**.
The path row above the preview names the open file. The leading directories collapse into a single `…` first, and the file name is the last thing to go. When no file is open, the path row names the current directory. The root reads `.`, and the Workspace's absolute path lives in the Session details card.
@@ -40,7 +42,7 @@ The tree and the open preview re-read when a turn finishes. The tree also re-rea
### Hide the tree or change its width
-At the left end of the panel's header row, select **Hide file tree** to slide the tree out of the panel's left edge. The search box, **Refresh** and **Upload** are hidden with it. Select **Show file tree** to bring the tree back. The tree is shown by default, and the panel remembers your choice in the browser.
+At the left end of the panel's header row, select **Hide file tree** to slide the tree out of the panel's left edge. The search box, **New**, **Refresh** and **Upload** are hidden with it. Select **Show file tree** to bring the tree back. The tree is shown by default, and the panel remembers your choice in the browser.
Drag the divider between the two panes to set the tree's width. When the divider has focus, the arrow keys nudge it. The panel remembers the width too.
@@ -78,7 +80,7 @@ A Markdown file larger than 64KB opens in the source view. You can still switch
An HTML file can also be opened in a new browser tab: in the preview, select **Open in new tab**.
> [!NOTE]
-> When the app is reached through an address with no separate preview origin, the tab opens sandboxed, without localStorage, cookies or third-party embeds. To avoid the sandbox, reach the app over 127.0.0.1 or localhost, or set `PENGUIN_PREVIEW_ORIGIN`.
+> When the app is reached through an address with no separate preview origin, the tab opens sandboxed, without localStorage, cookies or third-party embeds. To avoid the sandbox, reach the app over 127.0.0.1 or localhost, or set `PENGUIN_PREVIEW_ORIGIN`. On the new-chat page HTML always opens sandboxed: the separate preview origin serves a conversation's files only.
A text preview reads up to 1MB. A larger file is shown truncated, with the message "File too large; preview truncated, download for the full file", and cannot be edited here. **Download** is in the preview header.
@@ -86,12 +88,14 @@ Three buttons float over the top right of the file view: **Copy code**, **Wrap**
## Edit a text file
-1. Open the file in the preview, then select **Edit** at the top right of the file view. The preview becomes an editor: the same highlighted text with line numbers, now editable. There is no rich editor.
+1. Open the file in the preview, then select **Edit** at the top right of the file view. The preview becomes an editor: the same highlighted text with line numbers, now editable. There is no rich editor. The editor opens where the preview was scrolled, with the cursor at the start of the first line in view.
2. Make your changes.
3. Select **Save** (the check mark), or press Ctrl+S / Cmd+S.
4. In the **Save file** dialog, select **Save** to write the file back.
-Select **Cancel** (×) to return to the preview without saving.
+As in a code editor, saving leaves the editor open, with the cursor, the selection and the scroll where they were.
+
+Select **Stop editing** (×) to return to the preview. It asks first when there are unsaved changes, and the preview comes back where the editor was scrolled.
The panel asks before your unsaved changes are lost: when you switch to another file, close the panel's tab, or leave the page.
@@ -104,29 +108,44 @@ A save over the 14MB write limit is refused with a message.
## Handle a file that changed on disk
-The agent writes to the same Workspace, so a file can change while you are editing it. The panel checks for changes whenever a turn finishes. Your text is never replaced. As soon as the file has changed on disk, the editor header shows **Changed on disk**.
+The agent writes to the same Workspace, so a file can change while you are editing it. The panel checks for changes whenever a turn finishes:
+
+- If the editor holds no unsaved changes, it takes the new text in place. The cursor stays on its line and the view does not move.
+- If it holds unsaved changes, your text is never replaced. The editor header shows **Changed on disk**.
A save that would land on a changed file is refused before anything is written. The **File changed on disk** dialog asks whether to **Overwrite** the file with your version or keep editing. Your text is kept either way.
## Use the context menu
-Right-click a tree row or the file view to open the context menu. On a touch screen, long-press. On a keyboard, press Shift+F10 or the menu key.
+Right-click a tree row, the blank space under the rows, or the file view to open the context menu. On a touch screen, long-press. On a keyboard, press Shift+F10 or the menu key.
> [!NOTE]
> The context menu does not open inside an HTML or PDF preview, or inside the editor, where the browser's own menu is how text is pasted.
| Menu item | What it does | Available for |
| --- | --- | --- |
-| **Copy relative path** | Copies the path from the Workspace root. | Files and directories |
+| **Copy relative path** | Copies the path from the Workspace root to the clipboard of the computer your browser runs on, also when the app is reached over plain HTTP, such as a LAN address. | Files and directories |
| **Add to conversation** | Adds a reference to the file or directory to the composer as a chip. A directory's path ends in `/`. Nothing is sent until you send the message. | Files and directories |
| **Add selection to conversation** | On send, the message carries the selected text as a code block headed by the file and line range, such as `@src/app.ts:12-18`. | Files, in the file view, with text selected |
+| **New text file** / **New folder** | Creates one in this directory. See [Create a file or folder](#create-a-file-or-folder). | Directories, and the blank space under the rows (the Workspace root) |
| **Upload here** | Uploads into this directory. See [Upload files](#upload-files). | Directories |
| **Download** | Downloads the file. See [Download a file](#download-a-file). | Files |
-| **Rename or move** | Enter a **New path** relative to the Workspace root and select **Move**. Missing directories are created. An existing target is refused. | Files |
+| **Rename or move** | Enter a **New path** relative to the Workspace root and select **Move**. Missing directories are created. An existing target is refused. A directory moves with everything in it, and cannot move into itself; a file that was open follows it. | Files and directories |
| **Delete** | Deletes the file after a confirmation. The file does not go to a trash folder. | Files |
> [!NOTE]
-> Rename, move and delete read the file's current version first. If the agent rewrote the file while the dialog was open, they change nothing.
+> Rename, move and delete read the file's current version first. If the agent rewrote the file while the dialog was open, they change nothing. A directory has no version, so renaming one does not wait for this read.
+
+## Create a file or folder
+
+1. Choose where the new entry goes:
+ - To create in the current directory, the one the path row names, select **New** in the tree pane's header.
+ - To create inside a directory, right-click its row.
+ - To create at the Workspace root, right-click the blank space under the rows.
+2. Select **New text file** or **New folder**.
+3. Enter a name and select **Create**, or press Enter. A text file starts as `untitled.txt` with `untitled` selected, so typing replaces the name and keeps the extension. A `/` in the name also creates the folders in between.
+
+A new folder opens in the tree and becomes the current directory. A new text file is empty and opens in the editor, unless the editor holds unsaved changes. A name that is already taken is refused with "… already exists, so nothing was changed."; the dialog stays open so you can change the name.
## Upload files
diff --git a/packages/docs/content/files.zh.md b/packages/docs/content/files.zh.md
index 85239c5d..39073027 100644
--- a/packages/docs/content/files.zh.md
+++ b/packages/docs/content/files.zh.md
@@ -3,12 +3,12 @@ title: 文件面板
description: 浏览、预览、编辑和管理对话 Workspace 里的文件。
---
-**文件浏览**面板是对话页的侧边面板之一,展示当前对话的 Workspace:左侧是目录树,右侧是所选文件的预览。Project 的所有成员都可以在这里浏览、预览、编辑、上传、重命名和删除文件。
+**文件浏览**面板是对话页的侧边面板之一,展示当前对话的 Workspace,在新建对话页上则展示为新对话选定的文件夹:左侧是目录树,右侧是所选文件的预览。Project 的所有成员都可以在这里浏览、预览、编辑、上传和删除文件,新建、重命名和移动文件与文件夹。
- 第一次使用,见[打开文件面板](#打开文件面板)。
- 查找文件,见[搜索 Workspace](#搜索-workspace)。
- 修改文件,见[编辑文本文件](#编辑文本文件)和[使用右键菜单](#使用右键菜单)。
-- 添加文件,见[上传文件](#上传文件)。
+- 添加文件,见[新建文件或文件夹](#新建文件或文件夹)和[上传文件](#上传文件)。
## 打开文件面板
@@ -17,14 +17,16 @@ description: 浏览、预览、编辑和管理对话 Workspace 里的文件。
- 对话工具栏右上角:选择**右侧栏**或**下侧栏**,再选择**文件浏览**。如果侧栏里已经有别的面板,就用它的**添加面板**菜单。
- 对话区右缘的**快捷方式**悬浮球。
- 消息里的文件小卡片或文件卡片:点击后打开面板并定位到该文件。回复里指向 Workspace 内文件的链接也在这里打开,而不是让浏览器跳转;点击前不检查文件是否存在,文件不在时由面板给出提示。
+- 新建对话页:选择输入框下方工作区胶囊右侧的**文件浏览**。面板展示胶囊里选定的文件夹,改选文件夹即换到新的目录。**添加到对话**会加到新对话的输入框里。
+- 侧栏:在 Workspace 分组的 **…** 菜单中选择**打开文件浏览**。当前页面已经在这个文件夹上时,直接在原处打开面板;否则打开这个文件夹的新对话,并打开面板。
-对话开始后才能使用这个面板,见[使用侧边面板](/chat#使用侧边面板)。
+在新建对话页上,面板需要一个文件夹。临时工作区在发送第一条消息时才创建,在那之前**文件浏览**不可用,悬停提示会说明原因。发出第一条消息后,面板随新对话的 Workspace 继续。见[使用侧边面板](/chat#使用侧边面板)。
## 浏览文件树
目录第一次展开时才列出其中的内容。文件行在名称后显示文件大小,鼠标指向某一行可以看到它的路径、大小和修改时间。
-目录树的顶栏里有搜索框、**刷新**和**上传**。
+目录树的顶栏里有搜索框、**新建**、**刷新**和**上传**。
预览上方的路径行显示当前打开的文件。空间不够时,前面的目录先折叠成一个 `…`,文件名最后才省略。没有打开文件时,路径行显示当前目录。根目录写作 `.`,Workspace 的绝对路径在 Session 详情卡片里查看。
@@ -40,7 +42,7 @@ description: 浏览、预览、编辑和管理对话 Workspace 里的文件。
### 隐藏目录树或调整宽度
-在面板顶栏最左侧选择**隐藏文件树**,目录树会从面板左缘滑出,搜索框、**刷新**和**上传**也一起隐藏。选择**显示文件树**即可恢复。目录树默认显示,这个选择会记在浏览器里。
+在面板顶栏最左侧选择**隐藏文件树**,目录树会从面板左缘滑出,搜索框、**新建**、**刷新**和**上传**也一起隐藏。选择**显示文件树**即可恢复。目录树默认显示,这个选择会记在浏览器里。
拖动两栏之间的分隔条可以调整目录树的宽度;分隔条获得焦点时,也可以用方向键微调。宽度同样会被记住。
@@ -78,7 +80,7 @@ description: 浏览、预览、编辑和管理对话 Workspace 里的文件。
HTML 文件还可以在浏览器新标签页中打开:在预览中选择**新页面打开**。
> [!NOTE]
-> 如果当前访问地址没有独立的预览源,新标签页会以沙箱模式打开,localStorage、Cookie 和第三方嵌入内容都无法使用。要避开沙箱,请通过 127.0.0.1 或 localhost 访问应用,或设置 `PENGUIN_PREVIEW_ORIGIN`。
+> 如果当前访问地址没有独立的预览源,新标签页会以沙箱模式打开,localStorage、Cookie 和第三方嵌入内容都无法使用。要避开沙箱,请通过 127.0.0.1 或 localhost 访问应用,或设置 `PENGUIN_PREVIEW_ORIGIN`。在新建对话页上 HTML 一律以沙箱模式打开:独立预览源只提供对话的文件。
文本预览最多读取 1MB。更大的文件会截断显示,提示「内容过大,预览已截断,请下载查看完整文件」,并且不能在这里编辑。**下载**按钮在预览顶栏。
@@ -86,12 +88,14 @@ HTML 文件还可以在浏览器新标签页中打开:在预览中选择**新
## 编辑文本文件
-1. 在预览中打开文件,选择文件视图右上角的**编辑**。预览变成编辑器:依然是带高亮和行号的文本,只是可以修改了。这里没有富文本编辑器。
+1. 在预览中打开文件,选择文件视图右上角的**编辑**。预览变成编辑器:依然是带高亮和行号的文本,只是可以修改了。这里没有富文本编辑器。编辑器停在预览滚动到的位置,光标位于可见区第一行行首。
2. 修改内容。
3. 选择**保存**(对勾图标),或按 Ctrl+S / Cmd+S。
4. 在**保存文件**对话框中选择**保存**,写回文件。
-选择**取消**(×)会放弃编辑,回到预览。
+与代码编辑器一样,保存后编辑器仍然打开,光标、选区和滚动位置都保持原样。
+
+选择**退出编辑**(×)回到预览。有未保存的修改时会先询问;预览停在编辑器滚动到的位置。
未保存的修改有可能丢失时,面板会先询问,例如切换到其他文件、关闭面板标签页或离开页面。
@@ -104,29 +108,44 @@ HTML 文件还可以在浏览器新标签页中打开:在预览中选择**新
## 处理磁盘上已变更的文件
-Agent 也在写同一个 Workspace,所以你编辑的文件可能在此期间被改动。每轮对话结束时面板都会检查一次。你输入的文本不会被替换,但只要文件变了,编辑器顶栏就会标出**磁盘上已变更**。
+Agent 也在写同一个 Workspace,所以你编辑的文件可能在此期间被改动。每轮对话结束时面板都会检查一次:
+
+- 编辑器里没有未保存的修改时,直接换成新内容。光标留在原来那一行,视图不动。
+- 有未保存的修改时,你输入的文本不会被替换,编辑器顶栏会标出**磁盘上已变更**。
如果保存会覆盖一个已变更的文件,面板会在写入前拒绝,并弹出**文件在磁盘上已变更**对话框,让你选择**仍然覆盖**,或者继续编辑。无论选哪一项,你输入的文本都会保留。
## 使用右键菜单
-在目录树的某一行或文件视图上点击右键,即可打开右键菜单。触屏设备上长按,键盘上按 Shift+F10 或菜单键。
+在目录树的某一行、行下方的空白处或文件视图上点击右键,即可打开右键菜单。触屏设备上长按,键盘上按 Shift+F10 或菜单键。
> [!NOTE]
> HTML 或 PDF 预览内部以及编辑器里不会弹出这个菜单,在编辑器里要靠浏览器自带的右键菜单粘贴文本。
| 菜单项 | 作用 | 适用于 |
| --- | --- | --- |
-| **复制相对路径** | 复制从 Workspace 根目录开始的路径。 | 文件和目录 |
+| **复制相对路径** | 把从 Workspace 根目录开始的路径复制到浏览器所在电脑的剪贴板;通过明文 HTTP 访问应用(例如局域网地址)时同样如此。 | 文件和目录 |
| **添加到对话** | 把文件或目录的引用作为小卡片放进输入框,目录的路径以 `/` 结尾。发送消息前不会发出任何内容。 | 文件和目录 |
| **将选中内容添加到对话** | 发送时,选中的文本以代码块形式随消息发出,代码块开头标明文件和行号范围,例如 `@src/app.ts:12-18`。 | 文件,需在文件视图中选中文本 |
+| **新建文本文件** / **新建文件夹** | 在该目录下新建,见[新建文件或文件夹](#新建文件或文件夹)。 | 目录,以及行下方的空白处(Workspace 根目录) |
| **上传到此文件夹** | 把文件上传到该目录,见[上传文件](#上传文件)。 | 目录 |
| **下载** | 下载该文件,见[下载文件](#下载文件)。 | 文件 |
-| **重命名 / 移动** | 输入相对于 Workspace 根目录的**新的路径**,再选择**移动**。路径中不存在的目录会自动创建;目标已存在时拒绝操作。 | 文件 |
+| **重命名 / 移动** | 输入相对于 Workspace 根目录的**新的路径**,再选择**移动**。路径中不存在的目录会自动创建;目标已存在时拒绝操作。目录连同其中的一切一起移动,不能移入自身之下;打开中的文件会跟着过去。 | 文件和目录 |
| **删除** | 确认后删除文件。文件不会进入回收站。 | 文件 |
> [!NOTE]
-> 重命名、移动和删除都会先读取文件的当前版本。如果对话框打开期间 Agent 改写了该文件,这些操作不会做任何改动。
+> 重命名、移动和删除都会先读取文件的当前版本。如果对话框打开期间 Agent 改写了该文件,这些操作不会做任何改动。目录没有版本,所以重命名目录不必等待这次读取。
+
+## 新建文件或文件夹
+
+1. 选择新条目放在哪里:
+ - 放在当前目录(路径行显示的那个目录):在目录树顶栏选择**新建**。
+ - 放在某个目录下:在该目录的行上点击右键。
+ - 放在 Workspace 根目录:在行下方的空白处点击右键。
+2. 选择**新建文本文件**或**新建文件夹**。
+3. 输入名称,选择**创建**或按 Enter。文本文件的名称默认是 `untitled.txt`,并选中 `untitled`,直接输入即可替换名称、保留扩展名。名称里的 `/` 会同时建出中间的文件夹。
+
+新建的文件夹会在目录树中展开,并成为当前目录。新建的文本文件是空文件,建好后在编辑器中打开;编辑器里有未保存的修改时则只建不开。名称已被占用时会被拒绝,并提示「… 已存在,未做改动。」,对话框保持打开,方便修改名称。
## 上传文件
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 93f07149..dd4ab1dd 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -618,6 +618,11 @@ The paths below omit the `/api/projects/:projectId` prefix.
| GET | `/dirs?path=` | Server-side directory browser behind the Workspace picker |
| POST | `/dirs/access` | Desktop app: has the shell read a folder macOS refused, in the app's own name, so that macOS asks the user: `{path}` → `{granted, packaged}` |
| GET | `/dir-skills?path=` | The Skills a directory carries, for importing them into a new agent |
+| GET | `/workspace-files?workspace=&path=` | The **Files** panel on a directory no Session addresses yet (see below) |
+| GET / PUT / DELETE | `/workspace-files/content?workspace=&path=` | Reads, writes or deletes a file of that directory |
+| POST | `/workspace-files/create?workspace=` / `/workspace-files/move?workspace=` | Creates a file or folder / moves one |
+| GET | `/workspace-files/search?workspace=&q=` | Searches that directory by entry name |
+| POST | `/workspace-files/reveal?workspace=&path=` | Shows the file in the machine's own file manager |
- The Session list accepts optional query parameters. `limit` and `offset` page the list (`offset` requires `limit`). `category` (`active`, `subagent`, `schedule`, `benchmark` or `archived`) filters it before paging, and `workspaceGroup` filters it to one Workspace. `counts=1` adds `counts` (totals per category over the whole list), `workspaceCounts` (the same totals per Workspace path) and `workspaceLatest` (each Workspace's newest Session). Without paging parameters, the full list is returned.
- `excludeOrg=1` leaves an organization's desk, ticket and subagent Sessions out of the page and out of the `counts=1` totals together, which is what development mode's list asks for. Any other value is a 400.
@@ -628,6 +633,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
- `GET /dirs` starts at the home directory when `path` is omitted; an explicit `path` must be absolute. It answers `{path, parent, entries, platform}`: every entry carries its `kind` (`dir` or `file`) and `mtime`, and on Windows the home request adds `roots`, the drive roots that exist. A directory the server may not read answers `403 dir_permission_denied` rather than an empty list — on macOS that is usually a Files and Folders permission the user has not granted.
- `POST /dirs/access` is the Workspace picker's **Allow access** in the desktop app. macOS asks about Desktop, Documents and Downloads only on behalf of the app it holds responsible for the read, so the desktop shell's main process reads the absolute `path` once, and the answer waits for the user. `granted` says whether the read succeeded (always `true` off macOS, where nothing is read). `packaged` is `false` for a development instance started from a terminal, whose reads macOS charges to that terminal. The route returns `400` `dir_not_absolute` for a path that is not absolute, `503` `shell_unreachable` when the server has no desktop shell to ask, and `504` `timeout` when the shell has not answered within 120 seconds. Only the desktop app's own window may call it; any other session gets `403` `desktop_shell_only`.
- `GET /dir-skills` reads only `<path>/.agents/skills` and `<path>/.claude/skills` of an absolute `path`, and answers `{path, skills}`. A directory without Skills answers with an empty list. See `POST /agents` under [Agents](#agents).
+- `/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.
## Usage and Traces (Agent Level)
@@ -795,15 +801,18 @@ The Web App's `/model` switch has no dedicated endpoint. Like the `/agent` hando
| GET | `/files/content?path=&download=&preview=` | Reads a Workspace file (see [Workspace file responses](#workspace-file-responses)) |
| GET | `/files/preview-redirect?path=` | Opens an HTML file on the separate preview origin: mints a signed token and redirects with 302 |
| POST | `/files/stat` | Checks whether files exist: `{paths}` |
-| PUT | `/files/content?path=` | Uploads a file: `{dataBase64}`, up to 14MB |
-| POST | `/files/move` | Moves or renames one file: `{from, to, ifVersion?}` → 204 |
+| PUT | `/files/content?path=` | Writes a file whole: `{dataBase64, ifVersion?}`, up to 14MB → 204, with the version written in `ETag` |
+| POST | `/files/create` | Creates an empty text file or a folder: `{path, kind}` (`file` or `dir`) → 204 |
+| POST | `/files/move` | Moves or renames one file or folder: `{from, to, ifVersion?}` → 204 |
| DELETE | `/files/content?path=&ifVersion=` | Deletes one file → 204 |
| POST | `/files/reveal?path=` | Shows the file in the machine's own file manager → 204 |
| GET | `/files/search?q=` | Searches the whole Workspace by entry name |
| GET | `/scratchpad/:fileName` | Reads a scratch file of the Session, such as an input image or file attachment |
- `GET /files/preview-redirect` backs **Open in new tab** and the rendered HTML view of the **Files** panel; see [Preview on a separate origin](#preview-on-a-separate-origin).
-- `POST /files/move` works on files only: a directory has no single version marker, so the precondition that protects the move cannot be expressed for one, and the route returns 400. Missing parent directories of `to` are created. It returns 404 `path_not_found` when `from` is gone, and 409 `file_changed` when `ifVersion` no longer matches (a source that disappeared while a marker was given counts as changed). It returns 409 `target_exists` when something is already at `to`, because the destination was never read and so is refused rather than overwritten, and 400 for a move onto the file's own path.
+- `PUT /files/content` answers with the version it wrote in `ETag`: the marker the next conditional write of the same file carries, so the **Files** panel's editor keeps editing after a save.
+- `POST /files/create` creates one empty text file or one folder, making missing parent directories as a write does. Anything already at `path`, a link included (it is not followed), returns 409 `target_exists` with nothing written.
+- `POST /files/move` moves a file or a folder. Missing parent directories of `to` are created. It returns 404 `path_not_found` when `from` is gone, and for a file, 409 `file_changed` when `ifVersion` no longer matches (a source that disappeared while a marker was given counts as changed). A folder has no single version marker, so it moves whole without one: a folder sent with `ifVersion` returns 400, and so does a folder moved into itself. It returns 409 `target_exists` when something is already at `to`, because the destination was never read and so is refused rather than overwritten, and 400 for a move onto the entry's own path.
- `DELETE /files/content` also works on files only (400 for a directory). It returns 404 `path_not_found` when the file is gone, and 409 `file_changed` when `ifVersion` no longer matches. The marker is optional, and without it the delete is unconditional, but the **Files** panel always sends the marker its read returned.
- `POST /files/reveal` selects the file on macOS and Windows, and opens its directory on a Linux desktop. Only the desktop shell's own window may call it. It returns 404 `not_found` when the server was not started by a desktop shell, and 403 `desktop_shell_only` for a browser session against a desktop-mode server: such a session 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 same way as for a read (400 out of bounds, 404 `path_not_found`), and 502 `reveal_failed` means the file manager would not start.
- `GET /files/search` matches entry names only (a case-insensitive substring; the path is not matched) and answers `{hits: [{path, kind, sizeBytes, mtime}], truncated}`, each hit carrying what a directory listing entry carries. The search walks breadth-first from the root, so hits come shallowest first, and a capped result keeps the most relevant hits rather than whatever the first directory held. `truncated` means a cap stopped the walk: 200 hits, or 20000 directory entries visited. An empty `q`, or one longer than 100 characters, returns 400.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 448268b9..0ed7f822 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -618,6 +618,11 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| GET | `/dirs?path=` | Workspace 选择器背后的服务器端目录浏览器 |
| POST | `/dirs/access` | 桌面端:请 shell 以应用自身的身份读一次 macOS 拒绝的目录,让 macOS 询问用户:`{path}` → `{granted, packaged}` |
| GET | `/dir-skills?path=` | 目录所带的 Skill,用于导入到新 Agent |
+| GET | `/workspace-files?workspace=&path=` | 还没有 Session 可寻址时,**文件浏览**面板对一个目录的浏览(见下) |
+| GET / PUT / DELETE | `/workspace-files/content?workspace=&path=` | 读取、写入或删除该目录里的文件 |
+| POST | `/workspace-files/create?workspace=` / `/workspace-files/move?workspace=` | 新建文件或文件夹 / 移动 |
+| GET | `/workspace-files/search?workspace=&q=` | 按条目名搜索该目录 |
+| POST | `/workspace-files/reveal?workspace=&path=` | 在机器自带的文件管理器中显示文件 |
- Session 列表接受可选查询参数。`limit` 和 `offset` 用于分页(`offset` 必须搭配 `limit`)。`category`(`active`、`subagent`、`schedule`、`benchmark` 或 `archived`)先过滤再分页;`workspaceGroup` 只保留一个 Workspace 的会话。`counts=1` 会在响应里附加 `counts`(整个列表按类别的总数)、`workspaceCounts`(按 Workspace 路径统计的同类总数)和 `workspaceLatest`(每个 Workspace 最新的 Session)。不带分页参数时,返回完整列表。
- `excludeOrg=1` 会把组织的工位会话、工单会话和子 Session 一并移出这一页以及 `counts=1` 的总数,这正是开发模式的列表所要的。取其他值返回 400。
@@ -628,6 +633,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries, platform}`:每个条目带 `kind`(`dir` 或 `file`)与 `mtime`;在 Windows 上,请求主目录时另带 `roots`,即实际存在的各盘符根目录。服务无权读取的目录返回 `403 dir_permission_denied`,不再按空列表返回;在 macOS 上这通常是用户尚未授予的「文件与文件夹」权限。
- `POST /dirs/access` 是桌面端 Workspace 选择器里的**允许访问**。macOS 只替它认定为读取责任方的应用询问桌面、文稿与下载的访问权限,因此由桌面 shell 的主进程把绝对路径 `path` 读一次,响应要等用户作答后才返回。`granted` 表示这次读取是否成功(非 macOS 平台不读取,恒为 `true`)。`packaged` 为 `false` 表示这是从终端启动的开发实例,macOS 把它的读取记在该终端名下。`path` 不是绝对路径时返回 `400` `dir_not_absolute`;服务器没有可询问的桌面 shell 时返回 `503` `shell_unreachable`;shell 在 120 秒内没有应答时返回 `504` `timeout`。只有桌面应用自己的窗口可以调用,其他会话返回 `403` `desktop_shell_only`。
- `GET /dir-skills` 只读取绝对路径下的 `<path>/.agents/skills` 和 `<path>/.claude/skills`,响应为 `{path, skills}`。没有 Skill 的目录返回空列表。参见 [Agent](#agent) 一节中的 `POST /agents`。
+- `/workspace-files` 对 `workspace` 里以绝对路径指定的目录执行 [Workspace 文件](#workspace-文件)中的那组操作,供还没有 Session 的页面使用:新建对话页选定的文件夹,以及侧栏 Workspace 分组的**打开文件浏览**。响应与 Session 路由完全相同。调用方需要有该 Project 的访问权——也就是能在该目录下创建 Session 的同一种权限;`workspace` 必须是已存在的目录,校验口径与在该目录创建 Session 时相同(否则返回 400 `workspace_not_found`)。每个 `path` 都像对 Session 一样被限制在该目录内。这里没有预览跳转,因为预览令牌绑定 Session:目录里的 HTML 以 `preview=1` 在同源沙箱中预览。其他机器上的目录经该机器的 `/server/<machineId>` 代理访问。
## 用量与 Trace(Agent 级别)
@@ -795,15 +801,18 @@ Web App 的 `/model` 切换没有专用端点。和 `/agent` 交接一样,它
| GET | `/files/content?path=&download=&preview=` | 读取一个 Workspace 文件(见 [Workspace 文件响应](#workspace-文件响应)) |
| GET | `/files/preview-redirect?path=` | 在独立的预览源上打开 HTML 文件:签发签名 token 并以 302 重定向 |
| POST | `/files/stat` | 检查文件是否存在:`{paths}` |
-| PUT | `/files/content?path=` | 上传文件:`{dataBase64}`,最大 14MB |
-| POST | `/files/move` | 移动或重命名一个文件:`{from, to, ifVersion?}` → 204 |
+| PUT | `/files/content?path=` | 整体写入文件:`{dataBase64, ifVersion?}`,最大 14MB → 204,`ETag` 带回写入后的版本 |
+| POST | `/files/create` | 新建空文本文件或文件夹:`{path, kind}`(`file` 或 `dir`)→ 204 |
+| POST | `/files/move` | 移动或重命名一个文件或文件夹:`{from, to, ifVersion?}` → 204 |
| DELETE | `/files/content?path=&ifVersion=` | 删除一个文件 → 204 |
| POST | `/files/reveal?path=` | 在机器自带的文件管理器中显示文件 → 204 |
| GET | `/files/search?q=` | 按条目名搜索整个 Workspace |
| GET | `/scratchpad/:fileName` | 读取 Session 的一个暂存文件,例如输入图片或文件附件 |
- `GET /files/preview-redirect` 支撑**新页面打开**和**文件浏览**面板里的 HTML 渲染视图;见[独立源上的预览](#独立源上的预览)。
-- `POST /files/move` 只对文件生效:目录没有单一的版本标记,保护移动的前置条件无法对目录表达,所以对目录返回 400。`to` 缺失的父目录会自动创建。`from` 不存在时返回 404 `path_not_found`;`ifVersion` 不再匹配时返回 409 `file_changed`(带着标记时源文件却已消失,也算作已变化)。`to` 位置已有内容时返回 409 `target_exists`——目标从未读取过,所以选择拒绝而不是覆盖;移动到文件自身路径返回 400。
+- `PUT /files/content` 在 `ETag` 里带回写入后的版本:同一文件下一次带条件的写入就用这个标记,所以**文件浏览**面板的编辑器保存后可以继续编辑。
+- `POST /files/create` 新建一个空文本文件或一个文件夹,缺失的父目录与写入时一样自动创建。`path` 上已有任何条目(包括符号链接,不会跟随)时返回 409 `target_exists`,一个字节都不写。
+- `POST /files/move` 移动文件或文件夹。`to` 缺失的父目录会自动创建。`from` 不存在时返回 404 `path_not_found`;对文件,`ifVersion` 不再匹配时返回 409 `file_changed`(带着标记时源文件却已消失,也算作已变化)。文件夹没有单一的版本标记,因此整棵移动、不带前置条件:对文件夹带 `ifVersion` 返回 400,把文件夹移入它自身之下也返回 400。`to` 位置已有内容时返回 409 `target_exists`——目标从未读取过,所以选择拒绝而不是覆盖;移动到条目自身路径返回 400。
- `DELETE /files/content` 同样只对文件生效(对目录返回 400)。文件已不存在时返回 404 `path_not_found`;`ifVersion` 不再匹配时返回 409 `file_changed`。这个标记是可选的,不带标记时删除是无条件的,但**文件浏览**面板总是发送它读取时拿到的标记。
- `POST /files/reveal` 在 macOS 和 Windows 上选中文件,在 Linux 桌面上打开文件所在目录。只有桌面 shell 自己的窗口可以调用它。服务器不是由桌面 shell 启动时返回 404 `not_found`;浏览器会话访问桌面模式服务器时返回 403 `desktop_shell_only`:这种会话无法与远程会话区分,而在服务器所在的机器上打开文件夹,对那头的用户毫无用处。路径的限制与读取相同(越界 400,不存在 404 `path_not_found`);502 `reveal_failed` 表示文件管理器未能启动。
- `GET /files/search` 只匹配条目名(不区分大小写的子串;不匹配路径),响应为 `{hits: [{path, kind, sizeBytes, mtime}], truncated}`,每条命中都带有目录列表条目的全部字段。搜索从根目录开始广度优先遍历,所以浅层结果先出现;结果达到上限时,保留的是最相关的命中,而不是最先遍历到的那个目录里的内容。`truncated` 表示遍历因达到上限而停止:命中 200 条,或访问了 20000 个目录条目。`q` 为空或超过 100 个字符时返回 400。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index d0abada6..ac83219a 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2954,7 +2954,11 @@ export interface WorkspaceFilesResponse {
entries: WorkspaceFileEntry[];
}
-/** Write one Workspace file whole (the Upload button, a drop, and the Files panel's editor). */
+/**
+ * Write one Workspace file whole (the Upload button, a drop, and the Files panel's editor). A
+ * write answers 204 with the written file's version in `ETag` — the marker the next conditional
+ * write of the same file carries, so an editor can keep editing after a save.
+ */
export interface FilesWriteRequest {
/** The entire file, base64-encoded (≤14MB decoded). */
dataBase64: string;
@@ -2970,7 +2974,7 @@ export interface FilesWriteRequest {
ifVersion?: string;
}
-/** Move or rename one Workspace file (the Files panel's context menu). */
+/** Move or rename one Workspace file or folder (the Files panel's context menu). */
export interface FilesMoveRequest {
/** Source path, relative to the Workspace root. */
from: string;
@@ -2983,13 +2987,25 @@ export interface FilesMoveRequest {
* has none, because the caller never read it, which is why an occupied destination is
* refused with 409 `target_exists` rather than overwritten.
*
- * A directory `from` is a 400 whatever this field says: a directory carries no single
- * version marker, so the precondition that protects this operation cannot be expressed for
- * one, and silently moving a tree without that protection is worse than refusing to move it.
+ * A directory `from` takes none, and one sent with it is a 400: a directory carries no
+ * single version marker, so no precondition can be stated for it. A folder moves whole and
+ * unconditionally — nothing is lost that way, since whatever the Agent wrote into it meanwhile
+ * moves with it — and is refused only when the destination is occupied or lies inside it.
*/
ifVersion?: string;
}
+/**
+ * Create one empty text file or one folder in a Workspace (the Files panel's New menu). Missing
+ * parent directories are created as a write creates them. Anything already at `path` — a file,
+ * a folder or a link — is refused with 409 `target_exists` and nothing is written.
+ */
+export interface FilesCreateRequest {
+ /** The new entry's path, relative to the Workspace root. */
+ path: string;
+ kind: "file" | "dir";
+}
+
/**
* One Workspace search match. `kind`, `sizeBytes` and `mtime` are named and typed exactly as
* {@link WorkspaceFileEntry} names them: a hit is drawn by the same row renderer as a tree
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index abdf8692..a2be9e06 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -98,7 +98,6 @@ export interface SessionsRouteDeps {
/** Re-validates the session behind an open stream, once per heartbeat. */
auth: Auth;
}
-import { MAX_UPLOAD_BYTES } from "../../services/workspace-files-service.js";
import {
assertAttachmentBudget,
attachFilesToInput,
@@ -129,6 +128,7 @@ import { modelScopeAuthRoutes } from "./modelscope-auth.js";
import { chatDefaultsRoutes } from "./chat-defaults.js";
import { commandPolicyRoutes } from "./command-policy.js";
import { usageRoutes } from "./usage.js";
+import { registerWorkspaceFileRoutes, workspaceFilesRoutes } from "./workspace-files.js";
import { PreviewTokens } from "./preview.js";
import type {
Access,
@@ -1362,101 +1362,10 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
});
// —— Workspace file browsing (Files tab) ——
-
- app.get("/:sessionId/files", async (c) => {
- const row = resolveSession(c);
- const rel = c.req.query("path") ?? "";
- return c.json(await deps.workspaceFiles.list(row.workspace, rel));
- });
-
- app.get("/:sessionId/files/content", async (c) => {
- const row = resolveSession(c);
- const rel = c.req.query("path") ?? "";
- const download = c.req.query("download") === "1";
- // Sandboxed top-level preview ("open in a new tab" for html): the document keeps its REAL
- // content type but carries a CSP sandbox WITHOUT allow-same-origin — it renders and runs
- // fully in an opaque origin, so agent-generated markup cannot reach this origin's cookies
- // or API. The request itself still authenticates (top-level GET sends the Lax cookie).
- const preview = !download && c.req.query("preview") === "1";
- const { data, fileName, contentType, scriptable, version } = await deps.workspaceFiles.read(
- row.workspace,
- rel,
- );
- const disposition = download ? "attachment" : "inline";
- // Same-origin XSS defense: an inline HTML preview is always returned as plain text
- // (Workspace files may be Agent-generated and untrusted); downloads (attachment) keep
- // the real content type, and sandboxed previews keep it under the CSP above. Paired
- // with nosniff to prevent MIME sniffing from undoing this.
- // An SVG is a document AND an image. Downgrading it to text/plain made every <img> in a
- // Markdown preview (and every .svg preview) a broken image, so it keeps its real type —
- // an image never runs the SVG's scripts. What the type does re-open is a DIRECT
- // navigation to this URL, where the browser would render it as a same-origin document:
- // the sandbox CSP closes that (no allow-scripts, no allow-same-origin — opaque origin,
- // no script execution), and CSP sandbox is ignored for a subresource, so the <img> path
- // is unaffected.
- const inertSvg = !download && !preview && scriptable === "svg";
- const effectiveType =
- !download && scriptable === "html" && !preview ? "text/plain; charset=utf-8" : contentType;
- return new Response(new Uint8Array(data), {
- status: 200,
- headers: {
- "Content-Type": effectiveType,
- "Content-Disposition": `${disposition}; filename*=UTF-8''${encodeURIComponent(fileName)}`,
- "X-Content-Type-Options": "nosniff",
- // A Workspace file is whatever the Agent last wrote to that path. Letting a browser
- // cache it by URL is how a re-read after a settled turn paints the previous version.
- "Cache-Control": "no-store",
- // Not a cache validator — no-store above means nothing ever revalidates. It is the
- // version of the bytes in this response, which the Files panel's editor hands back
- // as `ifVersion` on save so the write can refuse to overwrite a newer file.
- ETag: version,
- ...(preview && scriptable
- ? {
- "Content-Security-Policy":
- "sandbox allow-scripts allow-popups allow-modals allow-forms",
- }
- : {}),
- ...(inertSvg ? { "Content-Security-Policy": "sandbox" } : {}),
- },
- });
- });
-
- /**
- * 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);
- });
+ // The operations a directory-addressed panel shares (http/routes/workspace-files.ts), here on
+ // the Session's own Workspace; the preview redirect and the batch existence check below are
+ // the Session's alone.
+ registerWorkspaceFileRoutes(app, "/:sessionId/files", deps, (c) => resolveSession(c).workspace);
// "Open in a new tab" for Workspace HTML: mints a token and redirects to the separate
// preview origin.
@@ -1529,62 +1438,6 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
return c.json({ existing } satisfies FilesStatResponse);
});
- app.put("/:sessionId/files/content", async (c) => {
- const row = resolveSession(c);
- const rel = c.req.query("path") ?? "";
- const body = await readJson(c);
- if (typeof body.dataBase64 !== "string") {
- throw badRequest("dataBase64 must be a base64 string.");
- }
- const data = Buffer.from(body.dataBase64, "base64");
- if (data.length > MAX_UPLOAD_BYTES) {
- throw new HttpError(413, "file_too_large", "Uploaded file exceeds the 14MB limit.");
- }
- // The editor's write precondition (see FilesWriteRequest); absent on an upload, which
- // read no version and so writes unconditionally.
- await deps.workspaceFiles.write(row.workspace, rel, data, optionalString(body, "ifVersion"));
- return c.body(null, 204);
- });
-
- /**
- * Move or rename one Workspace file (the Files panel's context menu). Files only — see
- * FilesMoveRequest for why a directory has no precondition that could protect it — and an
- * occupied destination is refused with 409 `target_exists` rather than overwritten.
- */
- app.post("/:sessionId/files/move", async (c) => {
- const row = resolveSession(c);
- const body = await readJson(c);
- await deps.workspaceFiles.move(
- row.workspace,
- requireString(body, "from"),
- requireString(body, "to"),
- optionalString(body, "ifVersion"),
- );
- return c.body(null, 204);
- });
-
- /**
- * Delete one Workspace file. `ifVersion` is the same write precondition the PUT carries,
- * here as a query parameter: absent, the delete is unconditional; present and stale, it is
- * 409 `file_changed` with the file left alone.
- */
- app.delete("/:sessionId/files/content", async (c) => {
- const row = resolveSession(c);
- const rel = c.req.query("path") ?? "";
- await deps.workspaceFiles.remove(row.workspace, rel, c.req.query("ifVersion"));
- return c.body(null, 204);
- });
-
- /**
- * Search the whole Workspace by entry name. Breadth-first from the root, so a capped result
- * is the shallowest matches rather than an arbitrary prefix of the walk; `truncated` says a
- * cap was reached.
- */
- app.get("/:sessionId/files/search", async (c) => {
- const row = resolveSession(c);
- return c.json(await deps.workspaceFiles.search(row.workspace, c.req.query("q") ?? ""));
- });
-
/**
* What the Session's current model context is made of, and where compaction will fire. Read on
* demand (the chat page's context ring opens its detail panel with it), not streamed: it
@@ -1718,6 +1571,12 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
auth: "user",
order: 260,
},
+ {
+ id: "session-api.workspace-files",
+ prefix: "/api/projects/:projectId/workspace-files",
+ auth: "user",
+ order: 265,
+ },
{
id: "session-api.sessions",
prefix: "/api/sessions",
@@ -1768,6 +1627,7 @@ export class SessionApiRoutes {
@Bind("session-api.vault") vaultRoutes!: Hono<AppEnv>;
@Bind("session-api.agent-sessions") agentSessionsRoutes!: Hono<AppEnv>;
@Bind("session-api.usage") usageRoutes!: Hono<AppEnv>;
+ @Bind("session-api.workspace-files") workspaceFilesRoutes!: Hono<AppEnv>;
@Bind("session-api.sessions") sessionsRoutes!: Hono<AppEnv>;
setup() {
const manager = this.manager as SessionManager;
@@ -1848,6 +1708,12 @@ export class SessionApiRoutes {
this.vaultRoutes = vaultRoutes({ agentConfigService, manager, access });
this.agentSessionsRoutes = agentSessionsRoutes(sessionsDeps);
this.usageRoutes = usageRoutes({ access, usageService: this.usage });
+ this.workspaceFilesRoutes = workspaceFilesRoutes({
+ access,
+ workspaceFiles: this.workspaceFiles,
+ desktopMode: sessionsDeps.desktopMode,
+ fileReveal: this.fileReveal,
+ });
this.sessionsRoutes = sessionsRoutes(sessionsDeps);
}
}
diff --git a/packages/server/src/http/routes/workspace-files.ts b/packages/server/src/http/routes/workspace-files.ts
new file mode 100644
index 00000000..d1594261
--- /dev/null
+++ b/packages/server/src/http/routes/workspace-files.ts
@@ -0,0 +1,264 @@
+/**
+ * The Files panel's operations over one Workspace directory, registered for the two ways a
+ * caller names that directory:
+ *
+ * - a Session: `/api/sessions/:sessionId/files…`, on the Session's own Workspace (the route
+ * group in sessions.ts, which also keeps the two Session-only routes, the preview redirect
+ * and the batch existence check);
+ * - the directory itself: `/api/projects/:projectId/workspace-files…?workspace=<absolute
+ * path>`, for the places that have no Session yet — the new-chat draft's chosen Workspace
+ * and a sidebar Workspace group's "Browse files".
+ *
+ * Both run the same handlers over the same service, so the confinement of every path, the
+ * inline hardening of untrusted content and the write preconditions cannot differ between
+ * them; only where the Workspace comes from does. Addressing by directory asks for nothing a
+ * caller could not already do: it takes Project access — the same access that lets the caller
+ * create a Session in that directory and read and write it through the Session's routes — and
+ * a directory that exists, checked as a Session's Workspace is checked when one is created.
+ * The preview origin's tokens name a Session, so directory addressing has no preview redirect:
+ * an HTML file there previews through the same-origin sandbox (`preview=1`).
+ */
+import path from "node:path";
+import { Hono } from "hono";
+import type { Context } from "hono";
+import type { AppEnv } from "../../auth/middleware.js";
+import type { Access } from "../../mechanisms/projects.js";
+import type { FileReveal, WorkspaceFiles } from "../../mechanisms/workspace.js";
+import { MAX_UPLOAD_BYTES } from "../../services/workspace-files-service.js";
+import { assertWorkspaceAllowed } from "../../services/workspace-guard.js";
+import { HttpError } from "../errors.js";
+import {
+ badRequest,
+ optionalString,
+ readJson,
+ requireEnum,
+ requireString,
+ requireValidId,
+} from "../validate.js";
+
+/** What the file handlers reach. */
+export interface WorkspaceFileRouteDeps {
+ 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;
+}
+
+/** Resolves the Workspace a request is about, after authorizing the caller for it. */
+export type WorkspaceResolver = (c: Context<AppEnv>) => string | Promise<string>;
+
+/**
+ * Registers the file handlers under `base` ("" or "/:sessionId/files"), reading the Workspace
+ * through `resolve` on every request.
+ */
+export function registerWorkspaceFileRoutes(
+ app: Hono<AppEnv>,
+ base: string,
+ deps: WorkspaceFileRouteDeps,
+ resolve: WorkspaceResolver,
+): void {
+ const at = (suffix: string): string => `${base}${suffix}` || "/";
+
+ app.get(at(""), async (c) => {
+ const workspace = await resolve(c);
+ return c.json(await deps.workspaceFiles.list(workspace, c.req.query("path") ?? ""));
+ });
+
+ app.get(at("/content"), async (c) => {
+ const workspace = await resolve(c);
+ const rel = c.req.query("path") ?? "";
+ const download = c.req.query("download") === "1";
+ // Sandboxed top-level preview ("open in a new tab" for html): the document keeps its REAL
+ // content type but carries a CSP sandbox WITHOUT allow-same-origin — it renders and runs
+ // fully in an opaque origin, so agent-generated markup cannot reach this origin's cookies
+ // or API. The request itself still authenticates (top-level GET sends the Lax cookie).
+ const preview = !download && c.req.query("preview") === "1";
+ const { data, fileName, contentType, scriptable, version } = await deps.workspaceFiles.read(
+ workspace,
+ rel,
+ );
+ const disposition = download ? "attachment" : "inline";
+ // Same-origin XSS defense: an inline HTML preview is always returned as plain text
+ // (Workspace files may be Agent-generated and untrusted); downloads (attachment) keep
+ // the real content type, and sandboxed previews keep it under the CSP above. Paired
+ // with nosniff to prevent MIME sniffing from undoing this.
+ // An SVG is a document AND an image. Downgrading it to text/plain made every <img> in a
+ // Markdown preview (and every .svg preview) a broken image, so it keeps its real type —
+ // an image never runs the SVG's scripts. What the type does re-open is a DIRECT
+ // navigation to this URL, where the browser would render it as a same-origin document:
+ // the sandbox CSP closes that (no allow-scripts, no allow-same-origin — opaque origin,
+ // no script execution), and CSP sandbox is ignored for a subresource, so the <img> path
+ // is unaffected.
+ const inertSvg = !download && !preview && scriptable === "svg";
+ const effectiveType =
+ !download && scriptable === "html" && !preview ? "text/plain; charset=utf-8" : contentType;
+ return new Response(new Uint8Array(data), {
+ status: 200,
+ headers: {
+ "Content-Type": effectiveType,
+ "Content-Disposition": `${disposition}; filename*=UTF-8''${encodeURIComponent(fileName)}`,
+ "X-Content-Type-Options": "nosniff",
+ // A Workspace file is whatever the Agent last wrote to that path. Letting a browser
+ // cache it by URL is how a re-read after a settled turn paints the previous version.
+ "Cache-Control": "no-store",
+ // Not a cache validator — no-store above means nothing ever revalidates. It is the
+ // version of the bytes in this response, which the Files panel's editor hands back
+ // as `ifVersion` on save so the write can refuse to overwrite a newer file.
+ ETag: version,
+ ...(preview && scriptable
+ ? {
+ "Content-Security-Policy":
+ "sandbox allow-scripts allow-popups allow-modals allow-forms",
+ }
+ : {}),
+ ...(inertSvg ? { "Content-Security-Policy": "sandbox" } : {}),
+ },
+ });
+ });
+
+ /**
+ * Writes one file whole. The editor's write precondition rides in `ifVersion` (see
+ * FilesWriteRequest); an upload reads no version and so writes unconditionally. The version
+ * the write produced comes back in `ETag`, which is what lets the editor keep editing after
+ * a save: it is the marker the next save of the same file carries.
+ */
+ app.put(at("/content"), async (c) => {
+ const workspace = await resolve(c);
+ const rel = c.req.query("path") ?? "";
+ const body = await readJson(c);
+ if (typeof body.dataBase64 !== "string") {
+ throw badRequest("dataBase64 must be a base64 string.");
+ }
+ const data = Buffer.from(body.dataBase64, "base64");
+ if (data.length > MAX_UPLOAD_BYTES) {
+ throw new HttpError(413, "file_too_large", "Uploaded file exceeds the 14MB limit.");
+ }
+ const version = await deps.workspaceFiles.write(
+ workspace,
+ rel,
+ data,
+ optionalString(body, "ifVersion"),
+ );
+ return c.body(null, 204, { ETag: version });
+ });
+
+ /**
+ * Delete one Workspace file. `ifVersion` is the same write precondition the PUT carries,
+ * here as a query parameter: absent, the delete is unconditional; present and stale, it is
+ * 409 `file_changed` with the file left alone.
+ */
+ app.delete(at("/content"), async (c) => {
+ const workspace = await resolve(c);
+ await deps.workspaceFiles.remove(
+ workspace,
+ c.req.query("path") ?? "",
+ c.req.query("ifVersion"),
+ );
+ return c.body(null, 204);
+ });
+
+ /**
+ * Create one empty text file or one folder (the Files panel's New menu). Anything already at
+ * the path is 409 `target_exists` with nothing written — see FilesCreateRequest.
+ */
+ app.post(at("/create"), async (c) => {
+ const workspace = await resolve(c);
+ const body = await readJson(c);
+ await deps.workspaceFiles.create(
+ workspace,
+ requireString(body, "path"),
+ requireEnum(body, "kind", ["file", "dir"] as const),
+ );
+ return c.body(null, 204);
+ });
+
+ /**
+ * Move or rename one file or folder (the Files panel's context menu). A file carries its
+ * version precondition, a folder none; an occupied destination is refused with 409
+ * `target_exists` rather than overwritten — see FilesMoveRequest.
+ */
+ app.post(at("/move"), async (c) => {
+ const workspace = await resolve(c);
+ const body = await readJson(c);
+ await deps.workspaceFiles.move(
+ workspace,
+ requireString(body, "from"),
+ requireString(body, "to"),
+ optionalString(body, "ifVersion"),
+ );
+ return c.body(null, 204);
+ });
+
+ /**
+ * Search the whole Workspace by entry name. Breadth-first from the root, so a capped result
+ * is the shallowest matches rather than an arbitrary prefix of the walk; `truncated` says a
+ * cap was reached.
+ */
+ app.get(at("/search"), async (c) => {
+ const workspace = await resolve(c);
+ return c.json(await deps.workspaceFiles.search(workspace, c.req.query("q") ?? ""));
+ });
+
+ /**
+ * 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(at("/reveal"), async (c) => {
+ const workspace = await resolve(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(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);
+ });
+}
+
+/** What the directory-addressed group reaches beyond the handlers. */
+export interface WorkspaceFilesRouteDeps extends WorkspaceFileRouteDeps {
+ access: Access;
+}
+
+/**
+ * `/api/projects/:projectId/workspace-files…?workspace=`: the file handlers over a directory
+ * named by its absolute path, for a caller with access to the Project. The directory is
+ * realpath'd and must exist (400 `workspace_not_found`), exactly as a Session's Workspace is
+ * checked when a Session is created in it; everything below it is confined as for a Session.
+ */
+export function workspaceFilesRoutes(deps: WorkspaceFilesRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+ registerWorkspaceFileRoutes(app, "", deps, async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
+ const workspace = c.req.query("workspace")?.trim() ?? "";
+ if (!path.isAbsolute(workspace)) {
+ throw new HttpError(400, "workspace_not_found", "workspace must be an absolute path.");
+ }
+ return await assertWorkspaceAllowed({ workspace });
+ });
+ return app;
+}
diff --git a/packages/server/src/mechanisms/workspace.ts b/packages/server/src/mechanisms/workspace.ts
index f8955e26..dd4b61ed 100644
--- a/packages/server/src/mechanisms/workspace.ts
+++ b/packages/server/src/mechanisms/workspace.ts
@@ -25,7 +25,8 @@ export abstract class WorkspaceFiles {
rel: string,
data: Buffer<ArrayBufferLike>,
ifVersion?: string,
- ): Promise<void>;
+ ): Promise<string>;
+ abstract create(workspace: string, rel: string, kind: "file" | "dir"): Promise<void>;
abstract move(workspace: string, from: string, to: string, ifVersion?: string): Promise<void>;
abstract remove(workspace: string, rel: string, ifVersion?: string): Promise<void>;
abstract search(workspace: string, q: string): Promise<WorkspaceSearchResponse>;
diff --git a/packages/server/src/services/workspace-files-service.ts b/packages/server/src/services/workspace-files-service.ts
index 0574d6a4..abde5be1 100644
--- a/packages/server/src/services/workspace-files-service.ts
+++ b/packages/server/src/services/workspace-files-service.ts
@@ -1,8 +1,8 @@
/**
* Workspace file browsing: list directory / read file (preview & download) / write file
- * (upload) / move, delete and search. Security: a relative path, once resolved, must stay
- * inside the Workspace — a logical prefix check plus a realpath check against the nearest
- * existing ancestor (guards against `..` and symlink escapes).
+ * (upload) / create a file or folder / move, delete and search. Security: a relative path, once
+ * resolved, must stay inside the Workspace — a logical prefix check plus a realpath check
+ * against the nearest existing ancestor (guards against `..` and symlink escapes).
*/
import fs from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
@@ -102,15 +102,25 @@ function fileChanged(): HttpError {
}
/**
- * A move's destination is occupied. Unlike the source, the destination has no precondition —
- * the caller never read it, so there is no marker it could have carried — which makes an
- * overwrite here a silent destruction of a file nobody looked at. Refuse instead.
+ * The path a move or a create would write is occupied. It has no precondition — the caller
+ * never read it, so there is no marker it could have carried — which makes an overwrite here a
+ * silent destruction of something nobody looked at. Refuse instead.
*/
-function targetExists(): HttpError {
+function targetExists(action: "move" | "create"): HttpError {
return new HttpError(
409,
"target_exists",
- "Something already exists at the destination; nothing was moved.",
+ action === "move"
+ ? "Something already exists at the destination; nothing was moved."
+ : "Something already exists at this path; nothing was created.",
+ );
+}
+
+/** Whether anything at all is at `p`, a dangling link included (lstat, not stat). */
+async function occupied(p: string): Promise<boolean> {
+ return fs.lstat(p).then(
+ () => true,
+ () => false,
);
}
@@ -492,8 +502,13 @@ export class WorkspaceFilesService implements WorkspaceFiles {
* changed". With a marker the file must already exist, so O_CREAT is left out — a
* missing file is a change like any other (ENOENT → the same 409), and a refused write
* must not leave an empty file behind.
+ *
+ * Resolves to the version the write produced, read as soon as the bytes are down: the marker
+ * the caller's next conditional write of this file carries. Reading it back with a second
+ * request instead would adopt a rewrite landing between the two as the caller's own, and the
+ * next save would silently overwrite it.
*/
- async write(workspace: string, rel: string, data: Buffer, ifVersion?: string): Promise<void> {
+ async write(workspace: string, rel: string, data: Buffer, ifVersion?: string): Promise<string> {
if (rel === "" || rel.endsWith("/")) throw badRequest("path must be a file path.");
if (data.length > MAX_UPLOAD_BYTES) {
throw new HttpError(413, "file_too_large", "Uploaded file exceeds the 14MB limit.");
@@ -518,6 +533,7 @@ export class WorkspaceFilesService implements WorkspaceFiles {
if (code === "EISDIR") throw badRequest("path is a directory.");
throw err;
}
+ let written: Stats;
try {
if (conditional) {
if (fileVersion(await handle.stat()) !== ifVersion) throw fileChanged();
@@ -526,31 +542,85 @@ export class WorkspaceFilesService implements WorkspaceFiles {
await handle.truncate(0);
}
await handle.writeFile(data);
+ written = await handle.stat();
} finally {
await handle.close();
}
+ // Windows may stamp a write's time when its handle closes rather than at the write, so there
+ // the version is read back once the handle is closed — the one a later read reports. lstat:
+ // the path is not followed anywhere. Elsewhere the open handle's own stat is exact, with no
+ // room for another writer between the bytes and the read.
+ return fileVersion(process.platform === "win32" ? await fs.lstat(file) : written);
}
/**
- * Move or rename one Workspace file.
+ * Create one empty file or one folder at `rel` (the Files panel's New menu), refusing anything
+ * already there.
*
- * **Files only** — a directory `from` is a 400. A directory has no single version marker, so
- * the precondition that protects this operation cannot be expressed for one, and moving a
- * whole tree with no precondition at all is worse than refusing to move it.
+ * Missing parents are created the way a write creates them (resolveWriteParent), so a
+ * symlinked ancestor pointing out of the Workspace is caught by the write path's own checks.
+ * The entry itself is made by the primitive that fails rather than replaces: `O_CREAT |
+ * O_EXCL` for a file — which on POSIX also refuses a symlink at the final segment instead of
+ * following it (Windows gets an lstat first, below) — and a non-recursive `mkdir` for a folder.
+ * Either way an occupied path is 409 `target_exists` with nothing written, and on POSIX there
+ * is no check-then-act window to lose to the Agent writing the same path.
+ */
+ async create(workspace: string, rel: string, kind: "file" | "dir"): Promise<void> {
+ if (rel === "" || rel.endsWith("/")) throw badRequest("path must name the new entry.");
+ const { dir, name } = await this.resolveWriteParent(workspace, rel);
+ const target = path.join(dir, name);
+ // Windows has no O_NOFOLLOW, and there O_EXCL alone does not refuse a final-segment link: the
+ // open follows it and creates whatever it points at, possibly outside the Workspace. So a link
+ // at the path is refused by lstat first, as assertNotSymlink refuses one for a write (best
+ // effort, the same window); POSIX keeps the atomic guarantee of the flags below.
+ if (process.platform === "win32" && (await occupied(target))) throw targetExists("create");
+ try {
+ if (kind === "dir") {
+ await fs.mkdir(target);
+ } else {
+ const handle = await fs.open(
+ target,
+ fsc.O_WRONLY | fsc.O_CREAT | fsc.O_EXCL | (fsc.O_NOFOLLOW ?? 0),
+ 0o644,
+ );
+ await handle.close();
+ }
+ } catch (err) {
+ // Platforms word an occupied path differently for a directory in the way (EISDIR, or a
+ // bare access error on Windows), so anything that is there answers the same.
+ if ((err as NodeJS.ErrnoException).code === "EEXIST" || (await occupied(target))) {
+ throw targetExists("create");
+ }
+ throw err;
+ }
+ }
+
+ /**
+ * Move or rename one Workspace file or folder.
*
- * The source is resolved as a mutable entry (canonical parent, O_NOFOLLOW on the final
- * segment, version marker read off the open handle); the destination is resolved as a write,
- * so its parent is created when missing under the same checks an upload runs. An occupied
+ * A file is resolved as a mutable entry (canonical parent, O_NOFOLLOW on the final segment,
+ * version marker read off the open handle); the destination is resolved as a write, so its
+ * parent is created when missing under the same checks an upload runs. An occupied
* destination is a 409 rather than an overwrite — see {@link targetExists} — and a move onto
* the file's own path is a 400 rather than a success that did nothing.
+ *
+ * A folder moves whole, and without a precondition: it has no single version marker, and
+ * one sent for it is a 400 rather than a check that silently never ran. See
+ * {@link moveFolder} for the two destinations it refuses.
*/
async move(workspace: string, from: string, to: string, ifVersion?: string): Promise<void> {
- if (from === "" || from.endsWith("/")) throw badRequest("from must be a file path.");
- if (to === "" || to.endsWith("/")) throw badRequest("to must be a file path.");
+ if (from === "" || from.endsWith("/")) throw badRequest("from must name a file or folder.");
+ if (to === "" || to.endsWith("/")) throw badRequest("to must name a file or folder.");
const conditional = ifVersion !== undefined;
const source = await this.resolveMutableEntry(workspace, from);
if (source === null) throw this.vanished(conditional);
const file = path.join(source.dir, source.name);
+ // lstat, not stat: a link to a folder is a link, which the file path below refuses.
+ if ((await fs.lstat(file).catch(() => null))?.isDirectory() === true) {
+ if (conditional) throw badRequest("ifVersion does not apply to a folder.");
+ await this.moveFolder(workspace, file, to);
+ return;
+ }
await this.assertFileAndVersion(file, ifVersion);
const { dir, name } = await this.resolveWriteParent(workspace, to);
@@ -570,7 +640,7 @@ export class WorkspaceFilesService implements WorkspaceFiles {
return;
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
- if (code === "EEXIST") throw targetExists();
+ if (code === "EEXIST") throw targetExists("move");
if (code === "EXDEV") {
// The two canonical parents are on different filesystems (a bind-mounted subdirectory,
// say), which neither link nor rename can cross. Copy, then drop the original.
@@ -579,7 +649,7 @@ export class WorkspaceFilesService implements WorkspaceFiles {
try {
await fs.copyFile(file, dest, fsc.COPYFILE_EXCL);
} catch (copyErr) {
- if ((copyErr as NodeJS.ErrnoException).code === "EEXIST") throw targetExists();
+ if ((copyErr as NodeJS.ErrnoException).code === "EEXIST") throw targetExists("move");
throw copyErr;
}
await fs.unlink(file);
@@ -594,14 +664,63 @@ export class WorkspaceFilesService implements WorkspaceFiles {
throw err;
}
}
- const occupied = await fs.lstat(dest).then(
- () => true,
- () => false,
- );
- if (occupied) throw targetExists();
+ if (await occupied(dest)) throw targetExists("move");
await fs.rename(file, dest);
}
+ /**
+ * The folder half of {@link move}: the whole tree by one rename, refusing two destinations.
+ *
+ * One inside the folder itself. That is decided on the canonical path of the destination's
+ * nearest existing ancestor, and decided BEFORE any missing parent of the destination is
+ * created — a refused move leaves no half-made directories behind.
+ *
+ * And an occupied one. `rename` replaces an empty directory silently, so the destination is
+ * lstat'ed first; the window left between the two can at most swallow an empty directory
+ * created inside it, and nothing with content is ever replaced (a non-empty directory fails
+ * the rename). Two filesystems cannot be crossed by a rename, and copying a tree across is
+ * not something to do behind a menu row, so that is refused too.
+ */
+ private async moveFolder(workspace: string, folder: string, to: string): Promise<void> {
+ const target = this.lexicalTarget(path.resolve(workspace), to);
+ let probe = path.dirname(target);
+ for (;;) {
+ let anchor: string;
+ try {
+ anchor = await fs.realpath(probe);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
+ const up = path.dirname(probe);
+ if (up === probe) break;
+ probe = up;
+ continue;
+ }
+ if (this.isInside(anchor, folder)) throw badRequest("A folder cannot move into itself.");
+ break;
+ }
+ const { dir, name } = await this.resolveWriteParent(workspace, to);
+ const dest = path.join(dir, name);
+ if (dest === folder) throw badRequest("to must differ from from.");
+ if (await occupied(dest)) throw targetExists("move");
+ try {
+ await fs.rename(folder, dest);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === "EEXIST" || code === "ENOTEMPTY" || code === "ENOTDIR") {
+ throw targetExists("move");
+ }
+ if (code === "EINVAL") throw badRequest("A folder cannot move into itself.");
+ if (code === "EXDEV") {
+ throw new HttpError(
+ 409,
+ "cross_device",
+ "The folder and its destination are on different filesystems; nothing was moved.",
+ );
+ }
+ throw err;
+ }
+ }
+
/**
* Delete one Workspace file. Files only, for the same reason {@link move} is: a directory
* carries no version marker, so nothing can protect a recursive delete from removing work
diff --git a/packages/server/test/workspace-files-create-move.test.ts b/packages/server/test/workspace-files-create-move.test.ts
new file mode 100644
index 00000000..729114cf
--- /dev/null
+++ b/packages/server/test/workspace-files-create-move.test.ts
@@ -0,0 +1,286 @@
+/**
+ * New files and folders, folder moves, the version a save hands back, and the Files panel's
+ * directory-addressed routes.
+ *
+ * Over a Session (`/api/sessions/:sessionId/files…`):
+ * - Creating a folder makes it; creating it again is refused with 409 target_exists and nothing
+ * is written.
+ * - Creating a text file makes it empty; a name already taken — by a file, a folder or a dangling
+ * link — is refused, and whatever was there is left untouched.
+ * - A new path's missing parents are made; a path that leaves the Workspace (`..`, or through a
+ * symlinked folder pointing out) creates nothing anywhere.
+ * - Renaming a folder moves everything under it; an occupied destination is refused with nothing
+ * moved; a folder cannot move into itself, and no half-made directory is left behind; a
+ * version marker sent for a folder is refused.
+ * - A save answers with the version it wrote: a second save carrying it lands, and one carrying
+ * it after the Agent rewrote the file is refused with the Agent's text kept.
+ *
+ * By directory (`/api/projects/:projectId/workspace-files…?workspace=`):
+ * - A Project member lists, reads, creates, writes, moves and searches a directory no Session
+ * was ever created in; paths stay confined to it, and inline HTML is still served as text.
+ * - An outsider to the Project gets 404 with nothing touched; a relative or missing directory is
+ * 400 workspace_not_found.
+ *
+ * One app for the file; every case works in a Workspace directory of its own.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import type {
+ ProjectCreateResponse,
+ SessionCreateResponse,
+ WorkspaceFilesResponse,
+ WorkspaceSearchResponse,
+} from "../src/api/types.js";
+import {
+ apiClient,
+ canCreateSymlink,
+ createTestApp,
+ makeTempRoot,
+ provisionUser,
+} from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const itWithSymlinks = it.skipIf(!canCreateSymlink());
+
+let t: TestApp;
+let owner: ReturnType<typeof apiClient>;
+let outsider: ReturnType<typeof apiClient>;
+let projectId: string;
+
+beforeAll(async () => {
+ t = await createTestApp();
+ owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);
+ outsider = apiClient(t.app, (await provisionUser(t.app, "outsider")).cookie);
+ const created = (await (
+ await owner.post("/api/projects", { projectId: "owner-folders", name: "project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ await owner.put(`/api/projects/${projectId}/models`, {
+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],
+ });
+});
+afterAll(async () => {
+ await t.cleanup();
+});
+
+/** A Workspace directory of the case's own, holding `a.txt` and `docs/guide/intro.md`. */
+let workspace: string;
+let outside: string;
+beforeEach(async () => {
+ workspace = await makeTempRoot();
+ outside = await makeTempRoot();
+ await fs.mkdir(path.join(workspace, "docs", "guide"), { recursive: true });
+ await fs.writeFile(path.join(workspace, "a.txt"), "A");
+ await fs.writeFile(path.join(workspace, "docs", "guide", "intro.md"), "# Intro");
+});
+afterEach(async () => {
+ await fs.rm(workspace, { recursive: true, force: true });
+ await fs.rm(outside, { recursive: true, force: true });
+});
+
+const exists = (p: string): Promise<boolean> =>
+ fs.lstat(p).then(
+ () => true,
+ () => false,
+ );
+
+const errorCode = async (res: Response): Promise<string> =>
+ ((await res.json()) as { error: { code: string } }).error.code;
+
+describe("over a Session", () => {
+ let base: string;
+ beforeEach(async () => {
+ const sess = (await (
+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, { workspace })
+ ).json()) as SessionCreateResponse;
+ base = `/api/sessions/${sess.session.sessionId}/files`;
+ });
+
+ it("creating a folder makes it, and creating it again is refused with nothing written", async () => {
+ const made = await owner.post(`${base}/create`, { path: "docs/drafts", kind: "dir" });
+ expect(made.status).toBe(204);
+ expect((await fs.stat(path.join(workspace, "docs", "drafts"))).isDirectory()).toBe(true);
+ await fs.writeFile(path.join(workspace, "docs", "drafts", "keep.txt"), "kept");
+
+ const again = await owner.post(`${base}/create`, { path: "docs/drafts", kind: "dir" });
+ expect(again.status).toBe(409);
+ expect(await errorCode(again)).toBe("target_exists");
+ expect(await fs.readFile(path.join(workspace, "docs", "drafts", "keep.txt"), "utf8")).toBe(
+ "kept",
+ );
+ });
+
+ it("creating a text file makes it empty, and a taken name is refused with what was there untouched", async () => {
+ const made = await owner.post(`${base}/create`, { path: "notes/untitled.txt", kind: "file" });
+ expect(made.status).toBe(204);
+ expect(await fs.readFile(path.join(workspace, "notes", "untitled.txt"), "utf8")).toBe("");
+
+ const overFile = await owner.post(`${base}/create`, { path: "a.txt", kind: "file" });
+ expect(overFile.status).toBe(409);
+ expect(await errorCode(overFile)).toBe("target_exists");
+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("A");
+
+ const overFolder = await owner.post(`${base}/create`, { path: "docs", kind: "file" });
+ expect(overFolder.status).toBe(409);
+ expect((await fs.stat(path.join(workspace, "docs"))).isDirectory()).toBe(true);
+
+ const fileOverFile = await owner.post(`${base}/create`, { path: "a.txt", kind: "dir" });
+ expect(fileOverFile.status).toBe(409);
+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("A");
+ });
+
+ itWithSymlinks("a dangling link at the path counts as taken and is not followed", async () => {
+ const target = path.join(outside, "planted.txt");
+ await fs.symlink(target, path.join(workspace, "link.txt"));
+ const res = await owner.post(`${base}/create`, { path: "link.txt", kind: "file" });
+ expect(res.status).toBe(409);
+ expect(await exists(target)).toBe(false);
+ });
+
+ it("a path out of the Workspace creates nothing anywhere", async () => {
+ const escape = `../${path.basename(outside)}/evil`;
+ expect((await owner.post(`${base}/create`, { path: escape, kind: "dir" })).status).toBe(400);
+ expect((await owner.post(`${base}/create`, { path: escape, kind: "file" })).status).toBe(400);
+ expect(await exists(path.join(outside, "evil"))).toBe(false);
+ expect((await owner.post(`${base}/create`, { path: "", kind: "dir" })).status).toBe(400);
+ expect((await owner.post(`${base}/create`, { path: "x", kind: "link" })).status).toBe(400);
+ });
+
+ itWithSymlinks("a symlinked folder pointing out cannot be created through", async () => {
+ await fs.symlink(outside, path.join(workspace, "out"));
+ expect((await owner.post(`${base}/create`, { path: "out/new", kind: "dir" })).status).toBe(400);
+ expect(
+ (await owner.post(`${base}/create`, { path: "out/deep/new.txt", kind: "file" })).status,
+ ).toBe(400);
+ expect(await fs.readdir(outside)).toEqual([]);
+ });
+
+ it("renaming a folder moves everything under it, and the old path is gone", async () => {
+ const res = await owner.post(`${base}/move`, { from: "docs", to: "handbook/docs-2026" });
+ expect(res.status).toBe(204);
+ expect(
+ await fs.readFile(path.join(workspace, "handbook", "docs-2026", "guide", "intro.md"), "utf8"),
+ ).toBe("# Intro");
+ expect(await exists(path.join(workspace, "docs"))).toBe(false);
+ });
+
+ it("a folder is not moved onto an occupied destination, into itself, or with a version marker", async () => {
+ await fs.mkdir(path.join(workspace, "taken"));
+ const occupied = await owner.post(`${base}/move`, { from: "docs", to: "taken" });
+ expect(occupied.status).toBe(409);
+ expect(await errorCode(occupied)).toBe("target_exists");
+ const ontoFile = await owner.post(`${base}/move`, { from: "docs", to: "a.txt" });
+ expect(ontoFile.status).toBe(409);
+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("A");
+
+ const intoItself = await owner.post(`${base}/move`, {
+ from: "docs",
+ to: "docs/guide/new/docs",
+ });
+ expect(intoItself.status).toBe(400);
+ // Refused before any missing parent of the destination was made.
+ expect(await exists(path.join(workspace, "docs", "guide", "new"))).toBe(false);
+
+ const marked = await owner.post(`${base}/move`, {
+ from: "docs",
+ to: "d2",
+ ifVersion: 'W/"1-1"',
+ });
+ expect(marked.status).toBe(400);
+ // Every refusal left the tree where it was.
+ expect(await fs.readFile(path.join(workspace, "docs", "guide", "intro.md"), "utf8")).toBe(
+ "# Intro",
+ );
+ });
+
+ it("a save answers with the version it wrote, which the next save carries until the Agent rewrites the file", async () => {
+ const url = `${base}/content?path=a.txt`;
+ const read = (await owner.get(url)).headers.get("etag")!;
+ const first = await owner.put(url, {
+ dataBase64: Buffer.from("first").toString("base64"),
+ ifVersion: read,
+ });
+ expect(first.status).toBe(204);
+ const written = first.headers.get("etag")!;
+ expect(written).toBe((await owner.get(url)).headers.get("etag"));
+
+ const second = await owner.put(url, {
+ dataBase64: Buffer.from("second, longer").toString("base64"),
+ ifVersion: written,
+ });
+ expect(second.status).toBe(204);
+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("second, longer");
+
+ await fs.writeFile(path.join(workspace, "a.txt"), "the agent's text");
+ const stale = await owner.put(url, {
+ dataBase64: Buffer.from("third").toString("base64"),
+ ifVersion: second.headers.get("etag")!,
+ });
+ expect(stale.status).toBe(409);
+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("the agent's text");
+ });
+});
+
+describe("by directory", () => {
+ const at = (suffix: string, query: string): string =>
+ `/api/projects/${projectId}/workspace-files${suffix}?workspace=${encodeURIComponent(workspace)}${query}`;
+
+ it("a member browses, creates, writes, moves and searches a directory no Session was created in", async () => {
+ const listing = (await (
+ await owner.get(at("", "&path=docs"))
+ ).json()) as WorkspaceFilesResponse;
+ expect(listing.entries.map((e) => `${e.kind}:${e.name}`)).toEqual(["dir:guide"]);
+
+ const read = await owner.get(at("/content", "&path=a.txt"));
+ expect(await read.text()).toBe("A");
+
+ expect((await owner.post(at("/create", ""), { path: "src", kind: "dir" })).status).toBe(204);
+ expect(
+ (await owner.post(at("/create", ""), { path: "src/untitled.txt", kind: "file" })).status,
+ ).toBe(204);
+ const empty = await owner.get(at("/content", "&path=src/untitled.txt"));
+ expect(await empty.text()).toBe("");
+ const written = await owner.put(at("/content", "&path=src/untitled.txt"), {
+ dataBase64: Buffer.from("hello").toString("base64"),
+ ifVersion: empty.headers.get("etag")!,
+ });
+ expect(written.status).toBe(204);
+ expect(await fs.readFile(path.join(workspace, "src", "untitled.txt"), "utf8")).toBe("hello");
+
+ expect((await owner.post(at("/move", ""), { from: "src", to: "lib" })).status).toBe(204);
+ expect(await fs.readFile(path.join(workspace, "lib", "untitled.txt"), "utf8")).toBe("hello");
+
+ const search = (await (
+ await owner.get(at("/search", "&q=intro"))
+ ).json()) as WorkspaceSearchResponse;
+ expect(search.hits.map((h) => h.path)).toEqual(["docs/guide/intro.md"]);
+ });
+
+ it("paths stay inside the named directory, and inline HTML is still served as text", async () => {
+ await fs.writeFile(path.join(outside, "secret.txt"), "secret");
+ const escape = `&path=${encodeURIComponent(`../${path.basename(outside)}/secret.txt`)}`;
+ expect((await owner.get(at("/content", escape))).status).toBe(400);
+
+ await fs.writeFile(path.join(workspace, "page.html"), "<script>1</script>");
+ const html = await owner.get(at("/content", "&path=page.html"));
+ expect(html.headers.get("content-type")).toBe("text/plain; charset=utf-8");
+ });
+
+ it("an outsider gets 404 and touches nothing; a relative or missing directory is refused", async () => {
+ const res = await outsider.post(at("/create", ""), { path: "intruder", kind: "dir" });
+ expect(res.status).toBe(404);
+ expect(await exists(path.join(workspace, "intruder"))).toBe(false);
+ expect((await outsider.get(at("", ""))).status).toBe(404);
+
+ const relative = await owner.get(`/api/projects/${projectId}/workspace-files?workspace=docs`);
+ expect(relative.status).toBe(400);
+ expect(await errorCode(relative)).toBe("workspace_not_found");
+ const missing = await owner.get(
+ `/api/projects/${projectId}/workspace-files?workspace=${encodeURIComponent(path.join(workspace, "nope"))}`,
+ );
+ expect(missing.status).toBe(400);
+ expect(await errorCode(missing)).toBe("workspace_not_found");
+ });
+});
diff --git a/packages/server/test/workspace-files.test.ts b/packages/server/test/workspace-files.test.ts
index 33f3da9f..3a3314a5 100644
--- a/packages/server/test/workspace-files.test.ts
+++ b/packages/server/test/workspace-files.test.ts
@@ -271,9 +271,11 @@ describe("workspace-files-service", () => {
expect.objectContaining({ status: 409, code: "file_changed" }),
);
- // A directory is refused outright: it carries no single version marker, so no
- // precondition could protect the tree under it.
- await expect(svc.move(ws, "sub", "sub2")).rejects.toMatchObject({ status: 400 });
+ // A directory carries no single version marker, so a marker sent for one is refused
+ // rather than taken as a check that never ran.
+ await expect(svc.move(ws, "sub", "sub2", fresh.version)).rejects.toMatchObject({
+ status: 400,
+ });
expect((await fs.stat(path.join(ws, "sub"))).isDirectory()).toBe(true);
expect(await fs.stat(path.join(ws, "sub2")).catch(() => null)).toBeNull();
});
@@ -650,7 +652,7 @@ describe("files/move, files/search and the files/content delete", () => {
({ sessionId, workspace } = await sessionWithFiles());
});
- it("files/move: 204 and the file is where it was sent; an occupied destination is 409 target_exists; a directory is a 400", async () => {
+ it("files/move: 204 and the file is where it was sent; an occupied destination is 409 target_exists", async () => {
const url = `/api/sessions/${sessionId}/files/move`;
const moved = await owner.post(url, { from: "a.txt", to: "archive/notes/a.txt" });
expect(moved.status).toBe(204);
@@ -670,8 +672,6 @@ describe("files/move, files/search and the files/content delete", () => {
"path_not_found",
);
- // A directory carries no version marker, so no precondition could protect the move.
- expect((await owner.post(url, { from: "sub", to: "sub2" })).status).toBe(400);
// A missing or non-string field is a 400 before anything touches the filesystem.
expect((await owner.post(url, { from: "a.txt" })).status).toBe(400);
expect((await owner.post(url, { from: "a.txt", to: "b.txt", ifVersion: 7 })).status).toBe(400);
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 7e1e7bf3..e8f3ffcb 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -1381,14 +1381,19 @@ router
const normalizePath = (path: string) => path.replace(/^\.?\/+/, "").replace(/\/+$/, "");
-router
- .get("/api/sessions/:sessionId/files", ({ store, query }): WorkspaceFilesResponse => {
+/**
+ * The Files panel's operations over the one demo Workspace, for both ways the panel names it: a
+ * Session (`/api/sessions/:sessionId/files…`) and a directory (`/api/projects/:projectId/
+ * workspace-files…?workspace=`, the new-chat draft's folder). Every scope sees the same files.
+ */
+const workspaceFiles = {
+ list: ({ store, query }: Ctx): WorkspaceFilesResponse => {
const path = normalizePath(query.get("path") ?? "");
const entries = store.f.workspace.entries[path];
if (!entries) notFound("Directory");
return { path, entries };
- })
- .get("/api/sessions/:sessionId/files/content", ({ store, query }) => {
+ },
+ read: ({ store, query }: Ctx) => {
const path = normalizePath(query.get("path") ?? "");
const content = store.f.workspace.content[path];
if (content === undefined) notFound("File");
@@ -1400,8 +1405,8 @@ router
? { "content-disposition": `attachment; filename="${name}"` }
: {}),
});
- })
- .put("/api/sessions/:sessionId/files/content", ({ store, query, body }) => {
+ },
+ write: ({ store, query, body }: Ctx) => {
const path = normalizePath(query.get("path") ?? "");
const data = str(record(body).dataBase64);
try {
@@ -1419,8 +1424,8 @@ router
existing.mtime = new Date().toISOString();
} else entries.push({ name, kind: "file", sizeBytes: size, mtime: new Date().toISOString() });
return empty();
- })
- .delete("/api/sessions/:sessionId/files/content", ({ store, query }) => {
+ },
+ remove: ({ store, query }: Ctx) => {
const path = normalizePath(query.get("path") ?? "");
delete store.f.workspace.content[path];
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
@@ -1429,49 +1434,71 @@ router
(e) => e.name !== name,
);
return empty();
- })
- .post("/api/sessions/:sessionId/files/reveal", () =>
- fail(404, "not_desktop", "Only the desktop shell can reveal a file."),
- )
- // The separate preview origin has no counterpart here: the file is served as the page itself.
- .get("/api/sessions/:sessionId/files/preview-redirect", ({ store, query }) => {
- const path = normalizePath(query.get("path") ?? "");
- const content = store.f.workspace.content[path];
- if (content === undefined) notFound("File");
- return raw(content, {
- "content-type": path.endsWith(".html")
- ? "text/html; charset=utf-8"
- : "text/plain; charset=utf-8",
- });
- })
- .post("/api/sessions/:sessionId/files/move", ({ store, body }) => {
+ },
+ reveal: () => fail(404, "not_desktop", "Only the desktop shell can reveal a file."),
+ create: ({ store, body }: Ctx) => {
+ const { path: named, kind } = record(body);
+ const path = normalizePath(str(named));
+ if (path === "") fail(400, "bad_request", "path must name the new entry.");
+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
+ const name = path.slice(path.lastIndexOf("/") + 1);
+ const entries = (store.f.workspace.entries[dir] ??= []);
+ if (entries.some((e) => e.name === name))
+ fail(409, "target_exists", "Something already exists at this path.");
+ const mtime = new Date().toISOString();
+ if (kind === "dir") {
+ entries.push({ name, kind: "dir", sizeBytes: 0, mtime });
+ store.f.workspace.entries[path] ??= [];
+ } else {
+ entries.push({ name, kind: "file", sizeBytes: 0, mtime });
+ store.f.workspace.content[path] = "";
+ }
+ return empty();
+ },
+ /** A file moves alone; a folder takes every listing and file under it along. */
+ move: ({ store, body }: Ctx) => {
const { from, to } = record(body);
const source = normalizePath(str(from));
const target = normalizePath(str(to));
- const content = store.f.workspace.content[source];
- if (content === undefined) notFound("File");
- if (store.f.workspace.content[target] !== undefined)
+ const ws = store.f.workspace;
+ const folder = ws.entries[source] !== undefined;
+ if (!folder && ws.content[source] === undefined) notFound("File");
+ if (ws.content[target] !== undefined || ws.entries[target] !== undefined)
fail(409, "target_exists", "The destination exists.");
- delete store.f.workspace.content[source];
- store.f.workspace.content[target] = content;
- const move = (path: string, remove: boolean) => {
- const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
- const name = path.slice(path.lastIndexOf("/") + 1);
- const entries = (store.f.workspace.entries[dir] ??= []);
- if (remove) store.f.workspace.entries[dir] = entries.filter((e) => e.name !== name);
- else
- entries.push({
- name,
- kind: "file",
- sizeBytes: content.length,
- mtime: new Date().toISOString(),
- });
- };
- move(source, true);
- move(target, false);
+ if (folder && target.startsWith(`${source}/`))
+ fail(400, "bad_request", "A folder cannot move into itself.");
+ const moved = (path: string) =>
+ path === source || path.startsWith(`${source}/`)
+ ? `${target}${path.slice(source.length)}`
+ : path;
+ for (const key of Object.keys(ws.content)) {
+ const next = moved(key);
+ if (next === key) continue;
+ ws.content[next] = ws.content[key]!;
+ delete ws.content[key];
+ }
+ for (const key of Object.keys(ws.entries)) {
+ const next = moved(key);
+ if (next === key) continue;
+ ws.entries[next] = ws.entries[key]!;
+ delete ws.entries[key];
+ }
+ const parentOf = (path: string) =>
+ path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
+ const nameOf = (path: string) => path.slice(path.lastIndexOf("/") + 1);
+ const was = (ws.entries[parentOf(source)] ?? []).find((e) => e.name === nameOf(source));
+ ws.entries[parentOf(source)] = (ws.entries[parentOf(source)] ?? []).filter(
+ (e) => e.name !== nameOf(source),
+ );
+ (ws.entries[parentOf(target)] ??= []).push({
+ name: nameOf(target),
+ kind: folder ? "dir" : "file",
+ sizeBytes: was?.sizeBytes ?? 0,
+ mtime: new Date().toISOString(),
+ });
return empty();
- })
- .get("/api/sessions/:sessionId/files/search", ({ store, query }): WorkspaceSearchResponse => {
+ },
+ search: ({ store, query }: Ctx): WorkspaceSearchResponse => {
const q = (query.get("q") ?? "").toLowerCase();
if (q === "") fail(400, "empty_query", "Nothing to search for.");
const hits: WorkspaceSearchResponse["hits"] = [];
@@ -1488,6 +1515,32 @@ router
}
}
return { hits, truncated: false };
+ },
+};
+
+for (const base of ["/api/sessions/:sessionId/files", "/api/projects/:projectId/workspace-files"]) {
+ router
+ .get(base, workspaceFiles.list)
+ .get(`${base}/content`, workspaceFiles.read)
+ .put(`${base}/content`, workspaceFiles.write)
+ .delete(`${base}/content`, workspaceFiles.remove)
+ .post(`${base}/reveal`, workspaceFiles.reveal)
+ .post(`${base}/create`, workspaceFiles.create)
+ .post(`${base}/move`, workspaceFiles.move)
+ .get(`${base}/search`, workspaceFiles.search);
+}
+
+router
+ // The separate preview origin has no counterpart here: the file is served as the page itself.
+ .get("/api/sessions/:sessionId/files/preview-redirect", ({ store, query }) => {
+ const path = normalizePath(query.get("path") ?? "");
+ const content = store.f.workspace.content[path];
+ if (content === undefined) notFound("File");
+ return raw(content, {
+ "content-type": path.endsWith(".html")
+ ? "text/html; charset=utf-8"
+ : "text/plain; charset=utf-8",
+ });
})
.post("/api/sessions/:sessionId/files/stat", ({ store, body }): FilesStatResponse => {
const paths = record(body).paths;
diff --git a/packages/ui-gallery/src/library/boards/files.tsx b/packages/ui-gallery/src/library/boards/files.tsx
index cd64c3ab..6407277a 100644
--- a/packages/ui-gallery/src/library/boards/files.tsx
+++ b/packages/ui-gallery/src/library/boards/files.tsx
@@ -108,6 +108,8 @@ export function FilesBoard() {
download: t.download,
rename: t.rename,
delete: t.delete,
+ newTextFile: t.newTextFile,
+ newFolder: t.newFolder,
};
const noop = () => undefined;
@@ -236,6 +238,9 @@ export function FilesBoard() {
onCopyPath={noop}
onAddToChat={noop}
onUploadInto={noop}
+ onNewFile={noop}
+ onNewFolder={noop}
+ onRename={noop}
onClose={noop}
/>
</div>
diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.ts
index 82ca8eb4..0234bd16 100644
--- a/packages/ui-gallery/src/strings-en.ts
+++ b/packages/ui-gallery/src/strings-en.ts
@@ -946,6 +946,8 @@ export const en: GalleryStrings = {
uploadHere: "Upload here",
rename: "Rename or move",
delete: "Delete",
+ newTextFile: "New text file",
+ newFolder: "New folder",
editor: "Editor",
editorLabel: (name: string) => `Editing ${name}`,
drop: "Drop feedback",
diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.ts
index 11509348..9d40a208 100644
--- a/packages/ui-gallery/src/strings.ts
+++ b/packages/ui-gallery/src/strings.ts
@@ -906,6 +906,8 @@ export const zh = {
uploadHere: "上传到此文件夹",
rename: "重命名 / 移动",
delete: "删除",
+ newTextFile: "新建文本文件",
+ newFolder: "新建文件夹",
editor: "编辑器",
editorLabel: (name: string) => `编辑 ${name}`,
drop: "拖放反馈",
diff --git a/packages/ui/src/components/content/workspace-file-editor/caret.ts b/packages/ui/src/components/content/workspace-file-editor/caret.ts
new file mode 100644
index 00000000..81e88196
--- /dev/null
+++ b/packages/ui/src/components/content/workspace-file-editor/caret.ts
@@ -0,0 +1,33 @@
+/**
+ * Where the Files panel editor's caret goes when its text changes under it, and where it starts:
+ * the positions a code editor keeps by line and column rather than by character offset. Pure, so
+ * the editor's two layout effects stay a few lines each and the arithmetic is tested directly.
+ */
+
+/** The offset of the start of line `line` (0-based) in `text`, clamped to its last line. */
+export function lineStartOffset(text: string, line: number): number {
+ let offset = 0;
+ for (let i = 0; i < line; i += 1) {
+ const next = text.indexOf("\n", offset);
+ if (next < 0) return offset;
+ offset = next + 1;
+ }
+ return offset;
+}
+
+/**
+ * Where a caret at `offset` in `before` lands once the text is `after`: the same line and
+ * column, pulled back to the last line and to the end of its line where `after` is shorter.
+ * What a code editor does when the file changes on disk under a clean buffer — the reader
+ * keeps their place instead of being thrown to the end.
+ */
+export function caretAfterReplace(before: string, after: string, offset: number): number {
+ const at = Math.max(0, Math.min(offset, before.length));
+ const head = before.slice(0, at);
+ const line = head.split("\n").length - 1;
+ const column = at - (head.lastIndexOf("\n") + 1);
+ const start = lineStartOffset(after, line);
+ const end = after.indexOf("\n", start);
+ const lineLength = (end < 0 ? after.length : end) - start;
+ return start + Math.min(column, lineLength);
+}
diff --git a/packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsx b/packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsx
index 51e4c775..8de81134 100644
--- a/packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsx
+++ b/packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsx
@@ -12,31 +12,63 @@
* size, line height, letter spacing, tab size, padding, wrap mode — and those are stated once,
* for both layers, in `.code-surface`.
*
+ * The editor keeps its place the way a code editor does. It opens where the source view was
+ * scrolled to (`initialScroll` — the scroll box reserves the same scrollbar gutter as the
+ * preview's, so one offset means one line in both), with the caret at the start of the first
+ * line wholly in view and focus taken without scrolling: pressing Edit moves nothing. A save
+ * leaves it mounted, so the caret, the selection and the scroll stay as they were. And when the
+ * text is replaced from outside — the caller swapping in the file an Agent rewrote under a clean
+ * editor — the caret keeps its line and column (clamped to the new text) and the scroll stays
+ * put, where a browser setting a textarea's value would throw the caret to the end.
+ *
* No spell-check or autocorrect, and the save shortcut saves (the caller's binding, ⌘S / Ctrl+S
* when it names none) — the browser's own "save page" default is suppressed while the focus is
* here. Long lines scroll sideways, as code should, unless the Wrap toggle soft-wraps them; the
* toggle, Save and Cancel all live in the panel's preview header, and this component owns only
* the text.
*/
-import { useEffect, useRef, useState } from "react";
-import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+import { useCallback, useLayoutEffect, useRef, useState } from "react";
+import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from "react";
import { CodeSurface } from "../code-block/code-block";
import { languageForFileName } from "../code-block/code-languages";
+import { caretAfterReplace, lineStartOffset } from "./caret";
/** Quiet period before re-highlighting, so a keystroke costs a re-render and not a tokenize. */
const EDIT_HIGHLIGHT_SETTLE_MS = 200;
+/** A scroll box's position. */
+export interface EditorScroll {
+ top: number;
+ left: number;
+}
+
/** Ctrl+S or ⌘S without Alt: the save key when the caller names no binding. */
function isDefaultSaveKey(event: KeyboardEvent): boolean {
return (event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "s";
}
+/**
+ * The index of the first rendered line wholly inside the scroll box. Wholly, not partly: a caret
+ * on a line cut by the top edge is one the browser scrolls into view at the first keystroke, or
+ * when focus comes back from a dialog — the very jump the opening position is there to avoid.
+ */
+function firstVisibleLine(box: HTMLElement): number {
+ const top = box.getBoundingClientRect().top;
+ const lines = box.querySelectorAll(".code-surface .line");
+ for (let i = 0; i < lines.length; i += 1) {
+ if (lines[i]!.getBoundingClientRect().top >= top - 1) return i;
+ }
+ return 0;
+}
+
export function WorkspaceFileEditor({
path,
value,
label,
wrap,
highlight = true,
+ initialScroll,
+ hostRef,
onChange,
onSave,
isSaveKey = isDefaultSaveKey,
@@ -53,19 +85,66 @@ export function WorkspaceFileEditor({
* rather than a stalled editor; the caller bounds it only by what a load can put here.
*/
highlight?: boolean;
+ /** Where the source view was scrolled when Edit was pressed; the editor opens there. */
+ initialScroll?: EditorScroll;
+ /** The scroll box, for a caller that hands the position back to the source view on the way out. */
+ hostRef?: RefObject<HTMLDivElement | null>;
onChange: (next: string) => void;
onSave: () => void;
/** Whether a keydown is the save shortcut; the app passes the user's binding. */
isSaveKey?: (event: KeyboardEvent) => boolean;
}) {
const ref = useRef<HTMLTextAreaElement | null>(null);
- useEffect(() => {
- ref.current?.focus();
- }, []);
+ const host = useRef<HTMLDivElement | null>(null);
+ const setHost = useCallback(
+ (el: HTMLDivElement | null) => {
+ host.current = el;
+ if (hostRef) hostRef.current = el;
+ },
+ [hostRef],
+ );
+ /** The text the textarea itself last produced: a `value` that differs came from outside. */
+ const own = useRef(value);
+ /** The caret and the scroll as the reader last left them, for an outside replacement to keep. */
+ const place = useRef({ start: 0, end: 0, top: 0, left: 0 });
// An IME writes its candidate text into the textarea before it reaches `value`, and the
// textarea's text is transparent — so the layers swap for the length of the composition.
const [composing, setComposing] = useState(false);
+ // Opening: the source view's scroll, the caret at the start of the first line wholly in view,
+ // and focus taken without scrolling to wherever the caret would otherwise have been.
+ useLayoutEffect(() => {
+ const box = host.current;
+ const textarea = ref.current;
+ if (box === null || textarea === null) return;
+ if (initialScroll !== undefined) {
+ box.scrollTop = initialScroll.top;
+ box.scrollLeft = initialScroll.left;
+ }
+ const caret = lineStartOffset(textarea.value, firstVisibleLine(box));
+ textarea.setSelectionRange(caret, caret);
+ textarea.focus({ preventScroll: true });
+ place.current = { start: caret, end: caret, top: box.scrollTop, left: box.scrollLeft };
+ // The opening position is read once: a later scroll is the reader's own.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Text replaced from outside: same line and column, same scroll.
+ useLayoutEffect(() => {
+ const box = host.current;
+ const textarea = ref.current;
+ if (box === null || textarea === null || value === own.current) return;
+ const before = own.current;
+ own.current = value;
+ const { start, end, top, left } = place.current;
+ textarea.setSelectionRange(
+ caretAfterReplace(before, value, start),
+ caretAfterReplace(before, value, end),
+ );
+ box.scrollTop = top;
+ box.scrollLeft = left;
+ }, [value]);
+
const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>): void => {
if (isSaveKey(e.nativeEvent)) {
// A held chord repeats: every repeat is kept from the browser (Save Page), one save runs.
@@ -74,12 +153,22 @@ export function WorkspaceFileEditor({
}
};
+ const remember = (textarea: HTMLTextAreaElement): void => {
+ place.current.start = textarea.selectionStart;
+ place.current.end = textarea.selectionEnd;
+ };
+
return (
<div
+ ref={setHost}
// The composing flag rides on the scroll box so the CSS can swap the layers without the
// surface needing to know an IME exists.
data-composing={composing}
- className="code-editor-host h-full min-h-0 overflow-auto text-xs leading-relaxed"
+ onScroll={(e) => {
+ place.current.top = e.currentTarget.scrollTop;
+ place.current.left = e.currentTarget.scrollLeft;
+ }}
+ className="code-editor-host h-full min-h-0 overflow-auto text-xs leading-relaxed [scrollbar-gutter:stable]"
>
<CodeSurface
language={languageForFileName(path)}
@@ -94,7 +183,12 @@ export function WorkspaceFileEditor({
<textarea
ref={ref}
value={value}
- onChange={(e) => onChange(e.target.value)}
+ onChange={(e) => {
+ own.current = e.target.value;
+ remember(e.target);
+ onChange(e.target.value);
+ }}
+ onSelect={(e) => remember(e.currentTarget)}
onKeyDown={onKeyDown}
onCompositionStart={() => setComposing(true)}
onCompositionEnd={() => setComposing(false)}
diff --git a/packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsx b/packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsx
index 820983c9..237d169b 100644
--- a/packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsx
+++ b/packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsx
@@ -5,10 +5,14 @@
* drift into naming the same action two ways.
*
* The two entries that hold for either kind come first — copy the relative path, add a
- * reference to the conversation — and the kind-specific one comes last: a folder takes an
- * upload, a file gives a download. Download is an `<a download>` rather than a button, the
- * same shape the preview header already uses: it is the browser's own save, not a fetch the
- * app has to run.
+ * reference to the conversation — and the kind-specific ones follow: a folder takes a new text
+ * file, a new folder and an upload, a file gives a download. Download is an `<a download>` rather
+ * than a button, the same shape the preview header already uses: it is the browser's own save,
+ * not a fetch the app has to run. Rename comes last for either kind, and delete, for a file,
+ * after it.
+ *
+ * `WorkspaceNewMenuRows` is the New menu on its own — the tree pane's New button and the blank
+ * space under the tree, where there is no entry to copy or add, only somewhere to create.
*
* The rows are the Menu rows at the small density, the one every overflow and context menu in
* the app uses, so they read the same as the Session row's menu.
@@ -22,8 +26,14 @@ export interface FileMenuTarget {
kind: "dir" | "file";
}
+/** The New menu's words, from the caller's dictionary. */
+export interface WorkspaceNewMenuLabels {
+ newTextFile: string;
+ newFolder: string;
+}
+
/** The rows' words, from the caller's dictionary. */
-export interface WorkspaceFileMenuLabels {
+export interface WorkspaceFileMenuLabels extends WorkspaceNewMenuLabels {
copyPath: string;
addToChat: string;
addSelectionToChat: string;
@@ -33,6 +43,41 @@ export interface WorkspaceFileMenuLabels {
delete: string;
}
+/** The two New rows: a text file and a folder, both created in the directory the caller names. */
+function NewRows({
+ labels,
+ onNewFile,
+ onNewFolder,
+}: {
+ labels: WorkspaceNewMenuLabels;
+ onNewFile: () => void;
+ onNewFolder: () => void;
+}) {
+ return (
+ <>
+ <MenuItem glyph={ICONS.filePlus} label={labels.newTextFile} onSelect={onNewFile} />
+ <MenuItem glyph={ICONS.folderPlus} label={labels.newFolder} onSelect={onNewFolder} />
+ </>
+ );
+}
+
+/** The New menu on its own: the tree pane's New button, and the blank space under the tree. */
+export function WorkspaceNewMenuRows({
+ labels,
+ onNewFile,
+ onNewFolder,
+}: {
+ labels: WorkspaceNewMenuLabels;
+ onNewFile: () => void;
+ onNewFolder: () => void;
+}) {
+ return (
+ <Menu density="sm">
+ <NewRows labels={labels} onNewFile={onNewFile} onNewFolder={onNewFolder} />
+ </Menu>
+ );
+}
+
export function WorkspaceFileMenuRows({
target,
labels,
@@ -41,6 +86,8 @@ export function WorkspaceFileMenuRows({
onCopyPath,
onAddToChat,
onUploadInto,
+ onNewFile,
+ onNewFolder,
onAddSelection,
onRename,
onDelete,
@@ -54,6 +101,10 @@ export function WorkspaceFileMenuRows({
onCopyPath: (target: FileMenuTarget) => void;
onAddToChat: (target: FileMenuTarget) => void;
onUploadInto: (dir: string) => void;
+ /** Creates an empty text file inside a folder; offered on folders when given. */
+ onNewFile?: (dir: string) => void;
+ /** Creates a folder inside a folder; offered on folders when given. */
+ onNewFolder?: (dir: string) => void;
/**
* Adds the text selected in the preview rather than the whole file. Offered only by the
* preview, and only while a selection actually sits inside it — a tree row has nothing
@@ -61,10 +112,8 @@ export function WorkspaceFileMenuRows({
*/
onAddSelection?: () => void;
/**
- * Renames or moves the file — one action, because both are the same write of a new path, and
- * offering them separately would mean asking which one the user meant. Files only: a
- * directory has no version marker, so the precondition that keeps this from overwriting the
- * agent's work cannot be stated for one.
+ * Renames or moves the entry — one action, because both are the same write of a new path, and
+ * offering them separately would mean asking which one the user meant. A folder moves whole.
*/
onRename?: (target: FileMenuTarget) => void;
/** Deletes the file, behind a confirmation and the same precondition. */
@@ -88,11 +137,27 @@ export function WorkspaceFileMenuRows({
/>
)}
{target.kind === "dir" ? (
- <MenuItem
- glyph={ICONS.upload}
- label={labels.uploadHere}
- onSelect={() => onUploadInto(target.path)}
- />
+ <>
+ {onNewFile !== undefined && onNewFolder !== undefined && (
+ <NewRows
+ labels={labels}
+ onNewFile={() => onNewFile(target.path)}
+ onNewFolder={() => onNewFolder(target.path)}
+ />
+ )}
+ <MenuItem
+ glyph={ICONS.upload}
+ label={labels.uploadHere}
+ onSelect={() => onUploadInto(target.path)}
+ />
+ {onRename !== undefined && (
+ <MenuItem
+ glyph={ICONS.penLine}
+ label={labels.rename}
+ onSelect={() => onRename(target)}
+ />
+ )}
+ </>
) : (
<>
<MenuItem
diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.ts
index 8829ff87..72274bca 100644
--- a/packages/ui/src/components/icons/icons.ts
+++ b/packages/ui/src/components/icons/icons.ts
@@ -166,6 +166,9 @@ export const ICONS = {
pencil: "M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3",
/** A folder outline, closed. */
folder: "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z",
+ /** The closed folder with a plus: a new folder made. */
+ folderPlus:
+ "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7zM12 10v6M9 13h6",
/** A folder outline, open (lucide folder-open: back panel and a tilted front flap). */
folderOpen:
"m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",
diff --git a/packages/ui/src/components/shell/panels-toolbar/panels-toolbar.tsx b/packages/ui/src/components/shell/panels-toolbar/panels-toolbar.tsx
index b519c22a..138b71aa 100644
--- a/packages/ui/src/components/shell/panels-toolbar/panels-toolbar.tsx
+++ b/packages/ui/src/components/shell/panels-toolbar/panels-toolbar.tsx
@@ -3,6 +3,10 @@
* putting it away. A toggle is `aria-expanded` while its dock is on screen, and may carry an
* attention dot for something waiting inside that dock. Everything a dock holds — its tabs, its
* add menu, its picker — lives on the dock itself, so this stays a row of toggles.
+ *
+ * A toggle with nothing to open yet (`unavailable`) stays in its place, muted, and its tooltip
+ * says why; it is `aria-disabled` rather than `disabled`, since a disabled button hears no
+ * pointer and could never show that reason.
*/
import type { HTMLAttributes } from "react";
import { ICON_SIZE } from "../../../icon-scale";
@@ -22,6 +26,8 @@ export interface PanelsToolbarToggle {
active: boolean;
/** An attention dot beside the glyph (a pending approval inside that dock). */
badge?: boolean;
+ /** Nothing to open yet: the toggle does nothing, and `tooltip` should say why. */
+ unavailable?: boolean;
onToggle: () => void;
}
@@ -41,14 +47,17 @@ export function PanelsToolbar({ toggles, className = "", ...rest }: PanelsToolba
key={toggle.key}
type="button"
aria-expanded={toggle.active}
- onClick={toggle.onToggle}
+ aria-disabled={toggle.unavailable === true ? true : undefined}
+ onClick={toggle.unavailable === true ? undefined : toggle.onToggle}
data-tooltip={toggle.tooltip ?? toggle.label}
aria-label={toggle.label}
data-testid={`dock-toggle-${toggle.key}`}
className={`relative flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${
- toggle.active
- ? "bg-line-muted text-fg"
- : "text-fg-muted hover:bg-line-muted hover:text-fg"
+ toggle.unavailable === true
+ ? "cursor-not-allowed text-fg-subtle opacity-60"
+ : toggle.active
+ ? "bg-line-muted text-fg"
+ : "text-fg-muted hover:bg-line-muted hover:text-fg"
}`}
>
<GlyphIcon d={toggle.glyph} size={ICON_SIZE.iconButton} />
diff --git a/packages/ui/test/panels-toolbar.test.ts b/packages/ui/test/panels-toolbar.test.ts
index 710b5c77..78b1d3f3 100644
--- a/packages/ui/test/panels-toolbar.test.ts
+++ b/packages/ui/test/panels-toolbar.test.ts
@@ -1,6 +1,7 @@
/**
* PanelsToolbar (src/components/shell/panels-toolbar/panels-toolbar.tsx): the toolbar's dock
- * toggles, each saying whether its dock is open.
+ * toggles, each saying whether its dock is open; a toggle with nothing to open yet stays in
+ * place, disabled for assistive technology, with its tooltip saying why.
*/
import { createElement } from "react";
import { describe, expect, it } from "vitest";
@@ -40,4 +41,26 @@ describe("PanelsToolbar", () => {
expect(html).toContain('data-tooltip="Bottom dock" aria-label="Bottom dock"');
expect(html.match(/bg-tone-attention-emphasis/g)).toHaveLength(1);
});
+
+ it("a toggle with nothing to open yet is disabled and its tooltip says why", () => {
+ const html = renderStatic(
+ createElement(PanelsToolbar, {
+ toggles: [
+ {
+ key: "files",
+ label: "Files",
+ tooltip: "Choose a folder to browse its files.",
+ glyph: "M0 0h1",
+ active: false,
+ unavailable: true,
+ onToggle: () => {},
+ },
+ ],
+ }),
+ );
+ expect(html).toContain('aria-disabled="true"');
+ expect(html).toContain(
+ 'data-tooltip="Choose a folder to browse its files." aria-label="Files"',
+ );
+ });
});
diff --git a/packages/ui/test/workspace-file-menu.test.ts b/packages/ui/test/workspace-file-menu.test.ts
index a7493e27..b15dcb92 100644
--- a/packages/ui/test/workspace-file-menu.test.ts
+++ b/packages/ui/test/workspace-file-menu.test.ts
@@ -1,12 +1,26 @@
/**
- * The Files panel's file menu rows and its in-place editor: the rows say the caller's words and
- * differ by what the entry is, and the editor's textarea takes its name from the caller over the
- * code surface it shares with the source view.
+ * The Files panel's file menu rows and its in-place editor.
+ *
+ * - The rows say the caller's words and differ by what the entry is: a folder offers new text
+ * files and folders inside it, an upload and a rename, never a download; a file offers its
+ * download, then rename and delete, delete in danger; the New menu alone offers the two New rows.
+ * - The editor's textarea takes its name from the caller over the code surface it shares with
+ * the source view, in a scroll box that reserves the same scrollbar gutter as the preview's.
+ * - When the text is replaced from outside, the caret keeps its line and column, pulled back to
+ * the last line and the end of its line where the new text is shorter; the opening caret sits
+ * at the start of the line in view.
*/
import { createElement } from "react";
import { describe, expect, it } from "vitest";
import { WorkspaceFileEditor } from "../src/components/content/workspace-file-editor/workspace-file-editor";
-import { WorkspaceFileMenuRows } from "../src/components/files/workspace-file-menu/workspace-file-menu";
+import {
+ caretAfterReplace,
+ lineStartOffset,
+} from "../src/components/content/workspace-file-editor/caret";
+import {
+ WorkspaceFileMenuRows,
+ WorkspaceNewMenuRows,
+} from "../src/components/files/workspace-file-menu/workspace-file-menu";
import type { FileMenuTarget } from "../src/components/files/workspace-file-menu/workspace-file-menu";
import { renderStatic } from "../src/testing";
@@ -18,6 +32,8 @@ const LABELS = {
download: "Download",
rename: "Rename or move",
delete: "Delete",
+ newTextFile: "New text file",
+ newFolder: "New folder",
};
const noop = () => undefined;
@@ -40,12 +56,27 @@ const rows = (
);
describe("WorkspaceFileMenuRows", () => {
- it("offers a folder an upload, and no download", () => {
- const html = rows({ path: "src", kind: "dir" });
+ it("offers a folder new files and folders inside it, an upload and a rename, and no download", () => {
+ const html = rows(
+ { path: "src", kind: "dir" },
+ { onNewFile: noop, onNewFolder: noop, onRename: noop, onDelete: noop },
+ );
expect(html).toContain('role="menu"');
expect(html).toContain(">Copy relative path</span>");
- expect(html).toContain(">Upload here</span>");
+ expect(html.indexOf(">New text file<")).toBeLessThan(html.indexOf(">New folder<"));
+ expect(html.indexOf(">New folder<")).toBeLessThan(html.indexOf(">Upload here<"));
+ expect(html.indexOf(">Upload here<")).toBeLessThan(html.indexOf(">Rename or move<"));
expect(html).not.toContain("Download");
+ expect(html).not.toContain(">Delete<");
+ });
+
+ it("the New menu alone offers the two New rows", () => {
+ const html = renderStatic(
+ createElement(WorkspaceNewMenuRows, { labels: LABELS, onNewFile: noop, onNewFolder: noop }),
+ );
+ expect(html).toContain('role="menu"');
+ expect(html.indexOf(">New text file<")).toBeLessThan(html.indexOf(">New folder<"));
+ expect(html).not.toContain("Copy relative path");
});
it("offers a file its download as a link, and its rename and delete last, delete in danger", () => {
@@ -81,6 +112,30 @@ describe("WorkspaceFileEditor", () => {
expect(html).toContain('spellCheck="false"');
expect(html).toContain('wrap="off"');
expect(html).toContain("code-editor-host");
+ expect(html).toContain("[scrollbar-gutter:stable]");
expect(render(true)).toContain('wrap="soft"');
});
+
+ it("an outside rewrite keeps the caret on its line and column", () => {
+ const before = "alpha\nbeta\ngamma\n";
+ const caret = before.indexOf("mma"); // line 2, column 2
+ const after = "alpha\nBETA, rewritten\ngamma ray\ndelta\n";
+ expect(caretAfterReplace(before, after, caret)).toBe(after.indexOf("mma ray"));
+ });
+
+ it("a shorter rewrite pulls the caret back to the end of its line and to the last line", () => {
+ const before = "one\nsecond line\nthird\n";
+ expect(caretAfterReplace(before, "one\nsec\nthird\n", before.indexOf("line"))).toBe(
+ "one\nsec".length,
+ );
+ expect(caretAfterReplace(before, "only", before.indexOf("third"))).toBe(0);
+ expect(caretAfterReplace(before, "", before.length)).toBe(0);
+ });
+
+ it("the opening caret sits at the start of the line in view", () => {
+ const text = "a\nbb\nccc";
+ expect(lineStartOffset(text, 0)).toBe(0);
+ expect(lineStartOffset(text, 2)).toBe(text.indexOf("ccc"));
+ expect(lineStartOffset(text, 9)).toBe(text.indexOf("ccc"));
+ });
});
diff --git a/packages/web/e2e/files-folders.spec.mjs b/packages/web/e2e/files-folders.spec.mjs
new file mode 100644
index 00000000..22045670
--- /dev/null
+++ b/packages/web/e2e/files-folders.spec.mjs
@@ -0,0 +1,235 @@
+/**
+ * The Files panel's folders and new files, its editor's place, copies on a plain-HTTP origin,
+ * and the panel on a Workspace that has no Session yet.
+ *
+ * - A folder made from the tree header opens as the current directory; a text file made from
+ * a folder's menu starts as untitled.txt with its stem selected and opens in the editor; a
+ * taken name is refused and nothing is written.
+ * - Renaming a folder moves its files, and the file open in the panel follows to its new path.
+ * - Copy relative path on an origin without the async Clipboard API (plain HTTP, not
+ * localhost) writes the Workspace-relative path to the clipboard of the machine the browser
+ * is on.
+ * - The editor keeps its place: Edit opens where the preview was scrolled, Save leaves it open
+ * with the caret and the scroll untouched, and a clean editor takes an Agent's rewrite in
+ * place, on the caret's line.
+ * - A Workspace group's "Browse files" lands on a new-chat draft for that folder with its Files
+ * panel open, and "add to conversation" there stages the reference in the draft's composer; a
+ * temporary Workspace has nothing to browse and the toggle says why.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "filesfolders";
+const P = "password123";
+
+/** A Workspace directory of the test's own, named so its sidebar group can be found. */
+function workspace(name, files) {
+ const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "e2e-files-")), name);
+ for (const [rel, text] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
+ fs.writeFileSync(path.join(dir, rel), text);
+ }
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+async function setUp(page, workspaces) {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+ const sessions = [];
+ for (const dir of workspaces) {
+ const res = await page.request.post(
+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
+ { data: { workspace: dir } },
+ );
+ expect(res.ok(), "create session").toBeTruthy();
+ sessions.push((await res.json()).session.sessionId);
+ }
+ return sessions;
+}
+
+async function openFiles(page, sessionId) {
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await page.getByTestId("dock-toggle-right").click();
+ await page.getByTestId("dock-pick-workspace").click();
+ return page.getByTestId("dock");
+}
+
+test("new folders and text files are made where asked, and a taken name changes nothing", async ({
+ page,
+}) => {
+ const dir = workspace("newstuff", { "README.md": "# hi\n" });
+ const [sid] = await setUp(page, [dir]);
+ const dock = await openFiles(page, sid);
+ await dock.locator('[data-tree-path="README.md"]').waitFor();
+
+ await dock.getByRole("button", { name: "新建", exact: true }).click();
+ await page.getByRole("menuitem", { name: "新建文件夹" }).click();
+ await page.getByRole("dialog").getByRole("textbox").fill("drafts");
+ await page.getByRole("dialog").getByRole("textbox").press("Enter");
+ await expect(dock.locator('[data-tree-path="drafts"]')).toBeVisible();
+ expect(fs.statSync(path.join(dir, "drafts")).isDirectory()).toBe(true);
+
+ await dock.locator('[data-tree-path="drafts"]').click({ button: "right" });
+ await page.getByRole("menuitem", { name: "新建文本文件" }).click();
+ const name = page.getByRole("dialog").getByRole("textbox");
+ await expect(name).toHaveValue("untitled.txt");
+ expect(await name.evaluate((el) => [el.selectionStart, el.selectionEnd])).toEqual([0, 8]);
+ await page.keyboard.type("plan");
+ await page.keyboard.press("Enter");
+ await expect(dock.getByRole("textbox", { name: "编辑 plan.txt" })).toBeFocused();
+ expect(fs.readFileSync(path.join(dir, "drafts", "plan.txt"), "utf8")).toBe("");
+
+ // The blank space under the tree creates at the root; a taken name is refused there.
+ const tree = await dock.locator('[role="tree"]').boundingBox();
+ await page.mouse.click(tree.x + 30, tree.y + tree.height - 12, { button: "right" });
+ await page.getByRole("menuitem", { name: "新建文本文件" }).click();
+ await page.getByRole("dialog").getByRole("textbox").fill("README.md");
+ await page.getByRole("dialog").getByRole("button", { name: "创建" }).click();
+ await expect(page.getByText("README.md 已存在,未做改动。").first()).toBeVisible();
+ await expect(page.getByRole("dialog")).toBeVisible();
+ expect(fs.readFileSync(path.join(dir, "README.md"), "utf8")).toBe("# hi\n");
+});
+
+test("renaming a folder moves its files and the open file follows", async ({ page }) => {
+ const dir = workspace("renamer", { "docs/guide/intro.txt": "intro text\n" });
+ const [sid] = await setUp(page, [dir]);
+ const dock = await openFiles(page, sid);
+ await dock.locator('[data-tree-path="docs"]').click();
+ await dock.locator('[data-tree-path="docs/guide"]').click();
+ await dock.locator('[data-tree-path="docs/guide/intro.txt"]').click();
+ await expect(dock.getByText("intro text")).toBeVisible();
+
+ await dock.locator('[data-tree-path="docs"]').click({ button: "right" });
+ await page.getByRole("menuitem", { name: "重命名 / 移动" }).click();
+ await page.getByRole("dialog").getByRole("textbox").fill("handbook/docs-2026");
+ await page.getByRole("dialog").getByRole("button", { name: "移动" }).click();
+
+ const moved = dock.locator('[data-tree-path="handbook/docs-2026/guide/intro.txt"]');
+ await expect(moved).toHaveAttribute("aria-selected", "true");
+ await expect(dock.getByText("intro text")).toBeVisible();
+ expect(
+ fs.readFileSync(path.join(dir, "handbook", "docs-2026", "guide", "intro.txt"), "utf8"),
+ ).toBe("intro text\n");
+ expect(fs.existsSync(path.join(dir, "docs"))).toBe(false);
+});
+
+test("copy relative path on a plain-HTTP origin writes the relative path", async ({ page }) => {
+ const dir = workspace("copier", { "src/app.ts": "export {};\n" });
+ const [sid] = await setUp(page, [dir]);
+ // The page as a LAN address serves it: no secure context, so no async Clipboard API.
+ await page.addInitScript(() => {
+ Object.defineProperty(window, "isSecureContext", { value: false });
+ Object.defineProperty(Navigator.prototype, "clipboard", { get: () => undefined });
+ });
+ const dock = await openFiles(page, sid);
+ expect(await page.evaluate(() => [window.isSecureContext, typeof navigator.clipboard])).toEqual([
+ false,
+ "undefined",
+ ]);
+ await dock.locator('[data-tree-path="src"]').click();
+ await dock.locator('[data-tree-path="src/app.ts"]').click({ button: "right" });
+ await page.getByRole("menuitem", { name: "复制相对路径" }).click();
+ await expect(page.getByText("已复制").first()).toBeVisible();
+ // Read back from a page that has the API: the text is on this machine's clipboard.
+ const reader = await page.context().newPage();
+ await reader.goto(`${BASE}/`);
+ expect(await reader.evaluate(() => navigator.clipboard.readText())).toBe("src/app.ts");
+ await reader.close();
+});
+
+test("the editor keeps its place through Edit, Save and an Agent's rewrite", async ({ page }) => {
+ const lines = Array.from({ length: 400 }, (_, i) => `line ${String(i + 1).padStart(4, "0")}`);
+ const dir = workspace("editor", { "long.txt": `${lines.join("\n")}\n` });
+ const [sid] = await setUp(page, [dir]);
+ const dock = await openFiles(page, sid);
+ await dock.locator('[data-tree-path="long.txt"]').click();
+ await dock.getByText("line 0001").first().waitFor();
+ const body = dock
+ .locator(".code-surface")
+ .first()
+ .locator("xpath=ancestor::div[contains(@class,'overflow-auto')][1]");
+ await body.evaluate((el) => (el.scrollTop = 3000));
+
+ await dock.getByRole("button", { name: "编辑" }).click();
+ const host = dock.locator(".code-editor-host");
+ const textarea = dock.locator("textarea");
+ await expect(textarea).toBeFocused();
+ expect(await host.evaluate((el) => el.scrollTop)).toBe(3000);
+ const caretLine = () =>
+ textarea.evaluate((el) => el.value.slice(0, el.selectionStart).split("\n").length);
+ const openedOn = await caretLine();
+ expect(openedOn).toBeGreaterThan(100);
+
+ await page.keyboard.type("edited ");
+ await page.keyboard.press("Control+s");
+ await page.getByRole("dialog").getByRole("button", { name: "保存" }).click();
+ await expect(page.getByText("已保存").first()).toBeVisible();
+ await expect(textarea).toBeFocused();
+ expect(await host.evaluate((el) => el.scrollTop)).toBe(3000);
+ expect(await caretLine()).toBe(openedOn);
+ expect(fs.readFileSync(path.join(dir, "long.txt"), "utf8")).toContain("edited line");
+
+ // The Agent rewrites a line further down while the editor holds nothing unsaved.
+ const ta = page.getByPlaceholder(/输入消息/);
+ await ta.fill("files rewrite test sed -i 's/^line 0300$/line 0300 by the agent/' long.txt");
+ await page.getByRole("button", { name: "发送" }).click();
+ await expect(page.getByText("The file was rewritten.")).toBeVisible();
+ await expect.poll(() => textarea.inputValue()).toContain("line 0300 by the agent");
+ expect(await caretLine()).toBe(openedOn);
+ expect(await host.evaluate((el) => el.scrollTop)).toBe(3000);
+ await expect(dock.getByText("磁盘上已变更")).toHaveCount(0);
+});
+
+test("Browse files on a Workspace group opens a draft on that folder, whose panel feeds the draft", async ({
+ page,
+}) => {
+ const alpha = workspace("alpha-proj", { "README.md": "# Alpha\n" });
+ const beta = workspace("beta-proj", { "notes.txt": "beta\n" });
+ const [, sBeta] = await setUp(page, [alpha, beta]);
+ await page.goto(`${BASE}/chat/${sBeta}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+
+ await page
+ .locator('div[class*="group/header"]')
+ .filter({ hasText: "alpha-proj" })
+ .getByRole("button", { name: "工作区选项" })
+ .click();
+ await page.getByRole("menuitem", { name: "打开文件浏览" }).click();
+ await expect(page).toHaveURL(/\/chat\/new/);
+ const dock = page.getByTestId("dock");
+ await expect(dock.locator('[data-tree-path="README.md"]')).toBeVisible();
+ await expect(page.getByTestId("dock-toggle-files")).toHaveAttribute("aria-expanded", "true");
+
+ await dock.locator('[data-tree-path="README.md"]').click({ button: "right" });
+ await page.getByRole("menuitem", { name: "添加到对话" }).click();
+ await expect(page.getByRole("button", { name: "移除引用 README.md" })).toBeVisible();
+
+ // A temporary Workspace: nothing to browse until the first message makes one.
+ await page.getByRole("button", { name: "新建对话" }).first().click();
+ const toggle = page.getByTestId("dock-toggle-files");
+ await expect(toggle).toHaveAttribute("aria-disabled", "true");
+ await expect(toggle).toHaveAttribute("data-tooltip", /临时工作区在发送第一条消息时才创建/);
+});
diff --git a/packages/web/e2e/mock-llm.mjs b/packages/web/e2e/mock-llm.mjs
index 5798713d..c088f99d 100644
--- a/packages/web/e2e/mock-llm.mjs
+++ b/packages/web/e2e/mock-llm.mjs
@@ -3,6 +3,8 @@
* Branches on request body:
* - title request (prompt contains "concise title") -> short text
* - files-card probe ("files card test") -> text with two backtick paths (one real, one missing)
+ * - "files rewrite test <cmd>" -> tool_use(exec_command) running <cmd>, then a short final text
+ * (files-folders.spec: the Agent rewrites a file the Files panel has open)
* - subagent's own turns (its prompt is the only user text) -> tool_use(exec_command) first,
* then the report text once the tool_result is back — the tool call gives the child a real
* approval point (under always-ask it parks on a NESTED approval, which the subagents-panel
@@ -251,6 +253,29 @@ const server = http.createServer((req, res) => {
return;
}
+ // Files-panel rewrite test: the Agent rewrites a Workspace file while the panel has it open.
+ // Keyed on the LAST message, since the history keeps every earlier request of the
+ // conversation: the user's own text names the command, and its tool_result ends the turn.
+ const lastMessage = JSON.stringify(messages[messages.length - 1] ?? {});
+ const rewrite = /files rewrite test ([^"\\]+)/.exec(lastMessage);
+ if (rewrite) {
+ block(
+ res,
+ 0,
+ { type: "tool_use", id: "toolu_files_rewrite", name: "exec_command", input: {} },
+ [{ type: "input_json_delta", partial_json: JSON.stringify({ cmd: rewrite[1].trim() }) }],
+ );
+ messageStop(res, "tool_use", 12);
+ return;
+ }
+ if (flat.includes("files rewrite test") && lastMessage.includes("tool_result")) {
+ block(res, 0, { type: "text", text: "" }, [
+ { type: "text_delta", text: "The file was rewritten." },
+ ]);
+ messageStop(res, "end_turn", 8);
+ return;
+ }
+
if (wantsMalformed && !hasToolResult) {
malformedTurns += 1;
if (malformedTurns === 1) {
diff --git a/packages/web/src/api/client.ts b/packages/web/src/api/client.ts
index 8cabdd11..d36e4e8a 100644
--- a/packages/web/src/api/client.ts
+++ b/packages/web/src/api/client.ts
@@ -67,6 +67,11 @@ export interface ApiFetchMeta {
* is readable cross-origin too.
*/
serverNowMs: number | null;
+ /**
+ * The response's `ETag`, or null when it carries none. A Workspace file write answers with the
+ * version it wrote there — the precondition the editor's next save of that file carries.
+ */
+ etag: string | null;
}
/** Makes an API request; non-2xx responses uniformly throw ApiError; 204/empty body returns undefined. */
@@ -132,9 +137,10 @@ export async function apiFetchWithMeta<T>(
const headerDate = Date.parse(response.headers.get("date") ?? "");
const serverNowMs = Number.isFinite(headerDate) ? headerDate : null;
+ const etag = response.headers.get("etag");
- if (response.status === 204) return { data: undefined as T, serverNowMs };
+ if (response.status === 204) return { data: undefined as T, serverNowMs, etag };
const text = await response.text();
- if (!text) return { data: undefined as T, serverNowMs };
- return { data: JSON.parse(text) as T, serverNowMs };
+ if (!text) return { data: undefined as T, serverNowMs, etag };
+ return { data: JSON.parse(text) as T, serverNowMs, etag };
}
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index ae0fbaed..1e4bc30d 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -47,6 +47,7 @@ import type {
FeishuBindingResponse,
FeishuTestRequest,
FeishuTestResponse,
+ FilesCreateRequest,
FilesMoveRequest,
FilesStatRequest,
FilesStatResponse,
@@ -1313,26 +1314,36 @@ export const revealWorkspaceFile = (sessionId: string, path: string) =>
* `ETag`: pass it and the write is refused with 409 `file_changed` unless the file is still
* the one that was read (the editor's save); leave it out and the write creates or replaces
* unconditionally (uploads, which read no version).
+ *
+ * Resolves to the version the write produced — the marker the next save of the same file
+ * carries — or null from a server that does not say.
*/
export const uploadWorkspaceFile = (
sessionId: string,
path: string,
dataBase64: string,
ifVersion?: string,
-) =>
- apiFetch<void>(`/api/sessions/${sessionId}/files/content`, {
+): Promise<string | null> =>
+ apiFetchWithMeta<void>(`/api/sessions/${sessionId}/files/content`, {
method: "PUT",
body: { dataBase64, ifVersion } satisfies FilesWriteRequest,
query: { path },
- });
+ }).then((res) => res.etag);
+
+/**
+ * Creates one empty text file or one folder. Missing parent directories are made; anything
+ * already at the path is refused with 409 `target_exists` and nothing is written.
+ */
+export const createWorkspaceEntry = (sessionId: string, body: FilesCreateRequest) =>
+ apiFetch<void>(`/api/sessions/${sessionId}/files/create`, { method: "POST", body });
/**
- * Moves or renames a Workspace file. `ifVersion` (see {@link uploadWorkspaceFile}) guards the
- * SOURCE: pass it and the move is refused with 409 `file_changed` unless the file is still the
- * one that was read. The destination has no such marker — nothing read it — so an occupied
- * destination is 409 `target_exists` rather than an overwrite. Files only: a directory is a
- * 400, since nothing could express a precondition over a whole tree. `to`'s parent directory
- * is created when it is missing.
+ * Moves or renames a Workspace file or folder. `ifVersion` (see {@link uploadWorkspaceFile})
+ * guards a file SOURCE: pass it and the move is refused with 409 `file_changed` unless the file
+ * is still the one that was read. A folder moves whole and takes none. The destination has no
+ * such marker — nothing read it — so an occupied destination is 409 `target_exists` rather than
+ * an overwrite, and a folder cannot move into itself. `to`'s parent directory is created when it
+ * is missing.
*/
export const moveWorkspaceFile = (sessionId: string, body: FilesMoveRequest) =>
apiFetch<void>(`/api/sessions/${sessionId}/files/move`, { method: "POST", body });
@@ -1357,6 +1368,96 @@ export const deleteWorkspaceFile = (sessionId: string, path: string, ifVersion?:
export const searchWorkspaceFiles = (sessionId: string, q: string) =>
apiFetch<WorkspaceSearchResponse>(`/api/sessions/${sessionId}/files/search`, { query: { q } });
+// Workspace files by directory ----------------------------------------------------------------
+
+/**
+ * A directory the Files panel addresses by its absolute path rather than through a Session: the
+ * new-chat draft's chosen folder and a sidebar Workspace group, where no Session exists yet.
+ * Access is the Project's; the directory must exist. `machineId` is the machine it is on (null:
+ * this server) — a path names a directory only together with it.
+ */
+export interface WorkspaceDir {
+ projectId: string;
+ workspace: string;
+ machineId: string | null;
+}
+
+const workspaceDirBase = (dir: WorkspaceDir): string =>
+ `/api/projects/${encodeURIComponent(dir.projectId)}/workspace-files`;
+
+export const listWorkspaceDirFiles = (dir: WorkspaceDir, path: string) =>
+ apiFetch<WorkspaceFilesResponse>(workspaceDirBase(dir), {
+ query: { workspace: dir.workspace, path },
+ server: dir.machineId,
+ });
+
+/** File content URL, as {@link workspaceFileUrl}; the machine's proxy prefix rides in the URL itself. */
+export const workspaceDirFileUrl = (dir: WorkspaceDir, path: string, download = false): string =>
+ apiUrl(
+ `${workspaceDirBase(dir)}/content?workspace=${encodeURIComponent(dir.workspace)}&path=${encodeURIComponent(path)}${download ? "&download=1" : ""}`,
+ dir.machineId,
+ );
+
+/**
+ * "Open in a new tab" for an HTML file of a directory: the same-origin sandboxed preview, since
+ * the separate preview origin's tokens name a Session.
+ */
+export const workspaceDirPreviewUrl = (dir: WorkspaceDir, path: string): string =>
+ apiUrl(
+ `${workspaceDirBase(dir)}/content?workspace=${encodeURIComponent(dir.workspace)}&path=${encodeURIComponent(path)}&preview=1`,
+ dir.machineId,
+ );
+
+/** As {@link uploadWorkspaceFile}: resolves to the version written, or null when the server does not say. */
+export const writeWorkspaceDirFile = (
+ dir: WorkspaceDir,
+ path: string,
+ dataBase64: string,
+ ifVersion?: string,
+): Promise<string | null> =>
+ apiFetchWithMeta<void>(`${workspaceDirBase(dir)}/content`, {
+ method: "PUT",
+ body: { dataBase64, ifVersion } satisfies FilesWriteRequest,
+ query: { workspace: dir.workspace, path },
+ server: dir.machineId,
+ }).then((res) => res.etag);
+
+export const createWorkspaceDirEntry = (dir: WorkspaceDir, body: FilesCreateRequest) =>
+ apiFetch<void>(`${workspaceDirBase(dir)}/create`, {
+ method: "POST",
+ body,
+ query: { workspace: dir.workspace },
+ server: dir.machineId,
+ });
+
+export const moveWorkspaceDirFile = (dir: WorkspaceDir, body: FilesMoveRequest) =>
+ apiFetch<void>(`${workspaceDirBase(dir)}/move`, {
+ method: "POST",
+ body,
+ query: { workspace: dir.workspace },
+ server: dir.machineId,
+ });
+
+export const deleteWorkspaceDirFile = (dir: WorkspaceDir, path: string, ifVersion?: string) =>
+ apiFetch<void>(`${workspaceDirBase(dir)}/content`, {
+ method: "DELETE",
+ query: { workspace: dir.workspace, path, ifVersion },
+ server: dir.machineId,
+ });
+
+export const searchWorkspaceDirFiles = (dir: WorkspaceDir, q: string) =>
+ apiFetch<WorkspaceSearchResponse>(`${workspaceDirBase(dir)}/search`, {
+ query: { workspace: dir.workspace, q },
+ server: dir.machineId,
+ });
+
+export const revealWorkspaceDirFile = (dir: WorkspaceDir, path: string) =>
+ apiFetch<void>(`${workspaceDirBase(dir)}/reveal`, {
+ method: "POST",
+ query: { workspace: dir.workspace, path },
+ server: dir.machineId,
+ });
+
/** Batch file-existence check (message file cards): both out-of-bounds and missing paths simply don't appear in `existing`; always returns 200. */
export const statSessionFiles = (sessionId: string, paths: string[]) =>
apiFetch<FilesStatResponse>(`/api/sessions/${sessionId}/files/stat`, {
diff --git a/packages/web/src/api/workspace-files.ts b/packages/web/src/api/workspace-files.ts
new file mode 100644
index 00000000..be02ac17
--- /dev/null
+++ b/packages/web/src/api/workspace-files.ts
@@ -0,0 +1,90 @@
+/**
+ * Where the Files panel's operations go. The panel is addressed by a Workspace, and a Workspace
+ * is reached one of two ways:
+ *
+ * - through a Session (`/api/sessions/:id/files…`): the conversation's own Workspace, routed to
+ * the machine the Session lives on by the path rule (lib/session-machines.ts);
+ * - by the directory itself (`/api/projects/:projectId/workspace-files…?workspace=`): the
+ * new-chat draft's chosen folder and a sidebar Workspace group, where no Session exists yet,
+ * sent to the machine that directory is on — a path names a directory only together with it.
+ *
+ * The two answer the same operations with the same results, except that previews on the
+ * separate preview origin are a Session's alone (the origin's tokens name one): a directory's
+ * HTML previews in the same-origin sandbox, which is what the panel shows when isolation is off.
+ */
+import type {
+ FilesCreateRequest,
+ FilesMoveRequest,
+ WorkspaceFilesResponse,
+ WorkspaceSearchResponse,
+} from "@prismshadow/penguin-server/api";
+import * as api from "./endpoints";
+import type { WorkspaceDir } from "./endpoints";
+
+/** What the Files panel browses. */
+export type FilesScope =
+ { kind: "session"; sessionId: string } | ({ kind: "workspace" } & WorkspaceDir);
+
+/**
+ * One string per scope, equal for equal scopes: what the panel starts over on when it changes,
+ * and what its unsaved drafts are filed under. A directory's machine is part of its identity.
+ */
+export function filesScopeKey(scope: FilesScope): string {
+ return scope.kind === "session"
+ ? `session:${scope.sessionId}`
+ : `workspace:${scope.machineId ?? ""}\0${scope.workspace}`;
+}
+
+/** The panel's operations over one scope. */
+export interface FilesApi {
+ list(path: string): Promise<WorkspaceFilesResponse>;
+ /** A URL an <img>, an <a> or a fetch can use: inline, or as a download. */
+ fileUrl(path: string, download?: boolean): string;
+ /** "Open in a new tab" for an HTML file. */
+ previewUrl(path: string): string;
+ /** Whether the separate preview origin can serve this scope at all (a Session only). */
+ isolatablePreviews: boolean;
+ /** Writes a file whole; resolves to the version written, or null when the server does not say. */
+ write(path: string, dataBase64: string, ifVersion?: string): Promise<string | null>;
+ create(body: FilesCreateRequest): Promise<void>;
+ move(body: FilesMoveRequest): Promise<void>;
+ remove(path: string, ifVersion?: string): Promise<void>;
+ search(q: string): Promise<WorkspaceSearchResponse>;
+ reveal(path: string): Promise<void>;
+}
+
+/** The operations for `scope`. */
+export function filesApi(scope: FilesScope): FilesApi {
+ if (scope.kind === "session") {
+ const id = scope.sessionId;
+ return {
+ list: (path) => api.listWorkspaceFiles(id, path),
+ fileUrl: (path, download) => api.workspaceFileUrl(id, path, download),
+ previewUrl: (path) => api.workspaceFilePreviewUrl(id, path),
+ isolatablePreviews: true,
+ write: (path, data, ifVersion) => api.uploadWorkspaceFile(id, path, data, ifVersion),
+ create: (body) => api.createWorkspaceEntry(id, body),
+ move: (body) => api.moveWorkspaceFile(id, body),
+ remove: (path, ifVersion) => api.deleteWorkspaceFile(id, path, ifVersion),
+ search: (q) => api.searchWorkspaceFiles(id, q),
+ reveal: (path) => api.revealWorkspaceFile(id, path),
+ };
+ }
+ const dir: WorkspaceDir = {
+ projectId: scope.projectId,
+ workspace: scope.workspace,
+ machineId: scope.machineId,
+ };
+ return {
+ list: (path) => api.listWorkspaceDirFiles(dir, path),
+ fileUrl: (path, download) => api.workspaceDirFileUrl(dir, path, download),
+ previewUrl: (path) => api.workspaceDirPreviewUrl(dir, path),
+ isolatablePreviews: false,
+ write: (path, data, ifVersion) => api.writeWorkspaceDirFile(dir, path, data, ifVersion),
+ create: (body) => api.createWorkspaceDirEntry(dir, body),
+ move: (body) => api.moveWorkspaceDirFile(dir, body),
+ remove: (path, ifVersion) => api.deleteWorkspaceDirFile(dir, path, ifVersion),
+ search: (q) => api.searchWorkspaceDirFiles(dir, q),
+ reveal: (path) => api.revealWorkspaceDirFile(dir, path),
+ };
+}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index be282dad..bce7121e 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -203,6 +203,8 @@ import {
} from "../../features/chat/draft-sessions";
import type { DraftSessionEntry } from "../../features/chat/draft-sessions";
import { prepareNewChatDraft } from "../../features/chat/new-chat";
+import { docksOnScreen, openPanel } from "../../features/dock/dock-state";
+import { dockWorkspace } from "../../features/dock/dock-terminal";
import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";
import { UserMenu } from "./user-menu";
import { PinnedBalanceBadge } from "../../features/models/group-balance";
@@ -1318,7 +1320,8 @@ export function Sidebar({
agentId,
workspace,
machineId,
- }: { agentId?: string; workspace?: string; machineId?: string } = {}) => {
+ browseFiles,
+ }: { agentId?: string; workspace?: string; machineId?: string; browseFiles?: boolean } = {}) => {
// Typed-but-unsent text in the ACTIVE new-chat draft becomes a parked draft
// conversation first (a row in the list below, sendable anytime — draft-sessions.ts),
// so this click always lands on an empty composer and never silently shelves content;
@@ -1331,11 +1334,30 @@ export function Sidebar({
// different directory on every machine, so handing the composer one without the other
// is handing it a directory it cannot find.
...(workspace !== undefined ? { workspace, machineId } : {}),
+ // The chat page opens the dock's Files panel on arrival (a group's "Browse files").
+ ...(browseFiles === true ? { browseFiles } : {}),
};
navigate(`/chat/${DRAFT_SESSION_ID}`, Object.keys(state).length > 0 ? { state } : undefined);
onNavigate?.();
};
+ /**
+ * A Workspace group's "Browse files": the dock's Files panel on that directory. A page already
+ * on it — the open conversation's Workspace, or the folder the draft picked, on the same
+ * machine — only brings the panel up. Anywhere else lands on a new-chat draft for the folder,
+ * the group's "+", whose Files panel is addressed by the directory itself: the dock belongs to
+ * the conversation on screen, so a folder another conversation is in has no panel here.
+ */
+ const browseFiles = (path: string, machineId: string | null) => {
+ const here = dockWorkspace();
+ if (docksOnScreen() && here !== null && here.path === path && here.machineId === machineId) {
+ openPanel("workspace");
+ onNavigate?.();
+ return;
+ }
+ newChat({ workspace: path, ...(machineId ? { machineId } : {}), browseFiles: true });
+ };
+
/** Confirmed parked-draft deletion: drops the entry; a deleted draft that is open falls back to the plain new-chat page. */
const confirmDeleteDraft = () => {
if (!deletingDraft) return;
@@ -2671,19 +2693,25 @@ export function Sidebar({
>
<Icon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />
</button>
- {/* Manually-added (registry-backed) Workspaces only: rename-alias /
- remove-from-sidebar overflow, to the right of the "+" (session-
- derived groups have no registry entry for these to act on). */}
- {fullPath !== null && registeredKeys.has(group.key) && (
+ {/* A group that is one directory (not the merged temporary group):
+ the overflow right of the "+" — browse its files, and, for a
+ manually-added (registry-backed) Workspace, rename the alias or
+ remove it from the sidebar (session-derived groups have no
+ registry entry for those two to act on). */}
+ {fullPath !== null && (
<GroupOverflowMenu
- onRename={() => openRenameWorkspace(fullPath, group.machineId)}
- onDelete={() =>
- setDeletingWorkspace({
- path: fullPath,
- machineId: group.machineId,
- label: group.label,
- })
- }
+ onBrowse={() => browseFiles(fullPath, group.machineId)}
+ {...(registeredKeys.has(group.key)
+ ? {
+ onRename: () => openRenameWorkspace(fullPath, group.machineId),
+ onDelete: () =>
+ setDeletingWorkspace({
+ path: fullPath,
+ machineId: group.machineId,
+ label: group.label,
+ }),
+ }
+ : {})}
/>
)}
</>
@@ -3041,12 +3069,21 @@ function SidebarSessionRow({
}
/**
- * Registry-backed workspace group's overflow (… to the right of the header's "+"):
- * 重命名工作区 / 删除工作区 as small Menu rows, like the session row's menu. Sits among the
- * header's action buttons — outside the header's collapse toggle, so opening it never
- * expands/collapses the group. Body-portaled like every menu inside the scroller.
+ * A workspace group's overflow (… to the right of the header's "+"): 打开文件浏览, then — for a
+ * registry-backed group — 重命名工作区 / 删除工作区, as small Menu rows like the session row's
+ * menu. Sits among the header's action buttons — outside the header's collapse toggle, so
+ * opening it never expands/collapses the group. Body-portaled like every menu inside the
+ * scroller.
*/
-function GroupOverflowMenu({ onRename, onDelete }: { onRename: () => void; onDelete: () => void }) {
+function GroupOverflowMenu({
+ onBrowse,
+ onRename,
+ onDelete,
+}: {
+ onBrowse: () => void;
+ onRename?: () => void;
+ onDelete?: () => void;
+}) {
const [open, setOpen] = useState(false);
/** Close first, then act (the rename modal opens on top; the delete is immediate). */
const item = (fn: () => void) => () => {
@@ -3058,7 +3095,7 @@ function GroupOverflowMenu({ onRename, onDelete }: { onRename: () => void; onDel
open={open}
setOpen={setOpen}
portal={{ direction: "down", align: "right" }}
- menuClass="w-32"
+ menuClass="w-max min-w-32"
className="shrink-0"
button={
/* No hover pill on this trigger (user: color, not background, should carry the
@@ -3081,13 +3118,22 @@ function GroupOverflowMenu({ onRename, onDelete }: { onRename: () => void; onDel
}
>
<Menu density="sm">
- <MenuItem glyph={ICONS.pencil} label={S.chat.renameWorkspace} onSelect={item(onRename)} />
<MenuItem
- glyph={ICONS.trash}
- label={S.chat.deleteWorkspace}
- danger
- onSelect={item(onDelete)}
+ glyph={ICONS.folderOpen}
+ label={S.chat.browseWorkspaceFiles}
+ onSelect={item(onBrowse)}
/>
+ {onRename !== undefined && (
+ <MenuItem glyph={ICONS.pencil} label={S.chat.renameWorkspace} onSelect={item(onRename)} />
+ )}
+ {onDelete !== undefined && (
+ <MenuItem
+ glyph={ICONS.trash}
+ label={S.chat.deleteWorkspace}
+ danger
+ onSelect={item(onDelete)}
+ />
+ )}
</Menu>
</Dropdown>
);
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index ea0f7ffe..6c49673f 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -427,6 +427,38 @@ export function ChatPage() {
// below treats the two alike.
const parkedDraftId = parkedDraftIdOf(routeSessionId);
const draft = routeSessionId === DRAFT_SESSION_ID || parkedDraftId !== null;
+ /**
+ * The folder the draft has picked, and its machine — what the dock's Files panel browses
+ * while there is no Session to address it by. Null for a temporary Workspace, which has no
+ * directory until the first message makes one.
+ */
+ const [draftWorkspace, setDraftWorkspace] = useState<{
+ path: string;
+ machineId: string | null;
+ } | null>(null);
+ const onDraftWorkspace = useCallback((path: string, machineId: string | null) => {
+ const trimmed = path.trim();
+ setDraftWorkspace((prev) =>
+ trimmed === ""
+ ? null
+ : prev !== null && prev.path === trimmed && prev.machineId === machineId
+ ? prev
+ : { path: trimmed, machineId },
+ );
+ }, []);
+ // A Workspace group's "Browse files" in the sidebar lands on a draft for that folder and asks
+ // for the Files panel: opened once per navigation, in the draft's own dock scope (AppLayout
+ // points the dock at the route in a layout effect, which runs before this one).
+ const browseFilesKey =
+ draft && (location.state as { browseFiles?: boolean } | null)?.browseFiles === true
+ ? location.key
+ : null;
+ const openedForBrowse = useRef<string | null>(null);
+ useEffect(() => {
+ if (browseFilesKey === null || openedForBrowse.current === browseFilesKey) return;
+ openedForBrowse.current = browseFilesKey;
+ openPanel("workspace");
+ }, [browseFilesKey]);
/**
* The row the direct lookup below produced, kept beside the list: the list is replaced by
* every reload, and a row that only a lookup knows about (an organization's desk, a
@@ -1814,6 +1846,24 @@ export function ChatPage() {
// The browser is one set of pages shared by every conversation, not a Session's view,
// so it needs no Session and works on the draft page too.
if (kind === "builtin-browser") return <BuiltinBrowserPanel active={active} />;
+ // The draft's Files panel browses the folder picked in the composer, addressed by the
+ // directory itself; a temporary Workspace has none yet.
+ if (!selected && draft && kind === "workspace" && projectId) {
+ return draftWorkspace !== null ? (
+ <WorkspaceBrowser
+ scope={{
+ kind: "workspace",
+ projectId,
+ workspace: draftWorkspace.path,
+ machineId: draftWorkspace.machineId,
+ }}
+ active={active}
+ onAddReference={addComposerReference}
+ />
+ ) : (
+ <EmptyState title={panelLabel(kind)} description={S.files.draftTemporary} />
+ );
+ }
if (!selected)
return (
<EmptyState
@@ -1849,7 +1899,7 @@ export function ChatPage() {
case "workspace":
return (
<WorkspaceBrowser
- session={selected}
+ scope={{ kind: "session", sessionId: selected.sessionId }}
openRequest={fileOpenRequest}
active={active}
reloadSignal={settledTurnSignal}
@@ -2391,6 +2441,8 @@ export function ChatPage() {
projectId={projectId}
models={models}
{...(parkedDraftId !== null ? { draftId: parkedDraftId } : {})}
+ composerRef={composerRef}
+ onWorkspaceChange={onDraftWorkspace}
/>
) : (
// Keyed by Session: the whole block does a light fade-in when switching sessions.
diff --git a/packages/web/src/features/chat/dock-toggles.tsx b/packages/web/src/features/chat/dock-toggles.tsx
index 8d4e5c97..2fc76be9 100644
--- a/packages/web/src/features/chat/dock-toggles.tsx
+++ b/packages/web/src/features/chat/dock-toggles.tsx
@@ -8,6 +8,10 @@
* The pending-approval amber dot rides the toggle of the dock that holds the agents tab
* (the right one while the panel is closed — the default edge panels open on), keeping a
* nested approval discoverable while the panel is off screen.
+ *
+ * The new-chat draft has no toolbar, and the one panel it has a use for is Files, on the folder
+ * picked there: `FilesPanelToggle` is the same toggle, for that one panel, beside the draft's
+ * Workspace pill.
*/
import { useSyncExternalStore } from "react";
import { ICONS, PanelsToolbar } from "@prismshadow/penguin-ui";
@@ -17,11 +21,14 @@ import { useShortcutTitle } from "../../lib/shortcuts/use-keymap";
import {
dockVersion,
isDockVisible,
+ isTabShown,
+ openPanel,
panelDock,
subscribeDock,
toggleDock,
type DockPosition,
} from "../dock/dock-state";
+import { panelLabel } from "../dock/panel-meta";
export interface DockTogglesProps {
/** A pending approval inside a subagent: amber dot beside the agents tab's dock toggle. */
@@ -63,3 +70,34 @@ export function DockToggles({ agentsPending }: DockTogglesProps) {
/>
);
}
+
+/**
+ * The dock's Files panel, from the new-chat draft: pressed while the panel is on screen, it puts
+ * that panel's dock away; otherwise it brings the panel up where it lives (the right dock the
+ * first time). A temporary Workspace has no directory until the first message makes one, so
+ * there the toggle has nothing to open and says so.
+ */
+export function FilesPanelToggle({ available }: { available: boolean }) {
+ useSyncExternalStore(subscribeDock, dockVersion);
+ const label = panelLabel("workspace");
+ const shown = available && isTabShown("workspace");
+ return (
+ <PanelsToolbar
+ toggles={[
+ {
+ key: "files",
+ label,
+ tooltip: available ? label : S.files.draftTemporary,
+ glyph: ICONS.folderOpen,
+ active: shown,
+ unavailable: !available,
+ onToggle: () => {
+ const home = panelDock("workspace");
+ if (shown && home !== null) toggleDock(home);
+ else openPanel("workspace");
+ },
+ },
+ ]}
+ />
+ );
+}
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index a0fdee77..75de850b 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -38,6 +38,7 @@
* always survive.
*/
import { useCallback, useEffect, useRef, useState } from "react";
+import type { RefObject } from "react";
import { useLocation, useNavigate } from "react-router";
import type {
AgentModelConfigDto,
@@ -99,6 +100,7 @@ import {
import { newChatAgentId } from "./new-chat";
import { effectiveThinkingLevel } from "./thinking-level";
import { WorkspaceSelect, pillClass } from "./workspace-select";
+import { FilesPanelToggle } from "./dock-toggles";
import { sameModelRef } from "../models/model-grouping";
/** Coalescing window for writing body text to the cache: keystrokes are frequent, so a short batch accumulates before persisting (option changes are still written immediately). */
@@ -153,12 +155,21 @@ export function DraftView({
projectId,
models,
draftId,
+ composerRef: pageComposerRef,
+ onWorkspaceChange,
}: {
projectId: string;
/** Project model config (already fetched by ChatPage): candidate list and default model. */
models: ModelsResponse | null;
/** Parked draft conversation id (`/chat/draft-…` — see draft-sessions.ts); absent = the ordinary active draft (`/chat/new`). */
draftId?: string;
+ /**
+ * The page's handle on the composer, so what the dock's panels hand the conversation (the
+ * Files panel's references) reaches this draft's composer as it reaches a live Session's.
+ */
+ composerRef?: RefObject<ComposerControl | null>;
+ /** The Workspace picked here ("" = a temporary one) and its machine, for the Files panel. */
+ onWorkspaceChange?: (path: string, machineId: string | null) => void;
}) {
const navigate = useNavigate();
const location = useLocation();
@@ -217,7 +228,8 @@ export function DraftView({
// that case falls back to home (setDockCwd's null).
useEffect(() => {
setDockCwd(workspace || null, workspaceMachine);
- }, [workspace, workspaceMachine]);
+ onWorkspaceChange?.(workspace, workspaceMachine);
+ }, [workspace, workspaceMachine, onWorkspaceChange]);
const [approvalMode, setApprovalMode] = useState<ApprovalMode>(
cached.approvalMode ?? "allow-all",
);
@@ -821,7 +833,8 @@ export function DraftView({
* in-flight guard to keep here, and everything else — where the prompt goes when text is
* already typed, focus, the caret — is the composer's, reached through this handle.
*/
- const composerRef = useRef<ComposerControl | null>(null);
+ const ownComposerRef = useRef<ComposerControl | null>(null);
+ const composerRef = pageComposerRef ?? ownComposerRef;
const fillExample = useCallback((task: ExampleTask) => {
// S is a live binding swapped on locale change: read the prompt at click time, not at render.
composerRef.current?.fillPrompt(S.chat.exampleTasks[task.id].prompt, task.skills);
@@ -933,6 +946,9 @@ export function DraftView({
chooseMachine
{...(agentId ? { agentId } : {})}
/>
+ {/* The dock's Files panel on the folder picked beside it; a temporary Workspace has
+ none yet (see FilesPanelToggle). */}
+ <FilesPanelToggle available={workspace.trim() !== ""} />
</div>
{/* Example tasks: canned builds showing off the one-sentence → app flow; a click fills
diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsx
index ccf17e06..bee899c0 100644
--- a/packages/web/src/features/chat/workspace-browser.tsx
+++ b/packages/web/src/features/chat/workspace-browser.tsx
@@ -5,8 +5,16 @@
* (click to zoom), PDF embedded, everything else offered as a download. Text files can be
* edited in place: Edit swaps the preview for a plain textarea, Save writes the file back
* through the content endpoint, and unsaved changes are guarded wherever they could be
- * lost. OS files dropped anywhere on the panel upload into the current directory — onto a
- * folder row, into that folder.
+ * lost. The editor keeps its place as a code editor does — it opens where the preview was
+ * scrolled, a save leaves it open with caret and scroll untouched, and when a finished turn
+ * rewrote the file under an editor holding nothing unsaved, it takes the new text in place.
+ * OS files dropped anywhere on the panel upload into the current directory — onto a folder
+ * row, into that folder. New text files and folders are made from the tree header's New
+ * menu, a folder's menu or the blank space under the tree; folders rename and move whole.
+ *
+ * The panel is addressed by its scope (api/workspace-files.ts): a Session's Workspace on the
+ * chat page, or a directory named by its path on the new-chat draft, where no Session exists
+ * yet. Everything below follows the scope; a new scope starts the panel over.
*
* A search box above the tree filters the rows the lazy tree has already loaded. The tree
* can be hidden (toolbar toggle, shown by default), and the divider between the two panes
@@ -65,6 +73,7 @@ import {
TreePane,
WorkspaceFileEditor,
WorkspaceFileMenuRows,
+ WorkspaceNewMenuRows,
isContextMenuKey,
isLongPressPointer,
languageForFileName,
@@ -76,14 +85,16 @@ import {
useRowContextMenu,
} from "@prismshadow/penguin-ui";
import type {
+ EditorScroll,
FileMenuTarget,
PreviewView,
TreeToggle,
WorkspaceFileMenuLabels,
} from "@prismshadow/penguin-ui";
-import type { SessionInfo, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";
-import * as api from "../../api/endpoints";
+import type { WorkspaceSearchHit } from "@prismshadow/penguin-server/api";
import { ApiError } from "../../api/client";
+import { filesApi, filesScopeKey } from "../../api/workspace-files";
+import type { FilesScope } from "../../api/workspace-files";
import { useAuth } from "../../state/auth";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
@@ -98,6 +109,7 @@ import { dropRegionAction, isFileDrag } from "../../lib/file-drop";
import type { DragSignal } from "../../lib/file-drop";
import { MB_BYTES, splitBySize } from "../../lib/upload-limits";
import {
+ DEFAULT_TEXT_FILE_NAME,
TEXT_PREVIEW_LIMIT,
TREE_MIN_WIDTH,
WORKSPACE_UPLOAD_LIMIT_MB,
@@ -112,9 +124,14 @@ import {
flattenTree,
isDirty,
isNarrowLayout,
+ isWithin,
looksLikeText,
maxTreeWidth,
+ movedListings,
+ movedPath,
+ movedSet,
needsDiscardConfirm,
+ newEntryName,
parentDir,
pathReference,
previewKindFor,
@@ -122,6 +139,7 @@ import {
readTreeVisible,
readTreeWidth,
selectionBlock,
+ stemEnd,
upsertEntry,
utf8Complete,
withExpanded,
@@ -211,15 +229,15 @@ interface Preview {
let previewSeq = 0;
/**
- * Unsaved editor drafts by Session and path, kept for the app's lifetime and written through
- * on every keystroke. Hiding the panel or its dock keeps this component mounted, draft and
- * all; what the map is for are the paths no confirm dialog can intercept, where the body
- * really is unmounted — a tab dragged to the other edge, a Session switched from the
- * sidebar. The draft outlives the component: opening the same file again reopens the
- * editor on it.
+ * Unsaved editor drafts by scope (a Session, or a directory — see filesScopeKey) and path,
+ * kept for the app's lifetime and written through on every keystroke. Hiding the panel or its
+ * dock keeps this component mounted, draft and all; what the map is for are the paths no
+ * confirm dialog can intercept, where the body really is unmounted — a tab dragged to the
+ * other edge, a Session switched from the sidebar. The draft outlives the component: opening
+ * the same file again reopens the editor on it.
*/
const unsavedDrafts = new Map<string, string>();
-const draftKey = (sessionId: string, path: string): string => `${sessionId}\n${path}`;
+const draftKey = (scopeKey: string, path: string): string => `${scopeKey}\n${path}`;
/**
* Reads a file as text, bounded to TEXT_PREVIEW_LIMIT bytes: the body is read as a stream
@@ -313,12 +331,22 @@ function hitRow(
}
/**
- * Why the confirm button is not offered yet. The action needs the file's current version, and
+ * The tree's blank space under the rows, or null: a gesture inside the tree that lands on no
+ * row. The search box sits above the tree, outside it, and so never counts.
+ */
+function hitBlank(target: EventTarget | null): HTMLElement | null {
+ if (!(target instanceof Element) || hitRow(target) !== null) return null;
+ return target.closest<HTMLElement>('[role="tree"]');
+}
+
+/**
+ * Why the confirm button is not offered yet. A file's action needs its current version, and
* until that read lands there is nothing to refuse an overwrite with — so the dialog says which
- * of the two it is rather than leaving a dead button with no explanation.
+ * of the two it is rather than leaving a dead button with no explanation. A folder has no
+ * version to wait for.
*/
function FileActionVersionNote({ target }: { target: FileActionTarget | null }) {
- if (target === null || target.version !== null) return null;
+ if (target === null || target.kind === "dir" || target.version !== null) return null;
return (
<p
className={`text-xs ${target.reading ? "text-gray-500 dark:text-gray-400" : toneInk.danger}`}
@@ -328,15 +356,22 @@ function FileActionVersionNote({ target }: { target: FileActionTarget | null })
);
}
-/** A file a rename or a delete has been asked about, and how far the read of its version got. */
+/** An entry a rename or a delete has been asked about, and how far the read of its version got. */
interface FileActionTarget {
path: string;
- /** Non-null once the version is known; the action is refused until then. */
+ /** A folder has no version marker: it is renamed whole, with nothing to read first. */
+ kind: "file" | "dir";
+ /** Non-null once a file's version is known; a file's action is refused until then. */
version: string | null;
/** True while the read is still in flight — which is what tells "not yet" from "could not". */
reading: boolean;
}
+/** Whether the dialog's action can run: a folder's at once, a file's once its version is known. */
+function actionReady(target: FileActionTarget | null): boolean {
+ return target !== null && (target.kind === "dir" || target.version !== null);
+}
+
/** A selection the preview offered to the conversation, with the source lines it covers when they could be resolved. */
interface PreviewSelection {
text: string;
@@ -424,13 +459,17 @@ const iconToggleClass = (on: boolean): string =>
`${iconActionBase} ${on ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100" : iconActionIdle}`;
export function WorkspaceBrowser({
- session,
+ scope,
openRequest,
active,
reloadSignal,
onAddReference,
}: {
- session: SessionInfo;
+ /**
+ * The Workspace on screen: a Session's (the chat page), or a directory named by its path (the
+ * new-chat draft's chosen folder). Changing it starts the panel over, as a Session switch does.
+ */
+ scope: FilesScope;
/** External navigation command (from clicking a file chip in a message): opens the tree
* down to that path and previews it. Triggers again whenever the object reference changes,
* even if path is the same as last time (clicking the same file again must still re-locate it). */
@@ -464,17 +503,25 @@ 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, desktopMode, sessionVia } = useAuth();
+ const { previewIsolated: serverPreviewIsolated, desktopMode, sessionVia } = useAuth();
const saveShortcut = useShortcutLabel("editor.save");
// 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 scopeKey = filesScopeKey(scope);
+ // Keyed by the scope's identity, not the object: the parent builds a fresh one every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const files = useMemo(() => filesApi(scope), [scopeKey]);
+ const filesRef = useRef(files);
+ filesRef.current = files;
+ const scopeKeyRef = useRef(scopeKey);
+ scopeKeyRef.current = scopeKey;
+ // A directory scope has no separate preview origin (its tokens name a Session), so its HTML
+ // takes the same-origin sandbox the panel falls back to whenever isolation is off.
+ const previewIsolated = serverPreviewIsolated && files.isolatablePreviews;
const previewIsolatedRef = useRef(previewIsolated);
previewIsolatedRef.current = previewIsolated;
- const sessionId = session.sessionId;
- const sessionIdRef = useRef(sessionId);
- sessionIdRef.current = sessionId;
// ------------------------------------------------------------------------------- tree
const [listings, setListings] = useState<Listings>(() => new Map());
@@ -563,11 +610,26 @@ export function WorkspaceBrowser({
// hundreds of rows — twice over while a closing subtree animates out. The row a gesture
// landed on is resolved from the event instead, and held here for as long as its menu is up.
const treeMenu = useRowContextMenu();
- const [treeMenuTarget, setTreeMenuTarget] = useState<FileMenuTarget | null>(null);
+ /** A row the menu was opened on, or the blank space under the rows ("blank": the root). */
+ const [treeMenuTarget, setTreeMenuTarget] = useState<FileMenuTarget | "blank" | null>(null);
+ /** The tree header's New menu. */
+ const [newMenuOpen, setNewMenuOpen] = useState(false);
+ /** The New dialog: what it creates, in which directory, and the name typed so far. */
+ const [createTarget, setCreateTarget] = useState<{ kind: "file" | "dir"; dir: string } | null>(
+ null,
+ );
+ const [createName, setCreateName] = useState("");
+ const [creating, setCreating] = useState(false);
const previewMenu = useRowContextMenu();
/** The selection the preview's menu was opened over; null when there was none inside it. */
const [menuSelection, setMenuSelection] = useState<PreviewSelection | null>(null);
const previewBodyRef = useRef<HTMLDivElement | null>(null);
+ /** Where the source view was scrolled when Edit was pressed: the editor opens there. */
+ const editorOpening = useRef<EditorScroll | undefined>(undefined);
+ /** The editor's scroll box, read on the way out of the editor. */
+ const editorHost = useRef<HTMLDivElement | null>(null);
+ /** Where the source view takes up once it is back on screen after the editor. */
+ const bodyScrollOnReturn = useRef<EditorScroll | null>(null);
/** The directory the menu's own picker uploads into (the toolbar's picker always means the current one). */
const menuUploadDir = useRef("");
const menuUploadRef = useRef<HTMLInputElement | null>(null);
@@ -591,16 +653,16 @@ export function WorkspaceBrowser({
/** Newest request per directory: only it may publish, so a slow older listing cannot overwrite a newer one. */
const dirSeq = useRef(new Map<string, number>());
- // Session switched: back to a fresh root with no preview. Reset during render (React's
- // documented "adjust state when a prop changes" pattern), not in an effect — an
- // effect-based reset lets one frame commit in which the old session's preview renders
- // against the new session, flipping the isolated iframe's src to the new session + the
- // old path and firing a doomed request. Bumping previewSeq also invalidates any
- // in-flight previewPath from the old session (its present() guard fails). An editor
- // draft survives in unsavedDrafts and comes back when the file is opened again.
- const [renderedSessionId, setRenderedSessionId] = useState(sessionId);
- if (renderedSessionId !== sessionId) {
- setRenderedSessionId(sessionId);
+ // Scope changed (another Session, or the draft's folder re-picked): back to a fresh root with
+ // no preview. Reset during render (React's documented "adjust state when a prop changes"
+ // pattern), not in an effect — an effect-based reset lets one frame commit in which the old
+ // scope's preview renders against the new one, flipping the isolated iframe's src to the new
+ // session + the old path and firing a doomed request. Bumping previewSeq also invalidates
+ // any in-flight previewPath from the old scope (its present() guard fails). An editor draft
+ // survives in unsavedDrafts and comes back when the file is opened again.
+ const [renderedScopeKey, setRenderedScopeKey] = useState(scopeKey);
+ if (renderedScopeKey !== scopeKey) {
+ setRenderedScopeKey(scopeKey);
setListings(new Map());
setExpanded(new Set());
setLoadingDirs(new Set());
@@ -630,6 +692,10 @@ export function WorkspaceBrowser({
previewMenu.close();
setTreeMenuTarget(null);
setMenuSelection(null);
+ setNewMenuOpen(false);
+ setCreateTarget(null);
+ setRenameTarget(null);
+ setRemoveTarget(null);
previewSeq++;
}
@@ -661,13 +727,13 @@ export function WorkspaceBrowser({
*/
const loadDir = useCallback(
async (dir: string): Promise<boolean> => {
- const sid = sessionId;
+ const key = scopeKey;
const seq = (dirSeq.current.get(dir) ?? 0) + 1;
dirSeq.current.set(dir, seq);
- const current = () => sessionIdRef.current === sid && dirSeq.current.get(dir) === seq;
+ const current = () => scopeKeyRef.current === key && dirSeq.current.get(dir) === seq;
setLoadingDirs((s) => new Set(s).add(dir));
try {
- const res = await api.listWorkspaceFiles(sid, dir);
+ const res = await files.list(dir);
if (!current()) return false;
setListings((m) => new Map(m).set(dir, res.entries));
if (dir === "") setRootError(null);
@@ -698,7 +764,7 @@ export function WorkspaceBrowser({
}
}
},
- [sessionId],
+ [scopeKey, files],
);
useEffect(() => {
@@ -732,7 +798,7 @@ export function WorkspaceBrowser({
const previewPath = useCallback(
async (filePath: string, opts?: { refresh?: boolean }) => {
const refresh = opts?.refresh === true;
- const sid = sessionId;
+ const key = scopeKey;
const name = baseName(filePath);
const kind = previewKindFor(name);
const nonce = ++previewSeq;
@@ -740,7 +806,7 @@ export function WorkspaceBrowser({
* two rapid calls interleave across the await, and the late loser must not
* overwrite the winner's preview. */
const present = (p: Preview) => {
- if (nonce === previewSeq && sessionIdRef.current === sid) setPreview(p);
+ if (nonce === previewSeq && scopeKeyRef.current === key) setPreview(p);
};
if (!refresh) {
setRichView("rendered");
@@ -769,10 +835,7 @@ export function WorkspaceBrowser({
// defense); this fetches the raw content back for text/Markdown previews and for
// the srcDoc fallback rendered view of non-isolated HTML. A name that says nothing
// about the type is sniffed: text opens as text, anything else stays a download.
- const result = await fetchTextPreview(
- api.workspaceFileUrl(sid, filePath),
- kind === "unknown",
- );
+ const result = await fetchTextPreview(files.fileUrl(filePath), kind === "unknown");
if (result === null) {
if (!refresh) present({ path: filePath, name, kind: "unsupported", nonce });
return;
@@ -798,13 +861,14 @@ export function WorkspaceBrowser({
!refresh &&
!truncated &&
nonce === previewSeq &&
- sessionIdRef.current === sid &&
+ scopeKeyRef.current === key &&
editorRef.current?.path !== filePath
) {
- const key = draftKey(sid, filePath);
- const stashed = unsavedDrafts.get(key);
- if (stashed === content) unsavedDrafts.delete(key);
+ const stashKey = draftKey(key, filePath);
+ const stashed = unsavedDrafts.get(stashKey);
+ if (stashed === content) unsavedDrafts.delete(stashKey);
else if (stashed !== undefined) {
+ editorOpening.current = undefined;
setEditor({ path: filePath, baseline: content, draft: stashed, version });
toastInfo(S.files.unsavedRestored(name));
}
@@ -815,7 +879,7 @@ export function WorkspaceBrowser({
if (!refresh) present({ path: filePath, name, kind: "unsupported", nonce });
}
},
- [sessionId],
+ [scopeKey, files],
);
// Lazy source fetch for isolated HTML previews: previewPath mounted the iframe without
@@ -831,7 +895,7 @@ export function WorkspaceBrowser({
setSourceError(null);
void (async () => {
try {
- const result = await fetchTextPreview(api.workspaceFileUrl(sessionId, target), false);
+ const result = await fetchTextPreview(files.fileUrl(target), false);
if (cancelled || result === null) return;
// Functional update with its own guard (not `present`): this must only fill the
// still-current, still-contentless HTML preview for the same path, never revive
@@ -853,7 +917,7 @@ export function WorkspaceBrowser({
return () => {
cancelled = true;
};
- }, [preview, richView, previewIsolated, sessionId]);
+ }, [preview, richView, previewIsolated, files]);
// -------------------------------------------------------------- navigation and guards
@@ -864,7 +928,7 @@ export function WorkspaceBrowser({
const discardEditor = useCallback(() => {
const current = editorRef.current;
- if (current !== null) unsavedDrafts.delete(draftKey(sessionIdRef.current, current.path));
+ if (current !== null) unsavedDrafts.delete(draftKey(scopeKeyRef.current, current.path));
setEditor(null);
}, []);
@@ -889,76 +953,113 @@ export function WorkspaceBrowser({
);
/**
- * Puts one of the two file actions on screen and starts reading the file's current version.
+ * Puts one of the two entry actions on screen and, for a file, starts reading its current
+ * version.
*
* The dialog opens first and the version lands in it: waiting for a round trip before showing
* anything would make a menu click feel broken. A dirty editor is asked about before either,
- * through the same guard navigation uses — both actions move the file out from under it.
+ * through the same guard navigation uses, when the action moves its file out from under it: a
+ * file's always, a folder's when the file being edited lies inside it.
*/
const beginFileAction = useCallback(
- (path: string, kind: "rename" | "delete") => {
- void navigateGuarded(null, () => {
- const opened: FileActionTarget = { path, version: null, reading: true };
- if (kind === "rename") {
+ (path: string, action: "rename" | "delete", kind: "file" | "dir" = "file") => {
+ const open = () => {
+ const opened: FileActionTarget = { path, kind, version: null, reading: kind === "file" };
+ if (action === "rename") {
setRenameDraft(path);
setRenameTarget(opened);
} else {
setRemoveTarget(opened);
}
+ if (kind === "dir") return;
const settle = (version: string | null) => {
const next = (t: FileActionTarget | null): FileActionTarget | null =>
- t !== null && t.path === path ? { path, version, reading: false } : t;
- if (kind === "rename") setRenameTarget(next);
+ t !== null && t.path === path ? { path, kind, version, reading: false } : t;
+ if (action === "rename") setRenameTarget(next);
else setRemoveTarget(next);
};
- void fetchFileVersion(api.workspaceFileUrl(sessionIdRef.current, path))
+ void fetchFileVersion(filesRef.current.fileUrl(path))
.then(settle)
.catch(() => settle(null));
- });
+ };
+ const editing = editorRef.current;
+ if (kind === "dir" && (editing === null || !isWithin(editing.path, path))) open();
+ else void navigateGuarded(null, open);
},
[navigateGuarded],
);
/**
- * Reports the one failure both actions share. Nothing was changed, so this is a toast and not
- * a dialog: there is no decision left to take, only the same action again on the file as it
- * now is.
+ * Reports the failures the entry actions share. Nothing was changed, so this is a toast and
+ * not a dialog: there is no decision left to take, only the same action again on the entry as
+ * it now is.
*/
- const reportFileActionError = (err: unknown, path: string): void => {
+ const reportFileActionError = (err: unknown, path: string, to?: string): void => {
if (err instanceof ApiError && err.code === "file_changed") {
toastError(S.files.changedBeforeAction(baseName(path)));
- } else if (err instanceof ApiError && err.code === "target_exists") {
- toastError(S.files.renameTargetExists(renameDraft.trim()));
+ } else if (err instanceof ApiError && err.code === "target_exists" && to !== undefined) {
+ toastError(S.files.targetExists(to));
} else {
toastError(apiErrorText(err));
}
};
+ /**
+ * The entry did not stop existing, it moved, and the panel follows it rather than emptying:
+ * the open folders, their loaded listings, the current directory and the selection carry over
+ * to the new path, a file on screen is read again there, and a draft stashed for a file that
+ * moved goes with it. The listings are re-read from the new paths — the refs are brought
+ * forward first, since the refresh reads them before the state lands.
+ */
+ const followMove = (from: string, to: string): void => {
+ const expandedNext = movedSet(expandedRef.current, from, to);
+ const listingsNext = movedListings(listingsRef.current, from, to);
+ expandedRef.current = expandedNext;
+ listingsRef.current = listingsNext;
+ setExpanded(expandedNext);
+ setListings(listingsNext);
+ const selectedNext = selectedPath === null ? null : movedPath(selectedPath, from, to);
+ if (selectedNext !== null) {
+ setSelectedPath(selectedNext);
+ setCurrentDir(parentDir(selectedNext));
+ } else {
+ const dirNext = movedPath(currentDirRef.current, from, to);
+ if (dirNext !== null) setCurrentDir(dirNext);
+ }
+ const open = previewRef.current?.path;
+ const openNext = open === undefined ? null : movedPath(open, from, to);
+ if (openNext !== null) void previewPath(openNext, { refresh: true });
+ const prefix = draftKey(scopeKey, "");
+ for (const [key, text] of [...unsavedDrafts]) {
+ const next = key.startsWith(prefix) ? movedPath(key.slice(prefix.length), from, to) : null;
+ if (next === null) continue;
+ unsavedDrafts.delete(key);
+ unsavedDrafts.set(draftKey(scopeKey, next), text);
+ }
+ refreshAll();
+ void locate(selectedNext ?? to);
+ };
+
const applyRename = async (): Promise<void> => {
const target = renameTarget;
- const to = renameDraft.trim();
- if (target === null || target.version === null || fileActionBusy) return;
+ const to = newEntryName(renameDraft);
+ if (target === null || !actionReady(target) || fileActionBusy) return;
if (to === "" || to === target.path) {
setRenameTarget(null);
return;
}
setFileActionBusy(true);
try {
- await api.moveWorkspaceFile(sessionIdRef.current, {
+ await files.move({
from: target.path,
to,
- ifVersion: target.version,
+ ...(target.kind === "file" && target.version !== null ? { ifVersion: target.version } : {}),
});
setRenameTarget(null);
- // The file did not stop existing, it moved: the panel follows it rather than emptying.
- if (selectedPath === target.path) {
- setSelectedPath(to);
- setCurrentDir(parentDir(to));
- }
- refreshAll();
+ followMove(target.path, to);
toastSuccess(S.files.renamed(baseName(to)));
} catch (err) {
- reportFileActionError(err, target.path);
+ reportFileActionError(err, target.path, to);
} finally {
setFileActionBusy(false);
}
@@ -969,7 +1070,7 @@ export function WorkspaceBrowser({
if (target === null || target.version === null || fileActionBusy) return;
setFileActionBusy(true);
try {
- await api.deleteWorkspaceFile(sessionIdRef.current, target.path, target.version);
+ await filesRef.current.remove(target.path, target.version);
setRemoveTarget(null);
if (selectedPath === target.path) setSelectedPath(null);
refreshAll();
@@ -995,9 +1096,9 @@ export function WorkspaceBrowser({
d === dir || !listingsRef.current.has(d) ? loadDir(d) : Promise.resolve(true),
),
);
- if (sessionIdRef.current === sessionId) setScrollTo({ path });
+ if (scopeKeyRef.current === scopeKey) setScrollTo({ path });
},
- [loadDir, sessionId],
+ [loadDir, scopeKey],
);
/** Selects a file in the tree and previews it; `locate` additionally loads the way down to it (an external open request). */
@@ -1019,10 +1120,12 @@ export function WorkspaceBrowser({
// the first run (the mount already read it) and while no preview is open. Reading the path
// from a ref keeps this effect keyed on the signal alone.
//
- // The file being edited is still not re-read — that would put the Agent's text under the
- // user's hands. It is version-checked instead: the save can no longer clobber the Agent's
- // write, but silence until then would leave the user typing into a file that has already
- // moved, so the editor says so as soon as the turn lands.
+ // The file being edited is version-checked first. An editor holding nothing of the user's
+ // follows the file the way a code editor does: it takes the Agent's text, and the editor
+ // keeps the caret's line and the scroll (WorkspaceFileEditor). One with unsaved changes is
+ // never re-read — that would put the Agent's text under the user's hands — but silence until
+ // the save would leave the user typing into a file that has already moved, so the editor says
+ // so as soon as the turn lands, and the save's precondition turns into the conflict question.
const lastReloadSignal = useRef(reloadSignal);
useEffect(() => {
if (reloadSignal === lastReloadSignal.current) return;
@@ -1035,18 +1138,48 @@ export function WorkspaceBrowser({
void previewPath(open, { refresh: true });
return;
}
- const sid = sessionIdRef.current;
+ const key = scopeKeyRef.current;
+ const source = filesRef.current;
+ const flagChanged = (version: string) =>
+ // Compared against the editor as it stands now, not the one captured above: it may have
+ // been closed and reopened on the Agent's own version while this was in flight, and that
+ // editor is not stale.
+ setEditor((e) =>
+ e !== null && e.path === open && e.version !== version && scopeKeyRef.current === key
+ ? { ...e, changedOnDisk: true }
+ : e,
+ );
void (async () => {
try {
- const version = await fetchFileVersion(api.workspaceFileUrl(sid, open));
- if (version === null) return;
- // Compared against the editor as it stands now, not the one captured above: it may
- // have been closed and reopened on the Agent's own version while this was in flight,
- // and that editor is not stale.
- setEditor((e) =>
- e !== null && e.path === open && e.version !== version && sessionIdRef.current === sid
- ? { ...e, changedOnDisk: true }
- : e,
+ const version = await fetchFileVersion(source.fileUrl(open));
+ if (version === null || editorRef.current?.version === version) return;
+ if (isDirty(editorRef.current)) {
+ flagChanged(version);
+ return;
+ }
+ const result = await fetchTextPreview(source.fileUrl(open), false);
+ if (scopeKeyRef.current !== key) return;
+ // A file grown past what the editor can hold whole cannot be taken in: say it moved.
+ if (result === null || result.truncated) {
+ flagChanged(version);
+ return;
+ }
+ setEditor((e) => {
+ if (e === null || e.path !== open || e.version === result.version) return e;
+ // Typed into while the read was in flight: the text is the user's now.
+ if (isDirty(e)) return { ...e, changedOnDisk: true };
+ return {
+ ...e,
+ baseline: result.content,
+ draft: result.content,
+ version: result.version,
+ changedOnDisk: false,
+ };
+ });
+ setPreview((p) =>
+ p !== null && p.path === open
+ ? { ...p, content: result.content, truncated: false, version: result.version }
+ : p,
);
} catch {
// A failed probe says nothing; the save's precondition is the guarantee.
@@ -1135,8 +1268,8 @@ export function WorkspaceBrowser({
}
const run = (searchSeq.current += 1);
const timer = setTimeout(() => {
- void api
- .searchWorkspaceFiles(sessionId, needle)
+ void files
+ .search(needle)
.then((res) => {
if (searchSeq.current !== run) return;
setSearchResult({ hits: res.hits, truncated: res.truncated });
@@ -1149,7 +1282,7 @@ export function WorkspaceBrowser({
});
}, SEARCH_DEBOUNCE_MS);
return () => clearTimeout(timer);
- }, [query, sessionId]);
+ }, [query, files]);
const openDirForFilter = useCallback(
(dir: string) => {
@@ -1188,9 +1321,16 @@ export function WorkspaceBrowser({
// ----------------------------------------------------------------------------- editing
+ /**
+ * Opens the editor on the file in the preview, where the preview was: the source view's
+ * scroll is read before anything awaits, and the editor opens at it with the caret at the
+ * start of the first line in view (WorkspaceFileEditor), so Edit moves nothing on screen.
+ */
const startEdit = async (): Promise<void> => {
const current = previewRef.current;
if (current === null || !canEditPreview(current)) return;
+ const body = previewBodyRef.current;
+ const at = body === null ? undefined : { top: body.scrollTop, left: body.scrollLeft };
// Content and version are read together and stored together, so one missing means both
// are: an isolated HTML preview mounted without its text. Read it now, and refuse a
// file the bounded read cannot hold whole — saving a partial text back would truncate
@@ -1199,7 +1339,7 @@ export function WorkspaceBrowser({
let version = current.version;
if (content === undefined || version === undefined) {
try {
- const result = await fetchTextPreview(api.workspaceFileUrl(sessionId, current.path), false);
+ const result = await fetchTextPreview(files.fileUrl(current.path), false);
if (result === null || result.truncated) {
toastError(S.files.editTooLarge(TEXT_PREVIEW_LIMIT / 1024));
return;
@@ -1216,14 +1356,26 @@ export function WorkspaceBrowser({
}
}
if (previewRef.current?.path !== current.path) return;
+ editorOpening.current = at;
setEditor({ path: current.path, baseline: content, draft: content, version });
};
+ // A file the New dialog just made: the editor opens on it as soon as its preview lands. Read
+ // off the committed preview, since that is what startEdit opens the editor on.
+ const editOnOpen = useRef<string | null>(null);
+ useEffect(() => {
+ if (preview === null || editOnOpen.current !== preview.path) return;
+ editOnOpen.current = null;
+ if (editorRef.current === null) void startEdit();
+ // startEdit is this render's own; the preview landing is the only trigger.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [preview]);
+
const updateDraft = (draft: string): void => {
const current = editorRef.current;
if (current === null) return;
setEditor({ ...current, draft });
- const key = draftKey(sessionId, current.path);
+ const key = draftKey(scopeKey, current.path);
if (draft === current.baseline) unsavedDrafts.delete(key);
else unsavedDrafts.set(key, draft);
};
@@ -1248,37 +1400,51 @@ export function WorkspaceBrowser({
* server refuses it (409) if the file has been rewritten since — the conflict dialog then
* offers `overwrite`, which is the same write with no precondition. The draft is never
* dropped on a refusal: the editor stays exactly as the user left it.
+ *
+ * A save that lands leaves the editor open, as a code editor does: nothing remounts it, so
+ * the caret, the selection and the scroll stay where they were. What was written becomes the
+ * baseline — anything typed while the write was in flight stays unsaved on top of it — and
+ * the version the write produced is the next save's precondition. A server that reports no
+ * version leaves nothing safe to save against, so there the editor closes and the next Edit
+ * reads the file again.
*/
const save = async (opts?: { overwrite?: boolean }): Promise<void> => {
setSaveConfirm(false);
setConflict(null);
const current = editorRef.current;
if (current === null) return;
- const blob = new Blob([current.draft]);
+ const sent = current.draft;
+ const blob = new Blob([sent]);
if (blob.size > WORKSPACE_UPLOAD_LIMIT_MB * MB_BYTES) {
toastError(S.files.saveTooLarge(WORKSPACE_UPLOAD_LIMIT_MB));
return;
}
- const sid = sessionId;
+ const key = scopeKey;
setSaving(true);
try {
- await api.uploadWorkspaceFile(
- sid,
+ const written = await files.write(
current.path,
await blobToBase64(blob),
opts?.overwrite ? undefined : current.version,
);
- if (sessionIdRef.current !== sid) return;
- unsavedDrafts.delete(draftKey(sid, current.path));
- setEditor(null);
- // The preview now shows what was written; a fresh nonce remounts an HTML iframe onto it.
- // The bytes are known, the version the write produced is not — it is dropped rather
- // than kept at its pre-save value, which would make the next Edit save against a
- // version the file has already left. startEdit re-reads when it finds none.
+ if (scopeKeyRef.current !== key) return;
+ const stash = draftKey(key, current.path);
+ if (written === null) {
+ unsavedDrafts.delete(stash);
+ setEditor(null);
+ } else {
+ setEditor((e) =>
+ e !== null && e.path === current.path
+ ? { ...e, baseline: sent, version: written, changedOnDisk: false }
+ : e,
+ );
+ if (editorRef.current?.draft === sent) unsavedDrafts.delete(stash);
+ }
+ // The preview holds what was written; a fresh nonce remounts an HTML iframe onto it.
const nonce = ++previewSeq;
setPreview((p) =>
p !== null && p.path === current.path
- ? { ...p, content: current.draft, truncated: false, version: undefined, nonce }
+ ? { ...p, content: sent, truncated: false, version: written ?? undefined, nonce }
: p,
);
const dir = parentDir(current.path);
@@ -1293,7 +1459,7 @@ export function WorkspaceBrowser({
void loadDir(dir);
toastSuccess(S.common.saved);
} catch (err) {
- if (sessionIdRef.current !== sid) return;
+ if (scopeKeyRef.current !== key) return;
// The write precondition refused it: the file is no longer the one that was opened.
// Ask rather than report — overwriting is a legitimate answer, it just has to be the
// user's, and neither answer costs them their text.
@@ -1304,25 +1470,33 @@ export function WorkspaceBrowser({
}
toastError(apiErrorText(err));
} finally {
- if (sessionIdRef.current === sid) setSaving(false);
+ if (scopeKeyRef.current === key) setSaving(false);
}
};
- const cancelEdit = (): void => {
- void navigateGuarded(null, () => undefined);
+ /**
+ * Leaves the editor for the source view, asking first when there are unsaved changes. The
+ * source view comes back where the editor was scrolled, not where it was before Edit.
+ */
+ const stopEditing = (): void => {
+ const host = editorHost.current;
+ const at = host === null ? null : { top: host.scrollTop, left: host.scrollLeft };
+ void navigateGuarded(null, () => {
+ bodyScrollOnReturn.current = at;
+ });
};
// ------------------------------------------------------------------------------ upload
- const doUpload = async (files: File[], dir: string): Promise<void> => {
- const sid = sessionId;
- setUploading({ done: 0, total: files.length });
+ const doUpload = async (picked: File[], dir: string): Promise<void> => {
+ const key = scopeKey;
+ setUploading({ done: 0, total: picked.length });
const uploaded: string[] = [];
try {
- for (const [i, file] of files.entries()) {
+ for (const [i, file] of picked.entries()) {
const b64 = await blobToBase64(file);
- await api.uploadWorkspaceFile(sid, joinWorkspacePath(dir, file.name), b64);
- if (sessionIdRef.current !== sid) return;
+ await files.write(joinWorkspacePath(dir, file.name), b64);
+ if (scopeKeyRef.current !== key) return;
uploaded.push(file.name);
// The row appears as each file lands; the listing is re-read afterwards for the
// server's own size and time.
@@ -1334,15 +1508,15 @@ export function WorkspaceBrowser({
mtime: new Date().toISOString(),
}),
);
- setUploading({ done: i + 1, total: files.length });
+ setUploading({ done: i + 1, total: picked.length });
}
toastSuccess(S.files.uploadedCount(uploaded.length));
} catch (err) {
toastError(apiErrorText(err));
} finally {
- if (sessionIdRef.current === sid) setUploading(null);
+ if (scopeKeyRef.current === key) setUploading(null);
}
- if (sessionIdRef.current !== sid || uploaded.length === 0) return;
+ if (scopeKeyRef.current !== key || uploaded.length === 0) return;
setExpanded((s) => withExpanded(s, dir, true));
void loadDir(dir);
// The first uploaded file opens, unless the editor holds typed changes — an upload is
@@ -1365,9 +1539,9 @@ export function WorkspaceBrowser({
);
}
if (accepted.length === 0) return;
- const sid = sessionId;
+ const key = scopeKey;
if (!listingsRef.current.has(dir) && !(await loadDir(dir))) return;
- if (sessionIdRef.current !== sid) return;
+ if (scopeKeyRef.current !== key) return;
const existing = new Set((listingsRef.current.get(dir) ?? []).map((entry) => entry.name));
const clashes = accepted.filter((f) => existing.has(f.name)).map((f) => f.name);
if (clashes.length > 0) setPendingUpload({ files: accepted, clashes, dir });
@@ -1375,16 +1549,71 @@ export function WorkspaceBrowser({
};
const onPick = (e: ChangeEvent<HTMLInputElement>): void => {
- const files = e.target.files ? [...e.target.files] : [];
+ const picked = e.target.files ? [...e.target.files] : [];
e.target.value = "";
- if (files.length > 0) void stageUpload(files, currentDirRef.current);
+ if (picked.length > 0) void stageUpload(picked, currentDirRef.current);
};
/** The menu's own picker: same staging, but into the folder that was right-clicked. */
const onMenuPick = (e: ChangeEvent<HTMLInputElement>): void => {
- const files = e.target.files ? [...e.target.files] : [];
+ const picked = e.target.files ? [...e.target.files] : [];
e.target.value = "";
- if (files.length > 0) void stageUpload(files, menuUploadDir.current);
+ if (picked.length > 0) void stageUpload(picked, menuUploadDir.current);
+ };
+
+ // --------------------------------------------------------------------------------- new
+
+ /**
+ * Opens the New dialog for a text file or a folder in `dir`. A text file starts as
+ * `untitled.txt` with the stem selected, so typing replaces the name and keeps the extension;
+ * a folder starts empty.
+ */
+ const beginCreate = (kind: "file" | "dir", dir: string): void => {
+ setCreateName(kind === "file" ? DEFAULT_TEXT_FILE_NAME : "");
+ setCreateTarget({ kind, dir });
+ };
+
+ /**
+ * Creates what the dialog names. An existing name is refused by the server with nothing
+ * written, and the dialog stays open on the name so it can be changed. A new folder opens in
+ * the tree and becomes the current directory, so the next upload or New lands in it. A new
+ * text file opens in the editor — unless the editor holds typed changes, which a new file is
+ * no reason to ask about (the rule uploads follow): then it is only shown in the tree.
+ */
+ const applyCreate = async (): Promise<void> => {
+ const target = createTarget;
+ const name = newEntryName(createName);
+ if (target === null || name === "" || creating) return;
+ const path = joinWorkspacePath(target.dir, name);
+ const key = scopeKey;
+ setCreating(true);
+ try {
+ await files.create({ path, kind: target.kind });
+ if (scopeKeyRef.current !== key) return;
+ setCreateTarget(null);
+ toastSuccess(S.files.created(baseName(path)));
+ if (target.kind === "dir") {
+ setCurrentDir(path);
+ setExpanded((s) => withExpanded(s, path, true));
+ await locate(path);
+ if (scopeKeyRef.current === key) void loadDir(path);
+ return;
+ }
+ if (isDirty(editorRef.current)) {
+ await locate(path);
+ return;
+ }
+ editOnOpen.current = path;
+ openFile(path, { locate: true });
+ } catch (err) {
+ if (err instanceof ApiError && err.code === "target_exists") {
+ toastError(S.files.targetExists(path));
+ } else {
+ toastError(apiErrorText(err));
+ }
+ } finally {
+ if (scopeKeyRef.current === key) setCreating(false);
+ }
};
/**
@@ -1395,7 +1624,7 @@ export function WorkspaceBrowser({
*/
const revealInFolder = async (filePath: string): Promise<void> => {
try {
- await api.revealWorkspaceFile(sessionId, filePath);
+ await files.reveal(filePath);
} catch (err) {
toastError(apiErrorText(err));
}
@@ -1431,19 +1660,20 @@ export function WorkspaceBrowser({
};
/**
- * The tree's context menu, hung on the whole pane. A gesture that lands between rows — the
- * search box, the empty space below the last row — resolves no target, so nothing is
- * suppressed and the browser's own menu stands, which is what the search box needs to be
- * pasteable into.
+ * The tree's context menu, hung on the whole pane. A row opens the menu for its entry, and the
+ * blank space under the rows opens the New menu for the Workspace root. A gesture on the
+ * search box resolves no target, so nothing is suppressed and the browser's own menu stands,
+ * which is what the search box needs to be pasteable into.
*/
const treeMenuProps = {
onContextMenu: (e: ReactMouseEvent) => {
const row = hitRow(e.target);
- if (row === null) return;
+ const blank = row === null ? hitBlank(e.target) : null;
+ if (row === null && blank === null) return;
// Before the hook reads it: the anchor for a keyboard-synthesized contextmenu is the
// row's own box, and the hook measures whatever `rowRef` currently points at.
- treeMenu.rowRef(row.el);
- setTreeMenuTarget({ path: row.path, kind: row.kind });
+ treeMenu.rowRef(row?.el ?? blank);
+ setTreeMenuTarget(row === null ? "blank" : { path: row.path, kind: row.kind });
treeMenu.rowProps.onContextMenu(e);
},
onKeyDown: (e: ReactKeyboardEvent) => {
@@ -1463,9 +1693,10 @@ export function WorkspaceBrowser({
// and running this for every click would re-render the panel on each one.
if (!isLongPressPointer(e.pointerType)) return;
const row = hitRow(e.target);
- if (row === null) return;
- treeMenu.rowRef(row.el);
- setTreeMenuTarget({ path: row.path, kind: row.kind });
+ const blank = row === null ? hitBlank(e.target) : null;
+ if (row === null && blank === null) return;
+ treeMenu.rowRef(row?.el ?? blank);
+ setTreeMenuTarget(row === null ? "blank" : { path: row.path, kind: row.kind });
treeMenu.rowProps.onPointerDown(e);
},
onPointerMove: treeMenu.rowProps.onPointerMove,
@@ -1596,9 +1827,9 @@ export function WorkspaceBrowser({
const onDrop = (e: ReactDragEvent<HTMLDivElement>): void => {
const { accept, targetDir } = applyDrag("drop", e, true);
if (!accept) return;
- const { files, dirs } = pickDroppedFiles(e.dataTransfer);
- if (dirs.length > 0) toastError(S.files.folderDropSkipped(dirs.join(", ")));
- if (files.length > 0) void stageUpload(files, targetDir);
+ const dropped = pickDroppedFiles(e.dataTransfer);
+ if (dropped.dirs.length > 0) toastError(S.files.folderDropSkipped(dropped.dirs.join(", ")));
+ if (dropped.files.length > 0) void stageUpload(dropped.files, targetDir);
};
// ------------------------------------------------------------------------------ render
@@ -1646,6 +1877,8 @@ export function WorkspaceBrowser({
download: S.files.download,
rename: S.files.renameTitle,
delete: S.common.delete,
+ newTextFile: S.files.newTextFile,
+ newFolder: S.files.newFolder,
};
// The tree pane: its body says, in order, that the root listing failed, that it is on its way,
@@ -1662,6 +1895,40 @@ export function WorkspaceBrowser({
}}
actions={
<>
+ {/* New: a text file or a folder, in the current directory — the one the breadcrumbs
+ name and uploads land in. */}
+ <Dropdown
+ open={newMenuOpen}
+ setOpen={setNewMenuOpen}
+ portal={{ direction: "down", align: "right" }}
+ className="shrink-0"
+ menuClass="w-max min-w-36"
+ button={
+ <button
+ type="button"
+ aria-label={S.files.newMenu}
+ data-tooltip={S.files.newMenu}
+ aria-haspopup="menu"
+ aria-expanded={newMenuOpen}
+ onClick={() => setNewMenuOpen(!newMenuOpen)}
+ className={iconActionClass}
+ >
+ <GlyphIcon d={ICONS.plus} size={ICON_SIZE.iconButton} />
+ </button>
+ }
+ >
+ <WorkspaceNewMenuRows
+ labels={fileMenuLabels}
+ onNewFile={() => {
+ setNewMenuOpen(false);
+ beginCreate("file", currentDirRef.current);
+ }}
+ onNewFolder={() => {
+ setNewMenuOpen(false);
+ beginCreate("dir", currentDirRef.current);
+ }}
+ />
+ </Dropdown>
<Tooltip label={S.files.refresh} placement="bottom" className="shrink-0">
<button
type="button"
@@ -1701,8 +1968,9 @@ export function WorkspaceBrowser({
note={
searchResult?.truncated === true ? S.files.searchTruncated(searchResult.hits.length) : null
}
- // The row menu. The anchor is the point the gesture landed on rather than any element of
- // the pane, and the panel is portaled (the same shape the sidebar's session row uses).
+ // The row menu, or the New menu for the blank space under the rows. The anchor is the point
+ // the gesture landed on rather than any element of the pane, and the panel is portaled (the
+ // same shape the sidebar's session row uses).
menu={
treeMenuTarget !== null && (
<Dropdown
@@ -1722,33 +1990,55 @@ export function WorkspaceBrowser({
menuClass="w-max min-w-36 max-w-[calc(100vw-2rem)]"
button={null}
>
- <WorkspaceFileMenuRows
- target={treeMenuTarget}
- labels={fileMenuLabels}
- downloadHref={(path) => api.workspaceFileUrl(sessionId, path, true)}
- downloadName={baseName}
- onCopyPath={(t) => {
- closeTreeMenu();
- copyPath(t);
- }}
- onAddToChat={(t) => {
- closeTreeMenu();
- addToChat(t);
- }}
- onUploadInto={(dir) => {
- closeTreeMenu();
- uploadInto(dir);
- }}
- onRename={(t) => {
- closeTreeMenu();
- beginFileAction(t.path, "rename");
- }}
- onDelete={(t) => {
- closeTreeMenu();
- beginFileAction(t.path, "delete");
- }}
- onClose={closeTreeMenu}
- />
+ {treeMenuTarget === "blank" ? (
+ <WorkspaceNewMenuRows
+ labels={fileMenuLabels}
+ onNewFile={() => {
+ closeTreeMenu();
+ beginCreate("file", "");
+ }}
+ onNewFolder={() => {
+ closeTreeMenu();
+ beginCreate("dir", "");
+ }}
+ />
+ ) : (
+ <WorkspaceFileMenuRows
+ target={treeMenuTarget}
+ labels={fileMenuLabels}
+ downloadHref={(path) => files.fileUrl(path, true)}
+ downloadName={baseName}
+ onCopyPath={(t) => {
+ closeTreeMenu();
+ copyPath(t);
+ }}
+ onAddToChat={(t) => {
+ closeTreeMenu();
+ addToChat(t);
+ }}
+ onUploadInto={(dir) => {
+ closeTreeMenu();
+ uploadInto(dir);
+ }}
+ onNewFile={(dir) => {
+ closeTreeMenu();
+ beginCreate("file", dir);
+ }}
+ onNewFolder={(dir) => {
+ closeTreeMenu();
+ beginCreate("dir", dir);
+ }}
+ onRename={(t) => {
+ closeTreeMenu();
+ beginFileAction(t.path, "rename", t.kind);
+ }}
+ onDelete={(t) => {
+ closeTreeMenu();
+ beginFileAction(t.path, "delete");
+ }}
+ onClose={closeTreeMenu}
+ />
+ )}
</Dropdown>
)
}
@@ -1867,7 +2157,7 @@ export function WorkspaceBrowser({
{/\.html?$/i.test(preview.name) && (
<Tooltip label={openInNewTabLabel} placement="bottom" className="shrink-0">
<a
- href={api.workspaceFilePreviewUrl(sessionId, preview.path)}
+ href={files.previewUrl(preview.path)}
target="_blank"
rel="noopener noreferrer"
aria-label={openInNewTabLabel}
@@ -1892,7 +2182,7 @@ export function WorkspaceBrowser({
// same file is re-read, so only a remount re-requests the bytes the agent just rewrote.
return {
kind: "image",
- src: api.workspaceFileUrl(sessionId, p.path),
+ src: files.fileUrl(p.path),
alt: p.name,
reloadKey: p.nonce,
};
@@ -1900,7 +2190,7 @@ export function WorkspaceBrowser({
if (p.kind === "pdf") {
return {
kind: "pdf",
- src: api.workspaceFileUrl(sessionId, p.path),
+ src: files.fileUrl(p.path),
title: p.name,
reloadKey: p.nonce,
};
@@ -1923,7 +2213,7 @@ export function WorkspaceBrowser({
// re-opened after the agent rewrote it.
<iframe
key={p.nonce}
- src={api.workspaceFilePreviewUrl(sessionId, p.path)}
+ src={files.previewUrl(p.path)}
title={p.name}
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads"
className="h-full min-h-[60vh] w-full rounded-md border border-gray-200 bg-white dark:border-gray-800"
@@ -1972,7 +2262,7 @@ export function WorkspaceBrowser({
<img
src={
typeof src === "string" && !EXTERNAL_REF_RE.test(src)
- ? `${api.workspaceFileUrl(sessionId, resolveRelative(parentDir(p.path), src))}&v=${p.nonce}`
+ ? `${files.fileUrl(resolveRelative(parentDir(p.path), src))}&v=${p.nonce}`
: src
}
alt={alt ?? ""}
@@ -1996,7 +2286,7 @@ export function WorkspaceBrowser({
const target = resolveRelative(parentDir(p.path), href);
return (
<a
- href={api.workspaceFileUrl(sessionId, target)}
+ href={files.fileUrl(target)}
onClick={(e) => {
e.preventDefault();
openFile(target, { locate: true });
@@ -2056,11 +2346,11 @@ export function WorkspaceBrowser({
is open: a `Button size="sm"` stands 29px against these 27px, and the header would
grow by two pixels the moment Edit was pressed. The save keeps no primary tint —
it opens a confirmation whose own button carries that weight. */}
- <Tooltip label={S.common.cancel} placement="bottom" className="shrink-0">
+ <Tooltip label={S.files.stopEditing} placement="bottom" className="shrink-0">
<button
type="button"
- aria-label={S.common.cancel}
- onClick={cancelEdit}
+ aria-label={S.files.stopEditing}
+ onClick={stopEditing}
disabled={saving}
className={`${iconActionClass} disabled:opacity-40`}
>
@@ -2096,7 +2386,7 @@ export function WorkspaceBrowser({
{richToggle}
<Tooltip label={S.files.download} placement="bottom" className="shrink-0">
<a
- href={api.workspaceFileUrl(sessionId, preview.path, true)}
+ href={files.fileUrl(preview.path, true)}
download={preview.name}
aria-label={S.files.download}
className={iconActionClass}
@@ -2155,6 +2445,8 @@ export function WorkspaceBrowser({
// its own would only refuse to colour a file for no gain. The bound left is the
// preview cap, which is all a load can put here.
highlight={editing.draft.length <= TEXT_PREVIEW_LIMIT}
+ initialScroll={editorOpening.current}
+ hostRef={editorHost}
onChange={updateDraft}
onSave={requestSave}
// The editor.save binding (⌘S / Ctrl+S by default), read from the keymap at the
@@ -2168,6 +2460,14 @@ export function WorkspaceBrowser({
// The same element is the menu's keyboard anchor and its scroll owner: a scroll of this
// box moves the point the panel hangs off.
previewMenu.rowRef(el);
+ // Back from the editor: the source view takes up where the editor was scrolled. Both
+ // lay out the same surface, so one offset is one line in either.
+ const at = bodyScrollOnReturn.current;
+ if (el !== null && at !== null) {
+ bodyScrollOnReturn.current = null;
+ el.scrollTop = at.top;
+ el.scrollLeft = at.left;
+ }
}}
bodyProps={{
onContextMenu: openPreviewMenu,
@@ -2203,7 +2503,7 @@ export function WorkspaceBrowser({
<WorkspaceFileMenuRows
target={{ path: shown.path, kind: "file" }}
labels={fileMenuLabels}
- downloadHref={(path) => api.workspaceFileUrl(sessionId, path, true)}
+ downloadHref={(path) => files.fileUrl(path, true)}
downloadName={baseName}
onCopyPath={(t) => {
previewMenu.close();
@@ -2398,13 +2698,14 @@ export function WorkspaceBrowser({
</ConfirmModal>
{/* Rename or move: one field holding the whole Workspace-relative path, so a rename and a
- move are one action rather than two that differ only in how much of the path changed. */}
+ move are one action rather than two that differ only in how much of the path changed.
+ A folder moves whole, with everything under it. */}
<ConfirmModal
open={renameTarget !== null}
title={S.files.renameTitle}
confirmLabel={S.files.renameConfirm}
cancelLabel={S.common.cancel}
- confirmDisabled={renameTarget?.version == null || renameDraft.trim() === ""}
+ confirmDisabled={!actionReady(renameTarget) || renameDraft.trim() === ""}
busy={fileActionBusy}
tone="primary"
onClose={() => setRenameTarget(null)}
@@ -2421,6 +2722,40 @@ export function WorkspaceBrowser({
/>
<FileActionVersionNote target={renameTarget} />
</ConfirmModal>
+ {/* New text file or folder: a name under the directory it goes in. Enter creates, as the
+ button does; a name the server finds taken leaves the dialog open on it. */}
+ <ConfirmModal
+ open={createTarget !== null}
+ title={createTarget?.kind === "dir" ? S.files.newFolder : S.files.newTextFile}
+ tone="primary"
+ confirmLabel={S.files.createConfirm}
+ cancelLabel={S.common.cancel}
+ confirmDisabled={newEntryName(createName) === ""}
+ busy={creating}
+ onClose={() => setCreateTarget(null)}
+ onConfirm={() => void applyCreate()}
+ >
+ <Input
+ label={createTarget?.kind === "dir" ? S.files.newFolderName : S.files.newFileName}
+ size="sm"
+ value={createName}
+ hint={S.files.createHint(dirLabel(createTarget?.dir ?? ""))}
+ autoFocus
+ {...noAutofill}
+ // Typing replaces the stem and keeps the extension (`untitled` of `untitled.txt`).
+ onFocus={(e) => {
+ const input = e.currentTarget;
+ if (input.value === DEFAULT_TEXT_FILE_NAME)
+ input.setSelectionRange(0, stemEnd(input.value));
+ }}
+ onChange={(e) => setCreateName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key !== "Enter" || e.nativeEvent.isComposing) return;
+ e.preventDefault();
+ void applyCreate();
+ }}
+ />
+ </ConfirmModal>
<ConfirmModal
open={removeTarget !== null}
title={S.files.deleteTitle}
diff --git a/packages/web/src/features/dock/dock-terminal.ts b/packages/web/src/features/dock/dock-terminal.ts
index 77ca45b5..d91da8b6 100644
--- a/packages/web/src/features/dock/dock-terminal.ts
+++ b/packages/web/src/features/dock/dock-terminal.ts
@@ -56,6 +56,15 @@ export function setDockCwd(path: string | null, machineId: string | null = null)
workspaceMachine = workspaceCwd === null ? null : machineId;
}
+/**
+ * The Workspace the page's docks belong to — the conversation's, or the one the draft picked —
+ * with its machine; null when none is known. Only meaningful while a page with docks is on
+ * screen (`docksOnScreen`): elsewhere it still names the last conversation's, for the hotkey.
+ */
+export function dockWorkspace(): { path: string; machineId: string | null } | null {
+ return workspaceCwd === null ? null : { path: workspaceCwd, machineId: workspaceMachine };
+}
+
/** A rejected working directory (gone, replaced by a file, relative) — see resolveCwd server-side. */
function isBadCwd(err: unknown): boolean {
return err instanceof HttpStatusError && err.status === 400 && err.message.includes("cwd_not_");
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 57b43480..33a35f26 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2416,12 +2416,14 @@ export const en: Strings = {
sortManual: "Manual order",
sortRecent: "Most recent",
newWorkspaceEntity: "New workspace",
- /** Registry-backed workspace group's overflow (… right of the header "+"): alias rename + sidebar-only removal. */
+ /** A Workspace group's overflow (… right of the header "+"): browse its files; a registry-backed group adds alias rename + sidebar-only removal. */
workspaceMenu: "Workspace options",
renameWorkspace: "Rename workspace",
renameWorkspaceLabel: "Name",
renameWorkspaceHint: "Leave empty to use the folder name",
deleteWorkspace: "Remove workspace",
+ /** A Workspace group's "more" menu: the dock's Files panel on that directory. */
+ browseWorkspaceFiles: "Browse files",
deleteWorkspaceConfirm: (name: string) =>
`Remove "${name}"? This only removes the workspace group from the sidebar — the directory on disk and existing chats are untouched, and it can be re-added anytime.`,
tempWorkspaces: "Temporary workspaces",
@@ -3498,6 +3500,8 @@ Scenarios:
discardBody: (name: string): string => `${name} has unsaved changes. Discard them?`,
discard: "Discard",
unsavedRestored: (name: string): string => `Restored unsaved changes to ${name}`,
+ /** The editor's ×: back to the preview (asking first when there are unsaved changes). */
+ stopEditing: "Stop editing",
/** The file was rewritten (by the Agent, most likely) while the editor was open on it. */
changedOnDisk: "Changed on disk",
changedOnDiskHint:
@@ -3510,7 +3514,8 @@ Scenarios:
renameHint:
"Relative to the Workspace root; a directory in the path that does not exist is created",
renameConfirm: "Move",
- renameTargetExists: (path: string): string => `${path} already exists, so nothing was changed.`,
+ /** A move or a New landed on a name that is taken: nothing was written. */
+ targetExists: (path: string): string => `${path} already exists, so nothing was changed.`,
renamed: (name: string): string => `Moved to ${name}`,
deleteTitle: "Delete file",
deleteBody: (name: string): string => `Delete ${name}? It does not go to a trash folder.`,
@@ -3526,6 +3531,20 @@ Scenarios:
conflictBody: (name: string): string =>
`${name} was rewritten after you opened it, most likely by the Agent during its turn, so nothing was saved. Overwrite it with your version, or keep editing and copy what you need out first — either way your text is kept.`,
overwriteAnyway: "Overwrite",
+ /** The tree header's New menu, a folder's menu and the blank space under the tree. */
+ newMenu: "New",
+ newTextFile: "New text file",
+ newFolder: "New folder",
+ newFileName: "File name",
+ newFolderName: "Folder name",
+ /** Formatting, kept on screen while typing: where the entry goes, and what a `/` does. */
+ createHint: (dir: string): string =>
+ `Created in ${dir}. A / in the name also creates the folders in between.`,
+ createConfirm: "Create",
+ created: (name: string): string => `Created ${name}`,
+ /** The new-chat draft's Files panel and its toggle, while the Workspace is a temporary one. */
+ draftTemporary:
+ "A temporary workspace is created with the first message. Choose a folder to browse its files.",
},
usage: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index e994a575..26b4b2e9 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2459,12 +2459,14 @@ export const zh = {
sortManual: "手动排序",
sortRecent: "最近更新",
newWorkspaceEntity: "新建工作区",
- /** Registry-backed workspace group's overflow (… right of the header "+"): alias rename + sidebar-only removal. */
+ /** A Workspace group's overflow (… right of the header "+"): browse its files; a registry-backed group adds alias rename + sidebar-only removal. */
workspaceMenu: "工作区选项",
renameWorkspace: "重命名工作区",
renameWorkspaceLabel: "名称",
renameWorkspaceHint: "留空则使用目录名",
deleteWorkspace: "删除工作区",
+ /** A Workspace group's "more" menu: the dock's Files panel on that directory. */
+ browseWorkspaceFiles: "打开文件浏览",
deleteWorkspaceConfirm: (name: string) =>
`确定移除「${name}」?仅从侧边栏移除该工作区分组,不影响磁盘目录与已有会话,可随时重新添加。`,
tempWorkspaces: "临时工作区",
@@ -3535,6 +3537,8 @@ Benchmark:
discardBody: (name: string): string => `${name} 有未保存的修改,放弃这些修改?`,
discard: "放弃",
unsavedRestored: (name: string): string => `已恢复 ${name} 的未保存修改`,
+ /** The editor's ×: back to the preview (asking first when there are unsaved changes). */
+ stopEditing: "退出编辑",
/** The file was rewritten (by the Agent, most likely) while the editor was open on it. */
changedOnDisk: "磁盘上已变更",
changedOnDiskHint: "该文件在你打开之后已被重写,保存会用你的版本覆盖它。",
@@ -3545,7 +3549,8 @@ Benchmark:
renameLabel: "新的路径",
renameHint: "相对 Workspace 根目录;路径中不存在的目录会自动创建",
renameConfirm: "移动",
- renameTargetExists: (path: string): string => `${path} 已存在,未做改动。`,
+ /** A move or a New landed on a name that is taken: nothing was written. */
+ targetExists: (path: string): string => `${path} 已存在,未做改动。`,
renamed: (name: string): string => `已移动到 ${name}`,
deleteTitle: "删除文件",
deleteBody: (name: string): string => `删除 ${name}?该文件不会进入回收站。`,
@@ -3560,6 +3565,18 @@ Benchmark:
conflictBody: (name: string): string =>
`${name} 在你打开之后被重写(多半是 Agent 本轮写的),本次没有保存任何内容。可以用你的版本覆盖它,也可以继续编辑、先把需要的内容取出来——两种选择都会保留你的文本。`,
overwriteAnyway: "仍然覆盖",
+ /** The tree header's New menu, a folder's menu and the blank space under the tree. */
+ newMenu: "新建",
+ newTextFile: "新建文本文件",
+ newFolder: "新建文件夹",
+ newFileName: "文件名",
+ newFolderName: "文件夹名",
+ /** Formatting, kept on screen while typing: where the entry goes, and what a `/` does. */
+ createHint: (dir: string): string => `建在 ${dir} 下;名称里的 / 会同时建出中间的文件夹`,
+ createConfirm: "创建",
+ created: (name: string): string => `已创建 ${name}`,
+ /** The new-chat draft's Files panel and its toggle, while the Workspace is a temporary one. */
+ draftTemporary: "临时工作区在发送第一条消息时才创建。选一个文件夹,即可浏览其中的文件。",
},
usage: {
diff --git a/packages/web/src/lib/workspace-tree.ts b/packages/web/src/lib/workspace-tree.ts
index 4745ed31..bd596afa 100644
--- a/packages/web/src/lib/workspace-tree.ts
+++ b/packages/web/src/lib/workspace-tree.ts
@@ -77,6 +77,57 @@ export function baseName(path: string): string {
return i >= 0 ? path.slice(i + 1) : path;
}
+/** Whether `path` is `dir` itself or lies inside it. */
+export function isWithin(path: string, dir: string): boolean {
+ return path === dir || path.startsWith(`${dir}/`);
+}
+
+/**
+ * Where `path` is once `from` has moved to `to`: `to` itself, or the same place under it when
+ * `path` lay inside `from`; null when the move did not touch it. A sibling that merely shares a
+ * prefix (`docs-old` beside `docs`) is untouched.
+ */
+export function movedPath(path: string, from: string, to: string): string | null {
+ return isWithin(path, from) ? `${to}${path.slice(from.length)}` : null;
+}
+
+/** The set with every path the move touched carried to its new place. */
+export function movedSet(set: ReadonlySet<string>, from: string, to: string): Set<string> {
+ return new Set([...set].map((p) => movedPath(p, from, to) ?? p));
+}
+
+/** The loaded listings with every directory the move touched filed under its new path. */
+export function movedListings(
+ listings: Listings,
+ from: string,
+ to: string,
+): Map<string, readonly WorkspaceFileEntry[]> {
+ return new Map([...listings].map(([dir, entries]) => [movedPath(dir, from, to) ?? dir, entries]));
+}
+
+/** What a new text file is called until it is named. */
+export const DEFAULT_TEXT_FILE_NAME = "untitled.txt";
+
+/**
+ * The end of a file name's stem — where its extension starts, or its whole length when it has
+ * none. The name field selects up to here, so typing replaces `untitled` and keeps `.txt`. A
+ * leading dot (`.env`) is part of the stem, not an extension.
+ */
+export function stemEnd(name: string): number {
+ const dot = name.lastIndexOf(".");
+ return dot > 0 ? dot : name.length;
+}
+
+/**
+ * A typed new-entry name made into the relative path it creates under the chosen directory:
+ * trimmed, with the slashes at either end dropped (a folder named `drafts/` is `drafts`, and a
+ * leading `/` would otherwise read as the Workspace root). A `/` inside stays: it creates the
+ * folders in between.
+ */
+export function newEntryName(raw: string): string {
+ return raw.trim().replace(/^\/+/, "").replace(/\/+$/, "");
+}
+
/** The directories from the root down to the path's parent, root first: "a/b/c.txt" → ["", "a", "a/b"]. */
export function ancestorDirs(path: string): string[] {
const out = [""];
diff --git a/packages/web/test/workspace-files-scope.test.ts b/packages/web/test/workspace-files-scope.test.ts
new file mode 100644
index 00000000..d31ecb15
--- /dev/null
+++ b/packages/web/test/workspace-files-scope.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Where the Files panel's operations go (api/workspace-files.ts).
+ *
+ * - A Session's files are asked of the Session, on the machine it lives on.
+ * - A directory's files are asked by its path, of the machine it is on, and of this server when
+ * it is on this one — for calls and for the URLs a browser follows alike.
+ * - A save hands back the version the server says it wrote.
+ * - The same path on two machines is two scopes: the panel never carries one's state to the
+ * other.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { filesApi, filesScopeKey } from "../src/api/workspace-files";
+import { forgetSessionMachines, rememberSessionMachine } from "../src/lib/session-machines";
+
+const MACHINE = "m7Kd0Q2xVbNzR1aP";
+
+describe("Files panel scopes", () => {
+ const calls: { url: string; method: string; body?: unknown }[] = [];
+ /** The file calls alone: the client may probe the session first. */
+ const fileCalls = () => calls.filter((c) => c.url.includes("files"));
+ let reply: () => Response;
+ beforeEach(() => {
+ calls.length = 0;
+ reply = () =>
+ new Response(JSON.stringify({ path: "src", entries: [] }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ vi.stubGlobal("WebSocket", undefined);
+ vi.stubGlobal("fetch", async (url: string, init?: { method?: string; body?: string }) => {
+ calls.push({
+ url,
+ method: init?.method ?? "GET",
+ ...(init?.body === undefined ? {} : { body: JSON.parse(init.body) }),
+ });
+ return reply();
+ });
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ forgetSessionMachines();
+ });
+
+ it("a Session's files are asked of the Session, on the machine it lives on", async () => {
+ rememberSessionMachine("session-on-m7", MACHINE);
+ const files = filesApi({ kind: "session", sessionId: "session-on-m7" });
+ expect(files.fileUrl("notes/a b.md", true)).toBe(
+ `/server/${MACHINE}/api/sessions/session-on-m7/files/content?path=notes%2Fa%20b.md&download=1`,
+ );
+ await files.list("src");
+ expect(fileCalls().map((c) => c.url)).toEqual([
+ `/server/${MACHINE}/api/sessions/session-on-m7/files?path=src`,
+ ]);
+ });
+
+ it("a directory's files are asked by its path, of the machine it is on", async () => {
+ const remote = filesApi({
+ kind: "workspace",
+ projectId: "alice-web",
+ workspace: "/srv/app",
+ machineId: MACHINE,
+ });
+ expect(remote.fileUrl("a b.txt")).toBe(
+ `/server/${MACHINE}/api/projects/alice-web/workspace-files/content?workspace=%2Fsrv%2Fapp&path=a%20b.txt`,
+ );
+ expect(remote.previewUrl("index.html")).toBe(
+ `/server/${MACHINE}/api/projects/alice-web/workspace-files/content?workspace=%2Fsrv%2Fapp&path=index.html&preview=1`,
+ );
+ expect(remote.isolatablePreviews).toBe(false);
+ await remote.create({ path: "src/new", kind: "dir" });
+
+ const local = filesApi({
+ kind: "workspace",
+ projectId: "alice-web",
+ workspace: "/srv/app",
+ machineId: null,
+ });
+ await local.list("src");
+ expect(fileCalls()).toEqual([
+ {
+ url: `/server/${MACHINE}/api/projects/alice-web/workspace-files/create?workspace=%2Fsrv%2Fapp`,
+ method: "POST",
+ body: { path: "src/new", kind: "dir" },
+ },
+ {
+ url: "/api/projects/alice-web/workspace-files?workspace=%2Fsrv%2Fapp&path=src",
+ method: "GET",
+ },
+ ]);
+ });
+
+ it("a save hands back the version the server says it wrote", async () => {
+ reply = () => new Response(null, { status: 204, headers: { etag: 'W/"5-1700000000000"' } });
+ const files = filesApi({
+ kind: "workspace",
+ projectId: "alice-web",
+ workspace: "/srv/app",
+ machineId: null,
+ });
+ await expect(files.write("a.txt", "aGVsbG8=", 'W/"1-1"')).resolves.toBe('W/"5-1700000000000"');
+ expect(fileCalls()[0]?.body).toEqual({ dataBase64: "aGVsbG8=", ifVersion: 'W/"1-1"' });
+
+ reply = () => new Response(null, { status: 204 });
+ await expect(files.write("a.txt", "aGVsbG8=")).resolves.toBeNull();
+ });
+
+ it("the same path on two machines is two scopes", () => {
+ const here = {
+ kind: "workspace",
+ projectId: "p",
+ workspace: "/srv/app",
+ machineId: null,
+ } as const;
+ const there = { ...here, machineId: MACHINE };
+ expect(filesScopeKey(here)).toBe(filesScopeKey({ ...here }));
+ expect(filesScopeKey(here)).not.toBe(filesScopeKey(there));
+ expect(filesScopeKey({ kind: "session", sessionId: "/srv/app" })).not.toBe(filesScopeKey(here));
+ });
+});
diff --git a/packages/web/test/workspace-tree-moves.test.ts b/packages/web/test/workspace-tree-moves.test.ts
new file mode 100644
index 00000000..75f1aac6
--- /dev/null
+++ b/packages/web/test/workspace-tree-moves.test.ts
@@ -0,0 +1,71 @@
+/**
+ * The Files panel following a rename, and naming a new entry (lib/workspace-tree.ts).
+ *
+ * - A folder's move carries it and every path under it to the new place, and leaves a sibling
+ * that only shares its prefix where it was.
+ * - The open folders and the loaded listings follow the move, so the tree keeps its shape.
+ * - A new text file's name field selects the stem, so typing replaces `untitled` and keeps the
+ * extension; a dotfile's leading dot is part of its stem.
+ * - A typed name loses the slashes at its ends, and a slash inside it stays: it creates the
+ * folders in between.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ DEFAULT_TEXT_FILE_NAME,
+ movedListings,
+ movedPath,
+ movedSet,
+ newEntryName,
+ stemEnd,
+} from "../src/lib/workspace-tree";
+
+const entry = (name: string, kind: "dir" | "file") => ({
+ name,
+ kind,
+ sizeBytes: 1,
+ mtime: "2026-10-01T00:00:00.000Z",
+});
+
+describe("following a move", () => {
+ it("a folder's move carries it and everything under it, and leaves a prefix-sharing sibling", () => {
+ expect(movedPath("docs", "docs", "handbook/docs")).toBe("handbook/docs");
+ expect(movedPath("docs/guide/intro.md", "docs", "handbook/docs")).toBe(
+ "handbook/docs/guide/intro.md",
+ );
+ expect(movedPath("docs-old/intro.md", "docs", "handbook/docs")).toBeNull();
+ expect(movedPath("src/docs", "docs", "handbook/docs")).toBeNull();
+ });
+
+ it("the open folders and the loaded listings follow the move", () => {
+ const expanded = movedSet(new Set(["", "docs", "docs/guide", "src"]), "docs", "manual");
+ expect([...expanded].sort()).toEqual(["", "manual", "manual/guide", "src"]);
+
+ const listings = movedListings(
+ new Map([
+ ["", [entry("docs", "dir"), entry("src", "dir")]],
+ ["docs/guide", [entry("intro.md", "file")]],
+ ["src", [entry("app.ts", "file")]],
+ ]),
+ "docs",
+ "manual",
+ );
+ expect([...listings.keys()].sort()).toEqual(["", "manual/guide", "src"]);
+ expect(listings.get("manual/guide")?.map((e) => e.name)).toEqual(["intro.md"]);
+ });
+});
+
+describe("naming a new entry", () => {
+ it("a new text file's name field selects the stem and keeps the extension", () => {
+ expect(DEFAULT_TEXT_FILE_NAME.slice(0, stemEnd(DEFAULT_TEXT_FILE_NAME))).toBe("untitled");
+ expect(stemEnd("archive.tar.gz")).toBe("archive.tar".length);
+ expect(stemEnd(".env")).toBe(".env".length);
+ expect(stemEnd("Makefile")).toBe("Makefile".length);
+ });
+
+ it("a typed name loses the slashes at its ends, and a slash inside creates the folders between", () => {
+ expect(newEntryName(" drafts/ ")).toBe("drafts");
+ expect(newEntryName("/notes.md")).toBe("notes.md");
+ expect(newEntryName("2026/q4/plan.md")).toBe("2026/q4/plan.md");
+ expect(newEntryName(" / ")).toBe("");
+ });
+});