A local-first multi-agent app development platform, built on PenguinHarness
Files panel: directory tree beside the preview, in-place text editing, drop to upload (#589)
Yaowei Zheng3ed7a7f5bc15
diff --git a/changelog/unreleased/2026-09-02-workspace-tree-editor.md b/changelog/unreleased/2026-09-02-workspace-tree-editor.mdnew file mode 100644index 00000000..7d7cfd79--- /dev/null+++ b/changelog/unreleased/2026-09-02-workspace-tree-editor.md@@ -0,0 +1,67 @@+# Files panel: a directory tree beside the preview, in-place text editing, drop to upload++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#589](https://github.com/Prism-Shadow/penguin-harness/pull/589)++[中文版](2026-09-02-workspace-tree-editor.zh.md)++The Workspace files panel became a two-pane browser — a directory tree on the left, the+selected file's preview on the right — with plain-text editing of text files and+drag-and-drop upload from the desktop.++## Details++- Tree: a directory lists its contents the first time it opens; expand/collapse chevrons,+ folder and file glyphs, the selected file highlighted, arrow-key navigation (up/down move,+ right opens or steps in, left closes or steps out), and opening or closing a directory+ grows its subtree out of its row, or shrinks it back into it, over about 200ms — the rows+ stay on screen until the collapse finishes, and reduced motion makes it immediate. A search box above the tree filters+ the rows already loaded — the name matched case-insensitively, a match keeping and opening+ its ancestors, a matching directory shown with its loaded children, and an empty result+ saying that nothing *loaded* matches. The breadcrumbs above the panes read out the current+ directory as plain text rather than links (the tree beside them is what navigates), and a+ path too long for the toolbar collapses its leading segments into a `…` so Refresh and+ Upload stay on the row; the root segment reads `.`, and there is no Details button — the+ Workspace's absolute path stays in the Session details card. A toolbar toggle hides or shows the tree — shown by default,+ remembered under one browser-local key (`penguin.files.treeVisible`, parsed tolerantly), and+ sliding out of and back into the panel's left edge over 200ms, the motion the docks+ themselves expand and collapse with — and the divider between the two panes sets its width+ by drag or arrow key, remembered under `penguin.files.treeWidth`. Below 480px of panel+ width the panel falls back to one column: the tree until a file is chosen, then the+ preview with a Back button; the divider has nothing to divide there. A message file card's click still lands on its file, now by+ opening the tree down to it.+- Preview: the same rendering as before (Markdown / HTML rendered with a source toggle, text+ highlighted, PDF embedded); images now zoom on click, and a file whose extension says+ nothing about its type is read as text when its first bytes look like text. Text reads stop+ at the 256KB cap instead of downloading the whole file.+- Editing: an **Edit** action on text files swaps the preview for a monospace text box, with a+ **Wrap** toggle in the header — off by default, so long lines scroll sideways as they would+ in a code editor, remembered under `penguin.files.editorWrap`;+ **Save** (Ctrl+S / Cmd+S) confirms, then writes through the existing+ `PUT /api/sessions/:id/files/content` endpoint and refreshes the row's size and time. A+ truncated preview stays read-only, and a save over the 14MB write limit is refused before+ it is sent. Unsaved changes ask before a file switch, before the tab's × removes the+ panel (the close-guard registry the dock consults there), and before the page unloads.+ Collapsing or hiding a dock asks nothing, because it takes nothing away: the panel stays+ mounted at zero size with its preview, its tree and its draft, and comes back untouched. A+ draft survives a Session switch and reopens with the file.+- Write precondition: `GET /api/sessions/:id/files/content` now returns the file's version in+ an `ETag` (`W/"<size>-<mtime>"`), and the write takes it back as `ifVersion` in the request+ body. The server compares it on the open write handle immediately before truncating and+ answers `409 file_changed` — having written nothing — when the file has moved on, so a save+ can no longer drop what the Agent wrote to the same file during the turn. A write that+ carries no marker is unconditional, which is what uploads and the first write of a new file+ do. The panel turns the 409 into a question: it names the file, offers **Overwrite**, and+ keeps the draft whichever way it is answered. It also stops waiting for the save to find+ out — when a turn settles the edited file is version-checked (its text is still left alone)+ and the editor header says **Changed on disk** as soon as it has.+- Upload: OS files dropped anywhere on the panel upload into the current directory, or into+ the folder row under the pointer (highlighted while hovering), using the chat area's drag+ decision helpers; the app-shell guard keeps cancelling drops elsewhere. Picks and drops+ share one path: a per-file 14MB check before anything is read, an overwrite confirmation+ against the target directory's real listing, per-file progress in the toolbar, and the+ first uploaded file opens afterwards.+- Docs: the Web App guide's Files Panel section describes the panel; the design specs'+ files-panel sentences moved with it.diff --git a/changelog/unreleased/2026-09-02-workspace-tree-editor.zh.md b/changelog/unreleased/2026-09-02-workspace-tree-editor.zh.mdnew file mode 100644index 00000000..f278df14--- /dev/null+++ b/changelog/unreleased/2026-09-02-workspace-tree-editor.zh.md@@ -0,0 +1,19 @@+# 文件面板:目录树与预览并排、就地纯文本编辑、拖放上传++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `web`, `server`, `docs`+- **PR:** [#589](https://github.com/Prism-Shadow/penguin-harness/pull/589)++[English](2026-09-02-workspace-tree-editor.md)++Workspace 文件面板改为两栏浏览器——左侧目录树、右侧所选文件的预览——并支持文本文件的纯文本编辑与从桌面拖放上传。++## 细节++- 目录树:目录在首次展开时才列出内容;展开 / 折叠箭头、文件夹与文件图标、选中文件高亮、方向键导航(上下移动、右展开或进入、左折叠或回到上级),展开 / 折叠时子树以高度过渡动画展开或收起(约 200ms,折叠期间行仍可见直至收起完成;系统减少动态时即时)。树上方的搜索框只过滤已加载的行——名称按大小写无关的子串匹配,命中项保留并展开其祖先目录,名称本身命中的目录连同已加载的子项一起显示,无结果时明说「已加载的目录中没有匹配项」。两栏上方的面包屑只以纯文本读出当前目录、不再是链接(导航交给旁边的目录树),路径长到工具栏放不下时前导段折叠为「…」,以保证刷新 / 上传不换行;根目录写作 `.`,工具栏不设详情按钮,Workspace 的绝对路径仍在会话详情卡片里。工具栏按钮可隐藏或显示目录树——默认显示,记在一条浏览器本地键(`penguin.files.treeVisible`,宽容解析)下,显隐时目录树连同分隔条以约 200ms 的宽度过渡从面板左缘滑出或滑入,与停靠面板展开 / 收起同款——两栏之间的分隔条可用拖动或方向键调整树宽,记在 `penguin.files.treeWidth` 下。面板宽度低于 480px 时退化为单栏:先显示目录树,选中文件后换成带「返回列表」按钮的预览,此时没有分隔条。消息文件卡片的点击仍会落到对应文件,现在是把目录树一路展开到它。+- 预览:渲染方式与之前一致(Markdown / HTML 渲染视图并可切换源码、文本高亮、PDF 内嵌);图片现在可点击放大,扩展名看不出类型的文件在首块字节看起来是文本时按文本读取。文本读取在 256KB 上限处停止,不再整文件下载。+- 编辑:文本文件的**编辑**把预览换成等宽文本框,标题栏带**自动换行**开关——缺省关闭,长行像代码编辑器那样横向滚动,记在 `penguin.files.editorWrap` 下;**保存**(Ctrl+S / Cmd+S)先确认,再经既有的 `PUT /api/sessions/:id/files/content` 接口写回并刷新该行的大小与时间。截断的预览保持只读,超过 14MB 写入上限的保存在发送前即被拒绝。未保存的修改在切换文件、以标签页的 × 关闭该面板(停靠面板在此处征询的关闭守卫注册表)、离开页面前都会先询问。折叠或隐藏停靠面板什么都不问,因为它什么都没拿走:面板连同预览、目录树与编辑草稿以零尺寸留在原地,重新展开即原样回来。切换 Session 时草稿保留,再次打开该文件即恢复。+- 写前置条件:`GET /api/sessions/:id/files/content` 现在以 `ETag` 返回该文件的版本标记(`W/"<size>-<mtime>"`),写接口以请求体的 `ifVersion` 原样收回。服务端在已打开的写句柄上、截断之前比对,文件已变则 `409 file_changed` 且一个字节都不写——用户的保存因此不会再把 Agent 本轮写进同一文件的内容抹掉。不带该字段的写仍是无条件的,上传与首次写入一个新文件走的正是这条路。前端把 409 变成一个问题:写明是哪个文件、提供**仍然覆盖**,无论怎么选都保留草稿。它也不再等到保存才发现——每轮 Task 结束时对正在编辑的文件做一次版本比对(其文本仍不被覆盖),一旦变了就在编辑器标题栏标出**磁盘上已变更**。+- 上传:把系统文件拖到面板任意位置即上传到当前目录,或上传到指针下的文件夹行(悬停时高亮),复用聊天区的拖放判定;外壳守卫继续取消其他位置的拖放。选择与拖放走同一条路:读取前先做单文件 14MB 检查、按目标目录的真实列表确认覆盖、工具栏逐文件显示进度、完成后打开第一个上传的文件。+- 文档:Web App 指南的文件面板一节描述了新面板;设计文档中文件面板的相关句子同步更新。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 29a09a70..db0ed6a7 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -72,7 +72,7 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to- Enter sends, Shift+Enter inserts a newline, and images can be pasted — an image placed inline in the conversation is capped at 20MB, separately from file attachments and not raised along with them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every session resume, whereas an attachment is only ever read from disk by path;- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, and by default ≤ 100MB each and 120MB in total — an admin can change both sizes under **System settings → Upload limits**, see below; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection, and the message names the limit actually in force); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;-- Files can also be **dragged onto the chat area** — the conversation and the composer, on the chat page and the draft page alike: while a file drag is over that region a "Drop files to attach" overlay covers it (it hides as soon as the drag moves off; dragging text or anything that isn't a file is ignored), and releasing attaches the whole batch to the composer — images join the pasted-image pipeline, everything else becomes file attachments, with the same type and size validation and the same errors as the "+" menu. Dropping works while a Task is running too (the attachments then send per the mid-run send mode below); goal mode takes dropped images but refuses files with a notice. Only the chat area reacts: dropping a file on the sidebar, the top bar, the docked panels or any page without a composer attaches nothing and shows nothing — it is simply ignored, instead of the browser navigating away to the dropped file;+- Files can also be **dragged onto the chat area** — the conversation and the composer, on the chat page and the draft page alike: while a file drag is over that region a "Drop files to attach" overlay covers it (it hides as soon as the drag moves off; dragging text or anything that isn't a file is ignored), and releasing attaches the whole batch to the composer — images join the pasted-image pipeline, everything else becomes file attachments, with the same type and size validation and the same errors as the "+" menu. Dropping works while a Task is running too (the attachments then send per the mid-run send mode below); goal mode takes dropped images but refuses files with a notice. Only the chat area attaches: dropping a file on the sidebar, the top bar, the other docked panels or any page without a composer attaches nothing and shows nothing — it is simply ignored, instead of the browser navigating away to the dropped file (the Files panel is the one other drop target, and it uploads — see below);- Typing `/` opens the slash menu: trigger context compaction (`/compact`), hand the conversation over to another Agent (`/agent`), switch the model (`/model`) — both switch commands appear in an active session only, since a draft has nothing to switch and picks its Agent and model up front — or toggle installed Skills — chosen Skills are sent along with the message in a `[use_skills]` block;- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced. Each queued hint line — an undelivered steering message or a queued follow-up — ends in a **recall** control (a curved-back arrow, "Recall") that withdraws the message back into the input box (attachments included) for editing and resending; a steering message that already reached the model can no longer be recalled. When the run ends before a steering message was delivered — pressing Stop while a tool is still running is the usual way — you do not have to reach for that control: the message returns to the input box on its own, attachments and all, ready to edit and send again, so an interrupt never eats what you had already typed;- **Goal mode** (the "+" menu, or `/goal`) turns the draft into an objective the system loops Tasks against. Attached images ride along and are always sent as scratchpad paths (a goal objective is re-injected as text every round — see [Goal mode](/goal-mode)); text is still required, since a picture alone states no objective, and file attachments are refused. Round 1's bubble shows the attachments in full, later rounds collapse them into a chip that expands on click;@@ -85,7 +85,13 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to### Files Panel-The files panel browses the Workspace tree, previews files (Markdown / HTML rendered), uploads files (≤ 14MB each), and downloads them.+The files panel shows the Workspace as a directory tree on the left and a preview of the selected file on the right. A directory lists its contents the first time it is opened; the tree takes the arrow keys (up/down move, right opens a directory or steps into it, left closes it or steps out), the selected file is highlighted, and the breadcrumbs above read out the current directory — a path, not a row of links, since the tree beside them is what navigates; when the path outgrows the toolbar its leading segments collapse into a single `…`, keeping the current directory visible and Refresh and Upload on the same row; the root segment reads `.`, and the Workspace's absolute path lives in the Session details card rather than on this toolbar. A search box above the tree filters what the tree holds: matching is on the entry's name, a match keeps its parent directories visible and open, and a directory whose own name matches is shown with its contents. The tree is lazy, so the search reaches only the directories that have been opened at least once — when nothing in them matches it says so rather than looking empty; Esc clears the box. Opening or closing a directory grows its subtree out of its row, or shrinks it back into it, over about 200ms — the rows stay on screen until the collapse finishes; with reduced motion the change is immediate. A toolbar toggle hides or shows the tree (shown by default; the choice is remembered in the browser) and slides out of and back into the panel's left edge over about 200ms, the motion the docks themselves expand and collapse with; the divider between the two panes drags to set the tree's width (arrow keys nudge it while it has focus, and the width is remembered too), and a panel too narrow for both panes falls back to one column — the tree until a file is chosen, then the preview with a Back button. Markdown and HTML preview rendered with a Source toggle, text files inline with highlighting, images inline (click to zoom), PDF embedded; anything else is offered as a download. A file whose extension says nothing about its type (a `Makefile`, a `LICENSE`) is read as text when its bytes look like text.++Text files can be edited in place: **Edit** replaces the preview with a plain monospace text box — no rich editor — and **Save** (also Ctrl+S / Cmd+S) writes the file back through the same content endpoint uploads use, after the usual save confirmation; Cancel returns to the preview. A **Wrap** toggle sits beside them: off by default, so long lines scroll sideways as they would in a code editor, and the choice carries to the next file you edit. The panel asks before unsaved changes would be lost — switching to another file, closing the panel's tab, leaving the page. Collapsing or hiding the dock loses nothing: the panel stays exactly as it was, preview, tree and draft included, and comes back untouched without asking. A draft survives a Session switch too: opening the same file again reopens the editor on it. A file larger than the 256KB preview cap is shown truncated and stays read-only (saving a partial text would overwrite the whole file), and a save over the 14MB write limit is refused with a message.++Because the Agent writes to the same Workspace, a file can change while you are editing it. It is checked whenever a turn finishes — your text is never replaced, but the editor header says **Changed on disk** as soon as it has — and a save that would land on a changed file is refused before anything is written: the panel asks whether to **Overwrite** it with your version or keep editing, and your text is kept either way.++Uploads go into the current directory (the toolbar's **Upload** button, several files at a time), or files can be **dragged from the desktop onto the panel**: a dashed frame names the directory they will land in, dropping onto a folder row uploads into that folder (the row highlights while the drag is over it), and the first uploaded file opens afterwards. Each file is limited to 14MB — oversize picks are named and skipped before anything is read — and a same-named file in the target directory is overwritten after confirmation. Download is in the preview header.## Agent Management (/agents)diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex ffaf12cf..e2b70f8c 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -72,7 +72,7 @@ penguin web- Enter 发送,Shift+Enter 换行,支持粘贴图片——嵌入对话的图片单独设有 20MB 上限,不随附件上限一起放宽:图片会进入对话与轨迹,此后每次翻阅历史、恢复会话都要重新付出它的体积,而附件只是按路径从磁盘读取;- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,默认单个 ≤ 100MB、合计 ≤ 120MB——两个尺寸均可由管理员在**系统设置 → 上传限制**中调整,见下文;超限的文件在读取前即被拒绝,不会先上传再报错,提示中会写出当前生效的上限),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;-- 也可以把文件**拖拽到聊天区**上传(聊天区即对话与输入框所在区域,会话页与草稿页皆可):文件拖到该区域上方时显示覆盖该区域的「松开以添加附件」浮层(拖离即消失,拖动文本等非文件内容不触发),松开即把整批文件附加到输入框——图片走粘贴图片的同一管线,其余文件成为附件,类型与大小校验及报错与「+」菜单一致。任务运行中同样可以拖入(附件按下述运行中发送方式送出);目标模式下拖入的图片照常附加、文件会以提示拒绝。只有聊天区会响应:把文件放到侧边栏、顶栏、右侧停靠面板或任何没有输入框的页面上,既不显示浮层也不会添加附件,只是被直接忽略,同时不会让浏览器跳转打开该文件;+- 也可以把文件**拖拽到聊天区**上传(聊天区即对话与输入框所在区域,会话页与草稿页皆可):文件拖到该区域上方时显示覆盖该区域的「松开以添加附件」浮层(拖离即消失,拖动文本等非文件内容不触发),松开即把整批文件附加到输入框——图片走粘贴图片的同一管线,其余文件成为附件,类型与大小校验及报错与「+」菜单一致。任务运行中同样可以拖入(附件按下述运行中发送方式送出);目标模式下拖入的图片照常附加、文件会以提示拒绝。只有聊天区会把文件作为附件:把文件放到侧边栏、顶栏、其他停靠面板或任何没有输入框的页面上,既不显示浮层也不会添加附件,只是被直接忽略,同时不会让浏览器跳转打开该文件(文件面板是另一处拖放目标,它把文件上传到 Workspace,见下文);- 输入 `/` 打开快捷菜单:触发上下文压缩(`/compact`)、把会话交接给其他 Agent(`/agent`)、切换模型(`/model`)——两个切换命令都只在进行中的会话里提供,草稿没有可切换的对话,Agent 与模型本就在草稿页选定——或勾选已安装的 Skill——所选 Skill 会以 `[use_skills]` 块随消息发送;- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失)。每条排队提示——未送达的插话或排队中的跟进消息——行尾都带一枚**撤回**按钮(一个向回弯的箭头图标),可把消息(含附件)撤回到输入框编辑后重新发送;插话一旦送达模型即不可撤回。运行在插话送达之前结束时(工具跑着的时候按停止是最常见的情形)不用你动手:这条插话会自动回到输入框,附件一并还原,改完可以直接再发——打断不会吃掉已经打好的话;- `/agent` 与 `/model` 都是暂存而非立即生效:选中的 Agent 或模型只在文本区上方留下一枚 chip,此时不发送任何内容,可以继续输入——按 Enter / 点发送才真正交接(为该 Agent 新开一个对话)或换用所选模型继续本对话,输入的文字随之带走;正文为空时自动填入默认消息,点 chip 上的 × 即可取消。两枚 chip 都随草稿缓存,刷新页面或切到别的会话再回来时与文字一同恢复;其中切换模型还需等待会话空闲——新会话要从本会话的 Trace 接续,而运行中的一轮或压缩仍在写入——等待期间输入框上方会给出说明;@@ -84,7 +84,13 @@ penguin web### 文件面板-文件面板可浏览 Workspace 目录树、预览文件(Markdown / HTML 渲染显示)、上传文件(单个 ≤ 14MB)与下载文件。+文件面板左侧是 Workspace 的目录树,右侧是所选文件的预览。目录在首次展开时才加载内容;目录树支持方向键(上下移动、右键展开目录或进入其中、左键收起或回到上级),选中的文件高亮,工具栏的面包屑只读出当前目录的路径、不再可点——旁边就是目录树,导航交给它;路径长到工具栏放不下时,前导段折叠成一个「…」,当前目录始终可见,刷新 / 上传也不会被挤到第二行;根目录在面包屑里写作 `.`,Workspace 的绝对路径在会话详情卡片里,不在这条工具栏上。目录树上方的搜索框按条目名称过滤:命中项的上级目录一并保留并展开,名称本身命中的目录连同其内容一起显示。目录树是懒加载的,搜索只能覆盖至少展开过一次的目录——都不匹配时会明说,而不是显示成空树;按 Esc 清空搜索框。展开 / 折叠时子树以高度过渡动画展开或收起(约 200ms,折叠期间行仍可见直至收起完成;系统设为减少动态时即时)。工具栏按钮可隐藏或显示目录树(默认显示,选择记在浏览器本地),显隐时目录树以约 200ms 的宽度过渡滑出或滑入,与停靠面板展开 / 收起同款;两栏之间的分隔条可拖动调整目录树宽度(获得焦点后可用左右方向键微调,宽度同样记住);面板宽度容不下两栏时退化为单栏——先显示目录树,选中文件后换成带「返回列表」按钮的预览。Markdown 与 HTML 以渲染视图预览并可切换源码,文本文件内联高亮显示,图片内联显示(点击放大),PDF 内嵌;其余类型提示下载。扩展名看不出类型的文件(`Makefile`、`LICENSE` 之类)在内容看起来是文本时按文本处理。++文本文件可以就地编辑:**编辑**把预览换成纯文本的等宽文本框——没有富文本编辑器——**保存**(也可按 Ctrl+S / Cmd+S)经上传所用的同一内容写接口写回文件,保存前先弹统一的确认框;取消则回到预览。旁边还有**自动换行**开关:缺省关闭,长行像代码编辑器那样横向滚动,选择会带到下一个编辑的文件。未保存的修改在可能丢失之前都会先询问——切换到别的文件、关闭该面板的标签页、离开页面。折叠或隐藏停靠面板不会丢失任何东西:面板连同预览、目录树状态与编辑草稿原样留着,重新展开即回到原处,也不会询问。切换 Session 时草稿也会保留:再次打开同一文件即回到编辑状态。超过 256KB 预览上限的文件以截断方式显示且保持只读(把不完整的文本存回去会覆盖整个文件);超过 14MB 写入上限的保存会被拒绝并给出提示。++Agent 写的是同一个 Workspace,你编辑期间文件可能被改动。每轮 Task 结束时都会检查一次——你的文本不会被替换,但编辑器标题栏会立即标出**磁盘上已变更**;若保存会落在已变更的文件上,写入前即被拒绝:面板会询问是用你的版本**仍然覆盖**,还是继续编辑,两种选择都保留你的文本。++上传写入当前目录(工具栏的**上传**按钮,可一次多选),也可以把文件**从桌面拖到面板上**:虚线框会标出文件将落入的目录,拖到某个文件夹行上松开即上传到该文件夹(拖动经过时该行高亮),完成后自动打开第一个上传的文件。单个文件上限 14MB——超限的文件在读取前即被点名跳过——目标目录中已有同名文件时先确认再覆盖。下载按钮在预览标题栏。## Agent 管理(/agents)diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex f9c4ca6e..6904c006 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -2569,6 +2569,22 @@ export interface WorkspaceFilesResponse {entries: WorkspaceFileEntry[];}+/** Write one Workspace file whole (the Upload button, a drop, and the Files panel's editor). */+export interface FilesWriteRequest {+ /** The entire file, base64-encoded (≤14MB decoded). */+ dataBase64: string;+ /**+ * Write precondition: the version marker the caller read off this file's `ETag` on+ * `GET files/content`. The server compares it against the file's state immediately+ * before writing and answers 409 `file_changed` — having written nothing — when they+ * differ, which is what stops the editor's save from quietly dropping what the Agent+ * wrote during the turn. Omitted by a caller that read no version (an upload creates or+ * replaces unconditionally); that absence, not a sentinel value, is what says there was+ * no prior version to match.+ */+ ifVersion?: string;+}+/** Batch file existence check (message file cards only list files that actually exist). */export interface FilesStatRequest {/** Paths relative to the Workspace root (≤100 items, each ≤512 characters). */diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 1dd4a62d..e1cc3a50 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -1223,7 +1223,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {// 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 } = await deps.workspaceFiles.read(+ const { data, fileName, contentType, scriptable, version } = await deps.workspaceFiles.read(row.workspace,rel,);@@ -1251,6 +1251,10 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {// 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":@@ -1344,7 +1348,9 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {if (data.length > MAX_UPLOAD_BYTES) {throw new HttpError(413, "file_too_large", "Uploaded file exceeds the 14MB limit.");}- await deps.workspaceFiles.write(row.workspace, rel, data);+ // 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);});diff --git a/packages/server/src/services/workspace-files-service.ts b/packages/server/src/services/workspace-files-service.tsindex 283889a9..2bbd1d72 100644--- a/packages/server/src/services/workspace-files-service.ts+++ b/packages/server/src/services/workspace-files-service.ts@@ -56,6 +56,30 @@ export interface WorkspaceFileContent {scriptable: "html" | "svg" | false;/** True when a bounded preview returned only the beginning of the file. */truncated?: boolean;+ /** The file's version at the moment it was read — see {@link fileVersion}. */+ version: string;+}++/**+ * A file's version marker: the weak size+mtime validator the static asset route already+ * mints (see app.ts) — the classic disk-file shape, and far cheaper than hashing every+ * read. Opaque to clients: they get it from a read and hand it straight back on a write.+ */+function fileVersion(stat: { size: number; mtimeMs: number }): string {+ return `W/"${stat.size}-${Math.round(stat.mtimeMs)}"`;+}++/**+ * A write precondition failed: the file is not the one the caller read. 409 rather than+ * HTTP's 412 — the marker travels in the request body, not as `If-Match`, so this is the+ * app's own conflict and rides the same route error path as the other 409s.+ */+function fileChanged(): HttpError {+ return new HttpError(+ 409,+ "file_changed",+ "File changed on disk since it was read; nothing was written.",+ );}export interface WorkspaceFileReadOptions {@@ -255,7 +279,16 @@ export class WorkspaceFilesService {return { path: rel, entries };}- /** Read a file (preview/download): IO on the canonical path (resolveRead has already eliminated symlink escapes). */+ /**+ * Read a file (preview/download): IO on the canonical path (resolveRead has already+ * eliminated symlink escapes).+ *+ * The stat below runs **before** the bytes are read, and that order is load-bearing now+ * that it also mints the version marker: a rewrite landing in between tags fresh bytes+ * with the older marker, so the worst case is one needless conflict on the next write.+ * Read-then-stat would fail the other way — old bytes carrying the new marker, which is+ * exactly the write the precondition exists to refuse.+ */async read(workspace: string,rel: string,@@ -301,6 +334,7 @@ export class WorkspaceFilesService {contentType: CONTENT_TYPES[ext] ?? "application/octet-stream",scriptable: ext === ".html" || ext === ".htm" ? "html" : ext === ".svg" ? "svg" : false,...(truncated ? { truncated: true } : {}),+ version: fileVersion(stat),};}@@ -311,8 +345,18 @@ export class WorkspaceFilesService {* O_NOFOLLOW, refusing to follow a symlink to write outside the Workspace* (together with resolveWriteParent's canonical-parent check, this blocks* sandbox escapes).+ *+ * `ifVersion` is the write precondition: the marker the caller got from its read, which+ * the file must still carry. It is compared on the **open handle** — a handle names an+ * inode, so what is stat'd is exactly what is about to be truncated, with no window in+ * between. A caller that passes none read no version and gets the unconditional+ * create-or-overwrite an upload wants: the field's absence, not some sentinel value, is+ * what separates "first write of a file that isn't there" from "the file I read has+ * 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.*/- async write(workspace: string, rel: string, data: Buffer): Promise<void> {+ async write(workspace: string, rel: string, data: Buffer, ifVersion?: string): Promise<void> {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.");@@ -329,19 +373,29 @@ export class WorkspaceFilesService {if (st?.isSymbolicLink()) throw badRequest("path must not be a symlink.");}// O_NOFOLLOW: open reports ELOOP if the final segment is a symlink, refusing to use it as leverage to overwrite a file outside the sandbox.- const flags = fsc.O_WRONLY | fsc.O_CREAT | fsc.O_TRUNC | (fsc.O_NOFOLLOW ?? 0);+ const conditional = ifVersion !== undefined;+ const flags =+ fsc.O_WRONLY | (fsc.O_NOFOLLOW ?? 0) | (conditional ? 0 : fsc.O_CREAT | fsc.O_TRUNC);let handle;try {handle = await fs.open(file, flags, 0o644);} catch (err) {const code = (err as NodeJS.ErrnoException).code;if (code === "ELOOP") throw badRequest("path must not be a symlink.");- if (code === "ENOENT")+ if (code === "ENOENT") {+ if (conditional) throw fileChanged();throw new HttpError(404, "path_not_found", "Parent directory does not exist.");+ }if (code === "EISDIR") throw badRequest("path is a directory.");throw err;}try {+ if (conditional) {+ if (fileVersion(await handle.stat()) !== ifVersion) throw fileChanged();+ // O_TRUNC was withheld above so the check could run first; do it now, on the same+ // handle, immediately before the bytes go down.+ await handle.truncate(0);+ }await handle.writeFile(data);} finally {await handle.close();diff --git a/packages/server/test/workspace-files.test.ts b/packages/server/test/workspace-files.test.tsindex fd641fa2..6e7e09ff 100644--- a/packages/server/test/workspace-files.test.ts+++ b/packages/server/test/workspace-files.test.ts@@ -120,6 +120,39 @@ describe("workspace-files-service", () => {// The outside file's content is unchanged.expect(await fs.readFile(victim, "utf8")).toBe("secret");});++ it("write precondition: a matching version writes, one the file has moved past is refused with nothing written", async () => {+ const { version } = await svc.read(ws, "b.txt");+ // The Agent rewrites the same file while the user is editing it. mtime resolution can be+ // coarse, so the size differs too — either half of the marker moving is a mismatch.+ await fs.writeFile(path.join(ws, "b.txt"), "agent wrote this");++ await expect(svc.write(ws, "b.txt", Buffer.from("user typed this"), version)).rejects.toEqual(+ expect.objectContaining({ status: 409, code: "file_changed" }),+ );+ expect(await fs.readFile(path.join(ws, "b.txt"), "utf8")).toBe("agent wrote this");++ // Re-reading picks up the new version, and the same save then goes through — and the+ // file is truncated to the new content, not left with a tail of the longer old one.+ const fresh = await svc.read(ws, "b.txt");+ await svc.write(ws, "b.txt", Buffer.from("user typed this"), fresh.version);+ expect(await fs.readFile(path.join(ws, "b.txt"), "utf8")).toBe("user typed this");+ });++ it("write precondition: no marker creates a file that was never there, a marker on a deleted file is refused and creates nothing", async () => {+ // An upload reads no version and so carries no marker: unconditional create.+ await svc.write(ws, "fresh.txt", Buffer.from("new"));+ expect(await fs.readFile(path.join(ws, "fresh.txt"), "utf8")).toBe("new");++ // The editor's marker says a file was read; the file being gone is a change like any+ // other — and a refused write must not leave the empty file O_CREAT would have made.+ const { version } = await svc.read(ws, "fresh.txt");+ await fs.rm(path.join(ws, "fresh.txt"));+ await expect(svc.write(ws, "fresh.txt", Buffer.from("x"), version)).rejects.toEqual(+ expect.objectContaining({ status: 409, code: "file_changed" }),+ );+ expect(await fs.stat(path.join(ws, "fresh.txt")).catch(() => null)).toBeNull();+ });});describe("files/stat route (batch existence check)", () => {@@ -221,6 +254,46 @@ describe("files/stat route (batch existence check)", () => {expect(res.headers.get("cache-control")).toBe("no-store");});+ it("files/content: the read carries a version the write demands back — a save over an Agent's rewrite is 409, not a silent overwrite", async () => {+ const url = `/api/sessions/${sessionId}/files/content?path=a.txt`;+ const read = await owner.get(url);+ const version = read.headers.get("etag");+ expect(version).toMatch(/^W\/"\d+-\d+"$/);++ // The user is editing a.txt when the Agent rewrites it mid-turn.+ await fs.writeFile(path.join(workspace, "a.txt"), "written by the agent");++ const stale = await owner.put(url, {+ dataBase64: Buffer.from("typed by the user").toString("base64"),+ ifVersion: version,+ });+ expect(stale.status).toBe(409);+ expect(await stale.json()).toEqual({+ error: { code: "file_changed", message: expect.any(String) },+ });+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("written by the agent");++ // The current version is accepted; so is a write that carries no version at all (an+ // upload, which read none) — that absence is what makes a first write of a new file work.+ const current = (await owner.get(url)).headers.get("etag");+ const saved = await owner.put(url, {+ dataBase64: Buffer.from("typed by the user").toString("base64"),+ ifVersion: current,+ });+ expect(saved.status).toBe(204);+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("typed by the user");++ const uploaded = await owner.put(`/api/sessions/${sessionId}/files/content?path=new.txt`, {+ dataBase64: Buffer.from("uploaded").toString("base64"),+ });+ expect(uploaded.status).toBe(204);+ expect(await fs.readFile(path.join(workspace, "new.txt"), "utf8")).toBe("uploaded");++ // A non-string marker is a bad request, not a silently dropped precondition.+ const bad = await owner.put(url, { dataBase64: "", ifVersion: 7 });+ expect(bad.status).toBe(400);+ });+it("existing files return in order, deduplicated; missing / directory / out-of-bounds all count as nonexistent, always 200", async () => {const res = await owner.post(`/api/sessions/${sessionId}/files/stat`, {paths: ["sub/b.md", "a.txt", "sub/b.md", "nope.txt", "sub", "../escape.txt", "/etc/passwd"],diff --git a/packages/web/e2e/chat.spec.mjs b/packages/web/e2e/chat.spec.mjsindex f62e517e..5f0cb955 100644--- a/packages/web/e2e/chat.spec.mjs+++ b/packages/web/e2e/chat.spec.mjs@@ -293,15 +293,12 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })// Rendered iframe present; the localStorage script ran on the preview origin → #shim-ok appended.await expect(page.locator("iframe")).toBeVisible();await expect(page.frameLocator("iframe").locator("#shim-ok")).toHaveText("1");- // The list and the preview are mutually exclusive: the toolbar only appears after- // returning to the list (which also triggers #59's return-refresh).- await page.getByRole("button", { name: "返回列表" }).click();+ // The tree stays beside the open preview, and the toolbar (breadcrumbs, Refresh, Upload)+ // sits above both — nothing to go back to.await expect(page.getByText("demo.html").first()).toBeVisible();- // Workspace path is hidden until the 详情 ("Details") toggle is used.+ // The absolute Workspace path is not on this panel; it belongs to the Session details card.const workspaceAbs = sess.session.workspace;await expect(page.getByText(workspaceAbs, { exact: false })).toHaveCount(0);- await page.getByRole("button", { name: "详情" }).click();- await expect(page.getByText(workspaceAbs, { exact: false }).first()).toBeVisible();// --- message files card: only files that really exist in the workspace make the card ---// The mock reply mentions two backtick paths: demo.html was truly uploaded above viadiff --git a/packages/web/e2e/dock.spec.mjs b/packages/web/e2e/dock.spec.mjsindex 826c5f59..7fd69920 100644--- a/packages/web/e2e/dock.spec.mjs+++ b/packages/web/e2e/dock.spec.mjs@@ -81,9 +81,11 @@ async function killAllTerminals(request) {.toBe(0);}+// A hidden dock stays in the DOM at zero size (its panels keep their state), so "on+// screen" is data-open, not the node's presence.const dockAt = (page, position) =>- page.locator(`[data-testid="dock"][data-position="${position}"]`);-const anyDock = (page) => page.locator('[data-testid="dock"]');+ page.locator(`[data-testid="dock"][data-position="${position}"][data-open="true"]`);+const anyDock = (page) => page.locator('[data-testid="dock"][data-open="true"]');const terminalBody = (page) => page.locator('[data-testid="dock-terminal-body"]:visible');const screenText = (page) => terminalBody(page).locator(".xterm-rows").innerText();diff --git a/packages/web/e2e/mobile-dock.spec.mjs b/packages/web/e2e/mobile-dock.spec.mjsindex e178ca8a..ace429c6 100644--- a/packages/web/e2e/mobile-dock.spec.mjs+++ b/packages/web/e2e/mobile-dock.spec.mjs@@ -60,6 +60,8 @@ test("mobile merged dock: workspace opens at the bottom → nested dir → md re// One merged bottom surface, never a right dock at this width.const dock = page.locator('[data-testid="dock"][data-position="bottom"]');await expect(dock).toBeVisible();+ // Absent, not hidden: a hidden dock would still be in the DOM (at zero size, keeping its+ // panels), while at this width there is no right surface to render at all.await expect(page.locator('[data-testid="dock"][data-position="right"]')).toHaveCount(0);await dock.getByTestId("dock-pick-workspace").click();await expect(dock.locator('[data-tab-id="workspace"][data-active="true"]')).toBeVisible();diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 8cbd9e30..92b71074 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -44,6 +44,7 @@ import type {FeishuTestResponse,FilesStatRequest,FilesStatResponse,+ FilesWriteRequest,GoalResponse,InstallResponse,McpServerTestResponse,@@ -996,10 +997,21 @@ export const workspaceFileUrl = (sessionId: string, path: string, download = falexport const workspaceFilePreviewUrl = (sessionId: string, path: string): string =>`/api/sessions/${sessionId}/files/preview-redirect?path=${encodeURIComponent(path)}`;-export const uploadWorkspaceFile = (sessionId: string, path: string, dataBase64: string) =>+/**+ * Writes a Workspace file whole. `ifVersion` is the marker a previous read returned in its+ * `ETag`: pass it and the write is refused with 409 `file_changed` unless the file is 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).+ */+export const uploadWorkspaceFile = (+ sessionId: string,+ path: string,+ dataBase64: string,+ ifVersion?: string,+) =>apiFetch<void>(`/api/sessions/${sessionId}/files/content`, {method: "PUT",- body: { dataBase64 },+ body: { dataBase64, ifVersion } satisfies FilesWriteRequest,query: { path },});diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 52082c77..79ed8c7e 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -117,6 +117,7 @@ import { panelLabel } from "../dock/panel-meta";import { setDockCwd } from "../dock/dock-terminal";import {adoptDockScope,+ closedDockView,dockViews,dockVersion,isTabShown,@@ -1538,11 +1539,19 @@ export function ChatPage() {// view arrives as a bottom view). They render on the draft page too — the arrangement is// the user's workbench, and a terminal opened while drafting must be visible — with the// session-bound panels showing a placeholder until the first send creates the Session.- // useDockMount keeps a closing dock mounted through its collapse transition and skips- // the animation for instant changes (scope switches, cross-dock moves).+ // useDockMount keeps a closing dock mounted through its collapse transition and then+ // holds it at zero size on closedDockView, so hiding a dock costs none of what its panels+ // hold; it skips the animation for instant changes (scope switches, cross-dock moves).+ // Narrow: the merged view is a bottom view, and the closed one goes to the same mount.const views = dockViews();- const rightMount = useDockMount(views.find((view) => view.position === "right") ?? null);- const bottomMount = useDockMount(views.find((view) => view.position === "bottom") ?? null);+ const rightMount = useDockMount(+ views.find((view) => view.position === "right") ?? null,+ closedDockView("right"),+ );+ const bottomMount = useDockMount(+ views.find((view) => view.position === "bottom") ?? null,+ closedDockView("bottom"),+ );const terminalSupported = terminalApiSupported();/**diff --git a/packages/web/src/features/chat/panels-toolbar.tsx b/packages/web/src/features/chat/panels-toolbar.tsxindex b0cc566a..245bc0cf 100644--- a/packages/web/src/features/chat/panels-toolbar.tsx+++ b/packages/web/src/features/chat/panels-toolbar.tsx@@ -57,6 +57,8 @@ export function PanelsToolbar({ agentsPending }: PanelsToolbarProps) {key={position}type="button"aria-expanded={isDockVisible(position)}+ // Hiding a dock keeps every body mounted (dock-panel.tsx renders it at zero+ // size), so a tab holding unsaved work has nothing to lose and nothing to ask.onClick={() => toggleDock(position)}title={label}aria-label={label}diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex 0cec48ed..01d0fcc6 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -1,93 +1,119 @@/**- * Workspace file browser (the "Browse All" tab of the Files panel): directory navigation- * (breadcrumbs, going up a level navigates via a breadcrumb segment), file list (name/size/- * modified time), preview (Markdown/HTML default to a rendered view + a source toggle, text/- * images shown inline, other types prompt a download), upload (multi-select in the current- * directory, single file <=14MB) and download. Path scoping is validated by the server (including- * auto-creating missing parent directories within the sandbox, an API-level capability).+ * Workspace file browser (the Files panel): a directory tree on the left, listing each+ * directory the first time it opens, and a preview of the selected file on the right —+ * Markdown / HTML rendered with a source toggle, text inline (highlighted), images inline+ * (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.*- * Single-column list <-> preview drill-down (no side-by-side layout): the panel's width is- * controlled by the outer Files panel and may be much narrower than the viewport, so `lg:`-style- * viewport breakpoints would misjudge things here (a wide viewport doesn't mean this component- * got a wide allotment of space) — so the list and preview are shown mutually exclusively,- * routed by whether the existing `preview` is null, without introducing extra state.+ * 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+ * sets its width; both, and the editor's soft-wrap toggle, are browser preferences.+ * The panel's width is the dock's, which may be far narrower than the viewport, so the+ * layout follows a measured width rather than a viewport breakpoint: below+ * TREE_LAYOUT_MIN_WIDTH the panes stop sharing the row and the tree and the preview show+ * one at a time — selecting a file replaces the tree, Back returns to it, and the divider+ * has nothing to divide. Path scoping is the server's job (including creating missing+ * parent directories inside the sandbox).+ *+ * The toolbar is one row that never wraps: the breadcrumbs read the current path (the tree+ * beside them is what navigates), and when the path outgrows the space its leading segments+ * collapse into a single "…" so Refresh and Upload keep their places.*/-import { useCallback, useEffect, useRef, useState } from "react";-import type { ChangeEvent } from "react";+import {+ Fragment,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import type {+ ChangeEvent,+ DragEvent as ReactDragEvent,+ KeyboardEvent as ReactKeyboardEvent,+} from "react";import ReactMarkdown from "react-markdown";import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";-import type { SessionInfo, WorkspaceFilesResponse } from "@prismshadow/penguin-server/api";+import type { SessionInfo } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";import { useAuth } from "../../state/auth";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { joinWorkspacePath } from "../../lib/file-path";-import { formatBytes, formatDateTime } from "../../lib/format";+import { dropRegionAction, isFileDrag } from "../../lib/file-drop";+import type { DragSignal } from "../../lib/file-drop";+import { MB_BYTES, splitBySize } from "../../lib/upload-limits";+import {+ CRUMB_ELLIPSIS,+ TEXT_PREVIEW_LIMIT,+ TREE_DIVIDER_PX,+ TREE_MIN_WIDTH,+ WORKSPACE_UPLOAD_LIMIT_MB,+ ancestorDirs,+ baseName,+ canEditPreview,+ clampTreeWidth,+ defaultTreeWidth,+ dropTargetDir,+ expandTo,+ extOf,+ filterTreeRows,+ flattenTree,+ isDirty,+ isNarrowLayout,+ looksLikeText,+ maxTreeWidth,+ needsDiscardConfirm,+ parentDir,+ previewKindFor,+ readEditorWrap,+ readTreeVisible,+ readTreeWidth,+ upsertEntry,+ utf8Complete,+ visibleCrumbSegments,+ withExpanded,+ writeEditorWrap,+ writeTreeVisible,+ writeTreeWidth,+} from "../../lib/workspace-tree";+import type { EditorState, Listings } from "../../lib/workspace-tree";import { Button } from "../../components/ui/button";import { ConfirmModal } from "../../components/ui/confirm-modal";-import { toastError, toastSuccess } from "../../components/ui/toast";-import { Dropdown } from "../../components/ui/dropdown";+import { EmptyState } from "../../components/ui/empty-state";+import { GlyphIcon } from "../../components/ui/glyph-icon";import { HiddenFileInput } from "../../components/ui/hidden-file-input";+import { CloseIcon } from "../../components/ui/icons";+import { noAutofill } from "../../components/ui/input";+import { ZoomableImage } from "../../components/ui/image-zoom";import { SkeletonList } from "../../components/ui/skeleton";+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";+import { ICON_SIZE } from "../../lib/icon-scale";+import { toneInk } from "../../lib/tone";+import { setCloseGuard } from "../dock/close-guard";+import { tabKey } from "../dock/dock-state";+import { DOCK_TRANSITION_MS } from "../dock/use-dock-mount";+import { usePointerDrag } from "../dock/use-pointer-drag";+import { PAPERCLIP_ICON } from "./attached-files-banner";import { CodeBlock } from "./code-block";import { languageForExtension } from "./code-languages";-import { toneInk } from "../../lib/tone";-import { GlyphIcon } from "../../components/ui/glyph-icon";-import { ICON_SIZE } from "../../lib/icon-scale";+import { WorkspaceFileEditor } from "./workspace-editor";+import { WorkspaceTreeView } from "./workspace-tree-view";+import type { TreeToggle } from "./workspace-tree-view";-const TEXT_EXTS = new Set([- "txt",- "md",- "json",- "js",- "mjs",- "cjs",- "ts",- "tsx",- "jsx",- "py",- "sh",- "bash",- "yaml",- "yml",- "toml",- "css",- "html",- "htm",- "csv",- "log",- "xml",- "ini",- "conf",- "rs",- "go",- "java",- "c",- "h",- "cpp",- "hpp",- "sql",- "rb",- "php",- "gitignore",- "env",-]);-const IMAGE_EXTS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg"]);-const HTML_EXTS = new Set(["html", "htm"]);-/** Read cap for text preview (beyond this, truncated with a download prompt). */-const TEXT_PREVIEW_LIMIT = 256 * 1024;-/** Source highlighting cap: tokenizing the full 256KB preview cap's worth of content in one go would block the main thread, so beyond this it falls back to unhighlighted. */+/** Source highlighting cap: tokenizing the full preview cap's worth of content in one go would block the main thread, so beyond this it falls back to unhighlighted. */const HIGHLIGHT_LIMIT = 64 * 1024;--function extOf(name: string): string {- const i = name.lastIndexOf(".");- return i >= 0 ? name.slice(i + 1).toLowerCase() : name.toLowerCase();-}--function dirOf(filePath: string): string {- return filePath.includes("/") ? filePath.slice(0, filePath.lastIndexOf("/")) : "";-}+/** Bytes examined to decide whether a file with an unknown extension is text. */+const SNIFF_BYTES = 8 * 1024;+/** Window with a left pane: the tree toggle. */+const PANEL_LEFT_ICON = "M4 5h16v14H4zM10 5v14";+/** Left-pointing chevron: the narrow layout's back-to-tree button. */+const BACK_ICON = "M15 18l-6-6 6-6";/** An external reference with a scheme (http(s)/mailto/data, etc.), passed through as-is in the md rendered view. */const EXTERNAL_REF_RE = /^[a-z][a-z0-9+.-]*:/i;@@ -133,6 +159,8 @@ interface Preview {/** Content for kind=text/md/html (may be truncated). */content?: string;truncated?: boolean;+ /** The version the content was read at; travels with it and only ever set together. */+ version?: string;/** Bumped on every previewPath call; keys the isolated HTML iframe so re-opening the* same path remounts it and refetches fresh content (its src alone would not change). */nonce: number;@@ -141,30 +169,177 @@ interface Preview {/** Monotonic counter behind Preview.nonce. Doubles as the staleness guard: previewPath* captures its value up front and publishes only while still the latest, so two rapid* calls can't have the slower loser overwrite the winner. Module scope is fine — the- * docked panel and the drawer never mount WorkspaceBrowser at the same time. */+ * panel mounts one browser per conversation on screen. */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.+ */+const unsavedDrafts = new Map<string, string>();+const draftKey = (sessionId: string, path: string): string => `${sessionId}\n${path}`;++/**+ * Reads a file as text, bounded to TEXT_PREVIEW_LIMIT bytes: the body is read as a stream+ * and cancelled past the cap, so a large log never downloads whole for a preview. With+ * `sniff`, the first chunk decides whether the file is text at all — null means it is not,+ * and nothing more of it is read. A response with no stream is thrown on rather than read+ * whole: `arrayBuffer()` would pull the entire file into memory, which is the one thing the+ * cap exists to prevent.+ *+ * The version marker is read alongside the bytes and is required: it is what the editor+ * saves against, and a response that carries content without it could only mean the+ * endpoint is broken — better a thrown read than a save with no precondition.+ */+async function fetchTextPreview(+ url: string,+ sniff: boolean,+): Promise<{ content: string; truncated: boolean; version: string } | null> {+ const res = await fetch(url, { credentials: "same-origin" });+ if (!res.ok) throw new Error(String(res.status));+ if (res.body === null) throw new Error("no response body");+ const version = res.headers.get("etag");+ if (version === null) throw new Error("no version header");+ const reader = res.body.getReader();+ const chunks: Uint8Array[] = [];+ let total = 0;+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ if (chunks.length === 0 && sniff && !looksLikeText(value.subarray(0, SNIFF_BYTES))) {+ await reader.cancel();+ return null;+ }+ chunks.push(value);+ total += value.length;+ if (total > TEXT_PREVIEW_LIMIT) {+ await reader.cancel();+ break;+ }+ }+ const bytes = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.length;+ }+ const truncated = total > TEXT_PREVIEW_LIMIT;+ const shown = truncated ? utf8Complete(bytes.subarray(0, TEXT_PREVIEW_LIMIT)) : bytes;+ return { content: new TextDecoder().decode(shown), truncated, version };+}++/**+ * The file's current version marker, without downloading it: the body is cancelled as soon+ * as the headers land. Null when the read did not get that far — the file is gone, or the+ * request failed; the caller says nothing in that case, because the save's own precondition+ * is what actually protects the file.+ */+async function fetchFileVersion(url: string): Promise<string | null> {+ const res = await fetch(url, { credentials: "same-origin" });+ await res.body?.cancel();+ return res.ok ? res.headers.get("etag") : null;+}++/** The content endpoint's payload: the base64 body of a data URL. A string Blob encodes as UTF-8, which is what a saved text file must be. */+function blobToBase64(blob: Blob): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ const url = reader.result as string;+ resolve(url.slice(url.indexOf(",") + 1));+ };+ reader.onerror = () => reject(new Error("read failed"));+ reader.readAsDataURL(blob);+ });+}++/** The tree row under a pointer, read off the row's data attributes. */+function hitRow(target: EventTarget | null): { kind: "dir" | "file"; path: string } | null {+ if (!(target instanceof Element)) return null;+ const row = target.closest<HTMLElement>("[data-tree-path]");+ if (row === null) return null;+ const kind = row.dataset.treeKind;+ const path = row.dataset.treePath;+ return (kind === "dir" || kind === "file") && path !== undefined ? { kind, path } : null;+}++/**+ * A drop's files, with dropped folders held out: the browser puts a directory into+ * `dataTransfer.files` as an unreadable pseudo-file, so uploading one gets as far as the+ * overwrite confirmation and then dies on a read error with nothing to say. Reading the+ * entries is the only way to tell the two apart; a browser that hands over no items at all+ * falls back to the plain file list.+ */+function pickDroppedFiles(data: DataTransfer): { files: File[]; dirs: string[] } {+ const files: File[] = [];+ const dirs: string[] = [];+ for (let i = 0; i < data.items.length; i += 1) {+ const item = data.items[i]!;+ const file = item.getAsFile();+ if (item.webkitGetAsEntry()?.isDirectory === true) {+ if (file !== null) dirs.push(file.name);+ } else if (file !== null) {+ files.push(file);+ }+ }+ return files.length + dirs.length > 0 ? { files, dirs } : { files: [...data.files], dirs };+}++/** ArrowLeft / ArrowRight on the focused divider, in px: coarse enough to get somewhere, fine enough to land. */+const TREE_WIDTH_STEP = 16;++/**+ * A breadcrumb item's rendered width, approximated: the toolbar has no text metrics to+ * measure against, so one character at the toolbar's text size costs CRUMB_CHAR_PX (a+ * wide character — CJK, full-width punctuation — two of those) and the item itself costs+ * its padding plus the separator drawn before it. Erring wide is the safe direction: it+ * collapses one segment early rather than letting the row outgrow its space.+ */+const CRUMB_CHAR_PX = 7;+const CRUMB_ITEM_PX = 16;+const WIDE_CHAR_RE =+ /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe6f\uff00-\uff60\uffe0-\uffe6]/;++function crumbItemWidth(text: string): number {+ let cells = 0;+ for (const ch of text) cells += WIDE_CHAR_RE.test(ch) ? 2 : 1;+ return CRUMB_ITEM_PX + cells * CRUMB_CHAR_PX;+}++const ghostActionClass =+ "inline-flex shrink-0 items-center gap-1 rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";++/** The same action, as a toggle: pressed is a filled resting state, not a hover that happens to stick. */+const toggleActionClass = (on: boolean): string =>+ `inline-flex shrink-0 items-center rounded-md border border-transparent px-2.5 py-1 text-xs font-medium transition-colors duration-150 ${+ on+ ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "bg-transparent text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"+ }`;+export function WorkspaceBrowser({session,openRequest,active,- onPreviewOpen,reloadSignal,}: {session: SessionInfo;- /** External navigation command (from clicking a file chip in a message): navigates to the- * directory and previews that path. Triggers again whenever the object reference changes,+ /** 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). */openRequest?: { path: string } | null;- /** Whether the panel is visible: when collapsed in the docked state, the component stays- * mounted (width 0), during which the list can go stale as the Agent writes files; a refresh- * is issued right at the moment it transitions from hidden to visible. */+ /** Whether the panel is on screen — false for a covered tab and for a hidden dock, both of+ * which keep the component mounted (at width 0) with everything it holds. The tree can go+ * stale as the Agent writes files while it is away, so a refresh is issued right at the+ * moment it transitions from hidden to visible. */active?: boolean;- /** Callback when entering file preview (used by the mobile Sheet to raise its snap point to full). */- onPreviewOpen?: () => void;/*** Bumped by the parent every time a Task settles on this session: the turn that just ended- * is exactly when the Agent's writes land, so the listing — and whatever file is open in+ * is exactly when the Agent's writes land, so the tree — and whatever file is open in* the preview — is stale the moment it does. Any change of the number means "re-read",* so the initial value is irrelevant and no edge tracking is needed.*/@@ -175,163 +350,335 @@ export function WorkspaceBrowser({// the new tab to the same-origin sandbox (which the link flags rather than failing// silently in the page) and the in-app rendered view to the srcDoc fallback.const { previewIsolated } = useAuth();- const [path, setPath] = useState("");- /**- * The loaded listing, bound to the path it was fetched for. Entry-row targets (descend /- * preview / download) are joined against `base` — the generation the rendered rows came- * from — never against the live `path` state: the stale rows stay on screen while a- * navigation fetch is in flight, and joining onto the already-advanced path would compound- * segments on a double-click ("home" → "home/home", a directory that does not exist).- * Base-bound targets make a repeated click recompute the same target, i.e. a no-op.- */- const [data, setData] = useState<{ base: string; res: WorkspaceFilesResponse } | null>(null);- const [error, setError] = useState<string | null>(null);+ 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());+ /** Open directories (the root is always open and never listed here). */+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());+ const [loadingDirs, setLoadingDirs] = useState<ReadonlySet<string>>(() => new Set());+ const [rootError, setRootError] = useState<string | null>(null);+ /** The directory the breadcrumbs name and uploads land in: the selected file's, or the last folder clicked. */+ const [currentDir, setCurrentDir] = useState("");+ /** The file chosen in the tree; the preview follows it once loaded. */+ const [selectedPath, setSelectedPath] = useState<string | null>(null);+ const [scrollTo, setScrollTo] = useState<{ path: string } | null>(null);+ /** The search box's text. Deliberately not persisted: a filter is a thing you are doing, not a setting. */+ const [query, setQuery] = useState("");+ /** The directory last opened or closed, so the tree animates exactly that subtree once. */+ const [toggled, setToggled] = useState<TreeToggle | null>(null);+ // -------------------------------------------------------------------- preview / editorconst [preview, setPreview] = useState<Preview | null>(null);- const [uploading, setUploading] = useState(false);- /** Picked files whose names collide with the loaded listing (non-null shows the overwrite confirm). */- const [pendingUpload, setPendingUpload] = useState<{ files: File[]; clashes: string[] } | null>(- null,- );- const [reloadTick, setReloadTick] = useState(0);- const [showPath, setShowPath] = useState(false);/** HTML / Markdown preview: rendered view (HTML via sandboxed iframe, Markdown via md-body) / source toggle. */const [richView, setRichView] = useState<"rendered" | "source">("rendered");/** Error from the lazy source fetch of an isolated HTML preview: scoped to the source* view — the rendered iframe keeps working no matter what happens to this fetch. */const [sourceError, setSourceError] = useState<string | null>(null);- /** Mirror for previewPath: reading previewIsolated through a ref keeps the callback's- * identity stable when /api/me refreshes it (previewPath drives the openRequest locate- * effect, which must not replay on an auth-context change). */- const previewIsolatedRef = useRef(previewIsolated);- previewIsolatedRef.current = previewIsolated;+ const [editor, setEditor] = useState<EditorState | null>(null);+ const [saving, setSaving] = useState(false);+ const [saveConfirm, setSaveConfirm] = useState(false);+ /** A save the server refused because the file had changed (non-null shows the conflict dialog). */+ const [conflict, setConflict] = useState<{ name: string } | null>(null);+ /** The open "discard unsaved changes?" question, resolving with the answer. */+ const [discardPrompt, setDiscardPrompt] = useState<{ resolve: (ok: boolean) => void } | null>(+ null,+ );+ // ------------------------------------------------------------------------ upload / drop+ const [uploading, setUploading] = useState<{ done: number; total: number } | null>(null);+ /** Picked files whose names collide with the target directory's listing (non-null shows the overwrite confirm). */+ const [pendingUpload, setPendingUpload] = useState<{+ files: File[];+ clashes: string[];+ dir: string;+ } | null>(null);+ const [drag, setDrag] = useState<{ active: boolean; targetDir: string }>({+ active: false,+ targetDir: "",+ });+ // ----------------------------------------------------------------------------- chrome+ const [treeVisible, setTreeVisible] = useState(() => readTreeVisible());+ /**+ * True for the length of the show/hide transition and only then. The pane's width is also+ * the panel's own size talking — dragging the divider, or the dock's edge, moves it too —+ * and a transition left permanently on would make those drags lag a fifth of a second+ * behind the pointer. The toggle arms it; the timer below disarms it.+ */+ const [treeSliding, setTreeSliding] = useState(false);+ /** The dragged tree width, or null while the user has never dragged it (the computed default stands). */+ const [treeWidthPref, setTreeWidthPref] = useState<number | null>(() => readTreeWidth());+ const [resizingTree, setResizingTree] = useState(false);+ const [editorWrap, setEditorWrap] = useState(() => readEditorWrap());+ const [width, setWidth] = useState(0);+ /** The breadcrumb strip's own width: it is `flex-1` over a zero basis, so it measures the space left by the actions and never its own content — no feedback loop. */+ const [crumbsWidth, setCrumbsWidth] = useState(0);+ const rootRef = useRef<HTMLDivElement | null>(null);+ const treePaneRef = useRef<HTMLDivElement | null>(null);+ const crumbsRef = useRef<HTMLDivElement | null>(null);- useEffect(() => {- let cancelled = false;- setError(null);- api- .listWorkspaceFiles(session.sessionId, path)- .then((res) => {- if (!cancelled) setData({ base: path, res });- })- .catch((e: unknown) => {- if (!cancelled) setError(e instanceof ApiError ? e.message : S.files.loadFailed);- });- return () => {- cancelled = true;- };- }, [session.sessionId, path, reloadTick, reloadSignal]);-- // Session switched: back to the root directory 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), so a late result can't resurrect old-session content after the reset.- const [renderedSessionId, setRenderedSessionId] = useState(session.sessionId);- if (renderedSessionId !== session.sessionId) {- setRenderedSessionId(session.sessionId);- setPath("");+ // Mirrors for the async flows and stable callbacks below, which must read the latest+ // value without re-creating themselves on every change.+ const listingsRef = useRef(listings);+ listingsRef.current = listings;+ const expandedRef = useRef(expanded);+ expandedRef.current = expanded;+ const editorRef = useRef(editor);+ editorRef.current = editor;+ const currentDirRef = useRef(currentDir);+ currentDirRef.current = currentDir;+ const previewRef = useRef(preview);+ previewRef.current = preview;+ const uploadingRef = useRef(uploading);+ uploadingRef.current = uploading;+ /** 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);+ setListings(new Map());+ setExpanded(new Set());+ setLoadingDirs(new Set());+ setRootError(null);+ setCurrentDir("");+ setSelectedPath(null);+ setScrollTo(null);+ setQuery("");+ setToggled(null);setPreview(null);- setData(null);setSourceError(null);+ setEditor(null);+ setSaveConfirm(false);+ setConflict(null);+ setDiscardPrompt(null);+ // The upload and save flows finish against the Session they captured and skip their own+ // state updates once it is no longer the one on screen — so the chrome they left behind+ // has to be cleared here, or an "Uploading 2/5…" label and its disabled picker outlive+ // the Session forever. A staged overwrite confirmation is dropped for the same reason:+ // answering it after the switch would upload the old Session's files into this one.+ setUploading(null);+ setPendingUpload(null);+ setSaving(false);previewSeq++;}- // Edge-triggered refresh on the panel's hidden -> visible transition (doesn't count the initial mount: mounting itself already fetches once).+ // ------------------------------------------------------------------ measured layout+ // The panel's own width decides the layout: a viewport breakpoint cannot know how much of+ // the window the dock was given. Measured in a layout effect so the first paint is right.+ useLayoutEffect(() => {+ const el = rootRef.current;+ if (!el) return;+ const measure = () => setWidth(Math.round(el.getBoundingClientRect().width));+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);+ const narrow = isNarrowLayout(width);++ // The breadcrumb strip is measured separately: how much room it has is what the+ // toolbar's actions leave over, which the panel's own width does not say.+ useLayoutEffect(() => {+ const el = crumbsRef.current;+ if (!el) return;+ const measure = () => setCrumbsWidth(Math.round(el.getBoundingClientRect().width));+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ // The tree pane's width: dragged if it ever was, otherwise the computed default, and+ // either way within the bounds this panel width allows.+ const treeWidth = clampTreeWidth(treeWidthPref ?? defaultTreeWidth(width), width);+ const treeWidthRef = useRef(treeWidth);+ treeWidthRef.current = treeWidth;++ // The show/hide transition's window: the toggle arms it, this disarms it once the slide+ // has played (toggling again mid-slide restarts the timer). DOCK_TRANSITION_MS is the+ // dock's own expand/collapse duration — the pane moves with the same motion — and the+ // duration-200 class on the sliding container has to match it.+ useEffect(() => {+ if (!treeSliding) return;+ const timer = window.setTimeout(() => setTreeSliding(false), DOCK_TRANSITION_MS);+ return () => window.clearTimeout(timer);+ }, [treeSliding, treeVisible]);++ // --------------------------------------------------------------------------- loading++ /**+ * Fetches one directory's listing into the tree. Resolves true when it published; false+ * when it failed or was superseded (a newer request for the same directory, or a Session+ * switch). The root's failure shows in the tree; a nested directory that fails to list+ * (deleted mid-turn) toasts and leaves the tree.+ */+ const loadDir = useCallback(+ async (dir: string): Promise<boolean> => {+ const sid = sessionId;+ const seq = (dirSeq.current.get(dir) ?? 0) + 1;+ dirSeq.current.set(dir, seq);+ const current = () => sessionIdRef.current === sid && dirSeq.current.get(dir) === seq;+ setLoadingDirs((s) => new Set(s).add(dir));+ try {+ const res = await api.listWorkspaceFiles(sid, dir);+ if (!current()) return false;+ setListings((m) => new Map(m).set(dir, res.entries));+ if (dir === "") setRootError(null);+ return true;+ } catch (err) {+ if (!current()) return false;+ const text = err instanceof ApiError ? err.message : S.files.loadFailed;+ if (dir === "") {+ setRootError(text);+ } else {+ toastError(text);+ setListings((m) => {+ if (!m.has(dir)) return m;+ const next = new Map(m);+ next.delete(dir);+ return next;+ });+ setExpanded((s) => withExpanded(s, dir, false));+ }+ return false;+ } finally {+ if (current()) {+ setLoadingDirs((s) => {+ const next = new Set(s);+ next.delete(dir);+ return next;+ });+ }+ }+ },+ [sessionId],+ );++ useEffect(() => {+ void loadDir("");+ }, [loadDir]);++ /** Re-reads everything on screen: the root and every open directory that has a listing. */+ const refreshAll = useCallback(() => {+ void loadDir("");+ for (const dir of expandedRef.current) {+ if (dir !== "" && listingsRef.current.has(dir)) void loadDir(dir);+ }+ }, [loadDir]);++ // Edge-triggered refresh on the panel's hidden -> visible transition (doesn't count the+ // initial mount: mounting itself already fetches once).const prevActive = useRef(active);useEffect(() => {- if (active && !prevActive.current) setReloadTick((t) => t + 1);+ if (active && !prevActive.current) refreshAll();prevActive.current = active;- }, [active]);+ }, [active, refreshAll]);- /** The preview callback goes through a ref: keeps previewPath's useCallback dependency stable,- * so even if the parent passes an inline arrow function, the openRequest locate effect doesn't- * replay just because previewPath's reference changed. */- const onPreviewOpenRef = useRef(onPreviewOpen);- onPreviewOpenRef.current = onPreviewOpen;+ // --------------------------------------------------------------------------- preview/**- * Opens `filePath` in the preview. `refresh` re-reads a file already on screen (the+ * Loads `filePath` into the preview. `refresh` re-reads a file already on screen (the* settled-turn refresh below): it must not touch the things that belong to the user's- * hands — the mobile sheet's snap point, the rendered/source choice — and a failed- * re-read leaves what is on screen alone instead of replacing a working preview with- * "unsupported".+ * hands — the rendered/source choice — and a failed re-read leaves what is on screen+ * alone instead of replacing a working preview with "unsupported".*/const previewPath = useCallback(async (filePath: string, opts?: { refresh?: boolean }) => {const refresh = opts?.refresh === true;- if (!refresh) onPreviewOpenRef.current?.();- const name = filePath.includes("/")- ? filePath.slice(filePath.lastIndexOf("/") + 1)- : filePath;- const ext = extOf(name);+ const sid = sessionId;+ const name = baseName(filePath);+ const kind = previewKindFor(name);const nonce = ++previewSeq;/** Publishes this call's result unless a newer previewPath call has started since:* 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) setPreview(p);+ if (nonce === previewSeq && sessionIdRef.current === sid) setPreview(p);};if (!refresh) {setRichView("rendered");setSourceError(null);}- if (IMAGE_EXTS.has(ext)) {+ if (kind === "image") {present({ path: filePath, name, kind: "image", nonce });return;}// PDF: the server returns it inline as application/pdf, embedded directly in an iframe and rendered by the browser.- if (ext === "pdf") {+ if (kind === "pdf") {present({ path: filePath, name, kind: "pdf", nonce });return;}- const isHtml = HTML_EXTS.has(ext);- const isMd = ext === "md";- if (!isHtml && !TEXT_EXTS.has(ext)) {- present({ path: filePath, name, kind: "unsupported", nonce });- return;- }// Isolated HTML: the rendered view is an iframe onto the preview origin and needs no// text here, so the iframe mounts with no upfront fetch — a large file isn't// downloaded twice, and a transient fetch failure can't downgrade a page the iframe// would serve fine. The source text is fetched lazily on the first Source toggle// (see the effect below).- if (isHtml && previewIsolatedRef.current) {+ if (kind === "html" && previewIsolatedRef.current) {present({ path: filePath, name, kind: "html", nonce });return;}try {// The server downgrades html/svg served inline to text/plain (a same-origin XSS// defense); this fetches the raw content back for text/Markdown previews and for- // the srcDoc fallback rendered view of non-isolated HTML.- const res = await fetch(api.workspaceFileUrl(session.sessionId, filePath), {- credentials: "same-origin",- });- if (!res.ok) throw new Error(String(res.status));- const full = await res.text();- const truncated = full.length > TEXT_PREVIEW_LIMIT;+ // 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",+ );+ if (result === null) {+ if (!refresh) present({ path: filePath, name, kind: "unsupported", nonce });+ return;+ }+ const { content, truncated, version } = result;// Oversized Markdown defaults to the source view (benefiting from the unhighlighted// highlight=false path): feeding the whole block to remark for parsing is a one-time// main-thread cost; the user can still manually switch to "rendered view" as an informed choice.- if (!refresh && isMd && full.length > HIGHLIGHT_LIMIT && nonce === previewSeq) {+ if (!refresh && kind === "md" && content.length > HIGHLIGHT_LIMIT && nonce === previewSeq) {setRichView("source");}present({path: filePath,name,- kind: isHtml ? "html" : isMd ? "md" : "text",- content: truncated ? full.slice(0, TEXT_PREVIEW_LIMIT) : full,+ kind: kind === "html" ? "html" : kind === "md" ? "md" : "text",+ content,truncated,+ version,nonce,});+ // A draft left behind on this file (see unsavedDrafts) reopens the editor on it.+ if (+ !refresh &&+ !truncated &&+ nonce === previewSeq &&+ sessionIdRef.current === sid &&+ editorRef.current?.path !== filePath+ ) {+ const key = draftKey(sid, filePath);+ const stashed = unsavedDrafts.get(key);+ if (stashed === content) unsavedDrafts.delete(key);+ else if (stashed !== undefined) {+ setEditor({ path: filePath, baseline: content, draft: stashed, version });+ toastInfo(S.files.unsavedRestored(name));+ }+ }} catch {// A re-read that fails (the Agent deleted the file mid-turn, a blip) keeps the// preview the user is looking at; only a fresh open reports it as unsupported.if (!refresh) present({ path: filePath, name, kind: "unsupported", nonce });}},- [session.sessionId],+ [sessionId],);// Lazy source fetch for isolated HTML previews: previewPath mounted the iframe without@@ -347,19 +694,19 @@ export function WorkspaceBrowser({setSourceError(null);void (async () => {try {- const res = await fetch(api.workspaceFileUrl(session.sessionId, target), {- credentials: "same-origin",- });- if (!res.ok) throw new Error(String(res.status));- const full = await res.text();- if (cancelled) return;- const truncated = full.length > TEXT_PREVIEW_LIMIT;+ const result = await fetchTextPreview(api.workspaceFileUrl(sessionId, 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// a preview the user has since navigated away from.setPreview((p) =>p !== null && p.kind === "html" && p.path === target && p.content === undefined- ? { ...p, content: truncated ? full.slice(0, TEXT_PREVIEW_LIMIT) : full, truncated }+ ? {+ ...p,+ content: result.content,+ truncated: result.truncated,+ version: result.version,+ }: p,);} catch {@@ -369,499 +716,1032 @@ export function WorkspaceBrowser({return () => {cancelled = true;};- }, [preview, richView, previewIsolated, session.sessionId]);+ }, [preview, richView, previewIsolated, sessionId]);++ // -------------------------------------------------------------- navigation and guards++ const promptDiscard = useCallback(+ () => new Promise<boolean>((resolve) => setDiscardPrompt({ resolve })),+ [],+ );++ const discardEditor = useCallback(() => {+ const current = editorRef.current;+ if (current !== null) unsavedDrafts.delete(draftKey(sessionIdRef.current, current.path));+ setEditor(null);+ }, []);++ /**+ * Runs `action` unless it would abandon typed changes, in which case the user is asked+ * first and a "keep editing" answer drops the action. `nextPath` is the file the action+ * lands on (null: none); landing on the file being edited keeps the editor as it is, and+ * a clean editor simply closes.+ */+ const navigateGuarded = useCallback(+ async (nextPath: string | null, action: () => void) => {+ const current = editorRef.current;+ if (needsDiscardConfirm(current, nextPath)) {+ if (!(await promptDiscard())) return;+ discardEditor();+ } else if (current !== null && current.path !== nextPath) {+ setEditor(null);+ }+ action();+ },+ [promptDiscard, discardEditor],+ );++ /**+ * Opens every directory above `path` and makes sure each is listed — the file's own+ * directory re-read, since a located file was most likely just written and its cached+ * listing predates it — then scrolls the row into view.+ */+ const locate = useCallback(+ async (path: string) => {+ setExpanded((s) => expandTo(s, path));+ const dir = parentDir(path);+ await Promise.all(+ ancestorDirs(path).map((d) =>+ d === dir || !listingsRef.current.has(d) ? loadDir(d) : Promise.resolve(true),+ ),+ );+ if (sessionIdRef.current === sessionId) setScrollTo({ path });+ },+ [loadDir, sessionId],+ );++ /** Selects a file in the tree and previews it; `locate` additionally loads the way down to it (an external open request). */+ const openFile = useCallback(+ (path: string, opts?: { locate?: boolean }) => {+ void navigateGuarded(path, () => {+ setSelectedPath(path);+ setCurrentDir(parentDir(path));+ if (opts?.locate) void locate(path);+ else setExpanded((s) => expandTo(s, path));+ void previewPath(path);+ });+ },+ [navigateGuarded, locate, previewPath],+ );// The same settled-turn signal re-reads whatever is open in the preview: watching a file// the Agent is editing is the reason this panel sits next to the conversation. Skipped on// 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 — depending on `preview` would- // re-run it on every preview change and re-read a file that was just read.- const previewPathRef = useRef<string | null>(null);- previewPathRef.current = preview?.path ?? null;+ // 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.const lastReloadSignal = useRef(reloadSignal);useEffect(() => {if (reloadSignal === lastReloadSignal.current) return;lastReloadSignal.current = reloadSignal;- const open = previewPathRef.current;- if (open !== null) void previewPath(open, { refresh: true });- }, [reloadSignal, previewPath]);-- // External navigation command (clicking a file chip in a message / a file card): navigates to- // the directory and previews the target path. Also refreshes the list: the target is most- // likely a file the Agent just wrote, so the cached list is very likely stale; and when it's- // the same directory, setPath is a same-value no-op that won't trigger the fetch effect, so it must be explicitly bumped.+ refreshAll();+ const open = previewRef.current?.path ?? null;+ if (open === null) return;+ const editing = editorRef.current;+ if (editing?.path !== open) {+ void previewPath(open, { refresh: true });+ return;+ }+ const sid = sessionIdRef.current;+ 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,+ );+ } catch {+ // A failed probe says nothing; the save's precondition is the guarantee.+ }+ })();+ }, [reloadSignal, refreshAll, previewPath]);++ // External navigation command (clicking a file chip in a message / a file card): opens+ // the tree down to the target and previews it.//// Each openRequest object is handled exactly once (the ref guard): this effect also- // re-runs when previewPath's identity changes with session.sessionId, at which point- // openRequest is still the OLD session's request — the parent clears it only after- // child effects. Replaying it against the new session would resurrect the preview the- // session-switch reset just cleared, for isolated HTML as a committed iframe onto a- // path the new Workspace doesn't have (a raw 404 page). browsePath creates a fresh- // object per click, so re-clicking the same file still re-triggers.+ // re-runs when openFile's identity changes with the session, at which point openRequest+ // is still the OLD session's request — the parent clears it only after child effects.+ // Replaying it against the new session would resurrect the preview the session-switch+ // reset just cleared. The parent creates a fresh object per click, so re-clicking the+ // same file still re-triggers.const handledOpenRequest = useRef<{ path: string } | null>(null);useEffect(() => {if (!openRequest || handledOpenRequest.current === openRequest) return;handledOpenRequest.current = openRequest;- const target = openRequest.path;- const dir = target.includes("/") ? target.slice(0, target.lastIndexOf("/")) : "";- setPath(dir);- setReloadTick((t) => t + 1);- void previewPath(target);- }, [openRequest, previewPath]);-- const doUpload = (files: File[]) => {- setUploading(true);- setError(null);- void (async () => {+ openFile(openRequest.path, { locate: true });+ }, [openRequest, openFile]);++ // Unsaved changes: the browser's leave-page prompt (reload, tab close — the only text the+ // browser shows is its own), and the dock's close guard for the tab's ×, the one gesture+ // that unmounts this body. Hiding the panel's dock only puts the surface away, draft and+ // all, so it asks nothing.+ const dirty = isDirty(editor);+ useEffect(() => {+ if (!dirty) return;+ const onBeforeUnload = (e: BeforeUnloadEvent) => {+ e.preventDefault();+ // Older engines show the prompt only for a set returnValue.+ e.returnValue = "";+ };+ window.addEventListener("beforeunload", onBeforeUnload);+ return () => window.removeEventListener("beforeunload", onBeforeUnload);+ }, [dirty]);+ useEffect(() => {+ if (!dirty) return;+ const key = tabKey({ kind: "panel", panel: "workspace" });+ setCloseGuard(key, async () => {+ const ok = await promptDiscard();+ if (ok) discardEditor();+ return ok;+ });+ return () => setCloseGuard(key, null);+ }, [dirty, promptDiscard, discardEditor]);++ // ------------------------------------------------------------------ tree interactions++ /** Opens or closes a directory and makes it the current one; a first open fetches its listing. */+ const toggleDir = useCallback(+ (dir: string) => {+ setCurrentDir(dir);+ const open = !expandedRef.current.has(dir);+ setExpanded((s) => withExpanded(s, dir, open));+ // The subtree this toggle moves is the one that animates. The serial makes toggling the+ // same directory again a new event; the mark stands until the next toggle, since an+ // opening directory's rows may arrive with the listing rather than in this commit.+ setToggled((last) => ({ dir, open, serial: (last?.serial ?? 0) + 1 }));+ if (open && !listingsRef.current.has(dir)) void loadDir(dir);+ },+ [loadDir],+ );++ /**+ * A directory row's click while the search box holds a query. Every listed directory is+ * already shown open there, so a click cannot mean "collapse this" — it makes the+ * directory current and, when it has never been listed, lists it, which is how the search+ * is extended past what the tree has loaded so far.+ */+ const openDirForFilter = useCallback(+ (dir: string) => {+ setCurrentDir(dir);+ setExpanded((s) => withExpanded(s, dir, true));+ if (!listingsRef.current.has(dir)) void loadDir(dir);+ },+ [loadDir],+ );++ const backToTree = (): void => {+ void navigateGuarded(null, () => {+ setSelectedPath(null);+ setPreview(null);+ });+ };++ const setTree = (visible: boolean): void => {+ setTreeVisible(visible);+ setTreeSliding(true);+ writeTreeVisible(visible);+ };++ const setWrap = (wrap: boolean): void => {+ setEditorWrap(wrap);+ writeEditorWrap(wrap);+ };++ // ------------------------------------------------------------------------- tree width+ // The divider between the two panes. The width follows the pointer against the tree+ // pane's own left edge rather than an accumulated delta, so a drag that outruns the+ // clamp comes back in step instead of offset by however far it overshot.+ const treeResizeProps = usePointerDrag<object>({+ threshold: 0,+ begin: (event) => {+ event.preventDefault(); // no text selection while the divider is dragged+ setResizingTree(true);+ return {};+ },+ onMove: (event) => {+ const rect = treePaneRef.current?.getBoundingClientRect();+ if (!rect) return;+ setTreeWidthPref(clampTreeWidth(event.clientX - rect.left, width));+ },+ onEnd: () => {+ setResizingTree(false);+ writeTreeWidth(treeWidthRef.current); // once per drag, not per frame+ },+ onCancel: () => setResizingTree(false),+ });++ const onDividerKey = (e: ReactKeyboardEvent<HTMLDivElement>): void => {+ const delta =+ e.key === "ArrowLeft" ? -TREE_WIDTH_STEP : e.key === "ArrowRight" ? TREE_WIDTH_STEP : 0;+ if (delta === 0) return;+ e.preventDefault();+ const next = clampTreeWidth(treeWidthRef.current + delta, width);+ setTreeWidthPref(next);+ writeTreeWidth(next);+ };++ // ----------------------------------------------------------------------------- editing++ const startEdit = async (): Promise<void> => {+ const current = previewRef.current;+ if (current === null || !canEditPreview(current)) return;+ // 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+ // the file.+ let content = current.content;+ let version = current.version;+ if (content === undefined || version === undefined) {try {- for (const file of files) {- const b64 = await new Promise<string>((resolve, reject) => {- const reader = new FileReader();- reader.onload = () => {- const url = reader.result as string;- resolve(url.slice(url.indexOf(",") + 1)); // Strip the data:...;base64, prefix- };- reader.onerror = () => reject(new Error("read failed"));- reader.readAsDataURL(file);- });- await api.uploadWorkspaceFile(session.sessionId, joinWorkspacePath(path, file.name), b64);+ const result = await fetchTextPreview(api.workspaceFileUrl(sessionId, current.path), false);+ if (result === null || result.truncated) {+ toastError(S.files.editTooLarge(TEXT_PREVIEW_LIMIT / 1024));+ return;}- toastSuccess(S.files.uploaded);- setReloadTick((t) => t + 1);- } catch (err) {- toastError(apiErrorText(err));- } finally {- setUploading(false);+ ({ content, version } = result);+ setPreview((p) =>+ p !== null && p.path === current.path+ ? { ...p, content: result.content, truncated: false, version: result.version }+ : p,+ );+ } catch {+ toastError(S.files.loadFailed);+ return;}- })();+ }+ if (previewRef.current?.path !== current.path) return;+ setEditor({ path: current.path, baseline: content, draft: content, version });};- const onUpload = (e: ChangeEvent<HTMLInputElement>) => {- const files = e.target.files ? [...e.target.files] : [];- e.target.value = "";- if (files.length === 0) return;- // Uploads overwrite same-name files: names already present in the loaded listing- // confirm first (the picker is stashed — confirm continues, cancel drops it).- const existing = new Set((data?.res.entries ?? []).map((entry) => entry.name));- const clashes = files.filter((f) => existing.has(f.name)).map((f) => f.name);- if (clashes.length > 0) setPendingUpload({ files, clashes });- else doUpload(files);+ const updateDraft = (draft: string): void => {+ const current = editorRef.current;+ if (current === null) return;+ setEditor({ ...current, draft });+ const key = draftKey(sessionId, current.path);+ if (draft === current.baseline) unsavedDrafts.delete(key);+ else unsavedDrafts.set(key, draft);+ };++ const requestSave = (): void => {+ const current = editorRef.current;+ if (current === null || saving) return;+ if (!isDirty(current)) {+ toastInfo(S.common.noChangesToSave);+ return;+ }+ // Already known to have moved under the editor: the ordinary "the file will be+ // overwritten" confirmation understates that, so ask the conflict question instead —+ // and sending the stale precondition first would only earn the same dialog a round+ // trip later.+ if (current.changedOnDisk === true) setConflict({ name: baseName(current.path) });+ else setSaveConfirm(true);};- const crumbs = path === "" ? [] : path.split("/");/**- * A navigation fetch is in flight: the rendered rows belong to a different directory than- * the one being loaded. Entry rows and breadcrumbs are disabled for the duration — the- * base-bound targets above are what make clicks safe regardless of timing; this is the- * user-visible feedback. Derived, not stored: initial load and same-path refreshes- * (reloadTick) don't count, and a failed navigation renders `error` instead of rows, so- * the disabled state can never outlive the fetch that justified it.+ * Writes the draft back. The save carries the version the editor opened with, so the+ * 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.*/- const busy = error === null && data !== null && data.base !== path;+ 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]);+ if (blob.size > WORKSPACE_UPLOAD_LIMIT_MB * MB_BYTES) {+ toastError(S.files.saveTooLarge(WORKSPACE_UPLOAD_LIMIT_MB));+ return;+ }+ const sid = sessionId;+ setSaving(true);+ try {+ await api.uploadWorkspaceFile(+ sid,+ 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.+ const nonce = ++previewSeq;+ setPreview((p) =>+ p !== null && p.path === current.path+ ? { ...p, content: current.draft, truncated: false, version: undefined, nonce }+ : p,+ );+ const dir = parentDir(current.path);+ setListings((m) =>+ upsertEntry(m, dir, {+ name: baseName(current.path),+ kind: "file",+ sizeBytes: blob.size,+ mtime: new Date().toISOString(),+ }),+ );+ void loadDir(dir);+ toastSuccess(S.common.saved);+ } catch (err) {+ if (sessionIdRef.current !== sid) 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.+ if (err instanceof ApiError && err.code === "file_changed") {+ setEditor((e) => (e === null ? e : { ...e, changedOnDisk: true }));+ setConflict({ name: baseName(current.path) });+ return;+ }+ toastError(apiErrorText(err));+ } finally {+ if (sessionIdRef.current === sid) setSaving(false);+ }+ };- if (preview !== null) {- return (- <div className="flex h-full min-h-0 flex-col">- {/* flex-wrap: the panel can be dragged down to a 320px minimum width, narrower than this- row's uncompressible content (back + view toggle + download ~= 370px+); without- wrapping, the panel's overflow-hidden would clip the right-side buttons off. */}- <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-800">+ const cancelEdit = (): void => {+ void navigateGuarded(null, () => undefined);+ };++ // ------------------------------------------------------------------------------ upload++ const doUpload = async (files: File[], dir: string): Promise<void> => {+ const sid = sessionId;+ setUploading({ done: 0, total: files.length });+ const uploaded: string[] = [];+ try {+ for (const [i, file] of files.entries()) {+ const b64 = await blobToBase64(file);+ await api.uploadWorkspaceFile(sid, joinWorkspacePath(dir, file.name), b64);+ if (sessionIdRef.current !== sid) 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.+ setListings((m) =>+ upsertEntry(m, dir, {+ name: file.name,+ kind: "file",+ sizeBytes: file.size,+ mtime: new Date().toISOString(),+ }),+ );+ setUploading({ done: i + 1, total: files.length });+ }+ toastSuccess(S.files.uploadedCount(uploaded.length));+ } catch (err) {+ toastError(apiErrorText(err));+ } finally {+ if (sessionIdRef.current === sid) setUploading(null);+ }+ if (sessionIdRef.current !== sid || 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+ // no reason to ask about those.+ if (!isDirty(editorRef.current)) openFile(joinWorkspacePath(dir, uploaded[0]!));+ };++ /**+ * Size-checks a picked or dropped batch against the endpoint's ceiling (oversize files are+ * named and skipped, nothing is uploaded to earn the refusal), then confirms overwrites:+ * names already present in the target directory — listed on demand, so the check is+ * against the real directory, not a stale or missing listing.+ */+ const stageUpload = async (picked: File[], dir: string): Promise<void> => {+ if (uploadingRef.current !== null) return;+ const { accepted, rejected } = splitBySize(picked, WORKSPACE_UPLOAD_LIMIT_MB);+ if (rejected.length > 0) {+ toastError(+ S.files.uploadTooLarge(rejected.map((f) => f.name).join(", "), WORKSPACE_UPLOAD_LIMIT_MB),+ );+ }+ if (accepted.length === 0) return;+ const sid = sessionId;+ if (!listingsRef.current.has(dir) && !(await loadDir(dir))) return;+ if (sessionIdRef.current !== sid) 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 });+ else void doUpload(accepted, dir);+ };++ const onPick = (e: ChangeEvent<HTMLInputElement>): void => {+ const files = e.target.files ? [...e.target.files] : [];+ e.target.value = "";+ if (files.length > 0) void stageUpload(files, currentDirRef.current);+ };++ // -------------------------------------------------------------------------------- drop+ // The panel is its own drop region, decided by the same stateless rule as the chat+ // area's (dropRegionAction): every event re-derives whether a file drag is over the panel,+ // so no missed event can strand the overlay. Claiming the drag here (preventDefault on+ // dragover) is what makes the app-shell guard stand aside and the browser deliver the+ // drop; the chat area's zone tests events against its own region and ignores these.+ const applyDrag = (+ signal: DragSignal,+ e: ReactDragEvent<HTMLDivElement>,+ inside: boolean,+ ): { accept: boolean; targetDir: string } => {+ const action = dropRegionAction(signal, isFileDrag(e.dataTransfer.types), inside);+ const targetDir =+ action.active || action.accept ? dropTargetDir(hitRow(e.target), currentDirRef.current) : "";+ if (action.claim) {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ }+ const shown = action.active ? targetDir : "";+ // dragover fires tens of times a second; only a real change is routed through state.+ setDrag((d) =>+ d.active === action.active && d.targetDir === shown+ ? d+ : { active: action.active, targetDir: shown },+ );+ return { accept: action.accept, targetDir };+ };+ const onDragOver = (e: ReactDragEvent<HTMLDivElement>): void => {+ applyDrag("over", e, true);+ };+ // `relatedTarget` is where the drag is going: still inside the panel means an internal+ // element boundary was crossed and nothing changed.+ const onDragLeave = (e: ReactDragEvent<HTMLDivElement>): void => {+ const root = rootRef.current;+ applyDrag(+ "leave",+ e,+ root !== null && e.relatedTarget instanceof Node && root.contains(e.relatedTarget),+ );+ };+ 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);+ };++ // ------------------------------------------------------------------------------ render++ const filter = query.trim();+ const rows = useMemo(() => {+ if (filter === "") return flattenTree(listings, expanded);+ // A filter walks every LISTED directory, whatever the user left open: the search+ // reaches exactly as far as the lazy tree has loaded, and a match is only reachable+ // with its ancestors open above it.+ return filterTreeRows(flattenTree(listings, new Set(listings.keys())), filter);+ }, [listings, expanded, filter]);+ const rootListing = listings.get("");+ const crumbSegments =+ currentDir === "" ? [S.files.root] : [S.files.root, ...currentDir.split("/")];+ const crumbPath = currentDir === "" ? S.files.root : `${S.files.root}/${currentDir}`;+ // An unmeasured strip (before the first ResizeObserver callback) shows the whole path:+ // the actions cannot be pushed off the row either way — they are shrink-0 and the strip+ // clips — and a "…" for one frame on a path that fits reads as a flicker.+ const crumbFit = visibleCrumbSegments(+ crumbSegments,+ crumbsWidth > 0 ? crumbsWidth : Number.POSITIVE_INFINITY,+ crumbItemWidth,+ );+ const showTree = narrow ? selectedPath === null : treeVisible;+ const showPreview = narrow ? selectedPath !== null : true;+ const canEdit = preview !== null && editor === null && canEditPreview(preview);+ const dirLabel = (dir: string): string => (dir === "" ? S.files.root : dir);++ const tree = (+ <div+ ref={treePaneRef}+ className={`flex min-h-0 flex-col ${narrow ? "flex-1" : "shrink-0 border-r border-gray-200 dark:border-gray-800"}`}+ style={narrow ? undefined : { width: treeWidth }}+ >+ {/* Search: filters the rows already loaded. Esc clears it rather than reaching the+ dock or a dialog above, which is what an Esc in a non-empty box means here. */}+ <div className="relative shrink-0 border-b border-gray-100 px-2 py-1.5 dark:border-gray-800">+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={(e) => {+ if (e.key !== "Escape" || query === "") return;+ e.preventDefault();+ e.stopPropagation();+ setQuery("");+ }}+ placeholder={S.files.searchPlaceholder}+ aria-label={S.files.searchPlaceholder}+ {...noAutofill}+ className="w-full rounded border border-gray-200 bg-transparent py-1 pl-2 pr-7 text-xs text-gray-700 placeholder:text-gray-400 focus:border-gray-400 focus:outline-none dark:border-gray-700 dark:text-gray-200 dark:placeholder:text-gray-500 dark:focus:border-gray-500"+ />+ {query !== "" && (<buttontype="button"- onClick={() => {- // Refreshes in passing when returning to the list: the Agent may have written new files during the preview.- setPreview(null);- setReloadTick((t) => t + 1);- }}- title={S.files.backToList}- className="flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-sm text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"+ aria-label={S.files.searchClear}+ title={S.files.searchClear}+ onClick={() => setQuery("")}+ className="absolute right-3.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200">- <GlyphIcon d="M15 18l-6-6 6-6" size={ICON_SIZE.rowLead} />- {S.files.backToList}+ <CloseIcon size={12} /></button>- {/* Shows only the filename (full path goes into the title hover tooltip): the- directory prefix and extension badge are both information the filename already- carries, and on a narrow panel they'd just crowd out the title space. */}- <span- className="min-w-0 flex-1 truncate font-mono text-sm font-semibold"- title={preview.path}- >- {preview.name}- </span>- {/* HTML / Markdown: rendered view / source toggle */}- {(preview.kind === "html" || preview.kind === "md") && (- <div className="flex shrink-0 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800">- {(- [- ["rendered", S.files.htmlRendered],- ["source", S.files.htmlSource],- ] as const- ).map(([key, label]) => (- <button- key={key}- type="button"- onClick={() => setRichView(key)}- className={`rounded px-2 py-0.5 text-xs transition-colors duration-150 ${- richView === key- ? "bg-white font-medium text-gray-900 shadow-sm dark:bg-gray-600 dark:text-gray-100"- : "text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"- }`}- >- {label}- </button>- ))}- </div>- )}- {/* Ghost style, matching the toolbar's upload label (text-xs, transparent until hover) — the bordered secondary look stood out from every neighbor. */}- {/* rel="noopener noreferrer" is load-bearing, not boilerplate: the preview must- not keep a handle back to this window, which is the whole point of serving- it from a separate origin. */}- {/\.html?$/i.test(preview.name) && (- <a- href={api.workspaceFilePreviewUrl(session.sessionId, preview.path)}- target="_blank"- rel="noopener noreferrer"- title={previewIsolated ? undefined : S.files.previewNotIsolatedHint}- className="inline-flex shrink-0 items-center gap-1 rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"- >- {S.files.openInNewTab}- {!previewIsolated && (- <span aria-label={S.files.previewNotIsolatedHint} className={toneInk.attention}>- ⚠- </span>- )}- </a>- )}- <a- href={api.workspaceFileUrl(session.sessionId, preview.path, true)}- download={preview.name}- className="inline-flex shrink-0 items-center rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"- >- {S.files.download}- </a>+ )}+ </div>+ {rootError !== null ? (+ <p className="px-3 py-3 text-sm text-red-600 dark:text-red-400">{rootError}</p>+ ) : rootListing === undefined ? (+ <SkeletonList rows={6} />+ ) : (+ <WorkspaceTreeView+ rows={rows}+ selectedPath={selectedPath}+ currentDir={currentDir}+ loadingDirs={loadingDirs}+ dropTargetDir={drag.active ? drag.targetDir : null}+ scrollTo={scrollTo}+ rootEmpty={rootListing.length === 0}+ filtering={filter !== ""}+ toggled={filter === "" ? toggled : null}+ onToggleDir={filter === "" ? toggleDir : openDirForFilter}+ onOpenFile={openFile}+ />+ )}+ </div>+ );++ // The divider: a real layout sibling, so the two panes always add up to the panel.+ const treeDivider = (+ <div+ role="separator"+ aria-orientation="vertical"+ aria-label={S.files.treeWidth}+ aria-valuenow={treeWidth}+ aria-valuemin={TREE_MIN_WIDTH}+ // Before the first measurement there is no ceiling yet (clampTreeWidth applies none),+ // so the current width is the honest maximum for that frame.+ aria-valuemax={Math.max(maxTreeWidth(width), treeWidth)}+ title={S.files.treeWidth}+ tabIndex={0}+ {...treeResizeProps}+ onKeyDown={onDividerKey}+ className={`w-1.5 shrink-0 cursor-col-resize outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/60 ${+ resizingTree+ ? "bg-gray-300 dark:bg-gray-600"+ : "bg-transparent hover:bg-gray-200 dark:hover:bg-gray-700"+ }`}+ />+ );++ const richToggle = preview !== null && (preview.kind === "html" || preview.kind === "md") && (+ <div className="flex shrink-0 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800">+ {(+ [+ ["rendered", S.files.htmlRendered],+ ["source", S.files.htmlSource],+ ] as const+ ).map(([key, label]) => (+ <button+ key={key}+ type="button"+ aria-pressed={richView === key}+ onClick={() => setRichView(key)}+ className={`rounded px-2 py-0.5 text-xs transition-colors duration-150 ${+ richView === key+ ? "bg-white font-medium text-gray-900 shadow-sm dark:bg-gray-600 dark:text-gray-100"+ : "text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"+ }`}+ >+ {label}+ </button>+ ))}+ </div>+ );++ const previewBody = (p: Preview) => {+ if (editor !== null && editor.path === p.path) {+ return (+ <div className="min-h-0 flex-1">+ <WorkspaceFileEditor+ path={editor.path}+ value={editor.draft}+ wrap={editorWrap}+ onChange={updateDraft}+ onSave={requestSave}+ /></div>- {/* scrollbar-gutter: an SVG carries no pixel size, so its height is whatever its width- divides to — which makes the content height a function of the scrollbar's presence.- Without a reserved gutter that closes a loop: content overflows -> scrollbar takes- width -> the image shrinks -> content fits -> scrollbar goes -> repeat, forever, as- a visible shake. Reserving it always breaks the feedback path (and is inert where- scrollbars are overlays). */}- <div className="min-h-0 flex-1 overflow-auto p-3 [scrollbar-gutter:stable]">- {preview.kind === "image" ? (- // Keyed on the nonce like the isolated HTML iframe: the src alone is unchanged- // when the same file is re-read, so only a remount re-requests the bytes the- // Agent just rewrote.- <img- key={preview.nonce}- src={api.workspaceFileUrl(session.sessionId, preview.path)}- alt={preview.name}- className="max-w-full rounded-md border border-gray-200 dark:border-gray-800"- />- ) : preview.kind === "pdf" ? (+ );+ }+ return (+ // scrollbar-gutter: an SVG carries no pixel size, so its height is whatever its width+ // divides to — which makes the content height a function of the scrollbar's presence.+ // Without a reserved gutter that closes a loop: content overflows -> scrollbar takes+ // width -> the image shrinks -> content fits -> scrollbar goes -> repeat, forever, as+ // a visible shake. Reserving it always breaks the feedback path (and is inert where+ // scrollbars are overlays).+ <div className="min-h-0 flex-1 overflow-auto p-3 [scrollbar-gutter:stable]">+ {p.kind === "image" ? (+ // Keyed on the nonce like the isolated HTML iframe: the src alone is unchanged+ // when the same file is re-read, so only a remount re-requests the bytes the+ // Agent just rewrote.+ <ZoomableImage+ key={p.nonce}+ src={api.workspaceFileUrl(sessionId, p.path)}+ alt={p.name}+ className="max-w-full rounded-md border border-gray-200 dark:border-gray-800"+ />+ ) : p.kind === "pdf" ? (+ <iframe+ key={p.nonce}+ src={api.workspaceFileUrl(sessionId, p.path)}+ title={p.name}+ className="h-full min-h-[60vh] w-full rounded-md border border-gray-200 dark:border-gray-800"+ />+ ) : p.kind === "html" && richView === "rendered" ? (+ previewIsolated ? (+ // Same URL and serving path as "open in new tab": the app-origin redirect mints+ // a token and 302s to the separate preview origin, where the document has a real+ // base URL — relative subresources (<img src="foo.png">, app.js, style.css)+ // resolve and load, and storage works, exactly as in the new-page preview.+ // allow-same-origin is safe here precisely because the document IS on a separate+ // origin: it grants the preview origin's identity, not the app's, so the frame+ // still can't reach the app's cookies or DOM. Popups stay sandboxed (no+ // allow-popups-to-escape-sandbox); allow-downloads keeps download links inside+ // the page working, as they do in the new tab. The key remounts the iframe on+ // every previewPath call — its src alone wouldn't change when the same file is+ // re-opened after the Agent rewrote it.<iframe- key={preview.nonce}- src={api.workspaceFileUrl(session.sessionId, preview.path)}- title={preview.name}- className="h-full min-h-[60vh] w-full rounded-md border border-gray-200 dark:border-gray-800"+ key={p.nonce}+ src={api.workspaceFilePreviewUrl(sessionId, 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"/>- ) : preview.kind === "html" && richView === "rendered" ? (- previewIsolated ? (- // Same URL and serving path as "open in new tab": the app-origin redirect mints- // a token and 302s to the separate preview origin, where the document has a real- // base URL — relative subresources (<img src="foo.png">, app.js, style.css)- // resolve and load, and storage works, exactly as in the new-page preview.- // allow-same-origin is safe here precisely because the document IS on a separate- // origin: it grants the preview origin's identity, not the app's, so the frame- // still can't reach the app's cookies or DOM. Popups stay sandboxed (no- // allow-popups-to-escape-sandbox); allow-downloads keeps download links inside- // the page working, as they do in the new tab. The key remounts the iframe on- // every previewPath call — its src alone wouldn't change when the same file is- // re-opened after the Agent rewrote it.- <iframe- key={preview.nonce}- src={api.workspaceFilePreviewUrl(session.sessionId, preview.path)}- title={preview.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"- />- ) : preview.content === undefined ? (- // Only reachable when previewIsolated flipped to false after an isolated- // preview mounted without content: the lazy source effect is already fetching- // it, and the srcDoc fallback renders once it lands.- sourceError !== null ? (- <p className="text-sm text-red-600 dark:text-red-400">{sourceError}</p>- ) : (- <SkeletonList rows={6} />- )+ ) : p.content === undefined ? (+ // Only reachable when previewIsolated flipped to false after an isolated+ // preview mounted without content: the lazy source effect is already fetching+ // it, and the srcDoc fallback renders once it lands.+ sourceError !== null ? (+ <p className="text-sm text-red-600 dark:text-red-400">{sourceError}</p>) : (- // No separate preview origin: srcDoc fallback. sandbox allows scripts but- // **without allow-same-origin**: the iframe has an opaque origin, so scripts can- // run to fully render the page, yet can't read the app's same-origin cookies /- // DOM (an XSS defense). The storage shim is injected to avoid a SecurityError- // when a script accesses localStorage from an opaque origin. srcdoc has no real- // base URL, so relative subresources cannot resolve here — that's what the- // isolated branch above fixes.- <iframe- srcDoc={withStorageShim(preview.content)}- title={preview.name}- sandbox="allow-scripts"- className="h-full min-h-[60vh] w-full rounded-md border border-gray-200 bg-white dark:border-gray-800"- />+ <SkeletonList rows={6} />)- ) : preview.kind === "md" && richView === "rendered" ? (- // Markdown's default rendered view: uses the same md-body layout as message bodies- // (ReactMarkdown outputs pure static HTML with no script execution surface, so no iframe sandbox is needed).- <>- <div className="md-body text-base leading-relaxed text-gray-800 dark:text-gray-100">- <ReactMarkdown- remarkPlugins={REMARK_PLUGINS}- rehypePlugins={REHYPE_PLUGINS}- components={{- // Relative images are resolved against the md file's directory into the file API (otherwise resolving against the app's origin would always 404).- // `v` is the read nonce, not a cache-buster for its own sake: a- // Workspace image is rewritten under the same path, and without it a- // re-read of the Markdown would keep painting the previous bytes from- // the browser's image cache.- img: ({ src, alt }) => (- <img- src={- typeof src === "string" && !EXTERNAL_REF_RE.test(src)- ? `${api.workspaceFileUrl(- session.sessionId,- resolveRelative(dirOf(preview.path), src),- )}&v=${preview.nonce}`- : src- }- alt={alt ?? ""}- loading="lazy"- className="max-w-full"- />- ),- // External links open in a new tab; relative links point to a Workspace- // file, clicking switches the preview directly; in-page anchors keep default behavior.- a: ({ href, children }) => {- if (typeof href !== "string" || href.startsWith("#")) {- return <a href={href}>{children}</a>;- }- if (EXTERNAL_REF_RE.test(href)) {- return (- <a href={href} target="_blank" rel="noreferrer">- {children}- </a>- );+ ) : (+ // No separate preview origin: srcDoc fallback. sandbox allows scripts but+ // **without allow-same-origin**: the iframe has an opaque origin, so scripts can+ // run to fully render the page, yet can't read the app's same-origin cookies /+ // DOM (an XSS defense). The storage shim is injected to avoid a SecurityError+ // when a script accesses localStorage from an opaque origin. srcdoc has no real+ // base URL, so relative subresources cannot resolve here — that's what the+ // isolated branch above fixes.+ <iframe+ srcDoc={withStorageShim(p.content)}+ title={p.name}+ sandbox="allow-scripts"+ className="h-full min-h-[60vh] w-full rounded-md border border-gray-200 bg-white dark:border-gray-800"+ />+ )+ ) : p.kind === "md" && richView === "rendered" ? (+ // Markdown's default rendered view: uses the same md-body layout as message bodies+ // (ReactMarkdown outputs pure static HTML with no script execution surface, so no iframe sandbox is needed).+ <>+ <div className="md-body text-base leading-relaxed text-gray-800 dark:text-gray-100">+ <ReactMarkdown+ remarkPlugins={REMARK_PLUGINS}+ rehypePlugins={REHYPE_PLUGINS}+ components={{+ // Relative images are resolved against the md file's directory into the file API (otherwise resolving against the app's origin would always 404).+ // `v` is the read nonce, not a cache-buster for its own sake: a+ // Workspace image is rewritten under the same path, and without it a+ // re-read of the Markdown would keep painting the previous bytes from+ // the browser's image cache.+ img: ({ src, alt }) => (+ <img+ src={+ typeof src === "string" && !EXTERNAL_REF_RE.test(src)+ ? `${api.workspaceFileUrl(+ sessionId,+ resolveRelative(parentDir(p.path), src),+ )}&v=${p.nonce}`+ : src}- const target = resolveRelative(dirOf(preview.path), href);+ alt={alt ?? ""}+ loading="lazy"+ className="max-w-full"+ />+ ),+ // External links open in a new tab; relative links point to a Workspace+ // file, clicking opens it in the tree and the preview; in-page anchors keep default behavior.+ a: ({ href, children }) => {+ if (typeof href !== "string" || href.startsWith("#")) {+ return <a href={href}>{children}</a>;+ }+ if (EXTERNAL_REF_RE.test(href)) {return (- <a- href={api.workspaceFileUrl(session.sessionId, target)}- onClick={(e) => {- e.preventDefault();- void previewPath(target);- }}- >+ <a href={href} target="_blank" rel="noreferrer">{children}</a>);- },- }}- >- {preview.content ?? ""}- </ReactMarkdown>- </div>- {preview.truncated && (+ }+ const target = resolveRelative(parentDir(p.path), href);+ return (+ <a+ href={api.workspaceFileUrl(sessionId, target)}+ onClick={(e) => {+ e.preventDefault();+ openFile(target, { locate: true });+ }}+ >+ {children}+ </a>+ );+ },+ }}+ >+ {p.content ?? ""}+ </ReactMarkdown>+ </div>+ {p.truncated && (+ <p className="mt-1 text-xs text-gray-400">… {S.files.previewTruncated}</p>+ )}+ </>+ ) : p.kind === "text" || p.kind === "html" || p.kind === "md" ? (+ p.content === undefined ? (+ // Isolated HTML reaches the Source view before its lazy fetch lands: show a+ // skeleton (or the fetch's own error) — toggling back to Rendered is+ // unaffected, and re-entering Source retries the fetch.+ sourceError !== null ? (+ <p className="text-sm text-red-600 dark:text-red-400">{sourceError}</p>+ ) : (+ <SkeletonList rows={6} />+ )+ ) : (+ // The source view reuses the message stream's CodeBlock: Shiki dual-theme+ // highlighting + language label + copy button, no line wrapping, horizontal scroll+ // instead (wrapping code is a disaster for readability, see the old mobile styling).+ <>+ <CodeBlock+ language={languageForExtension(extOf(p.name))}+ code={p.content}+ highlight={p.content.length <= HIGHLIGHT_LIMIT}+ />+ {p.truncated && (<p className="mt-1 text-xs text-gray-400">… {S.files.previewTruncated}</p>)}</>- ) : preview.kind === "text" || preview.kind === "html" || preview.kind === "md" ? (- preview.content === undefined ? (- // Isolated HTML reaches the Source view before its lazy fetch lands: show a- // skeleton (or the fetch's own error) — toggling back to Rendered is- // unaffected, and re-entering Source retries the fetch.- sourceError !== null ? (- <p className="text-sm text-red-600 dark:text-red-400">{sourceError}</p>- ) : (- <SkeletonList rows={6} />- )+ )+ ) : (+ <p className="text-sm text-gray-500 dark:text-gray-400">{S.files.previewUnsupported}</p>+ )}+ </div>+ );+ };++ const previewPane = (+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ {selectedPath === null ? (+ <EmptyState+ title={S.files.selectFile}+ action={+ !treeVisible && !narrow ? (+ <Button size="sm" onClick={() => setTree(true)}>+ {S.files.showTree}+ </Button>+ ) : undefined+ }+ />+ ) : preview === null || preview.path !== selectedPath ? (+ <SkeletonList rows={6} />+ ) : (+ <>+ {/* flex-wrap: the preview can be as narrow as the dock allows, narrower than this+ row's uncompressible content (view toggle + actions); without wrapping, the+ panel's overflow-hidden would clip the right-side buttons off. */}+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-800">+ {narrow && (+ <button+ type="button"+ onClick={backToTree}+ title={S.files.backToList}+ className="flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-sm text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"+ >+ <GlyphIcon d={BACK_ICON} size={ICON_SIZE.rowLead} />+ {S.files.backToList}+ </button>+ )}+ {/* Shows only the filename (full path goes into the title hover tooltip): the+ directory prefix is what the breadcrumbs above already say, and on a narrow+ panel it would just crowd out the title space. */}+ <span+ className="min-w-0 flex-1 truncate font-mono text-sm font-semibold"+ title={preview.path}+ >+ {preview.name}+ </span>+ {editor !== null && editor.path === preview.path ? (+ <>+ {editor.changedOnDisk === true && (+ <span+ className={`shrink-0 text-xs ${toneInk.attention}`}+ title={S.files.changedOnDiskHint}+ >+ {S.files.changedOnDisk}+ </span>+ )}+ {dirty && (+ <span className={`shrink-0 text-xs ${toneInk.attention}`}>{S.files.unsaved}</span>+ )}+ {/* Soft wrap: off is the editor's own default — long lines scroll sideways,+ as code should — and the choice is remembered for every file after. */}+ <button+ type="button"+ aria-pressed={editorWrap}+ onClick={() => setWrap(!editorWrap)}+ className={toggleActionClass(editorWrap)}+ >+ {S.files.editorWrap}+ </button>+ <Button size="sm" onClick={cancelEdit} disabled={saving}>+ {S.common.cancel}+ </Button>+ <Button+ size="sm"+ variant="primary"+ onClick={requestSave}+ disabled={saving}+ title={S.files.saveTitle}+ >+ {saving ? S.common.saving : S.common.save}+ </Button>+ </>) : (- // The source view reuses the message stream's CodeBlock: Shiki dual-theme- // highlighting + language label + copy button, no line wrapping, horizontal scroll- // instead (wrapping code is a disaster for readability, see the old mobile styling).<>- <CodeBlock- language={languageForExtension(extOf(preview.name))}- code={preview.content}- highlight={preview.content.length <= HIGHLIGHT_LIMIT}- />- {preview.truncated && (- <p className="mt-1 text-xs text-gray-400">… {S.files.previewTruncated}</p>+ {richToggle}+ {canEdit && (+ <button+ type="button"+ onClick={() => void startEdit()}+ className={ghostActionClass}+ >+ {S.common.edit}+ </button>)}+ {/* rel="noopener noreferrer" is load-bearing, not boilerplate: the preview must+ not keep a handle back to this window, which is the whole point of serving+ it from a separate origin. */}+ {/\.html?$/i.test(preview.name) && (+ <a+ href={api.workspaceFilePreviewUrl(sessionId, preview.path)}+ target="_blank"+ rel="noopener noreferrer"+ title={previewIsolated ? undefined : S.files.previewNotIsolatedHint}+ className={ghostActionClass}+ >+ {S.files.openInNewTab}+ {!previewIsolated && (+ <span+ aria-label={S.files.previewNotIsolatedHint}+ className={toneInk.attention}+ >+ ⚠+ </span>+ )}+ </a>+ )}+ <a+ href={api.workspaceFileUrl(sessionId, preview.path, true)}+ download={preview.name}+ className={ghostActionClass}+ >+ {S.files.download}+ </a></>- )- ) : (- <p className="text-sm text-gray-500 dark:text-gray-400">{S.files.previewUnsupported}</p>- )}- </div>- </div>- );- }+ )}+ </div>+ {previewBody(preview)}+ </>+ )}+ </div>+ );return (- <div className="flex h-full min-h-0 flex-col">- {/* Toolbar: breadcrumbs + actions */}- <div className="flex shrink-0 flex-wrap items-center gap-1 border-b border-gray-200 px-3 py-2 dark:border-gray-800">- <button- type="button"- disabled={busy}- onClick={() => {- setPath("");- }}- className="rounded px-1.5 py-0.5 text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800"- >- {S.files.root}- </button>- {crumbs.map((seg, i) => (- <span key={i} className="flex items-center gap-1">- <span className="text-gray-300 dark:text-gray-700">/</span>- <button- type="button"- disabled={busy}- onClick={() => setPath(crumbs.slice(0, i + 1).join("/"))}- className="max-w-32 truncate rounded px-1 py-0.5 text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800"- >- {seg}- </button>- </span>- ))}- <span className="flex-1" />- {/* Details: a popup card showing the full absolute Workspace path (break-all wraps in full, never truncated). */}- <Dropdown- open={showPath}- setOpen={setShowPath}- menuClass="right-0 top-full mt-1 w-max max-w-72 origin-top-right"- button={- <Button- size="sm"- variant={showPath ? "primary" : "ghost"}- onClick={() => setShowPath((v) => !v)}- >- {S.files.details}- </Button>- }+ <div+ ref={rootRef}+ className="relative flex h-full min-h-0 flex-col"+ onDragOver={onDragOver}+ onDragLeave={onDragLeave}+ onDrop={onDrop}+ >+ {/* Toolbar: tree toggle + the current directory's path + actions. One row that never+ wraps — the path strip absorbs the pressure (it clips, and its leading segments+ collapse), the actions keep their width. */}+ <div className="flex shrink-0 flex-nowrap items-center gap-1 border-b border-gray-200 px-2 py-1.5 dark:border-gray-800">+ {!narrow && (+ // Static accessible name, state on aria-pressed alone: a name that swaps Show/Hide+ // beside it reads as "Hide file tree, pressed", saying the state twice and+ // disagreeing with itself. The tooltip may still swap — it is presentation only.+ <button+ type="button"+ aria-pressed={treeVisible}+ title={treeVisible ? S.files.hideTree : S.files.showTree}+ aria-label={S.files.showTree}+ onClick={() => setTree(!treeVisible)}+ className={`flex h-6 w-6 shrink-0 items-center justify-center rounded transition-colors duration-150 ${+ treeVisible+ ? "text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-gray-800"+ : "text-gray-400 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"+ }`}+ >+ <GlyphIcon d={PANEL_LEFT_ICON} size={ICON_SIZE.iconButton} />+ </button>+ )}+ {/* The path, read out and not navigable: the tree beside it is what navigates, and a+ second way in would only be a second thing to keep in step with the editor's+ unsaved-changes guard. */}+ <div+ ref={crumbsRef}+ title={crumbPath}+ className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden px-1 text-sm">- <div className="px-3.5 py-2.5">- <p className="text-xs font-medium text-gray-500 dark:text-gray-400">- {S.files.workspacePath}- </p>- <p className="mt-1 break-all font-mono text-xs leading-5">{session.workspace}</p>- </div>- </Dropdown>- <Button size="sm" variant="ghost" onClick={() => setReloadTick((t) => t + 1)}>- {S.files.refresh}- </Button>- {/* Matches the same visual style and font size (sm = text-xs) as the adjacent ghost Buttons (Details/Refresh): no border, light background on hover. */}- <label className="inline-flex cursor-pointer items-center rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 focus-within:ring-2 focus-within:ring-gray-400/30 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100">- <HiddenFileInput multiple onChange={onUpload} disabled={uploading} />- {uploading ? S.common.saving : S.files.upload}- </label>+ {crumbFit.collapsed && (+ <span className="shrink-0 text-gray-400 dark:text-gray-500">{CRUMB_ELLIPSIS}</span>+ )}+ {crumbFit.visible.map((seg, i) => (+ <Fragment key={`${i}-${seg}`}>+ {(crumbFit.collapsed || i > 0) && (+ <span className="shrink-0 text-gray-300 dark:text-gray-700">/</span>+ )}+ <span+ className={+ i === crumbFit.visible.length - 1+ ? "min-w-0 truncate font-medium text-gray-700 dark:text-gray-200"+ : "shrink-0 whitespace-nowrap text-gray-500 dark:text-gray-400"+ }+ >+ {seg}+ </span>+ </Fragment>+ ))}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <Button size="sm" variant="ghost" onClick={refreshAll}>+ {S.files.refresh}+ </Button>+ {/* Matches the same visual style and font size (sm = text-xs) as the adjacent ghost Refresh Button: no border, light background on hover. */}+ <label className="inline-flex cursor-pointer items-center rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 focus-within:ring-2 focus-within:ring-gray-400/30 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100">+ <HiddenFileInput multiple onChange={onPick} disabled={uploading !== null} />+ {uploading !== null+ ? S.files.uploading(uploading.done, uploading.total)+ : S.files.upload}+ </label>+ </div></div>- <div className="min-h-0 flex-1 overflow-y-auto">- {error ? (- <p className="px-3 py-3 text-sm text-red-600 dark:text-red-400">{error}</p>- ) : data === null ? (- <SkeletonList rows={6} />- ) : data.res.entries.length === 0 ? (- <p className="px-3 py-3 text-sm text-gray-400">{S.files.empty}</p>- ) : (- // No "up a level" row: going up a level is done via the toolbar breadcrumbs (root / any segment is clickable).- // While a navigation is in flight (busy) the stale rows stay visible but dimmed and inert.- <ul- aria-busy={busy}- className={`divide-y divide-gray-100 dark:divide-gray-800/60 ${busy ? "opacity-60" : ""}`}+ <div className="relative flex min-h-0 flex-1">+ {/* Narrow: one column, tree or preview. */}+ {narrow && showTree && tree}+ {/* Wide: the tree and its divider stay mounted and slide in and out of the panel's+ left edge, on the same 200ms width transition the dock itself expands and+ collapses with. Both keep their own width inside the clipping window, so the tree+ does not reflow as it moves; the preview beside it takes the room it leaves.+ inert while away — a pane at zero width is not somewhere to tab into. */}+ {!narrow && (+ <div+ aria-hidden={!treeVisible}+ inert={!treeVisible}+ style={{ width: treeVisible ? treeWidth + TREE_DIVIDER_PX : 0 }}+ className={`flex min-h-0 shrink-0 overflow-hidden ${+ treeSliding ? "transition-[width] duration-200" : ""+ }`}>- {data.res.entries.map((entry) => (- <li key={entry.name}>- <div className="group flex items-center gap-2 px-3 py-1.5 transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50">- <button- type="button"- disabled={busy}- onClick={() => {- // Joined against the listing's own base (see the data state comment): a second- // click on the same stale row resolves to the same target, not a deeper one.- const target = joinWorkspacePath(data.base, entry.name);- if (entry.kind === "dir") setPath(target);- else void previewPath(target);- }}- className="flex min-w-0 flex-1 items-center gap-2 text-left"- title={entry.name}- >- <span className="shrink-0 text-gray-400" aria-hidden>- {entry.kind === "dir" ? (- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.7"- >- <path d="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-2z" />- </svg>- ) : (- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.7"- >- <path d="M6 3h8l4 4v14H6zM14 3v4h4" />- </svg>- )}- </span>- <span className="min-w-0 flex-1 truncate text-sm">{entry.name}</span>- </button>- <span className="shrink-0 font-mono text-xs text-gray-400 dark:text-gray-500">- {entry.kind === "file" ? formatBytes(entry.sizeBytes) : ""}- </span>- <span className="hidden shrink-0 font-mono text-xs text-gray-400 sm:block dark:text-gray-500">- {entry.mtime ? formatDateTime(entry.mtime) : ""}- </span>- {entry.kind === "file" && (- <a- href={api.workspaceFileUrl(- session.sessionId,- joinWorkspacePath(data.base, entry.name),- true,- )}- download={entry.name}- title={S.files.download}- className="shrink-0 rounded p-1 text-gray-300 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 group-hover:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.7"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden- >- <path d="M12 3v12m0 0l-4-4m4 4l4-4M4 21h16" />- </svg>- </a>- )}- </div>- </li>- ))}- </ul>+ {tree}+ {treeDivider}+ </div>+ )}+ {showPreview && previewPane}+ {/* Drop feedback: a dashed frame over the panel and a label naming the directory the+ files will land in. Pure feedback — pointer-events-none keeps the hit test on the+ rows underneath, which is how a folder row can be the target. */}+ {drag.active && (+ <div+ aria-hidden+ className="anim-fade pointer-events-none absolute inset-0 z-20 flex items-end justify-center p-3"+ >+ <div className="absolute inset-1 rounded-lg border-2 border-dashed border-gray-400 bg-white/40 dark:border-gray-500 dark:bg-gray-950/40" />+ <div className="relative flex items-center gap-2 rounded-md border border-gray-300 bg-white/95 px-3 py-1.5 text-xs font-medium text-gray-800 shadow-sm dark:border-gray-700 dark:bg-gray-900/95 dark:text-gray-100">+ <GlyphIcon d={PAPERCLIP_ICON} size={ICON_SIZE.rowLead} className="text-gray-400" />+ <span className="truncate">{S.files.dropToUpload(dirLabel(drag.targetDir))}</span>+ </div>+ </div>)}</div>- {/* Upload-overwrite confirmation: same-name files in this directory get replaced. */}+ {/* Upload-overwrite confirmation: same-name files in the target directory get replaced. */}<ConfirmModalopen={pendingUpload !== null}title={S.files.overwriteTitle}@@ -869,7 +1749,7 @@ export function WorkspaceBrowser({confirmLabel={S.files.upload}onClose={() => setPendingUpload(null)}onConfirm={() => {- if (pendingUpload) doUpload(pendingUpload.files);+ if (pendingUpload) void doUpload(pendingUpload.files, pendingUpload.dir);setPendingUpload(null);}}>@@ -886,6 +1766,55 @@ export function WorkspaceBrowser({</ul></div></ConfirmModal>++ {/* Save confirmation: the file in the Workspace is overwritten, like every server-side write. */}+ <ConfirmModal+ open={saveConfirm}+ title={S.files.saveConfirmTitle}+ tone="primary"+ confirmLabel={S.common.save}+ busy={saving}+ onClose={() => setSaveConfirm(false)}+ onConfirm={() => void save()}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {S.files.saveConfirm(editor !== null ? baseName(editor.path) : "")}+ </p>+ </ConfirmModal>++ {/* Write-precondition conflict: the file changed after the editor opened it, so the+ save was refused with nothing written. Cancel keeps the draft and the editor. */}+ <ConfirmModal+ open={conflict !== null}+ title={S.files.conflictTitle}+ tone="primary"+ confirmLabel={S.files.overwriteAnyway}+ onClose={() => setConflict(null)}+ onConfirm={() => void save({ overwrite: true })}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {S.files.conflictBody(conflict?.name ?? "")}+ </p>+ </ConfirmModal>++ {/* Unsaved-changes guard: leaving the edited file, closing the panel, cancelling. */}+ <ConfirmModal+ open={discardPrompt !== null}+ title={S.files.discardTitle}+ confirmLabel={S.files.discard}+ onClose={() => {+ discardPrompt?.resolve(false);+ setDiscardPrompt(null);+ }}+ onConfirm={() => {+ discardPrompt?.resolve(true);+ setDiscardPrompt(null);+ }}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {S.files.discardBody(editor !== null ? baseName(editor.path) : "")}+ </p>+ </ConfirmModal></div>);}diff --git a/packages/web/src/features/chat/workspace-editor.tsx b/packages/web/src/features/chat/workspace-editor.tsxnew file mode 100644index 00000000..035ca0c9--- /dev/null+++ b/packages/web/src/features/chat/workspace-editor.tsx@@ -0,0 +1,56 @@+/**+ * The Files panel's in-place text editor: one plain monospace textarea over the file's+ * text, nothing richer. No spell-check or autocorrect, and Ctrl+S / Cmd+S saves — the+ * browser's own "save page" default is suppressed while the focus is here. Long lines+ * scroll sideways, as code should, unless the header's 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 } from "react";+import type { KeyboardEvent as ReactKeyboardEvent } from "react";+import { S } from "../../lib/strings";+import { baseName } from "../../lib/workspace-tree";++export function WorkspaceFileEditor({+ path,+ value,+ wrap,+ onChange,+ onSave,+}: {+ path: string;+ value: string;+ /** Soft-wrap long lines instead of scrolling sideways (the preview header's toggle). */+ wrap: boolean;+ onChange: (next: string) => void;+ onSave: () => void;+}) {+ const ref = useRef<HTMLTextAreaElement | null>(null);+ useEffect(() => {+ ref.current?.focus();+ }, []);++ const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>): void => {+ if ((e.ctrlKey || e.metaKey) && !e.altKey && e.key.toLowerCase() === "s") {+ e.preventDefault();+ onSave();+ }+ };++ return (+ <textarea+ ref={ref}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={onKeyDown}+ aria-label={S.files.editorLabel(baseName(path))}+ spellCheck={false}+ autoCapitalize="off"+ autoCorrect="off"+ wrap={wrap ? "soft" : "off"}+ className={`h-full w-full resize-none bg-transparent p-3 font-mono text-xs leading-relaxed text-gray-800 outline-none dark:text-gray-100 ${+ wrap ? "whitespace-pre-wrap" : ""+ }`}+ />+ );+}diff --git a/packages/web/src/features/chat/workspace-tree-view.tsx b/packages/web/src/features/chat/workspace-tree-view.tsxnew file mode 100644index 00000000..294008e4--- /dev/null+++ b/packages/web/src/features/chat/workspace-tree-view.tsx@@ -0,0 +1,335 @@+/**+ * The Files panel's directory tree: one row per entry on screen (lib/workspace-tree.ts+ * flattens the listings), indented by depth, a chevron and a folder glyph on directories,+ * a page glyph and the size on files. Clicking a directory opens or closes it, clicking a+ * file opens it in the preview.+ *+ * Keyboard: the WAI-ARIA tree pattern with a roving tab stop — one row is in the tab order+ * (the focused one, else the selected one, else the first), arrows move between rows and+ * open/close directories (treeKeyStep), Enter and Space act like a click.+ *+ * While OS files are dragged over the panel, the folder row that would receive them is+ * highlighted; the rows carry `data-tree-path` / `data-tree-kind` so the panel's drop+ * handling can resolve the row under the pointer.+ *+ * The rows stay one flat list; what nests is the drawing. An open directory's descendants go+ * in a `role="group"` box whose height is animated, so a subtree grows out of its directory's+ * row and shrinks back into it. Only the directory the panel says was just toggled animates,+ * so a re-render, a filter or an unrelated commit animates nothing. Closing is the awkward+ * half: the rows are gone from `rows` by the time the view hears about it, so the view keeps+ * the last committed rows and re-renders the closed directory's own descendants, inert, for+ * as long as the shrink lasts.+ */+import { useEffect, useRef, useState } from "react";+import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";+import { S } from "../../lib/strings";+import { formatBytes, formatDateTime } from "../../lib/format";+import { subtreeEnd, treeKeyStep } from "../../lib/workspace-tree";+import type { TreeRow } from "../../lib/workspace-tree";+import { Chevron } from "../../components/ui/chevron";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { FOLDER_ICON, FOLDER_OPEN_ICON } from "../../components/ui/group-list";+import { ICON_SIZE } from "../../lib/icon-scale";+import { FILE_ICON } from "../../components/ui/icons";++/** Indent per nesting level, in px. */+const INDENT_PX = 14;++/**+ * How long a closing subtree is kept on screen when its animation never reports back. Under+ * `prefers-reduced-motion` the keyframes are off, so no `animationend` ever arrives and this+ * timer is the only thing that drops the retained rows. Comfortably past the 200ms shrink.+ */+const CLOSE_FALLBACK_MS = 260;++/** The directory whose open or close the tree should animate. `serial` makes toggling the same directory again a new event. */+export interface TreeToggle {+ dir: string;+ open: boolean;+ serial: number;+}++export function WorkspaceTreeView({+ rows,+ selectedPath,+ currentDir,+ loadingDirs,+ dropTargetDir,+ scrollTo,+ rootEmpty,+ filtering,+ toggled,+ onToggleDir,+ onOpenFile,+}: {+ rows: readonly TreeRow[];+ /** The file open in the preview (highlighted). */+ selectedPath: string | null;+ /** The directory uploads land in; highlighted while no file is selected. */+ currentDir: string;+ loadingDirs: ReadonlySet<string>;+ /** The folder a hovering file drag would drop into, or null while nothing is dragged. */+ dropTargetDir: string | null;+ /** A row to bring into view; a new object scrolls again even for the same path. */+ scrollTo: { path: string } | null;+ /** The root listing arrived and holds nothing. */+ rootEmpty: boolean;+ /** The search box holds a query, so no rows means "nothing loaded matches" rather than "empty". */+ filtering: boolean;+ /** The directory last opened or closed, whose subtree animates. Null: nothing to animate. */+ toggled: TreeToggle | null;+ onToggleDir: (dir: string) => void;+ onOpenFile: (path: string) => void;+}) {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const [focused, setFocused] = useState<string | null>(null);++ // The descendants of directories that have just closed, by directory path. They are no+ // longer in `rows` — the panel closed the directory in the same commit that reported the+ // toggle — so they are captured from the previous commit's rows and drawn until the shrink+ // is over. They are never in `rows`, and so never in treeKeyStep, the tab stop or onScreen.+ const [closing, setClosing] = useState<ReadonlyMap<string, readonly TreeRow[]>>(() => new Map());+ // The serial of the toggle already acted on. The serial, not the object: a filter hands the+ // prop null and then hands the very same toggle back when it is cleared, and replaying that+ // close would shrink a ghost subtree out of a directory the user never touched.+ const [seenSerial, setSeenSerial] = useState<number>(toggled?.serial ?? 0);+ const prevRowsRef = useRef<readonly TreeRow[]>(rows);++ if (toggled === null) {+ // A filter redraws the tree from a different row set; nothing left over belongs to it.+ if (closing.size > 0) setClosing(new Map());+ } else if (toggled.serial !== seenSerial) {+ // Adjusting state during render rather than in an effect: the retained rows have to be in+ // the same paint that dropped them, or the subtree blinks out and then shrinks from nothing.+ setSeenSerial(toggled.serial);+ if (toggled.open) {+ // Re-opened while shrinking: the live group takes over, animating open from where it is.+ if (closing.has(toggled.dir)) {+ const next = new Map(closing);+ next.delete(toggled.dir);+ setClosing(next);+ }+ } else {+ const prev = prevRowsRef.current;+ const at = prev.findIndex((r) => r.path === toggled.dir);+ const kept = at < 0 ? [] : prev.slice(at + 1, subtreeEnd(prev, at));+ if (kept.length > 0) setClosing(new Map(closing).set(toggled.dir, kept));+ }+ }++ useEffect(() => {+ prevRowsRef.current = rows;+ }, [rows]);++ const dropClosing = (dir: string): void => {+ setClosing((prev) => {+ if (!prev.has(dir)) return prev;+ const next = new Map(prev);+ next.delete(dir);+ return next;+ });+ };++ useEffect(() => {+ if (closing.size === 0) return;+ const timers = [...closing.keys()].map((dir) =>+ setTimeout(() => dropClosing(dir), CLOSE_FALLBACK_MS),+ );+ return () => {+ for (const timer of timers) clearTimeout(timer);+ };+ }, [closing]);++ const rowElement = (path: string): HTMLElement | null =>+ containerRef.current?.querySelector<HTMLElement>(`[data-tree-path="${CSS.escape(path)}"]`) ??+ null;++ useEffect(() => {+ if (scrollTo === null) return;+ if (scrollTo.path === "") containerRef.current?.scrollTo({ top: 0 });+ else rowElement(scrollTo.path)?.scrollIntoView({ block: "nearest" });+ }, [scrollTo]);++ const activate = (row: TreeRow): void => {+ setFocused(row.path);+ if (row.kind === "dir") onToggleDir(row.path);+ else onOpenFile(row.path);+ };++ const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>): void => {+ if (e.key === "Enter" || e.key === " ") {+ const row = rows.find((r) => r.path === focused);+ if (row === undefined) return;+ e.preventDefault();+ activate(row);+ return;+ }+ const step = treeKeyStep(rows, focused, e.key);+ if (step === null) return;+ e.preventDefault();+ if (step.focus !== undefined) {+ setFocused(step.focus);+ rowElement(step.focus)?.focus();+ }+ if (step.expand !== undefined) onToggleDir(step.expand);+ if (step.collapse !== undefined) onToggleDir(step.collapse);+ };++ // The one row in the tab order. A focused row that scrolled out of the rows (its+ // directory closed) hands the stop back to the selection or the first row.+ const onScreen = (path: string | null): boolean =>+ path !== null && rows.some((r) => r.path === path);+ const tabStop = onScreen(focused)+ ? focused+ : onScreen(selectedPath)+ ? selectedPath+ : (rows[0]?.path ?? null);++ /** One row. A retained row is a leftover of a closing subtree: it draws, and does nothing else. */+ const renderRow = (row: TreeRow, retained: boolean): ReactNode => {+ const selected =+ !retained &&+ (row.path === selectedPath ||+ (selectedPath === null && row.kind === "dir" && row.path === currentDir));+ const dropHere = !retained && row.kind === "dir" && row.path === dropTargetDir;+ const loading = row.kind === "dir" && loadingDirs.has(row.path);+ const detail =+ row.kind === "file"+ ? `${row.path} · ${formatBytes(row.sizeBytes)} · ${formatDateTime(row.mtime)}`+ : row.path;+ return (+ <div+ key={row.path}+ role="treeitem"+ tabIndex={retained || row.path !== tabStop ? -1 : 0}+ aria-level={row.depth + 1}+ aria-posinset={row.posInSet}+ aria-setsize={row.setSize}+ aria-selected={selected}+ {...(row.kind === "dir" ? { "aria-expanded": row.expanded } : {})}+ aria-busy={loading || undefined}+ // A retained row carries no path: rowElement() and the drop hit test both resolve a+ // row by this attribute, and neither may land on one that is on its way out.+ {...(retained ? {} : { "data-tree-path": row.path, "data-tree-kind": row.kind })}+ title={detail}+ {...(retained ? {} : { onClick: () => activate(row), onFocus: () => setFocused(row.path) })}+ style={{ paddingLeft: 6 + row.depth * INDENT_PX }}+ className={`flex cursor-pointer select-none items-center gap-1.5 py-1 pr-2 text-sm outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/60 ${+ dropHere+ ? "bg-sky-50 ring-2 ring-inset ring-sky-500/60 dark:bg-sky-950/40"+ : selected+ ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-800/50"+ } ${loading ? "opacity-60" : ""}`}+ >+ <span className="flex w-3.5 shrink-0 justify-center text-gray-400" aria-hidden>+ {row.kind === "dir" && <Chevron open={row.expanded} size={ICON_SIZE.chevronDense} />}+ </span>+ <GlyphIcon+ d={row.kind === "dir" ? (row.expanded ? FOLDER_OPEN_ICON : FOLDER_ICON) : FILE_ICON}+ size={ICON_SIZE.rowLead}+ className="text-gray-400"+ />+ <span className="min-w-0 flex-1 truncate">{row.name}</span>+ {row.kind === "file" && (+ <span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">+ {formatBytes(row.sizeBytes)}+ </span>+ )}+ </div>+ );+ };++ /** An open directory with nothing in it says so, in place of the children it lacks. */+ const renderEmptyLine = (row: TreeRow): ReactNode => (+ <p+ key={`empty:${row.path}`}+ className="py-1 pr-2 text-xs text-gray-400"+ style={{ paddingLeft: 6 + (row.depth + 1) * INDENT_PX + 14 }}+ >+ {S.files.empty}+ </p>+ );++ /**+ * The rows of `list` in `[start, end)`, with each open directory's descendants nested in a+ * group below it. `retained` marks a closing subtree, which draws its own nested groups but+ * animates nothing and takes no part in interaction.+ */+ const renderRange = (+ list: readonly TreeRow[],+ start: number,+ end: number,+ retained: boolean,+ ): ReactNode[] => {+ const out: ReactNode[] = [];+ let i = start;+ while (i < end) {+ const row = list[i]!;+ out.push(renderRow(row, retained));+ if (row.kind !== "dir") {+ i += 1;+ continue;+ }+ const childrenEnd = subtreeEnd(list, i);+ if (row.expanded && row.loaded) {+ // The group mounts only once the listing is there, so a first open of an unloaded+ // directory animates when its rows arrive rather than around an empty box.+ const opening = !retained && toggled !== null && toggled.open && toggled.dir === row.path;+ out.push(+ <div+ key={`group:${row.path}`}+ role="group"+ aria-label={row.name}+ className={`tree-group ${opening ? "tree-group-open" : ""}`}+ >+ <div>+ {row.empty ? renderEmptyLine(row) : renderRange(list, i + 1, childrenEnd, retained)}+ </div>+ </div>,+ );+ } else if (!retained && closing.has(row.path)) {+ const kept = closing.get(row.path)!;+ out.push(+ <div+ key={`closing:${row.path}`}+ role="group"+ aria-hidden+ inert+ className="tree-group tree-group-close"+ onAnimationEnd={(e) => {+ if (e.target === e.currentTarget) dropClosing(row.path);+ }}+ >+ <div>{renderRange(kept, 0, kept.length, true)}</div>+ </div>,+ );+ }+ i = childrenEnd;+ }+ return out;+ };++ return (+ <div+ ref={containerRef}+ role="tree"+ aria-label={S.files.treeLabel}+ onKeyDown={onKeyDown}+ className="min-h-0 flex-1 overflow-auto py-1"+ >+ {rows.length === 0 ? (+ filtering ? (+ <p className="px-3 py-2 text-sm text-gray-400">{S.files.searchNoMatch}</p>+ ) : rootEmpty ? (+ <p className="px-3 py-2 text-sm text-gray-400">{S.files.empty}</p>+ ) : null+ ) : (+ // `role="group"` is the tree pattern's own container for one level, so the rows inside+ // one are still `treeitem`s of this tree and keep stating their own aria-level,+ // aria-posinset and aria-setsize.+ renderRange(rows, 0, rows.length, false)+ )}+ </div>+ );+}diff --git a/packages/web/src/features/dock/close-guard.ts b/packages/web/src/features/dock/close-guard.tsnew file mode 100644index 00000000..2dd195e5--- /dev/null+++ b/packages/web/src/features/dock/close-guard.ts@@ -0,0 +1,32 @@+/**+ * Veto hooks for closing dock tabs. A panel whose body holds unsaved work (the Files+ * panel's text editor) registers a guard under its tab key; the tab's own × asks the+ * guards first and removes it only when each one resolves true. A guard typically opens+ * the panel's own confirm dialog and resolves with the user's answer. A tab with no guard+ * closes at once.+ *+ * That × is the only path here, because it is the only one that unmounts a body: hiding a+ * dock (its × or the toolbar's toggle) leaves every body mounted at zero size, so it takes+ * nothing away and asks nothing.+ */+export type CloseGuard = () => Promise<boolean>;++const guards = new Map<string, CloseGuard>();++/** Registers (or, with null, withdraws) the guard for one tab key. */+export function setCloseGuard(tabKey: string, guard: CloseGuard | null): void {+ if (guard === null) guards.delete(tabKey);+ else guards.set(tabKey, guard);+}++/**+ * Whether the tabs may close: asks each guarded tab in order and stops at the first veto,+ * so a user who keeps one panel open is not then asked about the next.+ */+export async function confirmClose(tabKeys: readonly string[]): Promise<boolean> {+ for (const key of tabKeys) {+ const guard = guards.get(key);+ if (guard !== undefined && !(await guard())) return false;+ }+ return true;+}diff --git a/packages/web/src/features/dock/dock-drag.tsx b/packages/web/src/features/dock/dock-drag.tsxindex 1a57e58c..11a23acc 100644--- a/packages/web/src/features/dock/dock-drag.tsx+++ b/packages/web/src/features/dock/dock-drag.tsx@@ -46,14 +46,17 @@ export function dockDropCandidate(x: number, y: number): DockPosition | null {/*** The exact region a dock at `position` would occupy after the drop — measured from the* live layout, not assumed: an already-open dock contributes its rendered rect; otherwise- * the stored sizes apply, clamped exactly like the docks' own CSS. The right region's top- * is the main row (`[data-dock-row]`, below the chat toolbar), the row the right dock- * really renders in.+ * the stored sizes apply, clamped exactly like the docks' own CSS. Only an OPEN dock+ * counts: a hidden one stays in the tree at zero size, and measuring that would preview a+ * region of nothing. The right region's top is the main row (`[data-dock-row]`, below the+ * chat toolbar), the row the right dock really renders in.*/function previewStyle(host: DOMRect, position: DockPosition): CSSProperties {const existing =document- .querySelector<HTMLElement>(`[data-testid='dock'][data-position='${position}']`)+ .querySelector<HTMLElement>(+ `[data-testid='dock'][data-position='${position}'][data-open='true']`,+ )?.getBoundingClientRect() ?? null;if (position === "bottom") {const height = Math.min(diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsxindex bca7a15e..a0bbaa5d 100644--- a/packages/web/src/features/dock/dock-panel.tsx+++ b/packages/web/src/features/dock/dock-panel.tsx@@ -8,14 +8,17 @@* session/stream state); terminal tabs' bodies are the pooled xterm views* (terminal-view-pool.tsx), adopted by DOM handoff so tab churn never reconnects a shell.* Every tab's body stays mounted while its tab is in the strip — switching tabs hides and- * shows, so a panel keeps its scroll and drill-down state — except terminal views, which- * the pool keeps only for shown terminals (an off-screen shell reattaches on return).+ * shows, and so does hiding the whole dock (which renders at zero size rather than+ * unmounting), so a panel keeps its scroll, its drill-down and its unsaved text — except+ * terminal views, which the pool keeps only for shown terminals (an off-screen shell+ * reattaches on return).** The header carries the strip, a "+" menu (panels, a fresh shell, and any live shell no* conversation holds), a detach button while a terminal is shown, a move-to-other-edge- * button, and the dock's × (hide — tabs stay; each tab's own always-visible × is what- * removes). Tabs drag sideways to reorder; dragging a tab out of the strip brings up the- * edge overlay (dock-drag.tsx) and dropping on the other edge moves that tab there.+ * button, and the dock's × (hide — tabs and everything their bodies hold stay; each tab's+ * own always-visible × is what removes). Tabs drag sideways to reorder; dragging a tab out+ * of the strip brings up the edge overlay (dock-drag.tsx) and dropping on the other edge+ * moves that tab there.* Dragging the header itself moves the whole dock the same way. The boundary with the* chat content resizes the dock — the right dock through the shared side-panel width,* the bottom dock through its height ratio.@@ -50,6 +53,7 @@ import {subscribeTerminalCloseRequests,} from "../terminal/terminal-view-pool";import type { TerminalInfo } from "../terminal/terminal-view";+import { confirmClose } from "./close-guard";import { createShellInDock, detachTerminal, openTerminalInDock } from "./dock-terminal";import { DockDragOverlay, dockDropCandidate } from "./dock-drag";import { panelGlyph, panelLabel } from "./panel-meta";@@ -185,7 +189,10 @@ function DockTabButton(props: {/*** A terminal tab's body: adopts the shown terminal's pooled container. Only while shown —* the pool keeps views for shown terminals alone, so adopting an inactive tab's container- * would hold an empty node.+ * would hold an empty node. A hidden dock is not shown either: the pool disposes the view+ * with the dock and builds a FRESH container on the way back, which the effect re-adopts+ * because `active` fell to false meanwhile (the shell keeps running server-side and its+ * screen is restored on reattach; xterm refits once the container has real size again).*/function TerminalBody({ id, active }: { id: string; active: boolean }) {const chrome = useTerminalChrome();@@ -324,15 +331,23 @@ export function DockPanel({// ---------------------------------------------------------------------------- selection// A terminal tab's × ends the shell itself (server-side) — an easy mis-click next to- // the tab, so it confirms first. Panel tabs close directly: nothing is lost.+ // the tab, so it confirms first. A panel tab closes directly unless its body registered+ // a close guard (the Files panel's editor holding unsaved text), which asks first: the+ // tab's × is the one gesture here that really unmounts a body.const [confirmKill, setConfirmKill] = useState<{ id: string; label: string } | null>(null);const closeTab = useCallback((tab: DockTab, label: string) => {if (tab.kind === "terminal") {setConfirmKill({ id: tab.terminalId, label });return;}- removeTab(tabKey(tab));+ const key = tabKey(tab);+ void confirmClose([key]).then((ok) => {+ if (ok) removeTab(key);+ });}, []);+ // Hiding puts the surface away and nothing else — every body stays mounted at zero size —+ // so there is nothing to ask about, however much unsaved work a tab is holding.+ const hide = useCallback(() => hideView(view), [view]);const killConfirmed = useCallback(() => {if (!confirmKill) return;void killTerminal(confirmKill.id);@@ -627,6 +642,28 @@ export function DockPanel({// eslint-disable-next-line react-hooks/exhaustive-deps}, []);+ // A flip the store marks instant (a scope switch, a cross-dock move) must apply without+ // sliding. Leaving the tree is no longer what makes that instant — the node outlives a+ // collapse now — so the transition class is left off for the commit that carries the flip+ // and restored two frames later, once the new size has been painted.+ const [snap, setSnap] = useState(false);+ const lastOpen = useRef(open);+ if (lastOpen.current !== open) {+ lastOpen.current = open;+ if (!animateEntrance) setSnap(true);+ }+ useEffect(() => {+ if (!snap) return;+ let inner = 0;+ const outer = requestAnimationFrame(() => {+ inner = requestAnimationFrame(() => setSnap(false));+ });+ return () => {+ cancelAnimationFrame(outer);+ cancelAnimationFrame(inner);+ };+ }, [snap]);+const overlayActive = headerDrag.active || tabDrag.active;const overlayCandidate = headerDrag.active ? headerDrag.candidate : tabDrag.candidate;@@ -728,7 +765,7 @@ export function DockPanel({/></DockButton>)}- <DockButton label={S.dock.hideDock} testId="dock-close" onClick={() => hideView(view)}>+ <DockButton label={S.dock.hideDock} testId="dock-close" onClick={hide}><CloseIcon size={12} /></DockButton></div>@@ -751,10 +788,13 @@ export function DockPanel({const active = key === activeKey;return (<div key={key} className={active ? "flex h-full min-h-0 flex-col" : "hidden"}>+ {/* A hidden dock's shown tab is no more on screen than a covered one: the+ bodies gate their polling and their reload-on-return on this, and a+ collapsed dock should cost nothing while it is away. */}{tab.kind === "panel" ? (- renderPanel(tab.panel, active)+ renderPanel(tab.panel, active && open)) : (- <TerminalBody id={tab.terminalId} active={active} />+ <TerminalBody id={tab.terminalId} active={active && open} />)}</div>);@@ -784,6 +824,9 @@ export function DockPanel({ref={rootRef}data-testid="dock"data-position="bottom"+ // A closed dock stays in the tree at zero size, so what is on screen is data-open,+ // not the node's presence (dock-drag.tsx and the e2e specs select on it).+ data-open={open}// Collapsed to 0 while closing/entering; the border belongs to the open state// only — with border-box sizing a collapsed dock would still paint its 1px,// leaving a hairline where nothing is.@@ -791,7 +834,7 @@ export function DockPanel({inert={!open}className={`relative flex w-full shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${open ? "border-t border-gray-200 dark:border-gray-800" : ""- } ${resizing ? "" : "transition-[height] duration-200"}`}+ } ${resizing || snap ? "" : "transition-[height] duration-200"}`}>{/* The handle straddles the boundary as an overlay, costing no height. Only whileopen — a collapsing dock must not keep a grabbable edge behind. */}@@ -845,12 +888,14 @@ export function DockPanel({ref={rootRef}data-testid="dock"data-position="right"+ // What is on screen is data-open, not the node's presence (see the bottom branch).+ data-open={open}// The border belongs to the open state only (see the bottom branch's note).style={{ width: open && entered ? sideWidth : 0 }}inert={!open}className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${open ? "border-l border-gray-200 dark:border-gray-800" : ""- } ${resizing ? "" : "transition-[width] duration-200"}`}+ } ${resizing || snap ? "" : "transition-[width] duration-200"}`}>{/* Fixed-width content inside the clipping window: while the outer elementanimates through intermediate widths, the content must not reflow frame bydiff --git a/packages/web/src/features/dock/dock-state.ts b/packages/web/src/features/dock/dock-state.tsindex 450a6837..9b3e69b6 100644--- a/packages/web/src/features/dock/dock-state.ts+++ b/packages/web/src/features/dock/dock-state.ts@@ -21,9 +21,10 @@* user likes a dock is one preference, not one per conversation.** Closing a TAB removes it (the last tab closing also puts the dock away); a dock's ×- * hides the surface keeping its tabs for the next open. Below the desktop breakpoint the- * two docks render as ONE merged bottom surface (a 320px-minimum right panel does not fit- * a phone); the stored arrangement splits back apart when the window widens.+ * hides the surface, keeping its tabs — and, through closedDockView, everything their+ * bodies hold — for the next open. Below the desktop breakpoint the two docks render as ONE+ * merged bottom surface (a 320px-minimum right panel does not fit a phone); the stored+ * arrangement splits back apart when the window widens.** A store (rather than component state) because the consumers live far apart: the chat* toolbar toggles the docks, the global hotkey flips the terminal, AppLayout points the@@ -372,15 +373,22 @@ export function dockActiveKey(position: DockPosition): string | null {return area(position).active;}+/** Whether a dock has anything to show at all — the closed merged view's counterpart to visibility. */+function hasTabs(position: DockPosition): boolean {+ return area(position).tabs.length > 0;+}+/**- * The merged view's active tab: the focused dock's active when that dock is on screen,- * else the other visible dock's. What "the shown tab" means below the breakpoint.+ * The merged view's active tab: the focused dock's active when that dock counts, else the+ * other's. What "the shown tab" means below the breakpoint. `counts` is what being on+ * screen means for the view being built — visibility for the merged view the docks render,+ * having tabs at all for the closed one that only keeps its panels mounted.*/-function mergedActiveKey(): string | null {+function mergedActiveKey(counts: (position: DockPosition) => boolean): string | null {const first = layout.focus;const second: DockPosition = first === "right" ? "bottom" : "right";- if (isDockVisible(first) && area(first).active !== null) return area(first).active;- if (isDockVisible(second)) return area(second).active;+ if (counts(first) && area(first).active !== null) return area(first).active;+ if (counts(second)) return area(second).active;return null;}@@ -412,14 +420,32 @@ export function dockViews(): DockView[] {...(isDockVisible("bottom") ? layout.bottom.tabs : []),...(isDockVisible("right") ? layout.right.tabs : []),];- return [{ position: "bottom", merged: true, tabs, activeKey: mergedActiveKey() }];+ return [{ position: "bottom", merged: true, tabs, activeKey: mergedActiveKey(isDockVisible) }];+}++/**+ * The view a CLOSED dock would render if it opened. The chat page keeps a collapsed dock's+ * node mounted on this, so hiding costs no panel state: the file preview, the editor draft+ * and the shell on screen are all still there on the way back. Null when there is nothing+ * to keep — the dock is open (dockViews() lists it then), it has no tabs, or it is the+ * narrow layout's right dock, whose tabs the merged bottom view carries.+ */+export function closedDockView(position: DockPosition): DockView | null {+ if (narrow) {+ if (position === "right" || isDockVisible("right") || isDockVisible("bottom")) return null;+ const tabs = [...layout.bottom.tabs, ...layout.right.tabs];+ if (tabs.length === 0) return null;+ return { position: "bottom", merged: true, tabs, activeKey: mergedActiveKey(hasTabs) };+ }+ if (isDockVisible(position) || !hasTabs(position)) return null;+ return { position, merged: false, tabs: area(position).tabs, activeKey: area(position).active };}/** Whether a tab is the one actually on screen (narrow-aware — what a toggle closes). */export function isTabShown(key: string): boolean {const home = tabHome(key);if (home === null || !isDockVisible(home)) return false;- return narrow ? mergedActiveKey() === key : area(home).active === key;+ return narrow ? mergedActiveKey(isDockVisible) === key : area(home).active === key;}/** Whether a tab sits in a visible dock at all (shown or behind another tab). */@@ -687,7 +713,7 @@ export function toggleTerminalDocks(): boolean {(position) =>isDockVisible(position) &&(narrow- ? mergedActiveKey()?.startsWith("terminal:") === true+ ? mergedActiveKey(isDockVisible)?.startsWith("terminal:") === true: area(position).active?.startsWith("terminal:") === true),);if (anyShown) {diff --git a/packages/web/src/features/dock/use-dock-mount.ts b/packages/web/src/features/dock/use-dock-mount.tsindex 75b79e77..20bf6873 100644--- a/packages/web/src/features/dock/use-dock-mount.ts+++ b/packages/web/src/features/dock/use-dock-mount.ts@@ -2,16 +2,22 @@* Mount state of one dock position, giving open/close its animation without giving one to* changes that must be instant.*- * The store's dockViews() only lists OPEN docks, but a collapse transition needs the node- * on both ends of it — so this hook keeps the last view mounted (open=false, sliding to- * zero) for the transition's duration before unmounting for real. Changes the store marks- * instant (scope switches, cross-dock moves — see instantVersion) skip both directions:- * a closing dock unmounts immediately, an opening one mounts at full size.+ * The node OUTLIVES the collapse. What a dock holds is the user's place in the work — the+ * file open in the preview, an editor draft, a running shell — and hiding a dock is a+ * gesture about the surface, not about that work, so a collapsed dock stays mounted at zero+ * size on the store's closedDockView and comes back exactly as it was. It unmounts only+ * when there is nothing left to keep (no tabs at all).+ *+ * The store's dockViews() only lists OPEN docks, so a collapse transition needs a view for+ * the frames it plays over: the hook keeps the LAST OPEN view mounted (open=false, sliding+ * to zero) for the transition's duration, which is also what carries a dock whose last tab+ * just closed through its exit. Changes the store marks instant (scope switches, cross-dock+ * moves — see instantVersion) skip the animation in both directions.** The animate/linger decision is frozen AT RENDER TIME of the open/close flip (a ref* adjusted during render — deterministic for a given store state, so a re-render replays* it identically): an effect would decide only after the flip already painted, which for- * a close means the node is gone before the transition could start.+ * a close means the transition would start a frame late.*/import { useEffect, useRef, useState } from "react";import type { DockView } from "./dock-state";@@ -25,15 +31,19 @@ import { instantVersion } from "./dock-state";export const DOCK_TRANSITION_MS = 200;export interface DockMount {- /** The view to render, kept through the exit transition; null = nothing mounted. */+ /** The view to render — open, collapsing, or collapsed; null = nothing mounted. */view: DockView | null;- /** False only while the mounted view is collapsing on its way out. */+ /** False while the mounted view is collapsing on its way out, and once it is away. */open: boolean;- /** Whether an opening dock plays the expand transition (false for instant changes). */+ /** Whether this open/close flip plays the transition (false for instant changes). */animateEntrance: boolean;}-export function useDockMount(view: DockView | null): DockMount {+/**+ * @param view the store's OPEN view for this position (null when the dock is not open)+ * @param closedView what to keep mounted while it is closed (dock-state's closedDockView)+ */+export function useDockMount(view: DockView | null, closedView: DockView | null): DockMount {const open = view !== null;const instant = instantVersion();// The most recent open view — what a collapse keeps on screen while it slides out.@@ -67,5 +77,5 @@ export function useDockMount(view: DockView | null): DockMount {if (open) return { view, open: true, animateEntrance: episode.current.animate };if (lingering.current && lastView.current !== null)return { view: lastView.current, open: false, animateEntrance: true };- return { view: null, open: false, animateEntrance: true };+ return { view: closedView, open: false, animateEntrance: episode.current.animate };}diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.tsindex 95470cc3..34914799 100644--- a/packages/web/src/lib/install-scope.ts+++ b/packages/web/src/lib/install-scope.ts@@ -137,6 +137,24 @@ export const KEY_RULES: readonly KeyRule[] = [scope: "browser",why: "Side-panel width in px; its own module calls it a layout preference, not session data.",},+ {+ kind: "exact",+ key: "penguin.files.treeVisible",+ scope: "browser",+ why: "Whether the Files panel shows its directory tree beside the preview; chrome layout, holds no entity.",+ },+ {+ kind: "exact",+ key: "penguin.files.treeWidth",+ scope: "browser",+ why: "How wide that tree pane was dragged, in px; the same layout preference, one axis over.",+ },+ {+ kind: "exact",+ key: "penguin.files.editorWrap",+ scope: "browser",+ why: "Whether the Files panel's editor soft-wraps long lines; a reading habit, valid against any root.",+ },{kind: "exact",key: "penguin.sidebarGroupMode",diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e697d80f..44c94f2e 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -2289,21 +2289,65 @@ Scenarios:previewNotIsolatedHint:"This address has no separate preview origin, so the page opens sandboxed: localStorage, cookies and third-party embeds will not work. Reach the app over 127.0.0.1 or localhost, or set PENGUIN_PREVIEW_ORIGIN.",refresh: "Refresh",- root: "Workspace root",+ /** The Workspace root, as the breadcrumbs and the drop overlay name it. "." is what a+ * shell calls the working directory, so it needs no translation. */+ root: ".",empty: "Empty directory",previewUnsupported: "Preview not supported for this type; download instead",- uploaded: "Uploaded",- /** Upload-overwrite confirmation: same-name files in the current directory will be replaced. */+ uploadedCount: (n: number): string => (n === 1 ? "1 file uploaded" : `${n} files uploaded`),+ uploading: (done: number, total: number): string => `Uploading ${done}/${total}…`,+ /** Oversize picks are named and skipped before anything is read. */+ uploadTooLarge: (names: string, mb: number): string =>+ `Over the ${mb}MB upload limit, skipped: ${names}`,+ /** A dropped folder is not a file the upload endpoint can take; it is named and skipped. */+ folderDropSkipped: (names: string): string => `Folders cannot be uploaded, skipped: ${names}`,+ /** Upload-overwrite confirmation: same-name files in the target directory will be replaced. */overwriteTitle: "Overwrite existing files",overwriteConfirm: (n: number): string =>- `The current directory already has ${n} file(s) with these names — uploading will overwrite:`,+ `The target directory already has ${n} file(s) with these names — uploading will overwrite:`,loadFailed: "Failed to load",previewTruncated: "File too large; preview truncated, download for the full file",- details: "Details",- workspacePath: "Workspace path",htmlRendered: "Rendered",htmlSource: "Source",backToList: "Back to list",+ /** The tree pane: its accessible name and the toolbar toggle's two states. */+ treeLabel: "File tree",+ showTree: "Show file tree",+ hideTree: "Hide file tree",+ /** The divider between the tree and the preview: drag, or nudge with the arrow keys. */+ treeWidth: "Resize the file tree",+ /** The search box above the tree; it reaches only as far as the lazy tree has been loaded. */+ searchPlaceholder: "Search files",+ searchClear: "Clear search",+ searchNoMatch: "Nothing loaded matches",+ selectFile: "Select a file to preview",+ /** Drop overlay label; `dir` is the directory the files will land in (the root's display name for the root). */+ dropToUpload: (dir: string): string => `Drop to upload into ${dir}`,+ /** In-place text editing. */+ editorLabel: (name: string): string => `Editing ${name}`,+ /** Editor soft-wrap toggle: off means long lines scroll sideways. */+ editorWrap: "Wrap",+ unsaved: "Unsaved changes",+ saveTitle: "Save (Ctrl+S / ⌘S)",+ saveConfirmTitle: "Save file",+ saveConfirm: (name: string): string =>+ `Save changes to ${name}? The file in the Workspace will be overwritten.`,+ editTooLarge: (kb: number): string =>+ `The file is larger than ${kb}KB and cannot be edited here — download it instead`,+ saveTooLarge: (mb: number): string =>+ `The content exceeds the ${mb}MB write limit and was not saved`,+ discardTitle: "Discard unsaved changes",+ discardBody: (name: string): string => `${name} has unsaved changes. Discard them?`,+ discard: "Discard",+ unsavedRestored: (name: string): string => `Restored unsaved changes to ${name}`,+ /** The file was rewritten (by the Agent, most likely) while the editor was open on it. */+ changedOnDisk: "Changed on disk",+ changedOnDiskHint:+ "This file has been rewritten since you opened it — saving replaces that version with yours.",+ conflictTitle: "File changed on disk",+ 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",},usage: {diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 86017616..40c26f05 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -2248,20 +2248,60 @@ Benchmark:previewNotIsolatedHint:"当前访问地址无法提供独立预览源,页面将以沙箱模式打开:localStorage、Cookie 与第三方 embed 不可用。经 127.0.0.1 或 localhost 访问,或配置 PENGUIN_PREVIEW_ORIGIN 即可解除。",refresh: "刷新",- root: "根目录",+ /** The Workspace root, as the breadcrumbs and the drop overlay name it. "." is what a+ * shell calls the working directory, so it needs no translation. */+ root: ".",empty: "空目录",previewUnsupported: "该类型不支持预览,请下载查看",- uploaded: "已上传",- /** Upload-overwrite confirmation: same-name files in the current directory will be replaced. */+ uploadedCount: (n: number): string => `已上传 ${n} 个文件`,+ uploading: (done: number, total: number): string => `正在上传 ${done}/${total}…`,+ /** Oversize picks are named and skipped before anything is read. */+ uploadTooLarge: (names: string, mb: number): string =>+ `超过 ${mb}MB 上传上限,已跳过:${names}`,+ /** A dropped folder is not a file the upload endpoint can take; it is named and skipped. */+ folderDropSkipped: (names: string): string => `不支持上传文件夹,已跳过:${names}`,+ /** Upload-overwrite confirmation: same-name files in the target directory will be replaced. */overwriteTitle: "覆盖同名文件",- overwriteConfirm: (n: number): string => `当前目录已存在以下 ${n} 个同名文件,上传将覆盖:`,+ overwriteConfirm: (n: number): string => `目标目录已存在以下 ${n} 个同名文件,上传将覆盖:`,loadFailed: "加载失败",previewTruncated: "内容过大,预览已截断,请下载查看完整文件",- details: "详情",- workspacePath: "Workspace 路径",htmlRendered: "渲染视图",htmlSource: "源码",backToList: "返回列表",+ /** The tree pane: its accessible name and the toolbar toggle's two states. */+ treeLabel: "文件树",+ showTree: "显示文件树",+ hideTree: "隐藏文件树",+ /** The divider between the tree and the preview: drag, or nudge with the arrow keys. */+ treeWidth: "调整文件树宽度",+ /** The search box above the tree; it reaches only as far as the lazy tree has been loaded. */+ searchPlaceholder: "搜索文件",+ searchClear: "清除搜索",+ searchNoMatch: "已加载的目录中没有匹配项",+ selectFile: "选择一个文件以预览",+ /** Drop overlay label; `dir` is the directory the files will land in (the root's display name for the root). */+ dropToUpload: (dir: string): string => `松开即上传到 ${dir}`,+ /** In-place text editing. */+ editorLabel: (name: string): string => `编辑 ${name}`,+ /** Editor soft-wrap toggle: off means long lines scroll sideways. */+ editorWrap: "自动换行",+ unsaved: "有未保存的修改",+ saveTitle: "保存(Ctrl+S / ⌘S)",+ saveConfirmTitle: "保存文件",+ saveConfirm: (name: string): string => `保存对 ${name} 的修改?Workspace 中的该文件将被覆盖。`,+ editTooLarge: (kb: number): string => `文件超过 ${kb}KB,无法在此编辑,请下载后编辑`,+ saveTooLarge: (mb: number): string => `内容超过 ${mb}MB 写入上限,未保存`,+ discardTitle: "放弃未保存的修改",+ discardBody: (name: string): string => `${name} 有未保存的修改,放弃这些修改?`,+ discard: "放弃",+ unsavedRestored: (name: string): string => `已恢复 ${name} 的未保存修改`,+ /** The file was rewritten (by the Agent, most likely) while the editor was open on it. */+ changedOnDisk: "磁盘上已变更",+ changedOnDiskHint: "该文件在你打开之后已被重写,保存会用你的版本覆盖它。",+ conflictTitle: "文件在磁盘上已变更",+ conflictBody: (name: string): string =>+ `${name} 在你打开之后被重写(多半是 Agent 本轮写的),本次没有保存任何内容。可以用你的版本覆盖它,也可以继续编辑、先把需要的内容取出来——两种选择都会保留你的文本。`,+ overwriteAnyway: "仍然覆盖",},usage: {diff --git a/packages/web/src/lib/workspace-tree.ts b/packages/web/src/lib/workspace-tree.tsnew file mode 100644index 00000000..e7bda4dc--- /dev/null+++ b/packages/web/src/lib/workspace-tree.ts@@ -0,0 +1,582 @@+/**+ * Workspace files panel logic, kept DOM-free so it can be unit-tested:+ * - the directory tree's shape — listings fetched lazily per directory and keyed by its+ * Workspace-relative path ("" is the root), the set of open directories, and the flat+ * row list the tree renders from the two;+ * - the keyboard step over those rows (the WAI-ARIA tree pattern: up/down move, right+ * opens a directory or steps into it, left closes it or steps out to its parent);+ * - the search box's filter over the rows that are loaded;+ * - which directory a dropped batch lands in;+ * - when the panel is too narrow for a tree beside a preview, and how wide the tree pane+ * may be dragged when it is not;+ * - how many breadcrumb segments fit on the toolbar's single row;+ * - which files count as text — by extension, or by looking at their first bytes when+ * the extension says nothing — and so can be previewed as text and edited in place;+ * - the persisted preferences (tree visibility, tree width, editor soft wrap) and the+ * unsaved-changes decision.+ */+import type { WorkspaceFileEntry } from "@prismshadow/penguin-server/api";+import { joinWorkspacePath } from "./file-path";++// ------------------------------------------------------------------------------- layout++/** Below this panel width the tree and the preview no longer fit side by side. */+export const TREE_LAYOUT_MIN_WIDTH = 480;++/**+ * Whether the panel falls back to the single-column drill-down (tree or preview, never+ * both). An unmeasured width (0, before the first ResizeObserver callback) keeps the+ * two-pane default rather than flashing the fallback for a frame.+ */+export function isNarrowLayout(panelWidth: number): boolean {+ return panelWidth > 0 && panelWidth < TREE_LAYOUT_MIN_WIDTH;+}++/** Narrowest the tree pane may be dragged: below this a nested name is all ellipsis. */+export const TREE_MIN_WIDTH = 160;++/**+ * The divider between the tree and the preview, in px — `w-1.5` in the panel. It rides with+ * the tree pane in the sliding container that shows and hides them together, which is why+ * that container's width has to know it.+ */+export const TREE_DIVIDER_PX = 6;++/** Room the preview keeps whatever the tree is dragged to. */+export const PREVIEW_MIN_WIDTH = 240;++/**+ * The tree pane's width until the user drags the divider: about a third of the panel,+ * within bounds that keep names readable and leave the preview its room.+ */+export function defaultTreeWidth(panelWidth: number): number {+ return Math.max(168, Math.min(256, Math.round(panelWidth * 0.36)));+}++/** Widest the tree pane may be dragged at this panel width — never below the tree's own minimum, so a panel with no room for both still has a draggable range of zero rather than an inverted one. */+export function maxTreeWidth(panelWidth: number): number {+ return Math.max(TREE_MIN_WIDTH, panelWidth - PREVIEW_MIN_WIDTH);+}++/**+ * A tree-pane width brought within this panel's bounds. An unmeasured panel (0, before the+ * first ResizeObserver callback) has no ceiling to apply: clamping against it would size+ * the pane to the minimum for one frame and then jump.+ */+export function clampTreeWidth(width: number, panelWidth: number): number {+ const requested = Math.max(TREE_MIN_WIDTH, Math.round(Number.isFinite(width) ? width : 0));+ return panelWidth <= 0 ? requested : Math.min(maxTreeWidth(panelWidth), requested);+}++// -------------------------------------------------------------------------------- paths++/** The directory a Workspace-relative path sits in ("" for a root-level entry). */+export function parentDir(path: string): string {+ const i = path.lastIndexOf("/");+ return i >= 0 ? path.slice(0, i) : "";+}++export function baseName(path: string): string {+ const i = path.lastIndexOf("/");+ return i >= 0 ? path.slice(i + 1) : path;+}++/** 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 = [""];+ const segments = path.split("/").filter((s) => s !== "");+ for (let i = 1; i < segments.length; i += 1) out.push(segments.slice(0, i).join("/"));+ return out;+}++// --------------------------------------------------------------------------------- tree++/** Loaded directory listings by directory path ("" = the Workspace root). A missing key means "not fetched yet". */+export type Listings = ReadonlyMap<string, readonly WorkspaceFileEntry[]>;++/** Directories first, then by name — the order the server lists in, reapplied after a client-side insertion. */+export function sortEntries(entries: readonly WorkspaceFileEntry[]): WorkspaceFileEntry[] {+ return [...entries].sort((a, b) =>+ a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "dir" ? -1 : 1,+ );+}++/**+ * The listings with `entry` in `dir`, inserted in sorted position and replacing a same-named+ * entry (an upload or a save overwrote it). Returns a new map; the input is left untouched.+ */+export function upsertEntry(+ listings: Listings,+ dir: string,+ entry: WorkspaceFileEntry,+): Map<string, readonly WorkspaceFileEntry[]> {+ const next = new Map(listings);+ const current = listings.get(dir) ?? [];+ next.set(dir, sortEntries([...current.filter((e) => e.name !== entry.name), entry]));+ return next;+}++/** The expanded set with every directory above `path` open, so the row for `path` is on screen. */+export function expandTo(expanded: ReadonlySet<string>, path: string): Set<string> {+ const next = new Set(expanded);+ for (const dir of ancestorDirs(path)) next.add(dir);+ return next;+}++/**+ * The expanded set with `dir` opened (its ancestors too, so it is reachable) or closed. Closing+ * leaves the descendants' own state alone: reopening the directory brings back the subtree the+ * way it was left.+ */+export function withExpanded(+ expanded: ReadonlySet<string>,+ dir: string,+ open: boolean,+): Set<string> {+ if (open) {+ const next = expandTo(expanded, dir);+ next.add(dir);+ return next;+ }+ const next = new Set(expanded);+ next.delete(dir);+ return next;+}++/** One rendered tree row: an entry plus where it sits and, for a directory, its open/loaded state. */+export interface TreeRow {+ path: string;+ name: string;+ kind: "dir" | "file";+ /** Nesting depth; a root-level entry is 0. */+ depth: number;+ /** 1-based position among its own directory's entries, and how many there are: the row list+ * is flat, so each row has to state its own set rather than infer it from its container. */+ posInSet: number;+ setSize: number;+ /** Directory rows: whether it is open. */+ expanded: boolean;+ /** Directory rows: whether its listing has arrived (an open, unloaded directory is being fetched). */+ loaded: boolean;+ /** Directory rows: loaded and holding nothing. */+ empty: boolean;+ sizeBytes: number;+ mtime: string;+}++/**+ * The rows the tree draws, top to bottom: a depth-first walk from the root (always open)+ * into every open directory whose listing has arrived. An open directory that is still+ * loading contributes its own row and no children.+ */+export function flattenTree(listings: Listings, expanded: ReadonlySet<string>): TreeRow[] {+ const rows: TreeRow[] = [];+ const walk = (dir: string, depth: number): void => {+ const entries = listings.get(dir) ?? [];+ for (const [index, entry] of entries.entries()) {+ const path = joinWorkspacePath(dir, entry.name);+ const isDir = entry.kind === "dir";+ const open = isDir && expanded.has(path);+ const children = isDir ? listings.get(path) : undefined;+ rows.push({+ path,+ name: entry.name,+ kind: entry.kind,+ depth,+ posInSet: index + 1,+ setSize: entries.length,+ expanded: open,+ loaded: !isDir || children !== undefined,+ empty: isDir && children !== undefined && children.length === 0,+ sizeBytes: entry.sizeBytes,+ mtime: entry.mtime,+ });+ if (open && children !== undefined) walk(path, depth + 1);+ }+ };+ walk("", 0);+ return rows;+}++/**+ * Where the row at `i` stops owning what follows it: the index of the first later row at its+ * own depth or shallower, or the end of the list. The rows in `(i, end)` are its descendants,+ * which is what lets the flat row list be drawn as nested containers.+ */+export function subtreeEnd(rows: readonly TreeRow[], i: number): number {+ const depth = rows[i]?.depth;+ if (depth === undefined) return rows.length;+ for (let j = i + 1; j < rows.length; j += 1) if (rows[j]!.depth <= depth) return j;+ return rows.length;+}++/**+ * The rows left by the search box, or all of them for an empty query. Matching is a+ * case-insensitive substring of the entry's own name; the panel hands in rows walked with+ * every LISTED directory open, so what can be searched is exactly what has been loaded.+ *+ * A kept row is one of three things: a match; an ancestor of a match, without which the+ * match would have nothing to hang under; or anything inside a directory that matched,+ * since a directory that matched is being shown as a directory, with its contents.+ */+export function filterTreeRows(rows: readonly TreeRow[], query: string): TreeRow[] {+ const needle = query.trim().toLowerCase();+ if (needle === "") return [...rows];+ const matched = new Set<string>();+ const keep = new Set<string>();+ for (const row of rows) {+ if (!row.name.toLowerCase().includes(needle)) continue;+ matched.add(row.path);+ keep.add(row.path);+ for (const dir of ancestorDirs(row.path)) if (dir !== "") keep.add(dir);+ }+ if (matched.size === 0) return [];+ return rows.filter(+ (row) =>+ keep.has(row.path) || ancestorDirs(row.path).some((dir) => dir !== "" && matched.has(dir)),+ );+}++/** What one navigation key does to the tree: move focus, open a directory, or close one. */+export interface TreeKeyAction {+ focus?: string;+ expand?: string;+ collapse?: string;+}++/**+ * The keyboard step for `key` with `focused` as the current row (null: none yet), or null+ * when the key is not a tree key or has nothing to do.+ * - ArrowDown / ArrowUp move within the rows on screen (clamped at the ends); with no+ * focused row either lands on the first row.+ * - ArrowRight opens a closed directory, steps into the first child of an open one.+ * - ArrowLeft closes an open directory, otherwise steps out to the parent row.+ * - Home / End jump to the first / last row.+ */+export function treeKeyStep(+ rows: readonly TreeRow[],+ focused: string | null,+ key: string,+): TreeKeyAction | null {+ if (rows.length === 0) return null;+ const first = rows[0]!;+ const index = focused === null ? -1 : rows.findIndex((r) => r.path === focused);+ const row = index >= 0 ? rows[index]! : null;+ switch (key) {+ case "ArrowDown":+ return { focus: rows[Math.min(rows.length - 1, index + 1)]!.path };+ case "ArrowUp":+ return { focus: rows[Math.max(0, index - 1)]!.path };+ case "Home":+ return { focus: first.path };+ case "End":+ return { focus: rows[rows.length - 1]!.path };+ case "ArrowRight": {+ if (row === null) return { focus: first.path };+ if (row.kind !== "dir") return null;+ if (!row.expanded) return { expand: row.path };+ const next = rows[index + 1];+ return next !== undefined && next.depth > row.depth ? { focus: next.path } : null;+ }+ case "ArrowLeft": {+ if (row === null) return null;+ if (row.kind === "dir" && row.expanded) return { collapse: row.path };+ return row.path.includes("/") ? { focus: parentDir(row.path) } : null;+ }+ default:+ return null;+ }+}++// -------------------------------------------------------------------------- breadcrumbs++/** The single item a run of dropped leading segments collapses into. */+export const CRUMB_ELLIPSIS = "…";++/** What of a path the toolbar can show: the trailing segments that fit, and whether anything was dropped ahead of them. */+export interface CrumbLayout {+ visible: string[];+ collapsed: boolean;+}++/**+ * Which breadcrumb segments fit across `availablePx`, tail first. The current directory —+ * the last segment — is always kept, however long it is; leading segments are taken while+ * they fit and the rest collapse into one ellipsis item, so the toolbar's actions never get+ * pushed onto a second row. `measure` gives a rendered item's width in px, ellipsis item+ * included, which is what lets a test state a fixed per-character width.+ */+export function visibleCrumbSegments(+ segments: readonly string[],+ availablePx: number,+ measure: (text: string) => number,+): CrumbLayout {+ if (segments.length === 0) return { visible: [], collapsed: false };+ const last = segments.length - 1;+ const visible = [segments[last]!];+ let used = measure(segments[last]!);+ for (let i = last - 1; i >= 0; i -= 1) {+ // Taking this segment still leaves an ellipsis ahead of it unless it is the first one,+ // so the ellipsis is priced into every step but the last.+ const ellipsis = i > 0 ? measure(CRUMB_ELLIPSIS) : 0;+ const width = measure(segments[i]!);+ if (used + width + ellipsis > availablePx) break;+ visible.unshift(segments[i]!);+ used += width;+ }+ return { visible, collapsed: visible.length < segments.length };+}++// --------------------------------------------------------------------------------- drop++/**+ * The directory a drop lands in: a folder row under the pointer takes the files itself, a+ * file row hands them to its own directory, and anywhere else in the panel means the+ * current directory.+ */+export function dropTargetDir(+ hit: { kind: "dir" | "file"; path: string } | null,+ currentDir: string,+): string {+ if (hit === null) return currentDir;+ return hit.kind === "dir" ? hit.path : parentDir(hit.path);+}++// ---------------------------------------------------------------------------- file kinds++const TEXT_EXTS = new Set([+ "txt",+ "md",+ "json",+ "js",+ "mjs",+ "cjs",+ "ts",+ "tsx",+ "jsx",+ "py",+ "sh",+ "bash",+ "yaml",+ "yml",+ "toml",+ "css",+ "csv",+ "log",+ "xml",+ "ini",+ "conf",+ "rs",+ "go",+ "java",+ "c",+ "h",+ "cpp",+ "hpp",+ "sql",+ "rb",+ "php",+ "gitignore",+ "env",+]);+const IMAGE_EXTS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg"]);+const HTML_EXTS = new Set(["html", "htm"]);++/**+ * How a file previews, decided from its name. `unknown` is not "unsupported" yet: the+ * browser reads such a file's first bytes and treats it as text when they look like text+ * (a Makefile, a LICENSE, a dotfile with no extension).+ */+export type PreviewKind = "text" | "md" | "image" | "html" | "pdf" | "unknown";++/** The lowercased extension, or the whole lowercased name when it has none ("Makefile" → "makefile", ".env" → "env"). */+export function extOf(name: string): string {+ const i = name.lastIndexOf(".");+ return i >= 0 ? name.slice(i + 1).toLowerCase() : name.toLowerCase();+}++export function previewKindFor(name: string): PreviewKind {+ const ext = extOf(name);+ if (IMAGE_EXTS.has(ext)) return "image";+ if (ext === "pdf") return "pdf";+ if (HTML_EXTS.has(ext)) return "html";+ if (ext === "md") return "md";+ if (TEXT_EXTS.has(ext)) return "text";+ return "unknown";+}++/**+ * `bytes` without a multi-byte UTF-8 sequence cut off at its end: a read chunk can end+ * anywhere, and judging validity on the partial character would call a text file binary.+ */+export function utf8Complete(bytes: Uint8Array): Uint8Array {+ let i = bytes.length - 1;+ let back = 0;+ while (i >= 0 && back < 3 && (bytes[i]! & 0xc0) === 0x80) {+ i -= 1;+ back += 1;+ }+ if (i < 0) return bytes;+ const lead = bytes[i]!;+ const need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;+ return bytes.length - i < need ? bytes.subarray(0, i) : bytes;+}++/** Control bytes a text file legitimately carries: tab, LF, CR, FF, backspace, escape (ANSI-colored logs). */+const TEXT_CONTROL_BYTES = new Set([8, 9, 10, 12, 13, 27]);++/**+ * Whether a sample of a file's bytes reads as text: no NUL byte, few other control bytes,+ * and valid UTF-8 once a trailing partial character is set aside. Deliberately strict —+ * a binary mistaken for text becomes an editable garble, while a text file of some other+ * encoding merely stays a download.+ */+export function looksLikeText(bytes: Uint8Array): boolean {+ if (bytes.length === 0) return true;+ let control = 0;+ for (const b of bytes) {+ if (b === 0) return false;+ if (b < 0x20 && !TEXT_CONTROL_BYTES.has(b)) control += 1;+ }+ if (control / bytes.length > 0.1) return false;+ try {+ new TextDecoder("utf-8", { fatal: true }).decode(utf8Complete(bytes));+ return true;+ } catch {+ return false;+ }+}++// ------------------------------------------------------------------------------ editing++/** Bytes a text preview reads before it is cut off; a longer file previews truncated and cannot be edited in place. */+export const TEXT_PREVIEW_LIMIT = 256 * 1024;++/** Per-file ceiling of the content write endpoint, in whole MB — the server's `MAX_UPLOAD_BYTES`, mirrored so an oversize save or upload is refused before any bytes travel. */+export const WORKSPACE_UPLOAD_LIMIT_MB = 14;++/**+ * Whether a preview can switch to the editor: a text-like kind whose full content is (or can+ * be) on hand. A truncated preview is exactly the case that must stay read-only — saving it+ * back would write the truncated text over the whole file.+ */+export function canEditPreview(preview: { kind: string; truncated?: boolean }): boolean {+ return (+ (preview.kind === "text" || preview.kind === "md" || preview.kind === "html") &&+ preview.truncated !== true+ );+}++/** The in-place editor: the file, the text it opened with, and what has been typed since. */+export interface EditorState {+ path: string;+ baseline: string;+ draft: string;+ /**+ * The version marker the baseline was read with, sent back as the save's write+ * precondition so the write cannot land on a file the Agent has since rewritten.+ */+ version: string;+ /** The file was found to carry a different version while this editor was open. */+ changedOnDisk?: boolean;+}++export function isDirty(editor: EditorState | null): boolean {+ return editor !== null && editor.draft !== editor.baseline;+}++/**+ * Whether landing on `nextPath` (null: on no file) would abandon typed changes and so must+ * ask first. Re-opening the file being edited keeps the editor and asks nothing.+ */+export function needsDiscardConfirm(editor: EditorState | null, nextPath: string | null): boolean {+ return isDirty(editor) && nextPath !== editor!.path;+}++// --------------------------------------------------------------------------- preference++/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */+export interface TreePreferenceStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/** Global preferences, not per Session: whether the tree pane is shown, how wide it is, and whether the editor soft-wraps. */+export const TREE_VISIBLE_KEY = "penguin.files.treeVisible";+export const TREE_WIDTH_KEY = "penguin.files.treeWidth";+export const EDITOR_WRAP_KEY = "penguin.files.editorWrap";++/** Tolerant parse: only an explicit "off" spelling hides the tree; nothing stored or anything unrecognized shows it (the default). */+export function parseTreeVisible(raw: string | null): boolean {+ if (raw === null) return true;+ const value = raw.trim().toLowerCase();+ return !(value === "0" || value === "false" || value === "hidden" || value === "no");+}++export function readTreeVisible(storage?: TreePreferenceStorage): boolean {+ try {+ // localStorage is resolved inside the try: merely touching it throws when site data is+ // blocked, and this runs from a useState initializer.+ return parseTreeVisible((storage ?? localStorage).getItem(TREE_VISIBLE_KEY));+ } catch {+ return true;+ }+}++export function writeTreeVisible(visible: boolean, storage?: TreePreferenceStorage): void {+ try {+ (storage ?? localStorage).setItem(TREE_VISIBLE_KEY, visible ? "1" : "0");+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}++/**+ * Tolerant parse of the stored tree width: null for nothing stored and for anything that is+ * not a positive number, which is what makes the caller fall back to the width the pane had+ * before it was ever dragged.+ */+export function parseTreeWidth(raw: string | null): number | null {+ if (raw === null) return null;+ const value = Number.parseInt(raw.trim(), 10);+ return Number.isFinite(value) && value > 0 ? value : null;+}++export function readTreeWidth(storage?: TreePreferenceStorage): number | null {+ try {+ return parseTreeWidth((storage ?? localStorage).getItem(TREE_WIDTH_KEY));+ } catch {+ return null;+ }+}++export function writeTreeWidth(width: number, storage?: TreePreferenceStorage): void {+ try {+ (storage ?? localStorage).setItem(TREE_WIDTH_KEY, String(Math.round(width)));+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}++/** Tolerant parse of the editor's soft-wrap preference: OFF unless an explicit on spelling is stored — long lines scrolling sideways is the default a code editor has. */+export function parseEditorWrap(raw: string | null): boolean {+ if (raw === null) return false;+ const value = raw.trim().toLowerCase();+ return value === "1" || value === "true" || value === "on" || value === "yes";+}++export function readEditorWrap(storage?: TreePreferenceStorage): boolean {+ try {+ return parseEditorWrap((storage ?? localStorage).getItem(EDITOR_WRAP_KEY));+ } catch {+ return false;+ }+}++export function writeEditorWrap(wrap: boolean, storage?: TreePreferenceStorage): void {+ try {+ (storage ?? localStorage).setItem(EDITOR_WRAP_KEY, wrap ? "1" : "0");+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex f6ccd65e..394604ba 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -260,6 +260,43 @@animation: msg-in 180ms ease-out both;}+/* Files panel: a directory's rows grow out of, and shrink back into, its row. Grid tracks+ rather than height so the closed state needs no measurement; the inner box clips. Under+ reduced motion the keyframes are off and each class rests at its own end state — open+ at 1fr, closing at 0fr — and the view drops a closed group on a timer. Matches the+ chevron's 200ms rotation. */+.tree-group {+ display: grid;+ grid-template-rows: 1fr;+}+.tree-group > div {+ min-height: 0;+ overflow: hidden;+}+.tree-group-open {+ animation: tree-group-open 200ms ease-out;+}+.tree-group-close {+ grid-template-rows: 0fr;+ animation: tree-group-close 200ms ease-in;+}+@keyframes tree-group-open {+ from {+ grid-template-rows: 0fr;+ }+ to {+ grid-template-rows: 1fr;+ }+}+@keyframes tree-group-close {+ from {+ grid-template-rows: 1fr;+ }+ to {+ grid-template-rows: 0fr;+ }+}+/* Outline jump feedback: a soft brand wash fading out over the landed-on message. Applied byconversation-outline.tsx to the [data-outline-anchor] wrapper via classList — deliberatelyoutside React's managed props, so stream re-renders don't strip it mid-flash. */diff --git a/packages/web/test/close-guard.test.ts b/packages/web/test/close-guard.test.tsnew file mode 100644index 00000000..223711ab--- /dev/null+++ b/packages/web/test/close-guard.test.ts@@ -0,0 +1,37 @@+/**+ * The dock's close guards (features/dock/close-guard.ts): a tab body holding unsaved work+ * registers a veto under its tab key, asked when that tab's × would unmount it. A close of+ * several tabs stops at the first veto — a user who keeps one panel open is not asked about+ * the next.+ */+import { describe, expect, it, vi } from "vitest";+import { confirmClose, setCloseGuard } from "../src/features/dock/close-guard";++describe("confirmClose", () => {+ it("closes unguarded tabs at once", async () => {+ await expect(confirmClose(["memory", "trace"])).resolves.toBe(true);+ await expect(confirmClose([])).resolves.toBe(true);+ });++ it("asks a registered guard and stops at the first veto", async () => {+ const veto = vi.fn(async () => false);+ const allow = vi.fn(async () => true);+ setCloseGuard("guard-a", veto);+ setCloseGuard("guard-b", allow);+ await expect(confirmClose(["guard-a", "guard-b"])).resolves.toBe(false);+ expect(veto).toHaveBeenCalledTimes(1);+ expect(allow).not.toHaveBeenCalled();+ await expect(confirmClose(["guard-b", "guard-a"])).resolves.toBe(false);+ expect(allow).toHaveBeenCalledTimes(1);+ setCloseGuard("guard-a", null);+ setCloseGuard("guard-b", null);+ });++ it("forgets a withdrawn guard", async () => {+ const veto = vi.fn(async () => false);+ setCloseGuard("guard-c", veto);+ setCloseGuard("guard-c", null);+ await expect(confirmClose(["guard-c"])).resolves.toBe(true);+ expect(veto).not.toHaveBeenCalled();+ });+});diff --git a/packages/web/test/dock-state.test.ts b/packages/web/test/dock-state.test.tsindex c2145c63..8a937398 100644--- a/packages/web/test/dock-state.test.ts+++ b/packages/web/test/dock-state.test.ts@@ -4,7 +4,8 @@* windows managing their own tabs: switching Sessions switches the whole arrangement, and* no conversation's tabs depend on another's. An open dock with no tabs is still visible* (it shows the picker); closing a tab removes it, and the last tab closing puts the dock- * away; a dock's own toggle hides it keeping its tabs.+ * away; a dock's own toggle hides it keeping its tabs — and, through closedDockView, the+ * mounted bodies behind them.** The module reads localStorage at import time, so the stub is installed first and the* module imported dynamically.@@ -353,4 +354,23 @@ describe("view models", () => {expect(views[0]?.activeKey).toBe("workspace");expect(views[1]?.activeKey).toBe("terminal:term-a");});++ it("a hidden dock keeps a view to stay mounted on, an empty one has nothing to keep", () => {+ dock.openPanel("workspace", "right");+ dock.openPanel("memory", "right");+ // Open: dockViews() owns it, so there is nothing to keep mounted separately.+ expect(dock.closedDockView("right")).toBeNull();+ dock.toggleDock("right");+ expect(dock.dockViews()).toEqual([]);+ expect(dock.closedDockView("right")).toEqual({+ position: "right",+ merged: false,+ tabs: dock.dockTabs("right"),+ activeKey: "memory",+ });+ // The last tab's × takes the dock away with it: no body left to keep.+ dock.closePanel("workspace");+ dock.closePanel("memory");+ expect(dock.closedDockView("right")).toBeNull();+ });});diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.tsindex fb237f64..c7ec5151 100644--- a/packages/web/test/install-scope.test.ts+++ b/packages/web/test/install-scope.test.ts@@ -79,6 +79,9 @@ function populated(): ReturnType<typeof memStorage> {"penguin.sidebarSortMode": "manual","penguin.sidebarNavGroupCollapsed": "collapsed","penguin.steerMode": "followup",+ "penguin.files.treeVisible": "0",+ "penguin.files.treeWidth": "220",+ "penguin.files.editorWrap": "1",});}@@ -100,6 +103,9 @@ const PREFERENCE_KEYS = ["penguin.sidebarSortMode","penguin.sidebarNavGroupCollapsed","penguin.steerMode",+ "penguin.files.treeVisible",+ "penguin.files.treeWidth",+ "penguin.files.editorWrap",];const WEB_SRC = fileURLToPath(new URL("../src", import.meta.url));diff --git a/packages/web/test/workspace-tree.test.ts b/packages/web/test/workspace-tree.test.tsnew file mode 100644index 00000000..c947ee9d--- /dev/null+++ b/packages/web/test/workspace-tree.test.ts@@ -0,0 +1,421 @@+/**+ * Files panel logic (lib/workspace-tree.ts): the tree's rows from lazily loaded listings,+ * the search box's filter over them, the keyboard step over those rows, where a drop lands,+ * the narrow-layout decision and the tree pane's width bounds, how much of a path the+ * toolbar can show, which files count as text (by name, or by their bytes when the name says+ * nothing), the preferences' tolerant parses, and when leaving the editor has to ask.+ */+import { describe, expect, it } from "vitest";+import type { WorkspaceFileEntry } from "@prismshadow/penguin-server/api";+import {+ PREVIEW_MIN_WIDTH,+ TREE_LAYOUT_MIN_WIDTH,+ TREE_MIN_WIDTH,+ ancestorDirs,+ canEditPreview,+ clampTreeWidth,+ defaultTreeWidth,+ dropTargetDir,+ expandTo,+ filterTreeRows,+ flattenTree,+ isDirty,+ isNarrowLayout,+ looksLikeText,+ maxTreeWidth,+ needsDiscardConfirm,+ parentDir,+ parseEditorWrap,+ parseTreeVisible,+ parseTreeWidth,+ previewKindFor,+ readEditorWrap,+ readTreeVisible,+ readTreeWidth,+ sortEntries,+ subtreeEnd,+ treeKeyStep,+ upsertEntry,+ utf8Complete,+ visibleCrumbSegments,+ withExpanded,+ writeEditorWrap,+ writeTreeVisible,+ writeTreeWidth,+} from "../src/lib/workspace-tree";+import type { Listings } from "../src/lib/workspace-tree";++const MTIME = "2026-09-02T00:00:00.000Z";+const dir = (name: string): WorkspaceFileEntry => ({+ name,+ kind: "dir",+ sizeBytes: 0,+ mtime: MTIME,+});+const file = (name: string, sizeBytes = 1): WorkspaceFileEntry => ({+ name,+ kind: "file",+ sizeBytes,+ mtime: MTIME,+});++/** root: a/ (b/ empty, y.md), x.txt — the shape every tree test walks. */+const LISTINGS: Listings = new Map([+ ["", [dir("a"), file("x.txt")]],+ ["a", [dir("b"), file("y.md")]],+ ["a/b", []],+]);++describe("paths", () => {+ it("names a path's parent and the directories above it, root first", () => {+ expect(parentDir("x.txt")).toBe("");+ expect(parentDir("a/b/c.txt")).toBe("a/b");+ expect(ancestorDirs("x.txt")).toEqual([""]);+ expect(ancestorDirs("a/b/c.txt")).toEqual(["", "a", "a/b"]);+ });++ it("expandTo opens the way down to a file without opening the file's own name as a directory", () => {+ expect([...expandTo(new Set(), "a/b/c.txt")].sort()).toEqual(["", "a", "a/b"]);+ });++ it("withExpanded opens a directory with its ancestors and closes only the directory itself", () => {+ const opened = withExpanded(new Set(), "a/b", true);+ expect(opened.has("a")).toBe(true);+ expect(opened.has("a/b")).toBe(true);+ // Closing "a" leaves "a/b" recorded, so reopening "a" shows the subtree as it was left.+ const closed = withExpanded(opened, "a", false);+ expect(closed.has("a")).toBe(false);+ expect(closed.has("a/b")).toBe(true);+ });+});++describe("listings", () => {+ it("sorts directories before files, each group by name", () => {+ expect(+ sortEntries([file("z.txt"), dir("m"), file("a.txt"), dir("b")]).map((e) => e.name),+ ).toEqual(["b", "m", "a.txt", "z.txt"]);+ });++ it("upsertEntry inserts in sorted position, replaces a same-named entry, and leaves the input alone", () => {+ const withFile = upsertEntry(LISTINGS, "", file("m.txt"));+ expect(withFile.get("")!.map((e) => e.name)).toEqual(["a", "m.txt", "x.txt"]);+ const withDir = upsertEntry(withFile, "", dir("z"));+ expect(withDir.get("")!.map((e) => e.name)).toEqual(["a", "z", "m.txt", "x.txt"]);+ const replaced = upsertEntry(withDir, "", file("x.txt", 99));+ expect(replaced.get("")!.filter((e) => e.name === "x.txt")).toEqual([file("x.txt", 99)]);+ expect(LISTINGS.get("")!.map((e) => e.name)).toEqual(["a", "x.txt"]);+ });++ it("upsertEntry into a directory with no listing yet starts one", () => {+ expect(upsertEntry(LISTINGS, "new", file("n.txt")).get("new")).toEqual([file("n.txt")]);+ });+});++describe("flattenTree", () => {+ it("walks open directories depth-first and skips closed ones", () => {+ const rows = flattenTree(LISTINGS, new Set(["a", "a/b"]));+ expect(rows.map((r) => [r.path, r.depth])).toEqual([+ ["a", 0],+ ["a/b", 1],+ ["a/y.md", 1],+ ["x.txt", 0],+ ]);+ expect(flattenTree(LISTINGS, new Set()).map((r) => r.path)).toEqual(["a", "x.txt"]);+ });++ it("numbers each row within its own directory, so a flat tree can state its set", () => {+ const rows = flattenTree(LISTINGS, new Set(["a"]));+ expect(rows.map((r) => [r.path, r.posInSet, r.setSize])).toEqual([+ ["a", 1, 2],+ ["a/b", 1, 2],+ ["a/y.md", 2, 2],+ ["x.txt", 2, 2],+ ]);+ });++ it("marks an open directory that is still loading, and an open one that is empty", () => {+ const loading = flattenTree(new Map([["", [dir("a")]]]), new Set(["a"]));+ expect(loading).toHaveLength(1);+ expect(loading[0]).toMatchObject({ path: "a", expanded: true, loaded: false, empty: false });+ const rows = flattenTree(LISTINGS, new Set(["a", "a/b"]));+ expect(rows.find((r) => r.path === "a/b")).toMatchObject({ loaded: true, empty: true });+ expect(rows.find((r) => r.path === "a")).toMatchObject({ loaded: true, empty: false });+ });+});++describe("subtreeEnd", () => {+ it("ends a row's subtree at the next row no deeper than it", () => {+ // root: a/ (b/ empty, y.md), x.txt — "a" owns rows 1..2, the nested "a/b" owns nothing,+ // and "x.txt" after them is where both stop.+ const rows = flattenTree(LISTINGS, new Set(["a", "a/b"]));+ expect(rows.map((r) => r.path)).toEqual(["a", "a/b", "a/y.md", "x.txt"]);+ expect(subtreeEnd(rows, 0)).toBe(3);+ expect(subtreeEnd(rows, 1)).toBe(2);+ expect(subtreeEnd(rows, 3)).toBe(4);+ });+});++describe("treeKeyStep", () => {+ const rows = flattenTree(LISTINGS, new Set(["a", "a/b"]));++ it("moves down and up within the rows on screen, clamped at the ends", () => {+ expect(treeKeyStep(rows, null, "ArrowDown")).toEqual({ focus: "a" });+ expect(treeKeyStep(rows, "a", "ArrowDown")).toEqual({ focus: "a/b" });+ expect(treeKeyStep(rows, "x.txt", "ArrowDown")).toEqual({ focus: "x.txt" });+ expect(treeKeyStep(rows, "a/b", "ArrowUp")).toEqual({ focus: "a" });+ expect(treeKeyStep(rows, "a", "ArrowUp")).toEqual({ focus: "a" });+ expect(treeKeyStep(rows, "a/b", "Home")).toEqual({ focus: "a" });+ expect(treeKeyStep(rows, "a", "End")).toEqual({ focus: "x.txt" });+ });++ it("ArrowRight opens a closed directory, steps into an open one, and does nothing on a file or an empty directory", () => {+ const closed = flattenTree(LISTINGS, new Set());+ expect(treeKeyStep(closed, "a", "ArrowRight")).toEqual({ expand: "a" });+ expect(treeKeyStep(rows, "a", "ArrowRight")).toEqual({ focus: "a/b" });+ expect(treeKeyStep(rows, "a/b", "ArrowRight")).toBeNull();+ expect(treeKeyStep(rows, "a/y.md", "ArrowRight")).toBeNull();+ expect(treeKeyStep(rows, null, "ArrowRight")).toEqual({ focus: "a" });+ });++ it("ArrowLeft closes an open directory, otherwise steps out to the parent row", () => {+ expect(treeKeyStep(rows, "a/b", "ArrowLeft")).toEqual({ collapse: "a/b" });+ expect(treeKeyStep(rows, "a/y.md", "ArrowLeft")).toEqual({ focus: "a" });+ // A root-level file has no parent row to step out to.+ expect(treeKeyStep(rows, "x.txt", "ArrowLeft")).toBeNull();+ expect(treeKeyStep(rows, null, "ArrowLeft")).toBeNull();+ });++ it("ignores keys that are not tree keys, and does nothing with no rows", () => {+ expect(treeKeyStep(rows, "a", "Enter")).toBeNull();+ expect(treeKeyStep([], null, "ArrowDown")).toBeNull();+ });+});++describe("dropTargetDir", () => {+ it("lands on a folder row, in a file row's directory, or in the current directory", () => {+ expect(dropTargetDir({ kind: "dir", path: "docs/api" }, "src")).toBe("docs/api");+ expect(dropTargetDir({ kind: "file", path: "docs/api/README.md" }, "src")).toBe("docs/api");+ expect(dropTargetDir({ kind: "file", path: "top.txt" }, "src")).toBe("");+ expect(dropTargetDir(null, "src")).toBe("src");+ });+});++describe("layout", () => {+ it("falls back to one column below the threshold and keeps two panes while unmeasured", () => {+ expect(isNarrowLayout(0)).toBe(false);+ expect(isNarrowLayout(TREE_LAYOUT_MIN_WIDTH - 1)).toBe(true);+ expect(isNarrowLayout(TREE_LAYOUT_MIN_WIDTH)).toBe(false);+ });++ it("gives an undragged tree about a third of the panel within readable bounds", () => {+ expect(defaultTreeWidth(480)).toBe(173);+ expect(defaultTreeWidth(320)).toBe(168);+ expect(defaultTreeWidth(1200)).toBe(256);+ });++ it("clamps a dragged width to the tree's minimum and the preview's room", () => {+ expect(clampTreeWidth(300, 1000)).toBe(300);+ expect(clampTreeWidth(40, 1000)).toBe(TREE_MIN_WIDTH);+ expect(clampTreeWidth(900, 1000)).toBe(1000 - PREVIEW_MIN_WIDTH);+ // A panel with no room for both still has bounds, just no range between them.+ expect(maxTreeWidth(300)).toBe(TREE_MIN_WIDTH);+ expect(clampTreeWidth(300, 300)).toBe(TREE_MIN_WIDTH);+ // Unmeasured (0, before the first ResizeObserver callback): no ceiling to apply yet.+ expect(clampTreeWidth(400, 0)).toBe(400);+ expect(clampTreeWidth(Number.NaN, 1000)).toBe(TREE_MIN_WIDTH);+ });+});++describe("filterTreeRows", () => {+ /** Every listed directory walked open, which is what the panel filters over. */+ const all = flattenTree(LISTINGS, new Set(LISTINGS.keys()));++ it("keeps a match with the ancestors it hangs under, and nothing else", () => {+ expect(filterTreeRows(all, "y").map((r) => r.path)).toEqual(["a", "a/y.md"]);+ });++ it("shows a matching directory with its loaded children", () => {+ expect(filterTreeRows(all, "a").map((r) => r.path)).toEqual(["a", "a/b", "a/y.md"]);+ });++ it("matches the name case-insensitively, keeps everything for an empty query, and drops everything for a miss", () => {+ expect(filterTreeRows(all, "X.TXT").map((r) => r.path)).toEqual(["x.txt"]);+ expect(filterTreeRows(all, " ").map((r) => r.path)).toEqual(all.map((r) => r.path));+ expect(filterTreeRows(all, "nothing-like-this")).toEqual([]);+ });+});++describe("visibleCrumbSegments", () => {+ /** A fixed advance per character, so the fit is arithmetic rather than a font. */+ const measure = (text: string): number => text.length * 10;++ it("shows the whole path when it fits", () => {+ expect(visibleCrumbSegments(["root", "aa", "bb"], 1000, measure)).toEqual({+ visible: ["root", "aa", "bb"],+ collapsed: false,+ });+ expect(visibleCrumbSegments([], 1000, measure)).toEqual({ visible: [], collapsed: false });+ });++ it("drops leading segments until the rest fit, pricing in the ellipsis they become", () => {+ // "cc" 20 + "bb" 20 + the ellipsis still ahead of them 10 = 50, within 60; "aa" would+ // make it 70.+ expect(visibleCrumbSegments(["root", "aa", "bb", "cc"], 60, measure)).toEqual({+ visible: ["bb", "cc"],+ collapsed: true,+ });+ // At 100 the first segment fits too, and with nothing left ahead of it there is no+ // ellipsis to pay for.+ expect(visibleCrumbSegments(["root", "aa", "bb", "cc"], 100, measure)).toEqual({+ visible: ["root", "aa", "bb", "cc"],+ collapsed: false,+ });+ });++ it("always keeps the current directory, however little room there is", () => {+ expect(visibleCrumbSegments(["root", "aa", "bb"], 0, measure)).toEqual({+ visible: ["bb"],+ collapsed: true,+ });+ });+});++describe("file kinds", () => {+ it("decides the preview kind from the name, leaving an unknown name to be sniffed", () => {+ expect(previewKindFor("README.md")).toBe("md");+ expect(previewKindFor("index.HTML")).toBe("html");+ expect(previewKindFor(".gitignore")).toBe("text");+ expect(previewKindFor("photo.PNG")).toBe("image");+ expect(previewKindFor("paper.pdf")).toBe("pdf");+ expect(previewKindFor("Makefile")).toBe("unknown");+ expect(previewKindFor("archive.tar.gz")).toBe("unknown");+ });++ it("takes UTF-8 text for text, including a chunk cut inside a multi-byte character", () => {+ const encode = (s: string) => new TextEncoder().encode(s);+ expect(looksLikeText(encode("all: build\n\tgo build ./...\n"))).toBe(true);+ expect(looksLikeText(encode("[32mok[0m 世界\n"))).toBe(true);+ // "世界" is six bytes; four of them end mid-character, which is a boundary, not binary.+ expect(looksLikeText(encode("世界").subarray(0, 4))).toBe(true);+ expect(utf8Complete(encode("世界").subarray(0, 4))).toEqual(encode("世"));+ expect(looksLikeText(new Uint8Array())).toBe(true);+ });++ it("rejects a NUL byte, a control-heavy sample, and bytes that are not UTF-8", () => {+ expect(+ looksLikeText(Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0])),+ ).toBe(false);+ expect(looksLikeText(Uint8Array.from([1, 2, 3, 4, 5, 0x41]))).toBe(false);+ // "café" in Latin-1: the lone 0xE9 followed by ASCII is not a UTF-8 sequence.+ expect(looksLikeText(Uint8Array.from([0x63, 0x61, 0x66, 0xe9, 0x20, 0x61]))).toBe(false);+ });+});++describe("editing", () => {+ it("offers the editor for whole text-like previews only", () => {+ expect(canEditPreview({ kind: "text" })).toBe(true);+ expect(canEditPreview({ kind: "md", truncated: false })).toBe(true);+ expect(canEditPreview({ kind: "html" })).toBe(true);+ // A truncated read must stay read-only: saving it would write the cut text over the file.+ expect(canEditPreview({ kind: "text", truncated: true })).toBe(false);+ expect(canEditPreview({ kind: "image" })).toBe(false);+ expect(canEditPreview({ kind: "unsupported" })).toBe(false);+ });++ it("asks before leaving typed changes, not for a clean editor or the file being edited", () => {+ const version = 'W/"1-1000"';+ const clean = { path: "a.txt", baseline: "x", draft: "x", version };+ const dirty = { path: "a.txt", baseline: "x", draft: "xy", version };+ expect(isDirty(null)).toBe(false);+ expect(isDirty(clean)).toBe(false);+ expect(isDirty(dirty)).toBe(true);+ expect(needsDiscardConfirm(null, "b.txt")).toBe(false);+ expect(needsDiscardConfirm(clean, "b.txt")).toBe(false);+ expect(needsDiscardConfirm(dirty, "b.txt")).toBe(true);+ expect(needsDiscardConfirm(dirty, null)).toBe(true);+ expect(needsDiscardConfirm(dirty, "a.txt")).toBe(false);+ });+});++/** In-memory stand-in for localStorage, and one that throws the way blocked site data does. */+function memPreferences(): {+ getItem: (k: string) => string | null;+ setItem: (k: string, v: string) => void;+} {+ const store = new Map<string, string>();+ return {+ getItem: (key: string) => store.get(key) ?? null,+ setItem: (key: string, value: string) => void store.set(key, value),+ };+}++const brokenPreferences = {+ getItem: (): string | null => {+ throw new Error("blocked");+ },+ setItem: (): void => {+ throw new Error("blocked");+ },+};++describe("tree width preference", () => {+ it("takes a positive integer and treats everything else as unset", () => {+ expect(parseTreeWidth(null)).toBeNull();+ expect(parseTreeWidth(" 220 ")).toBe(220);+ expect(parseTreeWidth("240px")).toBe(240);+ expect(parseTreeWidth("garbage")).toBeNull();+ expect(parseTreeWidth("0")).toBeNull();+ expect(parseTreeWidth("-40")).toBeNull();+ });++ it("round-trips through storage and reads as unset when storage throws", () => {+ const storage = memPreferences();+ expect(readTreeWidth(storage)).toBeNull();+ writeTreeWidth(233.4, storage);+ expect(readTreeWidth(storage)).toBe(233);+ expect(readTreeWidth(brokenPreferences)).toBeNull();+ expect(() => writeTreeWidth(200, brokenPreferences)).not.toThrow();+ });+});++describe("editor wrap preference", () => {+ it("wraps only on an explicit on value", () => {+ expect(parseEditorWrap(null)).toBe(false);+ expect(parseEditorWrap("0")).toBe(false);+ expect(parseEditorWrap("garbage")).toBe(false);+ expect(parseEditorWrap("1")).toBe(true);+ expect(parseEditorWrap(" TRUE ")).toBe(true);+ });++ it("round-trips through storage and reads as off when storage throws", () => {+ const storage = memPreferences();+ expect(readEditorWrap(storage)).toBe(false);+ writeEditorWrap(true, storage);+ expect(readEditorWrap(storage)).toBe(true);+ writeEditorWrap(false, storage);+ expect(readEditorWrap(storage)).toBe(false);+ expect(readEditorWrap(brokenPreferences)).toBe(false);+ expect(() => writeEditorWrap(true, brokenPreferences)).not.toThrow();+ });+});++describe("tree visibility preference", () => {+ it("shows the tree unless an explicit off value is stored", () => {+ expect(parseTreeVisible(null)).toBe(true);+ expect(parseTreeVisible("1")).toBe(true);+ expect(parseTreeVisible("garbage")).toBe(true);+ expect(parseTreeVisible("0")).toBe(false);+ expect(parseTreeVisible(" FALSE ")).toBe(false);+ });++ it("round-trips through storage and defaults to shown when storage throws", () => {+ const storage = memPreferences();+ expect(readTreeVisible(storage)).toBe(true);+ writeTreeVisible(false, storage);+ expect(readTreeVisible(storage)).toBe(false);+ writeTreeVisible(true, storage);+ expect(readTreeVisible(storage)).toBe(true);+ expect(readTreeVisible(brokenPreferences)).toBe(true);+ expect(() => writeTreeVisible(false, brokenPreferences)).not.toThrow();+ });+});