A local-first multi-agent app development platform, built on PenguinHarness
feat(web): a Files panel with a context menu, wrapping, and an editor that looks like the file (#682)
Yaowei Zhenge270ff17fce9
diff --git a/changelog/unreleased/2026-09-10-file-browser-context-menu.md b/changelog/unreleased/2026-09-10-file-browser-context-menu.mdnew file mode 100644index 00000000..f8725038--- /dev/null+++ b/changelog/unreleased/2026-09-10-file-browser-context-menu.md@@ -0,0 +1,102 @@+# The Files panel gets a context menu, wrapping, and an editor that looks like the file++- **Date:** 2026-09-10+- **Type:** feature+- **Scope:** `web`+- **PR:** [#682](https://github.com/Prism-Shadow/penguin-harness/pull/682)++[中文版](2026-09-10-file-browser-context-menu.zh.md)++The dock panel that browsed the Workspace is now called 文件浏览 / Files, a secondary click on it+carries the per-entry actions it had nowhere to put, and its source view and its in-place editor+became the same presentation of the file: numbered lines, the same highlighting, the same+wrapping, and no box around either.++## Details++- Right-click, Shift+F10 and touch press-and-hold all open the menu, on a tree row and on the+ preview body alike. One handler serves the whole tree, resolving the row a gesture landed on+ from the row itself; a gesture that lands between rows keeps the browser's own menu, as does+ one inside the in-place editor, where the native menu is how text is pasted. A right-click+ inside the HTML or PDF preview goes to the iframe and never reaches the panel.+- The menu copies an entry's Workspace-relative path, adds a reference to it to the conversation,+ uploads into a folder and downloads a file.+- "Add to conversation" stages the entry in the composer as a **chip**, in the same row `/agent`,+ `/model` and the selected skills already stage their picks in. A directory's reference keeps its+ trailing slash. Nothing is sent and nothing is parsed — the `@` is for the reader.+- A preview selection is staged the same way, its chip naming the file and the lines it covers.+ Nothing the panel contributes is written into the draft: a file, a directory and a quoted range+ are all whole things, and splicing one into a half-written sentence buries the sentence under+ what it points at. Chips are removable, and on send the message carries what they stand for in+ front of the typed text — for a selection, a fenced block headed by `@path:3-7`, verbatim,+ with the fence opened long enough to survive a selection containing fences of its own. The line+ range is given only where the source view can resolve it.+ The text stays selected afterwards: handing a quote to the composer focuses the composer, and+ focusing a text field drops whatever the document had highlighted, so the range is put back.+- The source view numbers its lines and lost its border, its language label and its header bar —+ it presents the text the way the editor does. The toggle above it now reads **Preview / Source**:+ it names what you are looking at rather than how it was produced.+- A selection inside a highlighted code block survives a re-render. The block handed React a fresh+ `{ __html }` object on every render, and React compares that prop by object identity rather than+ by the markup inside it — so every render rebuilt every node in the block, collapsing any+ selection anchored to them and re-parsing markup that had not changed. Right-clicking selected+ source text in this panel is where it showed; the message stream's code blocks had it too.+- Copy and Edit float over the top-right of the file itself. Both act on the body under them,+ while the title row names the file and carries what leaves it — the view toggle, wrap, the+ external link and download. They are always drawn rather than revealed on hover: a hover-only+ control is no control at all on a touch screen, and Edit has no other way in from here.+- The editor numbers its lines and highlights them too: it is now a transparent-text textarea+ over the same code surface the source view shows, stacked in one scroll container so the two+ layers cannot drift apart. It re-highlights whenever the text settles, at any size it can open.+- Highlighting runs on a **worker**, so the size of a file no longer costs the page its+ responsiveness. Tokenizing is linear in the input and runs to completion once it starts — about+ four milliseconds per kilobyte of TypeScript — which is why the source view gave up above 64KB+ and the editor above 32KB. Off the main thread there is nothing to give up on: the text appears+ at once, unhighlighted, and the colours replace it when they land. Over a 400KB file the page+ held a full 60 frames a second for the whole pass. Both ceilings are gone, and a text preview+ now reads up to 1MB rather than 256KB. Where a worker cannot be had at all, the work falls back+ to this thread, which is what it did before.+- Markdown **rendering** keeps its 64KB ceiling, because remark and the React tree it produces are+ main-thread work that a highlighting worker does nothing about. A larger file opens in the source+ view, and the reader can still switch.+- The panel has one header row, not two. It names whatever is open — the directories and the+ file's own name in one strip, fitted tail first, so the filename is the last thing to go and the+ leading directories collapse into a single "…" ahead of it. The view toggle and download stay+ there because they belong to the file; wrap, copy, edit and open-in-a-new-tab float over the body+ because they act on the text; refresh and upload sit in the tree pane's header because they are+ the panel's own.+- The search box searches the **whole Workspace**, on the server, instead of filtering the rows the+ lazy tree happened to have loaded — a match used to be reachable only if its ancestors were+ already open. Results are a flat list naming each hit's full path, shallowest first, and the+ walk stops at a cap and says so rather than running a very large Workspace dry.+- A file can be renamed, moved or deleted from either context menu. Rename and move are one+ action, because both are the same write of a new path. Both carry the same precondition the+ editor's save does: the file's current version is read when the dialog opens, and the action is+ refused if the Agent rewrites the file while the question is on screen. A directory has neither,+ so neither is offered for one.+- The path row puts the file's own name first. The directories give way before it does, and when+ the name alone outruns the row it is the stem that ellipsizes, so the extension survives — the+ view toggle beside it can no longer squeeze the name into an ellipsis. Line ranges read as+ `app.ts:10-12`, the form an editor and a stack trace already use, in the chip and in the quoted+ block alike. On a chip it is the name that ellipsizes and never the range — four characters, and+ the half a shortened name cannot tell you — with the whole path and range together in the tooltip.+- Every action in the panel — wrap, edit, copy, open in a new tab, download, refresh and upload,+ and the editor's own cancel and save — is an icon button rather than a word. That keeps the header+ one height in both states: a text button stands 29px against an icon button's 27px, so opening a+ draft used to push the row down by two pixels and closing it pulled the row back up. Each carries its name in its accessible name and shows it+ in a tooltip under the button, which is where a horizontal row of them needs it: a panel to the+ side would cover the buttons next to the one being asked about. While an upload runs the glyph+ becomes a spinner and the count moves into the tooltip, which is the only place left to say it;+ a preview that cannot be served from a separate origin folds that caveat into the link's name+ rather than hanging a ⚠ beside it.+- Soft wrap became a toggle in the source view as well, and the source view and the editor share+ one remembered answer: they are the same file seen two ways, and pressing Edit must not reflow+ the file under the line you were aiming at. Message code blocks still scroll sideways rather+ than wrap, which is a transcript's answer and not a file viewer's.++## Compatibility++Soft wrap now defaults to ON, in the editor as well as in the new source-view toggle. The stored+preference (`penguin.files.editorWrap`) is unchanged and still read: anyone who has ever used the+editor's Wrap toggle keeps the answer they gave, and only a browser with no stored value picks up+the new default. The key keeps its name because renaming it would silently discard those answers.diff --git a/changelog/unreleased/2026-09-10-file-browser-context-menu.zh.md b/changelog/unreleased/2026-09-10-file-browser-context-menu.zh.mdnew file mode 100644index 00000000..ad730e9b--- /dev/null+++ b/changelog/unreleased/2026-09-10-file-browser-context-menu.zh.md@@ -0,0 +1,71 @@+# 文件浏览面板新增右键菜单、自动换行,编辑器与阅读视图外观一致++- **Date:** 2026-09-10+- **Type:** feature+- **Scope:** `web`+- **PR:** [#682](https://github.com/Prism-Shadow/penguin-harness/pull/682)++[English](2026-09-10-file-browser-context-menu.md)++原先浏览 Workspace 的停靠面板改名为「文件浏览」,右键可用此前无处安放的单条目操作;源码视图与就地编辑器+也统一为同一种呈现:同样的行号、同样的高亮、同样的换行方式,两者都不再有外框。++## 细节++- 右键、Shift+F10 与触摸长按都能唤出菜单,文件树行与预览区一致。整棵树共用一个处理器,由手势落点所在+ 的行自行解析目标;落在行与行之间时保留浏览器自身的菜单,就地编辑器内同样保留——粘贴文本靠的正是它。+ HTML 与 PDF 预览是 iframe,其中的右键只会到达 iframe,不会传到面板。+- 菜单可复制条目在 Workspace 内的相对路径、把该条目的引用添加到对话,文件夹另有上传、文件另有下载。+- 「添加到对话」把该条目以**小块(chip)**暂存在输入框里,与 `/agent`、`/model` 及所选技能同处一行。+ 文件夹的引用保留末尾斜杠。不会发送任何内容,也没有任何解析——`@` 是写给人读的。+- 预览中的选中内容同样如此暂存,小块上标出文件名与所覆盖的行号。面板贡献的任何东西都不再写进草稿:+ 文件、文件夹、被引用的一段内容都是完整的一块,塞进写了一半的句子只会把句子埋掉。小块可以移除;+ 发送时,它们所代表的内容会置于所输入文字之前随消息发出——选中内容仍是以 `@path:3-7` 开头的+ 代码块,逐字保留,围栏长度按需加长以容纳本身含有围栏的内容。行号范围仅在源码视图能够确定时给出。选中范围随后仍然保留:+ 把引用交给输入框会让输入框获得焦点,而文本框获得焦点会清空文档中的选区,因此该范围会被重新选上。+- 源码视图显示行号,并去掉了外框、语言标签与顶栏——与编辑器一样直接展示文本。其上方的切换现在写作+ **预览 / 源码**:说的是你正在看什么,而不是它是怎么生成的。+- 高亮代码块中的选中内容不会再因为一次重新渲染而消失。此前代码块每次渲染都向 React 传入一个新的+ `{ __html }` 对象,而 React 对这个属性按对象身份比较、并不看其中的标记,于是每次渲染都重建块内+ 的全部节点:锚定其上的选区随之塌陷,未发生变化的标记也被重新解析一遍。在本面板中右键点击选中的+ 源码时最容易看到;对话流里的代码块同样如此。+- 复制与编辑浮在文件内容区的右上角。两者作用的都是它们下方的正文,而文件标题那一行只负责标出文件本身+ 以及把文件带走的操作——视图切换、自动换行、新页面打开与下载。它们始终可见,而非悬停才出现:在触摸屏+ 上,只在悬停时出现的控件等于没有,而编辑在这里没有第二个入口。+- 编辑器同样有行号与语法高亮:它现在是一个文字透明的 textarea,叠在源码视图所用的同一层代码之上,两层+ 共用一个滚动容器,因此不可能错位。每次输入停顿后它都会重新着色,能打开多大的文件就能着色到多大。+- 语法高亮改在 **Worker** 上运行,文件的体量不再以页面的响应换取。分词的耗时与输入量成正比,且一旦开始+ 就必须跑完——TypeScript 大致每 KB 四毫秒——这正是此前源码视图超过 64KB、编辑器超过 32KB 就放弃着色+ 的原因。放到主线程之外就无所谓放弃了:文字立即以无高亮的样子出现,颜色随后替换上去。在一个 400KB 的+ 文件上,整个着色过程中页面始终保持每秒 60 帧。两处上限都已取消,文本预览的读取上限也从 256KB 提高到+ 1MB。若运行环境根本没有 Worker,这项工作会退回本线程,也就是此前的做法。+- Markdown **渲染**仍保留 64KB 上限,因为 remark 解析及其产生的 React 树都是主线程的开销,高亮 Worker+ 对此无能为力。超过该体量的文件默认以源码视图打开,读者仍可自行切换。+- 面板只剩一行标题栏。它标出当前打开的对象——目录与文件名合为一条,按尾部优先排布:文件名最后才被舍弃,+ 前面的目录折叠成一个「…」。视图切换与下载留在这一行,因为它们属于文件本身;自动换行、复制、编辑与+ 新页面打开浮在正文之上,因为它们作用于文本;刷新与上传移到目录树那一栏的顶部,因为它们属于整个面板。+- 搜索框改为在服务端搜索**整个 Workspace**,而不再只是过滤懒加载目录树恰好已经载入的那些行——此前一条+ 匹配项必须其各级上级目录都已展开才够得着。结果是一串平铺的条目,各自标出完整路径,层级浅的在前;+ 遍历到达上限时会明说,而不是把一个很大的 Workspace 跑干。+- 两处右键菜单都能重命名、移动与删除文件。重命名与移动是同一个动作,因为两者都只是把文件写到一个新+ 路径。它们与编辑器的保存共用同一个前置条件:对话框打开时读取该文件的当前版本,若 Agent 在你决定+ 期间改写了它,操作即被拒绝。目录两者都没有,因此不提供这两项操作。+- 路径那一行优先显示文件自身的名字。目录先行让位;当名字本身也放不下时,缩略的是主干部分,扩展名得以+ 保留——旁边的视图切换不会再把文件名挤成一个省略号。行号统一写作 `app.ts:10-12`,与编辑器、调用栈+ 一贯的写法相同,小块与引用代码块都用这一种。小块上让位的始终是文件名而不是行号——行号只有四个字符,+ 且正是被缩略的名字说不出的那一半——完整路径连同行号一并放在 tooltip 里。+- 面板的全部操作——自动换行、编辑、复制、新页面打开、下载、刷新、上传,以及编辑器自身的取消与保存——+ 都改为图标按钮,不再显示文字。这也让标题行在两种状态下等高:文字按钮高 29px,图标按钮高 27px,+ 此前一进入编辑该行就被撑高两个像素,退出编辑又缩回去。+ 每个按钮的名称保留在无障碍名称中,并以 tooltip 显示在按钮下方:横排的一行图标若把提示放在侧边,就会+ 盖住紧挨着的其它按钮。上传进行中时图标变为转圈指示,件数移入 tooltip——此时已没有别处可以显示它;+ 预览无法使用独立源时,该提示并入链接自身的名称,而不再在旁边挂一个 ⚠。+- 源码视图也有了自动换行开关,并与编辑器共用同一个记忆值:两者是同一个文件的两种看法,按下编辑不应让+ 文件重新折行、把你正要改的那一行带走。对话流中的代码块仍然横向滚动而不换行——那是记录的答案,不是+ 文件阅读器的答案。++## 兼容性++自动换行的默认值改为开启,编辑器与新增的源码视图开关都是如此。存储的偏好项(`penguin.files.editorWrap`)+未改动且仍然读取:凡是用过编辑器换行开关的用户都保留自己的选择,只有从未存过值的浏览器才会采用新默认值。+该键保持原名,因为改名会悄无声息地丢掉这些选择。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 4510f9cd..5710a947 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -292,6 +292,9 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| GET | /files/preview-redirect?path= | "Open in a new tab" for html: mints a signed token and 302s to the separate preview origin || POST | /files/stat | Batch existence check: `{paths}` || PUT | /files/content?path= | Upload a file: `{dataBase64}`, capped at 14MB |+| POST | /files/move | Move or rename one Workspace file: `{from, to, ifVersion?}` → 204. **Files only** — a directory carries no single version marker, so the precondition that protects the operation cannot be expressed for one, and it is a 400. `to`'s parent directory is created when missing. 404 `path_not_found` when `from` is gone, 409 `file_changed` when `ifVersion` no longer matches it (a source that vanished under a marker counts as changed), 409 `target_exists` when something already sits at `to` — the destination was never read, so it is refused rather than overwritten — and 400 for a move onto the file's own path |+| DELETE | /files/content?path=&ifVersion= | Delete one Workspace file: 204. Files only (a directory is a 400); 404 `path_not_found`, and 409 `file_changed` when `ifVersion` no longer matches. The marker is optional on the wire — without it the delete is unconditional — and the Files panel always sends the one its read returned |+| GET | /files/search?q= | Search the whole Workspace by entry **name** (case-insensitive substring; the path is not matched) → `{hits: [{path, kind, sizeBytes, mtime}], truncated}`, each hit carrying what a directory listing's entry carries. Breadth-first from the root, so hits come shallowest-first and a capped result is the most relevant ones rather than whatever the first directory held; `truncated` says a cap stopped the walk — 200 hits, or 20000 directory entries visited. An empty `q`, or one over 100 characters, is a 400 || GET | /traces | List this Session's Trace files || GET | /traces/:index | Read Trace events (paginated) || GET | /traces/:index/analysis | Trace performance analysis |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 184d677c..0bf1836b 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -292,6 +292,9 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| GET | /files/preview-redirect?path= | html 的“新页面打开”:签发令牌并 302 跳转到独立预览源 || POST | /files/stat | 批量存在性检查:`{paths}` || PUT | /files/content?path= | 上传文件:`{dataBase64}`,上限 14MB |+| POST | /files/move | 移动或重命名单个 Workspace 文件:`{from, to, ifVersion?}` → 204。**仅限文件**——目录没有单一的版本标记,无法为其表达保护该操作的前置条件,因此返回 400。`to` 的父目录缺失时自动创建。`from` 不存在时 404 `path_not_found`;`ifVersion` 与文件不再匹配时 409 `file_changed`(带标记时源文件消失同样算作已变化);`to` 已被占用时 409 `target_exists`——目的地从未被读取过,因此只拒绝、不覆盖;移动到文件自身路径返回 400 |+| DELETE | /files/content?path=&ifVersion= | 删除单个 Workspace 文件:204。仅限文件(目录返回 400);文件不存在时 404 `path_not_found`,`ifVersion` 不再匹配时 409 `file_changed`。该标记在协议上可选——不带即为无条件删除——而 Files 面板总是回传其读取时拿到的那一枚 |+| GET | /files/search?q= | 按条目**名称**搜索整个 Workspace(大小写不敏感的子串匹配,不匹配路径)→ `{hits: [{path, kind, sizeBytes, mtime}], truncated}`,每条命中携带的字段与目录列表中的条目一致。自根目录广度优先遍历,因此命中按层级由浅至深排列,被截断时留下的是最相关的命中,而不是最先遍历到的那个目录里的内容;`truncated` 表示遍历触及上限——200 条命中,或访问 20000 个目录条目。`q` 为空或超过 100 字符返回 400 || GET | /traces | 本 Session 的 Trace 文件列表 || GET | /traces/:index | 读取 Trace 事件(分页) || GET | /traces/:index/analysis | Trace 性能分析结果 |diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex b7c30a9d..c175ab83 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -2669,6 +2669,50 @@ export interface FilesWriteRequest {ifVersion?: string;}+/** Move or rename one Workspace file (the Files panel's context menu). */+export interface FilesMoveRequest {+ /** Source path, relative to the Workspace root. */+ from: string;+ /** Destination path, relative to the Workspace root. Its parent directory is created when missing. */+ to: string;+ /**+ * Move precondition, read exactly like {@link FilesWriteRequest.ifVersion}: the marker the+ * caller got from this file's `ETag` on `GET files/content`, which the file must still+ * carry. It differs on only one point — the marker guards the **source**. The destination+ * has none, because the caller never read it, which is why an occupied destination is+ * refused with 409 `target_exists` rather than overwritten.+ *+ * A directory `from` is a 400 whatever this field says: a directory carries no single+ * version marker, so the precondition that protects this operation cannot be expressed for+ * one, and silently moving a tree without that protection is worse than refusing to move it.+ */+ ifVersion?: string;+}++/**+ * One Workspace search match. `kind`, `sizeBytes` and `mtime` are named and typed exactly as+ * {@link WorkspaceFileEntry} names them: a hit is drawn by the same row renderer as a tree+ * entry, and it can only render identically if it carries the same fields.+ */+export interface WorkspaceSearchHit {+ /** Workspace-relative, "/"-separated, with no leading "./" (a tree entry's `name` is only its last segment). */+ path: string;+ kind: "dir" | "file";+ sizeBytes: number;+ mtime: string;+}++export interface WorkspaceSearchResponse {+ /** Shallowest first, then directories before files, then by name — the order the breadth-first walk produced. */+ hits: WorkspaceSearchHit[];+ /**+ * A cap stopped the walk (200 hits, or 20000 directory entries visited), so this is a+ * partial list. Breadth-first is what makes that degrade well: the hits that survive+ * truncation are the shallowest ones, not the ones that happened to be enumerated first.+ */+ truncated: boolean;+}+/** 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 8bf6480b..a9f30198 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -60,6 +60,7 @@ import {positiveIntParam,readJson,requireEnum,+ requireString,requireValidId,} from "../validate.js";import type { AppDeps } from "../../app.js";@@ -1377,6 +1378,45 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {return c.body(null, 204);});+ /**+ * Move or rename one Workspace file (the Files panel's context menu). Files only — see+ * FilesMoveRequest for why a directory has no precondition that could protect it — and an+ * occupied destination is refused with 409 `target_exists` rather than overwritten.+ */+ app.post("/:sessionId/files/move", async (c) => {+ const row = resolveSession(c);+ const body = await readJson(c);+ await deps.workspaceFiles.move(+ row.workspace,+ requireString(body, "from"),+ requireString(body, "to"),+ optionalString(body, "ifVersion"),+ );+ return c.body(null, 204);+ });++ /**+ * Delete one Workspace file. `ifVersion` is the same write precondition the PUT carries,+ * here as a query parameter: absent, the delete is unconditional; present and stale, it is+ * 409 `file_changed` with the file left alone.+ */+ app.delete("/:sessionId/files/content", async (c) => {+ const row = resolveSession(c);+ const rel = c.req.query("path") ?? "";+ await deps.workspaceFiles.remove(row.workspace, rel, c.req.query("ifVersion"));+ return c.body(null, 204);+ });++ /**+ * Search the whole Workspace by entry name. Breadth-first from the root, so a capped result+ * is the shallowest matches rather than an arbitrary prefix of the walk; `truncated` says a+ * cap was reached.+ */+ app.get("/:sessionId/files/search", async (c) => {+ const row = resolveSession(c);+ return c.json(await deps.workspaceFiles.search(row.workspace, c.req.query("q") ?? ""));+ });+/*** What the Session's current model context is made of, and where compaction will fire. Read on* demand (the chat page's context ring opens its detail panel with it), not streamed: itdiff --git a/packages/server/src/services/workspace-files-service.ts b/packages/server/src/services/workspace-files-service.tsindex 2bbd1d72..5bdd4182 100644--- a/packages/server/src/services/workspace-files-service.ts+++ b/packages/server/src/services/workspace-files-service.ts@@ -1,13 +1,20 @@/**- * Workspace file browsing: list directory / read- * file (preview & download) / write file (upload). Security: a relative path, once- * resolved, must stay inside the Workspace — a logical prefix check plus a realpath- * check against the nearest existing ancestor (guards against `..` and symlink escapes).+ * Workspace file browsing: list directory / read file (preview & download) / write file+ * (upload) / move, delete and search. Security: a relative path, once resolved, must stay+ * inside the Workspace — a logical prefix check plus a realpath check against the nearest+ * existing ancestor (guards against `..` and symlink escapes).*/import fs from "node:fs/promises";+import type { FileHandle } from "node:fs/promises";import { constants as fsc } from "node:fs";+import type { Stats } from "node:fs";import path from "node:path";-import type { WorkspaceFileEntry, WorkspaceFilesResponse } from "../api/types.js";+import type {+ WorkspaceFileEntry,+ WorkspaceFilesResponse,+ WorkspaceSearchHit,+ WorkspaceSearchResponse,+} from "../api/types.js";import { HttpError } from "../http/errors.js";import { badRequest } from "../http/validate.js";@@ -16,6 +23,16 @@ const MAX_READ_BYTES = 50 * 1024 * 1024;/** Upload cap (stays within the 20MB request body limit even after base64 encoding). */export const MAX_UPLOAD_BYTES = 14 * 1024 * 1024;+/**+ * Search caps. Both bound the work, not the relevance: the walk stops at whichever comes+ * first and the response carries `truncated`, so a caller can tell "these are all the+ * matches" from "these are the first matches".+ */+export const SEARCH_MAX_HITS = 200;+export const SEARCH_MAX_ENTRIES = 20000;+/** Longest accepted query: past this it is not a name any entry could carry, so refuse rather than walk the Workspace for it. */+export const SEARCH_MAX_QUERY_LEN = 100;+const CONTENT_TYPES: Record<string, string> = {".html": "text/html; charset=utf-8",".htm": "text/html; charset=utf-8",@@ -82,6 +99,19 @@ function fileChanged(): HttpError {);}+/**+ * A move's destination is occupied. Unlike the source, the destination has no precondition —+ * the caller never read it, so there is no marker it could have carried — which makes an+ * overwrite here a silent destruction of a file nobody looked at. Refuse instead.+ */+function targetExists(): HttpError {+ return new HttpError(+ 409,+ "target_exists",+ "Something already exists at the destination; nothing was moved.",+ );+}+export interface WorkspaceFileReadOptions {/** Return at most this many bytes. Used for bounded text previews. */maxBytes?: number;@@ -202,6 +232,99 @@ export class WorkspaceFilesService {return { dir: canonicalParent, name };}+ /**+ * Source resolution for an operation that mutates the entry ITSELF (move, delete) rather+ * than its contents: the canonical parent is realpathed and checked — never created, since+ * an operation on a file that must already exist has no business making directories — and+ * the final segment is appended by name so the caller can open it with O_NOFOLLOW.+ *+ * Resolving the whole path the way {@link resolveRead} does would be wrong here: realpath+ * follows a final-segment symlink, so the version marker would describe the link's target+ * while the rename or unlink acted on the link. Returns null when the parent directory is+ * itself missing — the file is gone, and the caller decides whether that is a 404 or a 409.+ */+ private async resolveMutableEntry(+ workspace: string,+ rel: string,+ ): Promise<{ dir: string; name: string } | null> {+ const realBase = await this.realBase(workspace);+ const target = this.lexicalTarget(path.resolve(workspace), rel);+ const name = path.basename(target);+ if (name === "" || name === "." || name === "..") throw badRequest("path must be a file path.");+ let canonicalParent: string;+ try {+ canonicalParent = await fs.realpath(path.dirname(target));+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw err;+ }+ this.assertInside(canonicalParent, realBase);+ return { dir: canonicalParent, name };+ }++ /**+ * The file an operation named is not there. Without a precondition that is a plain 404;+ * with one it is the same conflict a stale marker raises — a caller that passed a marker+ * read the file and needs to hear that it moved on, which is the rule {@link write} already+ * follows when a conditional write finds the file deleted.+ */+ private vanished(conditional: boolean): HttpError {+ return conditional+ ? fileChanged()+ : new HttpError(404, "path_not_found", "File does not exist.");+ }++ /**+ * Windows has no O_NOFOLLOW (the `?? 0` at every open erases it), so the atomic ELOOP guard+ * never fires there — refuse a final-segment symlink via lstat instead. Best effort (a link+ * created between this check and the open wins the race), but it closes the practical+ * "Agent presets a symlink -> the operation is used as leverage to reach a file outside the+ * sandbox" escape; POSIX keeps the atomic open-time guarantee.+ */+ private async assertNotSymlink(file: string): Promise<void> {+ if (process.platform !== "win32") return;+ const st = await fs.lstat(file).catch(() => null);+ if (st?.isSymbolicLink()) throw badRequest("path must not be a symlink.");+ }++ /**+ * The two things a move and a delete both demand of their subject: that it is a regular+ * file, and that it still carries the caller's version marker. Both are read off an **open+ * handle** — a handle names an inode, so what was inspected is the file the caller is about+ * to move or remove — and the open uses O_NOFOLLOW, refusing a symlink at the final segment+ * so a preset link cannot be used as leverage to rename or unlink a file outside the+ * Workspace.+ *+ * The handle is closed before the operation runs. Holding it across the call would buy no+ * atomicity — neither rename nor unlink has an fd-addressed form, and Node exposes none —+ * so the check-then-act window is inherent here in a way it is not for {@link write}, which+ * truncates the handle it checked. What the window cannot produce is an escape: rename and+ * unlink never follow a final-segment symlink either, so a path swapped underneath acts on+ * the link rather than on whatever it points at.+ */+ private async assertFileAndVersion(file: string, ifVersion: string | undefined): Promise<void> {+ await this.assertNotSymlink(file);+ let handle: FileHandle;+ try {+ handle = await fs.open(file, fsc.O_RDONLY | (fsc.O_NOFOLLOW ?? 0));+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === "ELOOP") throw badRequest("path must not be a symlink.");+ // Opening a directory read-only succeeds on POSIX and fails with EISDIR on Windows;+ // both land on the same refusal (the POSIX one below, on the handle's stat).+ if (code === "EISDIR") throw badRequest("path is a directory.");+ if (code === "ENOENT") throw this.vanished(ifVersion !== undefined);+ throw err;+ }+ try {+ const stat = await handle.stat();+ if (stat.isDirectory()) throw badRequest("path is a directory.");+ if (ifVersion !== undefined && fileVersion(stat) !== ifVersion) throw fileChanged();+ } finally {+ await handle.close();+ }+ }+/*** Batch existence check (a message's file card lists only files that actually* exist): each item goes through the same containment resolution as reading@@ -363,15 +486,7 @@ export class WorkspaceFilesService {}const { dir, name } = await this.resolveWriteParent(workspace, rel);const file = path.join(dir, name);- // Windows has no O_NOFOLLOW (the `?? 0` below erases it), so the atomic ELOOP guard never- // fires there — refuse a final-segment symlink via lstat instead. Best effort (a link- // created between this check and the open wins the race), but it closes the practical- // "preset a symlink, overwrite an outside file by upload" escape; POSIX keeps the atomic- // open-time guarantee.- if (process.platform === "win32") {- const st = await fs.lstat(file).catch(() => null);- if (st?.isSymbolicLink()) throw badRequest("path must not be a symlink.");- }+ await this.assertNotSymlink(file);// 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 conditional = ifVersion !== undefined;const flags =@@ -401,4 +516,214 @@ export class WorkspaceFilesService {await handle.close();}}++ /**+ * Move or rename one Workspace file.+ *+ * **Files only** — a directory `from` is a 400. A directory has no single version marker, so+ * the precondition that protects this operation cannot be expressed for one, and moving a+ * whole tree with no precondition at all is worse than refusing to move it.+ *+ * The source is resolved as a mutable entry (canonical parent, O_NOFOLLOW on the final+ * segment, version marker read off the open handle); the destination is resolved as a write,+ * so its parent is created when missing under the same checks an upload runs. An occupied+ * destination is a 409 rather than an overwrite — see {@link targetExists} — and a move onto+ * the file's own path is a 400 rather than a success that did nothing.+ */+ async move(workspace: string, from: string, to: string, ifVersion?: string): Promise<void> {+ if (from === "" || from.endsWith("/")) throw badRequest("from must be a file path.");+ if (to === "" || to.endsWith("/")) throw badRequest("to must be a file path.");+ const conditional = ifVersion !== undefined;+ const source = await this.resolveMutableEntry(workspace, from);+ if (source === null) throw this.vanished(conditional);+ const file = path.join(source.dir, source.name);+ await this.assertFileAndVersion(file, ifVersion);++ const { dir, name } = await this.resolveWriteParent(workspace, to);+ const dest = path.join(dir, name);+ // Both parents are canonical, so this compares the two real paths rather than the two+ // spellings the caller happened to send.+ if (dest === file) throw badRequest("to must differ from from.");+ // The destination is never overwritten, and "never" has to hold against the Agent writing+ // that exact path while this runs — the whole point of the precondition on the source.+ // `link` is the primitive that says so in the kernel: it fails EEXIST rather than replacing,+ // and it keeps the inode, so the file that lands is the file that was checked. `rename`+ // would replace silently, and an lstat in front of it only narrows the window instead of+ // closing it.+ try {+ await fs.link(file, dest);+ await fs.unlink(file);+ return;+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === "EEXIST") throw targetExists();+ if (code === "EXDEV") {+ // The two canonical parents are on different filesystems (a bind-mounted subdirectory,+ // say), which neither link nor rename can cross. Copy, then drop the original.+ // COPYFILE_EXCL refuses an existing destination in the kernel, so this path keeps the+ // same guarantee.+ try {+ await fs.copyFile(file, dest, fsc.COPYFILE_EXCL);+ } catch (copyErr) {+ if ((copyErr as NodeJS.ErrnoException).code === "EEXIST") throw targetExists();+ throw copyErr;+ }+ await fs.unlink(file);+ return;+ }+ // Filesystems that have no hard links at all (FAT, some network and container mounts,+ // and Windows outside NTFS) report one of these. There is nothing atomic left to reach+ // for, so the check-then-act window comes back — narrowed to a single lstat, and only on+ // the mounts that cannot do better. lstat, not stat: a dangling symlink at the+ // destination is still something rename would replace.+ if (code !== "EPERM" && code !== "ENOSYS" && code !== "EMLINK" && code !== "EOPNOTSUPP") {+ throw err;+ }+ }+ const occupied = await fs.lstat(dest).then(+ () => true,+ () => false,+ );+ if (occupied) throw targetExists();+ await fs.rename(file, dest);+ }++ /**+ * Delete one Workspace file. Files only, for the same reason {@link move} is: a directory+ * carries no version marker, so nothing can protect a recursive delete from removing work+ * the Agent did after the panel last looked.+ *+ * `ifVersion` is optional in the wire shape — the service will delete unconditionally+ * without it — but the Files panel always sends the marker its read returned, so a file the+ * Agent rewrote under the user's cursor is a 409 rather than a lost file.+ */+ async remove(workspace: string, rel: string, ifVersion?: string): Promise<void> {+ if (rel === "" || rel.endsWith("/")) throw badRequest("path must be a file path.");+ const conditional = ifVersion !== undefined;+ const entry = await this.resolveMutableEntry(workspace, rel);+ if (entry === null) throw this.vanished(conditional);+ const file = path.join(entry.dir, entry.name);+ await this.assertFileAndVersion(file, ifVersion);+ try {+ await fs.unlink(file);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") throw this.vanished(conditional);+ throw err;+ }+ }++ /**+ * Search the whole Workspace: case-insensitive substring match on an entry's **name**, not+ * on its path, so typing a directory the file happens to sit under does not turn every file+ * under it into a hit.+ *+ * **Breadth-first from the Workspace root**, and that is load-bearing rather than an+ * implementation detail: shallow matches are found first, so hitting a cap degrades the+ * result into "the most relevant hits" instead of "whatever happened to be in the first+ * directory the walk descended into". The sort keeps the same order the walk produced.+ *+ * Entries whose canonical path leaves the Workspace are skipped exactly as {@link list}+ * skips them, and every directory is entered at most once by canonical path, so a symlink+ * pointing back up cannot spin the walk in a cycle.+ */+ async search(workspace: string, q: string): Promise<WorkspaceSearchResponse> {+ if (q.length > SEARCH_MAX_QUERY_LEN) {+ throw badRequest(`q must be at most ${SEARCH_MAX_QUERY_LEN} characters.`);+ }+ const needle = q.trim().toLowerCase();+ if (needle === "") throw badRequest("q must not be empty.");+ const realBase = await this.realBase(workspace);++ const hits: Array<WorkspaceSearchHit & { depth: number; name: string }> = [];+ let truncated = false;+ let visited = 0;+ const seenDirs = new Set<string>([realBase]);+ let level: Array<{ dir: string; rel: string; depth: number }> = [+ { dir: realBase, rel: "", depth: 0 },+ ];+ walk: while (level.length > 0) {+ const next: typeof level = [];+ for (const node of level) {+ let dirents;+ try {+ dirents = await fs.readdir(node.dir, { withFileTypes: true });+ } catch {+ continue; // Unreadable directory: skipped, the way `list` skips an entry it cannot stat.+ }+ for (const d of dirents) {+ if (visited >= SEARCH_MAX_ENTRIES) {+ truncated = true;+ break walk;+ }+ visited += 1;+ const rel = node.rel === "" ? d.name : `${node.rel}/${d.name}`;+ let canonical = path.join(node.dir, d.name);+ let isDir = d.isDirectory();+ // A hit reports the size and mtime of the entry itself, the way `list` does, so a+ // search result renders as the same row a tree entry does. Only a link and a match+ // are statted: `kind` comes from the dirent for everything else, which keeps the+ // per-entry cost of a 20000-entry walk at one readdir slot rather than one syscall.+ let stat: Stats | null = null;+ if (d.isSymbolicLink()) {+ // Only a link needs the realpath round trip: node.dir is canonical, so any other+ // child of it is canonical already and cannot name anything outside the Workspace.+ try {+ canonical = await fs.realpath(canonical);+ this.assertInside(canonical, realBase);+ stat = await fs.stat(canonical);+ isDir = stat.isDirectory();+ } catch {+ continue; // Out of bounds or broken: omitted, the same way `list` omits it.+ }+ }+ const kind = isDir ? "dir" : "file";+ if (d.name.toLowerCase().includes(needle)) {+ if (hits.length >= SEARCH_MAX_HITS) {+ truncated = true;+ break walk;+ }+ const found = stat ?? (await fs.stat(canonical).catch(() => null));+ // Gone between the readdir and the stat: no row can be drawn for it, so it is+ // omitted rather than reported with invented figures. A directory that is still+ // there is descended into below regardless.+ if (found) {+ hits.push({+ path: rel,+ kind,+ sizeBytes: found.size,+ mtime: found.mtime.toISOString(),+ depth: node.depth,+ name: d.name,+ });+ }+ }+ if (isDir && !seenDirs.has(canonical)) {+ seenDirs.add(canonical);+ next.push({ dir: canonical, rel, depth: node.depth + 1 });+ }+ }+ }+ level = next;+ }++ // Shallow-first, then directories, then by name — the order the breadth-first walk+ // produced, made total (the path breaks a tie between same-named entries in two+ // directories) so the same Workspace always answers in the same order.+ hits.sort(+ (a, b) =>+ a.depth - b.depth ||+ (a.kind === b.kind ? 0 : a.kind === "dir" ? -1 : 1) ||+ a.name.localeCompare(b.name) ||+ a.path.localeCompare(b.path),+ );+ return {+ hits: hits.map(({ path: rel, kind, sizeBytes, mtime }) => ({+ path: rel,+ kind,+ sizeBytes,+ mtime,+ })),+ truncated,+ };+ }}diff --git a/packages/server/test/workspace-files.test.ts b/packages/server/test/workspace-files.test.tsindex 6e7e09ff..1de812c7 100644--- a/packages/server/test/workspace-files.test.ts+++ b/packages/server/test/workspace-files.test.ts@@ -1,17 +1,22 @@/*** Unit tests for the Workspace files service: directory-listing order, read/write,- * path confinement (`..` traversal and symlink escape), size-limit protection,- * batch existence checks (files/stat); and the Agent delete route (default_agent+ * move / delete / search, path confinement (`..` traversal and symlink escape), size-limit+ * protection, batch existence checks (files/stat); and the Agent delete route (default_agent* cannot be deleted, owner-only, directory and index cleanup).*/import fs from "node:fs/promises";import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { WorkspaceFilesService } from "../src/services/workspace-files-service.js";+import {+ SEARCH_MAX_HITS,+ SEARCH_MAX_QUERY_LEN,+ WorkspaceFilesService,+} from "../src/services/workspace-files-service.js";import type {AgentCreateResponse,ProjectCreateResponse,SessionCreateResponse,+ WorkspaceSearchResponse,} from "../src/api/types.js";import { apiClient, createTestApp, makeTempRoot, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -153,6 +158,247 @@ describe("workspace-files-service", () => {);expect(await fs.stat(path.join(ws, "fresh.txt")).catch(() => null)).toBeNull();});++ it("move: a rename inside a directory, a move across directories, and a destination parent created on the way", async () => {+ await svc.move(ws, "b.txt", "renamed.txt");+ expect(await fs.readFile(path.join(ws, "renamed.txt"), "utf8")).toBe("hello");+ expect(await fs.stat(path.join(ws, "b.txt")).catch(() => null)).toBeNull();++ await svc.move(ws, "sub/c.md", "sub/notes.md");+ expect(await fs.readFile(path.join(ws, "sub", "notes.md"), "utf8")).toBe("# md");++ // Across directories, into a parent that does not exist yet — created under the same+ // checks an upload's auto-creation runs.+ await svc.move(ws, "sub/notes.md", "archive/2026/notes.md");+ expect(await fs.readFile(path.join(ws, "archive", "2026", "notes.md"), "utf8")).toBe("# md");+ expect(await fs.stat(path.join(ws, "sub", "notes.md")).catch(() => null)).toBeNull();+ });++ it("move: an occupied destination is refused rather than overwritten; a missing source is 404; moving onto its own path is a 400", async () => {+ await expect(svc.move(ws, "b.txt", "sub/c.md")).rejects.toEqual(+ expect.objectContaining({ status: 409, code: "target_exists" }),+ );+ // Neither file moved: the destination still holds what it held, the source is still there.+ expect(await fs.readFile(path.join(ws, "sub", "c.md"), "utf8")).toBe("# md");+ expect(await fs.readFile(path.join(ws, "b.txt"), "utf8")).toBe("hello");++ // A directory sitting at the destination is equally occupied.+ await expect(svc.move(ws, "b.txt", "sub")).rejects.toMatchObject({ status: 409 });++ await expect(svc.move(ws, "nope.txt", "x.txt")).rejects.toEqual(+ expect.objectContaining({ status: 404, code: "path_not_found" }),+ );+ // A source whose whole parent directory is gone is the same 404, not a 500.+ await expect(svc.move(ws, "gone/nope.txt", "x.txt")).rejects.toMatchObject({ status: 404 });++ // Same path spelled differently: a 400, not a success that did nothing.+ await expect(svc.move(ws, "b.txt", "./b.txt")).rejects.toMatchObject({ status: 400 });+ await expect(svc.move(ws, "sub/c.md", "sub/../sub/c.md")).rejects.toMatchObject({+ status: 400,+ });+ });++ it("move precondition: a stale marker moves nothing, a vanished source under one is a conflict, and a directory has no marker to offer at all", async () => {+ const { version } = await svc.read(ws, "b.txt");+ await fs.writeFile(path.join(ws, "b.txt"), "agent wrote this");++ await expect(svc.move(ws, "b.txt", "moved.txt", version)).rejects.toEqual(+ expect.objectContaining({ status: 409, code: "file_changed" }),+ );+ expect(await fs.readFile(path.join(ws, "b.txt"), "utf8")).toBe("agent wrote this");+ expect(await fs.stat(path.join(ws, "moved.txt")).catch(() => null)).toBeNull();++ // Re-reading picks up the new version and the same move goes through.+ const fresh = await svc.read(ws, "b.txt");+ await svc.move(ws, "b.txt", "moved.txt", fresh.version);+ expect(await fs.readFile(path.join(ws, "moved.txt"), "utf8")).toBe("agent wrote this");++ // The file the caller read is gone: a change like any other, the same 409 `write` gives.+ const stale = await svc.read(ws, "moved.txt");+ await fs.rm(path.join(ws, "moved.txt"));+ await expect(svc.move(ws, "moved.txt", "again.txt", stale.version)).rejects.toEqual(+ expect.objectContaining({ status: 409, code: "file_changed" }),+ );++ // A directory is refused outright: it carries no single version marker, so no+ // precondition could protect the tree under it.+ await expect(svc.move(ws, "sub", "sub2")).rejects.toMatchObject({ status: 400 });+ expect((await fs.stat(path.join(ws, "sub"))).isDirectory()).toBe(true);+ expect(await fs.stat(path.join(ws, "sub2")).catch(() => null)).toBeNull();+ });++ it("delete: the file goes; a stale marker keeps it; a directory and a missing file are both refused", async () => {+ await svc.remove(ws, "b.txt");+ expect(await fs.stat(path.join(ws, "b.txt")).catch(() => null)).toBeNull();++ const { version } = await svc.read(ws, "sub/c.md");+ await fs.writeFile(path.join(ws, "sub", "c.md"), "# the agent rewrote this");+ await expect(svc.remove(ws, "sub/c.md", version)).rejects.toEqual(+ expect.objectContaining({ status: 409, code: "file_changed" }),+ );+ expect(await fs.readFile(path.join(ws, "sub", "c.md"), "utf8")).toBe(+ "# the agent rewrote this",+ );++ const fresh = await svc.read(ws, "sub/c.md");+ await svc.remove(ws, "sub/c.md", fresh.version);+ expect(await fs.stat(path.join(ws, "sub", "c.md")).catch(() => null)).toBeNull();++ // A directory is refused for the same reason a move refuses one, and stays put.+ await expect(svc.remove(ws, "sub")).rejects.toMatchObject({ status: 400 });+ expect((await fs.stat(path.join(ws, "sub"))).isDirectory()).toBe(true);++ await expect(svc.remove(ws, "nope.txt")).rejects.toEqual(+ expect.objectContaining({ status: 404, code: "path_not_found" }),+ );+ // With a marker, a file that is not there is a conflict rather than a 404.+ await expect(svc.remove(ws, "nope.txt", 'W/"1-1"')).rejects.toMatchObject({+ status: 409,+ code: "file_changed",+ });+ });++ it("move and delete confinement: `..` at either end, a symlinked destination directory, and a symlink at the final segment are all refused", async () => {+ const outsideName = path.basename(outside);+ await fs.symlink(outside, path.join(ws, "link-out"));++ // `..` in the source: the file outside is neither read nor moved in.+ await expect(svc.move(ws, `../${outsideName}/secret.txt`, "stolen.txt")).rejects.toMatchObject({+ status: 400,+ });+ expect(await fs.stat(path.join(ws, "stolen.txt")).catch(() => null)).toBeNull();++ // `..` in the destination: nothing lands outside the Workspace.+ await expect(svc.move(ws, "b.txt", "../escape.txt")).rejects.toMatchObject({ status: 400 });+ expect(await fs.stat(path.join(path.dirname(ws), "escape.txt")).catch(() => null)).toBeNull();+ expect(await fs.readFile(path.join(ws, "b.txt"), "utf8")).toBe("hello");++ // A destination parent that is a symlink pointing outside: caught by the same+ // canonical-parent check an upload runs, including through a directory it would create.+ await expect(svc.move(ws, "b.txt", "link-out/evil.txt")).rejects.toMatchObject({ status: 400 });+ await expect(svc.move(ws, "b.txt", "link-out/new/evil.txt")).rejects.toMatchObject({+ status: 400,+ });+ expect(await fs.stat(path.join(outside, "evil.txt")).catch(() => null)).toBeNull();++ // `..` in a delete: the file outside survives.+ await expect(svc.remove(ws, `../${outsideName}/secret.txt`)).rejects.toMatchObject({+ status: 400,+ });+ expect(await fs.readFile(path.join(outside, "secret.txt"), "utf8")).toBe("secret");++ // A symlink at the final segment — the Agent's "preset a link, act on it by proxy"+ // pattern: O_NOFOLLOW refuses it, so neither the link's target nor the link is touched.+ await fs.symlink(path.join(outside, "secret.txt"), path.join(ws, "report.pdf"));+ await expect(svc.move(ws, "report.pdf", "sub/report.pdf")).rejects.toMatchObject({+ status: 400,+ });+ await expect(svc.remove(ws, "report.pdf")).rejects.toMatchObject({ status: 400 });+ expect(await fs.readFile(path.join(outside, "secret.txt"), "utf8")).toBe("secret");+ expect((await fs.lstat(path.join(ws, "report.pdf"))).isSymbolicLink()).toBe(true);+ });++ it("search: finds a file several directories down that no listing ever reached, reports it as a tree row would, and matches the name rather than the path", async () => {+ await fs.mkdir(path.join(ws, "a", "b", "c"), { recursive: true });+ await fs.writeFile(path.join(ws, "a", "b", "c", "needle.txt"), "found me");+ await fs.mkdir(path.join(ws, "logs"));+ await fs.writeFile(path.join(ws, "logs", "report.md"), "r");++ const deep = await svc.search(ws, "needle");+ expect(deep.truncated).toBe(false);+ expect(deep.hits).toEqual([+ {+ path: "a/b/c/needle.txt",+ kind: "file",+ sizeBytes: 8,+ mtime: (await fs.stat(path.join(ws, "a", "b", "c", "needle.txt"))).mtime.toISOString(),+ },+ ]);++ // Case-insensitive.+ expect((await svc.search(ws, "NeEdLe")).hits.map((h) => h.path)).toEqual(["a/b/c/needle.txt"]);++ // The match is on the NAME: "logs" finds the directory, not everything under it. And a+ // hit reports its own size and mtime, not the enclosing directory's.+ const byDir = await svc.search(ws, "logs");+ const dirStat = await fs.stat(path.join(ws, "logs"));+ expect(byDir.hits).toEqual([+ {+ path: "logs",+ kind: "dir",+ sizeBytes: dirStat.size,+ mtime: dirStat.mtime.toISOString(),+ },+ ]);+ const byFile = await svc.search(ws, "report");+ expect(byFile.hits.map((h) => h.path)).toEqual(["logs/report.md"]);+ // The figures are the hit's own, not the enclosing directory's.+ expect(byFile.hits[0]!.sizeBytes).toBe(1);+ expect(byFile.hits[0]!.mtime).toBe(+ (await fs.stat(path.join(ws, "logs", "report.md"))).mtime.toISOString(),+ );++ // A path fragment is not a name and so matches nothing.+ expect((await svc.search(ws, "logs/report")).hits).toEqual([]);+ });++ it("search: shallow matches come first, directories ahead of files at the same depth", async () => {+ await fs.mkdir(path.join(ws, "sub", "deep"), { recursive: true });+ await fs.mkdir(path.join(ws, "match-dir"));+ await fs.writeFile(path.join(ws, "match.txt"), "1");+ await fs.writeFile(path.join(ws, "sub", "match.txt"), "2");+ await fs.writeFile(path.join(ws, "sub", "deep", "match.txt"), "3");++ const res = await svc.search(ws, "match");+ expect(res.hits.map((h) => `${h.kind}:${h.path}`)).toEqual([+ "dir:match-dir",+ "file:match.txt",+ "file:sub/match.txt",+ "file:sub/deep/match.txt",+ ]);+ });++ it("search confinement: an out-of-bounds symlink is never walked into and never appears as a hit, and a link back to the root cannot spin the walk", async () => {+ await fs.writeFile(path.join(outside, "secret-needle.txt"), "s");+ await fs.symlink(outside, path.join(ws, "link-out"));+ // A cycle: the Workspace root reachable from inside itself, twice over.+ await fs.symlink(ws, path.join(ws, "self"));+ await fs.symlink(ws, path.join(ws, "sub", "back"));++ // Nothing outside is reachable, and the link that points there is not itself a hit.+ expect((await svc.search(ws, "secret")).hits).toEqual([]);+ expect((await svc.search(ws, "link-out")).hits).toEqual([]);++ // The walk terminates and reports each in-bounds entry once.+ const all = await svc.search(ws, "b.txt");+ expect(all.hits.map((h) => h.path)).toEqual(["b.txt"]);+ expect(all.truncated).toBe(false);+ // A self-link is an in-bounds directory, so it is a legitimate hit — it is only never+ // descended into a second time.+ expect((await svc.search(ws, "self")).hits.map((h) => h.path)).toEqual(["self"]);+ });++ it("search: the hit cap truncates and says so; an empty or oversize query is a 400", async () => {+ await Promise.all(+ Array.from({ length: SEARCH_MAX_HITS + 5 }, (_, i) =>+ fs.writeFile(path.join(ws, `cap-${String(i).padStart(3, "0")}.txt`), "x"),+ ),+ );+ const capped = await svc.search(ws, "cap-");+ expect(capped.hits).toHaveLength(SEARCH_MAX_HITS);+ expect(capped.truncated).toBe(true);++ // A search that fits reports the whole truth.+ const whole = await svc.search(ws, "cap-001");+ expect(whole.hits.map((h) => h.path)).toEqual(["cap-001.txt"]);+ expect(whole.truncated).toBe(false);++ await expect(svc.search(ws, "")).rejects.toMatchObject({ status: 400 });+ await expect(svc.search(ws, " ")).rejects.toMatchObject({ status: 400 });+ await expect(svc.search(ws, "x".repeat(SEARCH_MAX_QUERY_LEN + 1))).rejects.toMatchObject({+ status: 400,+ });+ });});describe("files/stat route (batch existence check)", () => {@@ -323,6 +569,132 @@ describe("files/stat route (batch existence check)", () => {});});+describe("files/move, files/search and the files/content delete", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let outsider: ReturnType<typeof apiClient>;+ let sessionId: string;+ let workspace: string;++ beforeEach(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner");+ const b = await provisionUser(t.app, "outsider");+ owner = apiClient(t.app, a.cookie);+ outsider = apiClient(t.app, b.cookie);+ const created = (await (+ await owner.post("/api/projects", { projectId: "owner-ops", name: "project" })+ ).json()) as ProjectCreateResponse;+ const projectId = created.project.projectId;+ await owner.put(`/api/projects/${projectId}/models`, {+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],+ });+ const sess = (await (+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})+ ).json()) as SessionCreateResponse;+ sessionId = sess.session.sessionId;+ workspace = sess.session.workspace;+ await fs.mkdir(path.join(workspace, "sub"));+ await fs.writeFile(path.join(workspace, "a.txt"), "A");+ await fs.writeFile(path.join(workspace, "sub", "b.md"), "B");+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("files/move: 204 and the file is where it was sent; an occupied destination is 409 target_exists; a directory is a 400", async () => {+ const url = `/api/sessions/${sessionId}/files/move`;+ const moved = await owner.post(url, { from: "a.txt", to: "archive/notes/a.txt" });+ expect(moved.status).toBe(204);+ expect(await fs.readFile(path.join(workspace, "archive", "notes", "a.txt"), "utf8")).toBe("A");+ expect(await fs.stat(path.join(workspace, "a.txt")).catch(() => null)).toBeNull();++ const occupied = await owner.post(url, { from: "archive/notes/a.txt", to: "sub/b.md" });+ expect(occupied.status).toBe(409);+ expect(await occupied.json()).toEqual({+ error: { code: "target_exists", message: expect.any(String) },+ });+ expect(await fs.readFile(path.join(workspace, "sub", "b.md"), "utf8")).toBe("B");++ const missing = await owner.post(url, { from: "nope.txt", to: "x.txt" });+ expect(missing.status).toBe(404);+ expect(((await missing.json()) as { error: { code: string } }).error.code).toBe(+ "path_not_found",+ );++ // A directory carries no version marker, so no precondition could protect the move.+ expect((await owner.post(url, { from: "sub", to: "sub2" })).status).toBe(400);+ // A missing or non-string field is a 400 before anything touches the filesystem.+ expect((await owner.post(url, { from: "a.txt" })).status).toBe(400);+ expect((await owner.post(url, { from: "a.txt", to: "b.txt", ifVersion: 7 })).status).toBe(400);+ });++ it("files/content DELETE: the marker the read returned is honoured — a stale one is 409 file_changed with the file left alone, a fresh one removes it", async () => {+ const url = `/api/sessions/${sessionId}/files/content?path=a.txt`;+ const version = (await owner.get(url)).headers.get("etag")!;++ // The Agent rewrites the file while the panel is still showing the old one.+ await fs.writeFile(path.join(workspace, "a.txt"), "written by the agent");+ const stale = await owner.delete(`${url}&ifVersion=${encodeURIComponent(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");++ const current = (await owner.get(url)).headers.get("etag")!;+ const gone = await owner.delete(`${url}&ifVersion=${encodeURIComponent(current)}`);+ expect(gone.status).toBe(204);+ expect(await fs.stat(path.join(workspace, "a.txt")).catch(() => null)).toBeNull();++ // Without a marker the delete is unconditional, which is what an already-missing file+ // answers as a plain 404 rather than a conflict.+ const missing = await owner.delete(`/api/sessions/${sessionId}/files/content?path=a.txt`);+ expect(missing.status).toBe(404);+ expect(((await missing.json()) as { error: { code: string } }).error.code).toBe(+ "path_not_found",+ );+ expect((await owner.delete(`/api/sessions/${sessionId}/files/content?path=sub`)).status).toBe(+ 400,+ );+ });++ it("files/search: hits come back shallow-first carrying what a tree row draws; an empty q is a 400", async () => {+ await fs.mkdir(path.join(workspace, "sub", "deep"), { recursive: true });+ await fs.writeFile(path.join(workspace, "sub", "deep", "b.md"), "deep");+ const res = await owner.get(`/api/sessions/${sessionId}/files/search?q=b.m`);+ expect(res.status).toBe(200);+ const body = (await res.json()) as WorkspaceSearchResponse;+ expect(body.truncated).toBe(false);+ expect(body.hits.map((h) => h.path)).toEqual(["sub/b.md", "sub/deep/b.md"]);+ expect(body.hits[0]).toEqual({+ path: "sub/b.md",+ kind: "file",+ sizeBytes: 1,+ mtime: expect.any(String),+ });++ expect((await owner.get(`/api/sessions/${sessionId}/files/search?q=`)).status).toBe(400);+ expect((await owner.get(`/api/sessions/${sessionId}/files/search`)).status).toBe(400);+ expect(+ (await owner.get(`/api/sessions/${sessionId}/files/search?q=${"x".repeat(101)}`)).status,+ ).toBe(400);+ });++ it("outsider access → 404 on all three (no existence leak, and no Workspace touched)", async () => {+ expect(+ (await outsider.post(`/api/sessions/${sessionId}/files/move`, { from: "a.txt", to: "x.txt" }))+ .status,+ ).toBe(404);+ expect(+ (await outsider.delete(`/api/sessions/${sessionId}/files/content?path=a.txt`)).status,+ ).toBe(404);+ expect((await outsider.get(`/api/sessions/${sessionId}/files/search?q=a`)).status).toBe(404);+ expect(await fs.readFile(path.join(workspace, "a.txt"), "utf8")).toBe("A");+ });+});+describe("agent delete route", () => {let t: TestApp;let owner: ReturnType<typeof apiClient>;diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex b69e94fa..8ef88d12 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -42,6 +42,7 @@ import type {FeishuBindingResponse,FeishuTestRequest,FeishuTestResponse,+ FilesMoveRequest,FilesStatRequest,FilesStatResponse,FilesWriteRequest,@@ -147,6 +148,7 @@ import type {VaultUpdateRequest,VersionResponse,WorkspaceFilesResponse,+ WorkspaceSearchResponse,} from "@prismshadow/penguin-server/api";import type { MCPServerConfig } from "@prismshadow/penguin-core/interfaces";import { apiFetch, apiFetchWithMeta } from "./client";@@ -1046,6 +1048,37 @@ export const uploadWorkspaceFile = (query: { path },});+/**+ * Moves or renames a Workspace file. `ifVersion` (see {@link uploadWorkspaceFile}) guards the+ * SOURCE: pass it and the move is refused with 409 `file_changed` unless the file is still the+ * one that was read. The destination has no such marker — nothing read it — so an occupied+ * destination is 409 `target_exists` rather than an overwrite. Files only: a directory is a+ * 400, since nothing could express a precondition over a whole tree. `to`'s parent directory+ * is created when it is missing.+ */+export const moveWorkspaceFile = (sessionId: string, body: FilesMoveRequest) =>+ apiFetch<void>(`/api/sessions/${sessionId}/files/move`, { method: "POST", body });++/**+ * Deletes a Workspace file. `ifVersion` is the same marker a write carries: with it, a file+ * the Agent rewrote since the panel read it is refused with 409 `file_changed` instead of+ * being removed. Files only — a directory is a 400.+ */+export const deleteWorkspaceFile = (sessionId: string, path: string, ifVersion?: string) =>+ apiFetch<void>(`/api/sessions/${sessionId}/files/content`, {+ method: "DELETE",+ query: { path, ifVersion },+ });++/**+ * Searches the whole Workspace by entry name (case-insensitive substring), breadth-first from+ * the root so the shallowest matches come first. `truncated` says a cap stopped the walk: the+ * hits are then the most relevant ones rather than all of them. An empty query is a 400 — the+ * caller decides what an empty search box shows, and it is never "every file".+ */+export const searchWorkspaceFiles = (sessionId: string, q: string) =>+ apiFetch<WorkspaceSearchResponse>(`/api/sessions/${sessionId}/files/search`, { query: { q } });+/** Batch file-existence check (message file cards): both out-of-bounds and missing paths simply don't appear in `existing`; always returns 200. */export const statSessionFiles = (sessionId: string, paths: string[]) =>apiFetch<FilesStatResponse>(`/api/sessions/${sessionId}/files/stat`, {diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsxindex d22d7ea3..1202fc98 100644--- a/packages/web/src/components/ui/icons.tsx+++ b/packages/web/src/components/ui/icons.tsx@@ -164,6 +164,18 @@ export function CloseButton({/** Info circle: the app's 9-radius status circle with a bar and a dot inside it. */export const INFO_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01";+/**+ * Opening quotation marks: a passage carried in from somewhere else. The composer's chip for a+ * Workspace selection wears it, where a paperclip would have claimed the file was attached — the+ * file is not; a few of its lines are quoted.+ */+export const QUOTE_ICON =+ "M9.5 6.5C7 7.5 5.5 9.5 5.5 12.5v4h5v-5h-3c0-1.8.9-3.1 2.6-3.8zM19.5 6.5c-2.5 1-4 3-4 6v4h5v-5h-3c0-1.8.9-3.1 2.6-3.8z";++/** A pane with an arrow leaving it: this opens somewhere outside the app, in a tab of its own. */+export const EXTERNAL_LINK_ICON =+ "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3";+/*** Window with a bottom pane / a right pane: the two dock edges. Drawn by the chat toolbar's* pull-open buttons and the dock header's move-dock buttons, so one mark stands for one edge@@ -238,6 +250,29 @@ export const FILE_ICON = "M6 3h8l4 4v14H6zM14 3v4h4";export const FILE_WRITE_ICON = "M6 3h8l4 4v14H6zM12 11v6M9 14h6";export const FILE_EDIT_ICON = "M12 20h9M16.5 3.5a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z";+/**+ * Moving a file in or out of the Workspace: a tray with an arrow leaving it (upload) or+ * landing in it (download). The same tray both ways, so the pair reads as one axis; the+ * arrow's direction is the only difference, and each is labelled where it is drawn.+ */+export const UPLOAD_ICON = "M12 15V4m0 0L8 8m4-4 4 4M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3";+export const DOWNLOAD_ICON = "M12 4v11m0 0 4-4m-4 4-4-4M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3";++/**+ * Two arcs chasing each other round a circle: re-read what is on disk. The arc idiom is the+ * app's existing one (see HISTORY_ICON in app-layout.tsx), so the mark sits in the same family+ * as the other round-trip glyphs rather than introducing a second way to draw a turn.+ */+export const REFRESH_ICON =+ "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M3 21v-5h5";++/**+ * Soft wrap: three lines of text where the middle one runs past the edge, turns back and+ * returns with an arrow. The turn is the whole mark — a plain stack of lines would be any of+ * a dozen list glyphs — so it keeps the full bulge rather than being tucked in to save room.+ */+export const WRAP_TEXT_ICON = "M4 6h16M4 12h12a3 3 0 1 1 0 6h-3m2-2-2 2 2 2M4 18h5";+/*** Activity trace (a flat line with one tall beat in it): work still going on behind the* conversation — the background-task mark on a session row, the matching count in the chat@@ -252,6 +287,15 @@ export const FILE_EDIT_ICON = "M12 20h9M16.5 3.5a2.85 2.85 0 1 1 4 4L7.5 20.5 2*/export const BACKGROUND_TASKS_ICON = "M2 12h4l3 9 6-18 3 9h4";+/**+ * The same bubble with a plus in it: putting something into the conversation rather than+ * sending it — the Files panel's "add to conversation" drops a reference in the composer+ * and stops there. Bubble-plus-plus follows the file pair's own convention (FILE_ICON vs+ * FILE_WRITE_ICON): the plus is what the action adds, drawn on the thing it adds to.+ */+export const ADD_TO_CHAT_ICON =+ "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2zM12 7v6M9 10h6";+/*** Paper plane: remote control — the session-row mark for a Session that is relaying through* a messaging channel, the row menu's action that sets one up, and the dock's remote-controldiff --git a/packages/web/src/components/ui/tooltip.tsx b/packages/web/src/components/ui/tooltip.tsxindex b5809ce7..6de9e164 100644--- a/packages/web/src/components/ui/tooltip.tsx+++ b/packages/web/src/components/ui/tooltip.tsx@@ -12,6 +12,10 @@* portaled-panel layer (z-[60]) and takes no pointer events, so it can never swallow a click* meant for what it covers.*+ * Two geometries, chosen by the shape of the control strip rather than by taste: `right` for+ * a vertical rail, `bottom` for a horizontal toolbar, where a panel to the side would cover+ * the very buttons next to the one being asked about.+ ** Deliberately NOT `role="tooltip"` + `aria-describedby`: its callers label their triggers* with the same words it shows, and a description repeating the accessible name makes a* screen reader say the entry twice. The panel is decorative here and hidden from the@@ -36,14 +40,59 @@ const OPEN_DELAY_MS = 400;const PANEL_GAP = 8;const VIEWPORT_MARGIN = 8;+/** Which side of its trigger the panel hangs off. */+export type TooltipPlacement = "right" | "bottom";++/**+ * The viewport point the panel is pinned at. Exactly one horizontal edge is given: `left`+ * grows the panel rightward from that point, `right` leftward. Anchoring by the far edge is+ * what keeps a panel on screen without anyone measuring a width that does not exist until+ * after it renders.+ */+interface PanelPosition {+ top: number;+ left?: number;+ right?: number;+}++/**+ * To the right of the trigger — an icon rail against the left edge of the window. Vertically+ * centred on the trigger and clamped so a rail entry scrolled to the very top or bottom still+ * gets a panel on screen.+ */+function besideTrigger(rect: DOMRect): PanelPosition {+ return {+ top: Math.min(+ Math.max(rect.top + rect.height / 2, VIEWPORT_MARGIN),+ window.innerHeight - VIEWPORT_MARGIN,+ ),+ left: rect.right + PANEL_GAP,+ };+}++/**+ * Under the trigger, aligned to whichever of its vertical edges faces the roomier half of the+ * window, so the panel always grows inward. A toolbar button near the right edge of a docked+ * panel is the case this exists for: left-aligned there, the panel would run off screen.+ */+function belowTrigger(rect: DOMRect): PanelPosition {+ const top = rect.bottom + PANEL_GAP;+ return rect.left + rect.width / 2 > window.innerWidth / 2+ ? { top, right: Math.max(window.innerWidth - rect.right, VIEWPORT_MARGIN) }+ : { top, left: Math.max(rect.left, VIEWPORT_MARGIN) };+}+export function Tooltip({label,+ placement = "right",suppressed,className,children,}: {/** The words the panel shows — the trigger's own name, so the two cannot disagree. */label: string;+ /** Which side of the trigger the panel hangs off; `right` suits a vertical rail, `bottom` a horizontal toolbar. */+ placement?: TooltipPlacement;/*** Hold the panel closed and refuse to open it. For a trigger that owns something else on* screen while it is active: the rail avatar's open user menu hangs off the same corner,@@ -56,8 +105,8 @@ export function Tooltip({}) {const anchorRef = useRef<HTMLSpanElement>(null);const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- /** Non-null only while the panel is up; the measured viewport point its left edge and vertical centre sit at. */- const [position, setPosition] = useState<{ top: number; left: number } | null>(null);+ /** Non-null only while the panel is up; the measured viewport point it hangs from. */+ const [position, setPosition] = useState<PanelPosition | null>(null);const hide = useCallback(() => {if (timerRef.current !== null) {@@ -73,16 +122,7 @@ export function Tooltip({timerRef.current = null;const rect = anchorRef.current?.getBoundingClientRect();if (!rect) return;- // Placed to the right of the trigger — the one geometry the callers need, an icon rail- // against the left edge of the window. Vertically centred on the trigger and clamped so- // a rail entry scrolled to the very top or bottom still gets a panel on screen.- setPosition({- top: Math.min(- Math.max(rect.top + rect.height / 2, VIEWPORT_MARGIN),- window.innerHeight - VIEWPORT_MARGIN,- ),- left: rect.right + PANEL_GAP,- });+ setPosition(placement === "bottom" ? belowTrigger(rect) : besideTrigger(rect));}, OPEN_DELAY_MS);};@@ -129,8 +169,13 @@ export function Tooltip({<divdata-testid="tooltip"aria-hidden- style={{ position: "fixed", top: position.top, left: position.left }}- className="anim-fade pointer-events-none z-[60] w-max max-w-64 -translate-y-1/2 rounded-md border border-gray-200 bg-white px-2 py-1 text-xs text-gray-700 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200"+ style={{+ position: "fixed",+ top: position.top,+ left: position.left,+ right: position.right,+ }}+ className={`anim-fade pointer-events-none z-[60] w-max max-w-64 rounded-md border border-gray-200 bg-white px-2 py-1 text-xs text-gray-700 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 ${placement === "right" ? "-translate-y-1/2" : ""}`}>{label}</div>,diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 3316d84e..56a2ea28 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -96,7 +96,8 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";import { Button } from "../../components/ui/button";import { Dropdown } from "../../components/ui/dropdown";import { GlyphIcon } from "../../components/ui/glyph-icon";-import { CheckIcon, ChevronDown } from "../../components/ui/icons";+import { CheckIcon, ChevronDown, FILE_ICON, QUOTE_ICON } from "../../components/ui/icons";+import { FOLDER_ICON } from "../../components/ui/group-list";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { noAutofill } from "../../components/ui/input";import { toastError, toastInfo } from "../../components/ui/toast";@@ -129,6 +130,8 @@ import { modelWindowBelowCompactionLimit } from "../../lib/context";import { toneStrip } from "../../lib/tone";import { splitDroppedFiles } from "../../lib/file-drop";import { splitBySize } from "../../lib/upload-limits";+import { lineSuffix } from "../../lib/workspace-tree";+import type { ComposerReference } from "../../lib/workspace-tree";const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];@@ -751,10 +754,50 @@ function appendAttachmentParts(}}+/**+ * The message body: the staged quotations, then what was typed. Blank parts are dropped so a+ * quotation sent with no sentence after it does not trail an empty line.+ */+function withReferences(references: readonly ComposerReference[], typed: string): string {+ if (references.length === 0) return typed;+ return [...references.map((r) => r.text), typed].filter((part) => part !== "").join("\n\n");+}++/**+ * A staged reference, split for display: the entry's own name, and the quoted lines as a+ * `:from-to` suffix. The `file:line` form rather than a worded one — it is the shape every editor+ * and stack trace already uses, it needs no translating, and a chip has no room for a sentence.+ *+ * Returned in two pieces because the chip draws them differently: a long name ellipsizes, and the+ * line numbers must not go with it. They are the smaller half and the half the name does not+ * already say.+ */+function referenceParts(reference: ComposerReference): { name: string; lines: string } {+ const name = reference.path.split("/").pop() ?? reference.path;+ const lines =+ reference.fromLine === undefined || reference.toLine === undefined+ ? ""+ : lineSuffix(reference.fromLine, reference.toLine);+ return { name, lines };+}++/** The whole of what a chip stands for, for its tooltip and its accessible name: path and lines. */+function referenceTitle(reference: ComposerReference): string {+ return `${reference.path}${referenceParts(reference).lines}`;+}++/** A directory, a file, or a passage carried in from one — each says what the chip stands for. */+const REFERENCE_ICON: Record<ComposerReference["kind"], string> = {+ dir: FOLDER_ICON,+ file: FILE_ICON,+ quote: QUOTE_ICON,+};+/*** What a parent can ask of a mounted composer, handed over through ChatInput's `controlRef`.- * One entry so far: a surface that composes a prompt puts it in this composer instead of- * submitting it on its own.+ * Two entries: a surface that composes a whole prompt puts it in this composer instead of+ * submitting it on its own, and a surface that contributes one reference splices it into+ * whatever is already being typed.*/export interface ComposerControl {/**@@ -764,6 +807,12 @@ export interface ComposerControl {* leave the composer's own Skill selection untouched.*/fillPrompt: (prompt: string, pinnedSkills: readonly string[]) => void;+ /**+ * Stage what the Files panel contributes as a chip rather than typing it into the draft — a+ * file, a directory, or a quoted range. The text rides the message when it is sent; what the+ * composer shows is the thing it points at.+ */+ addReference: (reference: ComposerReference) => void;}/**@@ -1059,6 +1108,12 @@ export function ChatInput({// like images — a draft has no Session yet, so there is nothing to upload them to ahead of// time; they travel with the task request and the server files them into the scratchpad.const [attachments, setAttachments] = useState<Attachment[]>([]);+ /**+ * Quotations staged from the Files panel. Held here rather than in the draft cache, exactly+ * like attachments: what they quote is a file on disk that may have moved on by the time a+ * stale draft is reopened, so they belong to this composer's life and not to the text's.+ */+ const [references, setReferences] = useState<ComposerReference[]>([]);const [busy, setBusy] = useState(false);const [slashIndex, setSlashIndex] = useState(0);// Slash token start where Escape closed the menu: it stays shut for that one token.@@ -1100,6 +1155,7 @@ export function ChatInput({text.trim().length > 0 ||images.length > 0 ||attachments.length > 0 ||+ references.length > 0 ||target !== null ||pendingModel !== null ||selectedSkills.length > 0;@@ -1449,7 +1505,13 @@ export function ChatInput({},[skills, selectedSkills, onTextChange, onSkillsChange],);- useImperativeHandle(controlRef, () => ({ fillPrompt }), [fillPrompt]);+ const addReference = useCallback((reference: ComposerReference) => {+ setReferences((prev) => [...prev, reference]);+ // The chip is above the text body, so the caret stays where it was; focus follows the+ // gesture back to the composer, which is where the sentence about it gets typed.+ requestAnimationFrame(() => textareaRef.current?.focus());+ }, []);+ useImperativeHandle(controlRef, () => ({ fillPrompt, addReference }), [fillPrompt, addReference]);/** The slash token currently under the caret (kept in a ref so command run() closures always remove the live token). */const slashMatchRef = useRef<ReturnType<typeof matchSlash>>(null);@@ -1829,14 +1891,17 @@ export function ChatInput({// skills invocation when skills are selected, otherwise the model-switch line for a staged// switch. A handoff needs no fallback: its first message may legitimately be nothing but// the [handoff_from] source block.+ // Staged quotations go in front of what was typed: they are what the message is about, and+ // the sentence after them reads as being about them.+ const quoted = withReferences(references, t);const bodyText =- t !== ""- ? t+ quoted !== ""+ ? quoted: selectedSkills.length > 0? S.chat.skillsAutoMessage(selectedSkills): switchModel? S.chat.modelSwitchAutoMessage- : t;+ : quoted;// With non-empty selected skills: the text body is replaced with a [use_skills] block + the text (every branch wraps its body the same way).const body = buildSkillsMessage(selectedSkills, bodyText);const input: TaskInputPart[] = [];@@ -1857,6 +1922,7 @@ export function ChatInput({setText("");setImages([]);setAttachments([]);+ setReferences([]);setTarget(null);setPendingModel(null);setSelectedSkills([]);@@ -1883,7 +1949,7 @@ export function ChatInput({// for the running agent; all are sent and cleared together — selected skills stay for// a normal send (a staged switch chip blocks this branch outright, see midRunAction).if (!steerAction) return;- const steerText = text.trim();+ const steerText = withReferences(references, text.trim());const steerImages = images;const steerFiles = attachments.map((f) => ({ fileName: f.name, dataUrl: f.dataUrl }));setBusy(true);@@ -1898,6 +1964,7 @@ export function ChatInput({setText("");setImages([]);setAttachments([]);+ setReferences([]);}} finally {setBusy(false);@@ -2349,14 +2416,19 @@ export function ChatInput({breakpoints wouldn't judge it accurately. */}<div className="@container rounded-lg border border-gray-300 bg-white px-2.5 pb-2 pt-2 transition-[border-color,box-shadow] duration-200 focus-within:border-gray-500 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-400">{/* Chip row above the text body: the staged switch target (an /agent handoff or a- /model fork — never both) followed by the selected skills, all sharing the same- chip look. Remove buttons recolor the x on hover (no background wash). */}- {(target !== null || pendingModel !== null || selectedSkills.length > 0 || goalOn) && (+ /model fork — never both), the selected skills, and whatever the Files panel has+ contributed, all sharing the same chip look. Remove buttons recolor the x on hover+ (no background wash). */}+ {(target !== null ||+ pendingModel !== null ||+ selectedSkills.length > 0 ||+ references.length > 0 ||+ goalOn) && (<div className="mb-1 flex flex-wrap items-center gap-1">{/* Goal-mode chip: the budget stays compact as a value button; its editor is afixed upward popover so it never covers the objective textarea below. */}{goalOn && (- <span className="anim-pop flex max-w-full items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200">+ <span className="anim-pop flex max-w-full items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"><span className="flex shrink-0 items-center gap-1" title={S.chat.goalModeDesc}><GlyphIcon d={GOAL_ICON} size={13} className="text-gray-500 dark:text-gray-400" /><span>{S.chat.goalMode}</span>@@ -2459,7 +2531,7 @@ export function ChatInput({{target !== null && (<spantitle={S.chat.handoffTargetTitle(agentDisplayName(target))}- className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200"+ className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"><AgentAvatarid={target.agentId}@@ -2487,7 +2559,7 @@ export function ChatInput({{pendingModel !== null && (<spantitle={S.chat.modelSwitchTargetTitle(modelLabel(pendingModel))}- className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200"+ className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"><ProviderLogo provider={pendingModel.provider} className="h-3.5 w-3.5 shrink-0" /><span className="truncate">{modelLabel(pendingModel)}</span>@@ -2509,7 +2581,7 @@ export function ChatInput({return (<spankey={name}- className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200"+ className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"{...(meta ? { title: localizedShortText(locale, meta) } : {})}><SkillIcon@@ -2529,6 +2601,42 @@ export function ChatInput({</span>);})}+ {/* Staged from the Files panel: a file, a directory, or a quoted range. The text+ itself never enters the draft — the chip names what it points at, and the+ message carries it on send. */}+ {references.map((reference, i) => {+ const { name, lines } = referenceParts(reference);+ const title = referenceTitle(reference);+ return (+ <span+ key={i}+ title={title}+ className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"+ >+ <GlyphIcon+ d={REFERENCE_ICON[reference.kind]}+ size={13}+ className="shrink-0 text-gray-500 dark:text-gray-400"+ />+ {/* The name gives way, the line numbers do not: they are four characters, and+ they are the half the truncated name cannot tell you. The tooltip carries+ the whole path and the range together. */}+ <span className="min-w-0 truncate">{name}</span>+ {lines !== "" && <span className="shrink-0">{lines}</span>}+ <button+ type="button"+ aria-label={`${S.files.removeReference} ${title}`}+ onClick={() => {+ setReferences((prev) => prev.filter((_, j) => j !== i));+ textareaRef.current?.focus();+ }}+ className="shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"+ >+ ×+ </button>+ </span>+ );+ })}</div>)}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex f75fb685..76fc6c09 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -82,6 +82,7 @@ import type { ForkTarget } from "./task-stats-line";import { latestTaskHasSubagent, modelTaskStartCount, taskStartCount } from "./agent-topology";import { ChatInput } from "./chat-input";import type { ComposerControl } from "./chat-input";+import type { ComposerReference } from "../../lib/workspace-tree";import {compactionTally,heldThinkingSwitch,@@ -1270,6 +1271,16 @@ export function ChatPage() {// An empty pin list: a schedule prompt names no Skills, so the composer's own selection stands.composerRef.current?.fillPrompt(text, []);}, []);+ /**+ * The Files panel's exit into the conversation: a `@path` reference, or a fenced block+ * around what was selected in a preview, spliced into the draft at the caret. Nothing is+ * sent and nothing already typed is disturbed — the panel contributes a line to a message+ * the user is writing.+ */+ /** Staged as a chip, so the draft keeps whatever the user was in the middle of writing. */+ const addComposerReference = useCallback((reference: ComposerReference) => {+ composerRef.current?.addReference(reference);+ }, []);// Pins a picked level on the Session so it outlives this tab: PATCH, then swap the// returned row into the session store (the picker reads it back from there); it applies@@ -1647,6 +1658,7 @@ export function ChatPage() {openRequest={fileOpenRequest}active={active}reloadSignal={settledTurnSignal}+ onAddReference={addComposerReference}/>);case "memory":diff --git a/packages/web/src/features/chat/code-block.tsx b/packages/web/src/features/chat/code-block.tsxindex e2e33f50..1fee03f3 100644--- a/packages/web/src/features/chat/code-block.tsx+++ b/packages/web/src/features/chat/code-block.tsx@@ -1,52 +1,156 @@/**- * Code block (visual reference: better-chatbot's pre-block): top bar = language label + copy- * button, body highlighted via Shiki — inline CSS variables for both the github-light /- * github-dark themes, with dark mode switched via style overrides under html.dark (see- * styles.css), so theme switching doesn't require re-highlighting.- * The highlighter is dynamically imported (its own chunk, loaded only once the first code block+ * Code rendering, in two layers.+ *+ * `CodeSurface` is the code itself: a `<pre>` highlighted via Shiki — inline CSS variables for+ * both the github-light / github-dark themes, with dark mode switched via style overrides under+ * html.dark (see styles.css), so theme switching doesn't require re-highlighting. The+ * highlighter is dynamically imported (its own chunk, loaded only once the first code block* appears; see highlighter.ts); before loading completes, and for languages that chunk doesn't- * carry, it falls back to an unhighlighted <pre>.+ * carry, it falls back to unhighlighted text. It carries no chrome at all, which is what lets+ * the Files panel put its source view and its editor on the same layer and know they agree.+ *+ * `CodeBlock` is that surface inside the chat message's chrome (visual reference:+ * better-chatbot's pre-block): a bordered box with a top bar carrying the language label and a+ * copy button. Message code blocks keep no line numbers and no wrapping — see the Files panel+ * for why wrapping is a file viewer's answer and not a transcript's.** highlight=false (while a message is streaming) skips highlighting and falls back to plain* text: every streaming frame re-renders the full code with a growing length, and re-tokenizing* the whole block each time would be O(n^2) main-thread cost, and an in-progress highlight can't* be canceled; once streaming settles, highlight flips true and a single final highlight is done.*/-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";+import type { CSSProperties, ReactNode } from "react";import { S } from "../../lib/strings";import { CopyButton } from "../../components/ui/copy-button";-export function CodeBlock({+/**+ * The highlighted code, with no box around it.+ *+ * With `lineNumbers`, the lines become blocks (see highlighter.ts's BLOCK_LINES) so a CSS+ * counter can draw a gutter that survives wrapping, and the unhighlighted fallback is split+ * into the same line elements — one gutter, whichever path rendered the code, and one shape for+ * a caller that needs to lay something else over it.+ */+export function CodeSurface({language,code,highlight = true,+ lineNumbers = false,+ wrap = false,+ settleMs = 0,+ className = "",+ children,}: {language: string;code: string;highlight?: boolean;+ /** Draw a line-number gutter (and, with it, put each line in a block of its own). */+ lineNumbers?: boolean;+ /** Soft-wrap long lines instead of scrolling sideways. */+ wrap?: boolean;+ /**+ * Wait this long after the last change before highlighting. 0 (the default) highlights every+ * change, which is right for code that is rendered once; an editor passes a delay so that+ * typing costs nothing but a re-render. While a highlight is pending the surface shows the+ * CURRENT text unhighlighted rather than the previous text's colours — a code layer that+ * lags the keystrokes it sits under is worse than a colourless one.+ */+ settleMs?: number;+ className?: string;+ /** Laid over the code in the same scroll box (the Files panel's editor puts its textarea here). */+ children?: ReactNode;}) {- const [html, setHtml] = useState<string>();+ const [highlighted, setHighlighted] = useState<{ code: string; html: string }>();useEffect(() => {if (!highlight) {- setHtml(undefined);+ setHighlighted(undefined);return;}let alive = true;- void import("./highlighter")- .then((mod) => mod.highlightToHtml(code, language))- .then((out) => {- if (alive) setHtml(out);- })- .catch(() => {- // Unknown language / failed to load: keep the unhighlighted fallback.- if (alive) setHtml(undefined);- });+ const run = () => {+ void import("./highlighter")+ .then((mod) => mod.highlightToHtml(code, language, { blockLines: lineNumbers }))+ .then((out) => {+ if (alive && out !== undefined) setHighlighted({ code, html: out });+ })+ .catch(() => {+ // Unknown language / failed to load: keep the unhighlighted fallback.+ });+ };+ if (settleMs <= 0) {+ run();+ return () => {+ alive = false;+ };+ }+ const timer = window.setTimeout(run, settleMs);return () => {alive = false;+ window.clearTimeout(timer);};- }, [code, language, highlight]);+ }, [code, language, highlight, lineNumbers, settleMs]);++ // Split once per code change, and only where a gutter needs it: the digit count sizes the+ // gutter, and the unhighlighted fallback renders the lines it returns.+ const lines = useMemo(() => (lineNumbers ? code.split("\n") : null), [code, lineNumbers]);+ // Only the current text's own highlight may be shown (see settleMs).+ const html = highlighted?.code === code ? highlighted.html : undefined;+ /**+ * The `dangerouslySetInnerHTML` payload, held stable across renders that do not change the+ * markup. React compares this prop by object identity and re-sets `innerHTML` whenever it+ * differs, so a fresh `{ __html }` literal rebuilds every node in the block on every render+ * of the surrounding component — discarding any selection the reader had made inside it, and+ * re-parsing the whole highlighted body for nothing.+ */+ const htmlProp = useMemo(() => (html === undefined ? undefined : { __html: html }), [html]);+ return (+ <div+ className={`code-surface ${wrap ? "code-wrap" : "code-nowrap"} ${+ lines === null ? "" : "code-lines"+ } ${className}`}+ style={+ lines === null+ ? undefined+ : // `ch` and not `rem`: an overlaid textarea has to indent by exactly this much, and+ // only a character-relative unit is the same length in both layers. +2 is the+ // clearance between the number and the code.+ ({ "--code-gutter": `${String(lines.length).length + 2}ch` } as CSSProperties)+ }+ >+ {htmlProp !== undefined ? (+ <div dangerouslySetInnerHTML={htmlProp} />+ ) : (+ <pre>+ <code>+ {lines === null+ ? code+ : // No newline between the spans: they are blocks, and the text a selection+ // serialises out of a run of blocks already carries the breaks.+ lines.map((line, i) => (+ <span key={i} className="line">+ {line}+ </span>+ ))}+ </code>+ </pre>+ )}+ {children}+ </div>+ );+}++export function CodeBlock({+ language,+ code,+ highlight = true,+}: {+ language: string;+ code: string;+ highlight?: boolean;+}) {return (<div className="code-block my-2 overflow-hidden rounded-lg border border-gray-200 dark:border-gray-800"><div className="flex items-center justify-between border-b border-gray-200 bg-gray-50 px-3 py-1 dark:border-gray-800 dark:bg-gray-900">@@ -57,13 +161,7 @@ export function CodeBlock({<CopyButton text={code} label={S.chat.copyCode} /></div><div className="overflow-x-auto bg-white text-[13px] leading-relaxed dark:bg-gray-950">- {html ? (- <div dangerouslySetInnerHTML={{ __html: html }} />- ) : (- <pre className="m-0 px-3 py-2.5 font-mono text-gray-800 dark:text-gray-200">- <code>{code}</code>- </pre>- )}+ <CodeSurface language={language} code={code} highlight={highlight} /></div></div>);diff --git a/packages/web/src/features/chat/highlighter-core.ts b/packages/web/src/features/chat/highlighter-core.tsnew file mode 100644index 00000000..decb723d--- /dev/null+++ b/packages/web/src/features/chat/highlighter-core.ts@@ -0,0 +1,92 @@+/**+ * The Shiki engine itself: the core, the lazily loaded grammars, and one call that turns code+ * into dual-theme HTML. Imported by `highlighter.worker.ts` and, when a worker cannot be had, by+ * `highlighter.ts` directly — so the two paths share the engine rather than agreeing about it.+ *+ * Assembled from `shiki/core` with the language list in code-languages.ts instead of importing+ * `shiki` (its full bundle): that entry point drags in the oniguruma WASM engine and a registry of+ * all 332 bundled grammars, and both land on the *first* code block a conversation renders — 230 KB+ * gzip of WASM before a single token is colored. The pure-JS regex engine replaces it for free:+ * every pattern in every bundled grammar translates to a JS RegExp, and its token output is+ * byte-identical to oniguruma's. Measured on this app: ~308 KB -> ~70 KB gzip for the first block.+ *+ * The trade is coverage — a fence in a language not listed in code-languages.ts renders+ * unhighlighted instead of highlighted, where the full bundle would have known it.+ *+ * Both themes are baked into one pass as CSS variables (`--shiki-dark`, see styles.css), so+ * switching light/dark never re-highlights. Grammars load lazily and are cached per language, so a+ * conversation downloads only the languages it shows, once each.+ */+import { createHighlighterCore, type HighlighterCore, type LanguageInput } from "shiki/core";+import { createJavaScriptRegexEngine } from "shiki/engine/javascript";+import { LANGUAGE_LOADERS, isPlainTextLanguage, resolveLanguage } from "./code-languages";++let corePromise: Promise<HighlighterCore> | undefined;+const grammarPromises = new Map<string, Promise<void>>();++function getCore(): Promise<HighlighterCore> {+ corePromise ??= createHighlighterCore({+ themes: [import("@shikijs/themes/github-light"), import("@shikijs/themes/github-dark")],+ langs: [],+ engine: createJavaScriptRegexEngine(),+ });+ return corePromise;+}++/** Loads a grammar at most once, even when several code blocks of the same language settle together. */+function loadGrammar(+ core: HighlighterCore,+ id: string,+ load: () => Promise<unknown>,+): Promise<void> {+ let pending = grammarPromises.get(id);+ if (!pending) {+ pending = load()+ .then((mod) => core.loadLanguage((mod as { default: LanguageInput }).default))+ .then(() => undefined)+ .catch((err: unknown) => {+ // Don't cache a failed load: a transient chunk fetch failure shouldn't leave the language+ // permanently unhighlighted for the rest of the session.+ grammarPromises.delete(id);+ throw err;+ });+ grammarPromises.set(id, pending);+ }+ return pending;+}++/**+ * Shiki separates its `<span class="line">` wrappers with a literal newline, which is what+ * breaks the lines when they stay inline. A gutter needs them to be blocks instead — only a+ * block takes the per-line padding and negative text-indent that keep a wrapped line's+ * continuation rows clear of its number — and those separators would then each add a blank+ * row of their own. Dropping them is this transformer's whole job; the line elements, and so+ * the text a selection serialises out of them, are untouched.+ */+const BLOCK_LINES = {+ code(node: { children: { type: string }[] }) {+ node.children = node.children.filter((child) => child.type !== "text");+ },+};++/**+ * Highlights `code` as `language`, returning Shiki's dual-theme HTML, or undefined when the+ * language isn't one this bundle carries. Rejects only on an unexpected failure (chunk fetch,+ * grammar error); callers fall back to unhighlighted text either way.+ */+export async function highlight(+ code: string,+ language: string,+ blockLines: boolean,+): Promise<string | undefined> {+ const id = resolveLanguage(language);+ if (!id) return undefined;+ const core = await getCore();+ const load = isPlainTextLanguage(id) ? undefined : LANGUAGE_LOADERS.get(id);+ if (load) await loadGrammar(core, id, load);+ return core.codeToHtml(code, {+ lang: id,+ themes: { light: "github-light", dark: "github-dark" },+ ...(blockLines ? { transformers: [BLOCK_LINES] } : {}),+ });+}diff --git a/packages/web/src/features/chat/highlighter.ts b/packages/web/src/features/chat/highlighter.tsindex fad630da..6e0ed742 100644--- a/packages/web/src/features/chat/highlighter.ts+++ b/packages/web/src/features/chat/highlighter.ts@@ -1,57 +1,54 @@/**- * Shiki highlighter for code blocks — the chunk CodeBlock dynamically imports.+ * The code viewer's highlighting entry point: the same call as before, answered on a worker.*- * Assembled from `shiki/core` with the language list in code-languages.ts instead of importing- * `shiki` (its full bundle): that entry point drags in the oniguruma WASM engine and a registry of- * all 332 bundled grammars, and both land on the *first* code block a conversation renders — 230 KB- * gzip of WASM before a single token is colored. The pure-JS regex engine replaces it for free:- * every pattern in every bundled grammar translates to a JS RegExp, and its token output is- * byte-identical to oniguruma's. Measured on this app: ~308 KB -> ~70 KB gzip for the first block.+ * Tokenizing is linear in the size of the file — about four milliseconds per kilobyte of+ * TypeScript, measured on this app's own sources — and it runs to completion once it starts. On+ * the main thread that put a hard ceiling on what could be coloured at all, because half a+ * megabyte meant two seconds of frozen page. A worker removes the ceiling rather than raising it:+ * the code renders unhighlighted, the colours replace it when they land, and nothing blocks.*- * The trade is coverage — a fence in a language not listed in code-languages.ts renders- * unhighlighted instead of highlighted (`highlightToHtml` returns undefined and CodeBlock keeps its- * plain <pre> fallback), where the full bundle would have known it.- *- * Both themes are baked into one pass as CSS variables (`--shiki-dark`, see styles.css), so- * switching light/dark never re-highlights. Grammars load lazily and are cached per language, so a- * conversation downloads only the languages it shows, once each.+ * The worker is created on the first call and kept for the page's life, so a conversation pays for+ * the engine and each grammar once. Where a worker cannot be had at all — a runtime without it, a+ * CSP that forbids it, a construction that throws — the work falls back to this thread, which is+ * exactly the old behaviour and still correct, only blocking.*/-import { createHighlighterCore, type HighlighterCore, type LanguageInput } from "shiki/core";-import { createJavaScriptRegexEngine } from "shiki/engine/javascript";-import { LANGUAGE_LOADERS, isPlainTextLanguage, resolveLanguage } from "./code-languages";+import type { HighlightRequest, HighlightResponse } from "./highlighter.worker";-let corePromise: Promise<HighlighterCore> | undefined;-const grammarPromises = new Map<string, Promise<void>>();+/** undefined: not tried yet. null: unavailable here, use the main thread. */+let worker: Worker | null | undefined;+let nextId = 0;+const pending = new Map<number, (response: HighlightResponse) => void>();-function getCore(): Promise<HighlighterCore> {- corePromise ??= createHighlighterCore({- themes: [import("@shikijs/themes/github-light"), import("@shikijs/themes/github-dark")],- langs: [],- engine: createJavaScriptRegexEngine(),- });- return corePromise;+function settleAll(response: (id: number) => HighlightResponse): void {+ for (const [id, resolve] of pending) resolve(response(id));+ pending.clear();}-/** Loads a grammar at most once, even when several code blocks of the same language settle together. */-function loadGrammar(- core: HighlighterCore,- id: string,- load: () => Promise<unknown>,-): Promise<void> {- let pending = grammarPromises.get(id);- if (!pending) {- pending = load()- .then((mod) => core.loadLanguage((mod as { default: LanguageInput }).default))- .then(() => undefined)- .catch((err: unknown) => {- // Don't cache a failed load: a transient chunk fetch failure shouldn't leave the language- // permanently unhighlighted for the rest of the session.- grammarPromises.delete(id);- throw err;- });- grammarPromises.set(id, pending);+function getWorker(): Worker | null {+ if (worker !== undefined) return worker;+ try {+ const created = new Worker(new URL("./highlighter.worker.ts", import.meta.url), {+ type: "module",+ });+ created.onmessage = (event: MessageEvent<HighlightResponse>) => {+ const resolve = pending.get(event.data.id);+ if (resolve) {+ pending.delete(event.data.id);+ resolve(event.data);+ }+ };+ // A worker that dies takes every request in flight with it. Answer them as "no highlight"+ // rather than leaving their promises open forever, and send the next call to the main+ // thread instead of a socket that is gone.+ created.onerror = () => {+ worker = null;+ settleAll((id) => ({ id, error: "worker failed" }));+ };+ worker = created;+ } catch {+ worker = null;}- return pending;+ return worker;}/**@@ -59,14 +56,28 @@ function loadGrammar(* language isn't one this bundle carries. Rejects only on an unexpected failure (chunk fetch,* grammar error); callers fall back to unhighlighted text either way.*/-export async function highlightToHtml(code: string, language: string): Promise<string | undefined> {- const id = resolveLanguage(language);- if (!id) return undefined;- const core = await getCore();- const load = isPlainTextLanguage(id) ? undefined : LANGUAGE_LOADERS.get(id);- if (load) await loadGrammar(core, id, load);- return core.codeToHtml(code, {- lang: id,- themes: { light: "github-light", dark: "github-dark" },+export async function highlightToHtml(+ code: string,+ language: string,+ options?: { blockLines?: boolean },+): Promise<string | undefined> {+ const blockLines = options?.blockLines === true;+ const w = getWorker();+ if (w === null) {+ // Imported here and not at the top: the engine is already in the worker's bundle, and a+ // static import would put a second copy of it on the main thread for every reader whose+ // worker works — which is all of them.+ const { highlight } = await import("./highlighter-core");+ return highlight(code, language, blockLines);+ }+ const id = (nextId += 1);+ const request: HighlightRequest = { id, code, language, blockLines };+ const answer = await new Promise<HighlightResponse>((resolve) => {+ pending.set(id, resolve);+ w.postMessage(request);});+ // The worker reports a failure rather than throwing across the boundary; treat it the way the+ // main-thread path treats one, so a caller sees the same unhighlighted fallback either way.+ if (answer.error !== undefined) return undefined;+ return answer.html;}diff --git a/packages/web/src/features/chat/highlighter.worker.ts b/packages/web/src/features/chat/highlighter.worker.tsnew file mode 100644index 00000000..be7f74c4--- /dev/null+++ b/packages/web/src/features/chat/highlighter.worker.ts@@ -0,0 +1,44 @@+/**+ * Highlighting, off the main thread.+ *+ * Tokenizing is linear in the size of the file and runs to completion once it starts — roughly+ * four milliseconds per kilobyte, so half a megabyte of TypeScript is a couple of seconds. On the+ * main thread that is a couple of seconds of frozen scrolling, which is why the viewer used to+ * refuse to highlight anything large. Here it costs nothing anyone can feel: the code shows+ * unhighlighted, the colours arrive when they arrive, and the page stays live throughout.+ *+ * The protocol is one message each way, correlated by an id the caller mints, because several+ * blocks can settle at once and their answers come back in whatever order they finish.+ */+import { highlight } from "./highlighter-core";++export interface HighlightRequest {+ id: number;+ code: string;+ language: string;+ blockLines: boolean;+}++export interface HighlightResponse {+ id: number;+ html?: string;+ /** Present when the attempt threw; the caller renders the code unhighlighted. */+ error?: string;+}++self.onmessage = (event: MessageEvent<HighlightRequest>) => {+ const { id, code, language, blockLines } = event.data;+ highlight(code, language, blockLines).then(+ (html) => {+ const done: HighlightResponse = html === undefined ? { id } : { id, html };+ self.postMessage(done);+ },+ (err: unknown) => {+ const failed: HighlightResponse = {+ id,+ error: err instanceof Error ? err.message : "failed",+ };+ self.postMessage(failed);+ },+ );+};diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex d3b47dd2..e38d36a7 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -21,6 +21,14 @@* 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.+ *+ * A secondary click carries the panel's per-entry actions — copy the relative path, add a+ * `@path` reference to the conversation, upload into a folder, download a file — on the tree+ * rows and again on the preview body, where the file it acts on is the one being previewed+ * and a selection inside it can be added as a fenced block instead of the whole file. Two+ * gestures reach nothing and are left to the browser on purpose: inside the HTML and PDF+ * previews, which are iframes no handler on this side can hear, and inside the in-place+ * editor, where the native menu is how text gets pasted.*/import {Fragment,@@ -35,10 +43,12 @@ import type {ChangeEvent,DragEvent as ReactDragEvent,KeyboardEvent as ReactKeyboardEvent,+ MouseEvent as ReactMouseEvent,+ PointerEvent as ReactPointerEvent,} from "react";import ReactMarkdown from "react-markdown";import { REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";-import type { SessionInfo } from "@prismshadow/penguin-server/api";+import type { SessionInfo, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";import { useAuth } from "../../state/auth";@@ -62,7 +72,7 @@ import {dropTargetDir,expandTo,extOf,- filterTreeRows,+ searchRows,flattenTree,isDirty,isNarrowLayout,@@ -70,46 +80,78 @@ import {maxTreeWidth,needsDiscardConfirm,parentDir,+ pathReference,previewKindFor,- readEditorWrap,+ readWrapLines,readTreeVisible,readTreeWidth,+ selectionBlock,+ splitFileName,upsertEntry,utf8Complete,visibleCrumbSegments,withExpanded,- writeEditorWrap,+ writeWrapLines,writeTreeVisible,writeTreeWidth,} from "../../lib/workspace-tree";-import type { EditorState, Listings } from "../../lib/workspace-tree";+import type { ComposerReference, EditorState, Listings } from "../../lib/workspace-tree";+import { isContextMenuKey, isLongPressPointer } from "../../lib/context-menu";import { Button } from "../../components/ui/button";import { ConfirmModal } from "../../components/ui/confirm-modal";+import { useRowContextMenu } from "../../components/ui/context-menu";+import {+ CopiedStatus,+ CopyCheckGlyph,+ useCopied,+ writeClipboard,+} from "../../components/ui/copy-button";+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 {+ CloseIcon,+ DOWNLOAD_ICON,+ EXTERNAL_LINK_ICON,+ FILE_EDIT_ICON,+ REFRESH_ICON,+ UPLOAD_ICON,+ WRAP_TEXT_ICON,+} from "../../components/ui/icons";+import { Input, noAutofill } from "../../components/ui/input";import { ZoomableImage } from "../../components/ui/image-zoom";import { SkeletonList } from "../../components/ui/skeleton";+import { Tooltip } from "../../components/ui/tooltip";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { ICON_SIZE } from "../../lib/icon-scale";+import { STAT_ICONS } from "../../lib/stat-icons";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 { CodeSurface } from "./code-block";import { languageForExtension } from "./code-languages";import { WorkspaceFileEditor } from "./workspace-editor";+import { WorkspaceFileMenuRows } from "./workspace-file-menu";+import type { FileMenuTarget } from "./workspace-file-menu";import { WorkspaceTreeView } from "./workspace-tree-view";import type { TreeToggle } from "../../components/ui/file-tree";-/** 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;+/**+ * Above this, a Markdown file opens in the source view rather than rendered. Highlighting moved to+ * a worker and no longer needs a ceiling, but rendering Markdown is remark parsing plus a React+ * tree, both on the main thread — so this one is still a real cost and still has to be bounded.+ * The reader can switch to the rendered view themselves, which makes it their informed choice.+ */+const MD_RENDER_LIMIT = 64 * 1024;+/** Bytes examined to decide whether a file with an unknown extension is text. */const SNIFF_BYTES = 8 * 1024;+/** How long the search box settles before the query is sent. A Workspace walk is not free, and nobody reads results for a prefix they are still typing. */+const SEARCH_DEBOUNCE_MS = 250;/** 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. */@@ -257,14 +299,113 @@ function blobToBase64(blob: Blob): Promise<string> {});}-/** The tree row under a pointer, read off the row's data attributes. */-function hitRow(target: EventTarget | null): { kind: "dir" | "file"; path: string } | null {+/**+ * The tree row under a pointer, read off the row's data attributes — the drop hit test and+ * the context menu both resolve their target this way rather than through a handler per row,+ * which a tree of hundreds of rows cannot afford. The element travels with the answer because+ * the menu anchors and returns focus to it.+ */+function hitRow(+ target: EventTarget | null,+): { kind: "dir" | "file"; path: string; el: HTMLElement } | 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;+ return (kind === "dir" || kind === "file") && path !== undefined ? { kind, path, el: row } : null;+}++/**+ * Why the confirm button is not offered yet. The action needs the file's current version, and+ * until that read lands there is nothing to refuse an overwrite with — so the dialog says which+ * of the two it is rather than leaving a dead button with no explanation.+ */+function FileActionVersionNote({ target }: { target: FileActionTarget | null }) {+ if (target === null || target.version !== null) return null;+ return (+ <p+ className={`text-xs ${target.reading ? "text-gray-500 dark:text-gray-400" : toneInk.danger}`}+ >+ {target.reading ? S.files.actionVersionReading : S.files.actionVersionFailed}+ </p>+ );+}++/** A file a rename or a delete has been asked about, and how far the read of its version got. */+interface FileActionTarget {+ path: string;+ /** Non-null once the version is known; the action is refused until then. */+ version: string | null;+ /** True while the read is still in flight — which is what tells "not yet" from "could not". */+ reading: boolean;+}++/** A selection the preview offered to the conversation, with the source lines it covers when they could be resolved. */+interface PreviewSelection {+ text: string;+ fromLine?: number;+ toLine?: number;+ /**+ * The selected range itself, cloned at the gesture. Handing the block to the composer+ * focuses its textarea, and focusing a text field drops whatever the document had+ * selected — so the highlight has to be put back by hand afterwards (restoreSelection).+ */+ range: Range;+}++/**+ * Puts `range` back as the document's one selection, a frame after the caller hands text to+ * the composer: the composer focuses its textarea inside a requestAnimationFrame of its own,+ * scheduled first, and that focus is what clears the selection this restores.+ *+ * A range whose ends have since left the document is dropped rather than re-applied — the+ * preview it was read from is no longer on screen, and re-selecting detached nodes would+ * either throw or select nothing.+ */+function restoreSelection(range: Range): void {+ requestAnimationFrame(() => {+ if (!range.startContainer.isConnected || !range.endContainer.isConnected) return;+ const selection = window.getSelection();+ if (selection === null) return;+ selection.removeAllRanges();+ selection.addRange(range);+ });+}++/**+ * The text selected inside `host`, or null when there is none, when it lies elsewhere on the+ * page, or when it is only whitespace. `lines` are the rendered source lines to measure the+ * range against — empty for the rendered Markdown and HTML views, which have no line+ * structure to honestly report, so those give up the range and keep the text.+ */+function readSelection(+ host: HTMLElement | null,+ lines: readonly HTMLElement[],+): PreviewSelection | null {+ if (host === null) return null;+ const selection = window.getSelection();+ if (selection === null || selection.isCollapsed || selection.rangeCount === 0) return null;+ const range = selection.getRangeAt(0);+ if (!host.contains(range.commonAncestorContainer)) return null;+ const text = selection.toString();+ if (text.trim() === "") return null;+ // Cloned, not held: the live range moves with the selection, and the selection is about to+ // be cleared by the composer taking focus.+ const captured = range.cloneRange();+ // Which lines the range actually touches, asked of the DOM rather than inferred from the+ // text: a selection that starts or ends on a line boundary lands on a node between the line+ // spans, where walking up from the boundary finds no line at all.+ let from = -1;+ let to = -1;+ for (const [i, line] of lines.entries()) {+ if (!range.intersectsNode(line)) continue;+ if (from < 0) from = i;+ to = i;+ }+ return from < 0+ ? { text, range: captured }+ : { text, range: captured, fromLine: from + 1, toLine: to + 1 };}/**@@ -310,22 +451,28 @@ function crumbItemWidth(text: string): number {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 panel's actions, with their names taken off them: a square the size of the tree toggle, drawn in+ * the toolbar and in the preview header alike so the panel's two rows of marks line up. A+ * control with no visible text needs its name in two places to be readable at all — the+ * element's own `aria-label`, and the Tooltip it is wrapped in.+ */+const iconActionBase =+ "inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors duration-150";+const iconActionIdle =+ "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";+const iconActionClass = `${iconActionBase} ${iconActionIdle}`;-/** 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"- }`;+/** The same square, as a toggle: pressed is a filled resting state, not a hover that happens to stick. */+const iconToggleClass = (on: boolean): string =>+ `${iconActionBase} ${on ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100" : iconActionIdle}`;export function WorkspaceBrowser({session,openRequest,active,reloadSignal,+ onAddReference,}: {session: SessionInfo;/** External navigation command (from clicking a file chip in a message): opens the tree@@ -344,6 +491,18 @@ export function WorkspaceBrowser({* so the initial value is irrelevant and no edge tracking is needed.*/reloadSignal?: number;+ /**+ * Puts a Workspace reference into the conversation's composer at its caret — the context+ * menu's "add to conversation". The panel composes the text (a `@path`, or a fenced block+ * around a preview selection) and says how it should sit; where the caret is, and what is+ * already typed around it, are the composer's own business.+ */+ /**+ * Stages what the panel contributes in the composer as a chip: a file, a directory, or a+ * quoted range. All three are whole things rather than words in a sentence, so none of them+ * is spliced into the draft the user is writing.+ */+ onAddReference: (reference: ComposerReference) => void;}) {// Whether the HTML preview lands on a separate origin. True routes both the in-app// rendered view and "open in new tab" through the preview origin; false downgrades@@ -367,8 +526,19 @@ export function WorkspaceBrowser({/** 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. */+ /** The search box's text. Deliberately not persisted: a search is a thing you are doing, not a setting. */const [query, setQuery] = useState("");+ /**+ * The server's answer for the query the box currently holds — null while none has arrived for+ * it, which is also how the tree tells "still looking" from "nothing there".+ */+ const [searchResult, setSearchResult] = useState<{+ hits: WorkspaceSearchHit[];+ truncated: boolean;+ } | null>(null);+ const [searchError, setSearchError] = useState<string | null>(null);+ /** Which search each in-flight answer belongs to; an older one must not overwrite a newer. */+ const searchSeq = useRef(0);/** The directory last opened or closed, so the tree animates exactly that subtree once. */const [toggled, setToggled] = useState<TreeToggle | null>(null);// -------------------------------------------------------------------- preview / editor@@ -383,6 +553,20 @@ export function WorkspaceBrowser({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 file a rename or a delete is being asked about, and the version it carried when the+ * dialog opened.+ *+ * The version is read at the dialog rather than taken from whatever the preview last loaded:+ * what it guards is the Agent rewriting the file while the question is on screen, and a+ * marker from five minutes ago would refuse actions nobody needed warning about. Until it+ * arrives the action is not offered at all — an unconditional move or delete is exactly the+ * thing this is here to prevent.+ */+ const [renameTarget, setRenameTarget] = useState<FileActionTarget | null>(null);+ const [renameDraft, setRenameDraft] = useState("");+ const [removeTarget, setRemoveTarget] = useState<FileActionTarget | null>(null);+ const [fileActionBusy, setFileActionBusy] = useState(false);/** The open "discard unsaved changes?" question, resolving with the answer. */const [discardPrompt, setDiscardPrompt] = useState<{ resolve: (ok: boolean) => void } | null>(null,@@ -411,13 +595,33 @@ export function WorkspaceBrowser({/** 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());+ /** Soft wrap, shared by the source view and the editor so Edit reflows nothing (see parseWrapLines). */+ const [wrapLines, setWrapLines] = useState(() => readWrapLines());+ /**+ * The preview header's copy action. Driven by the hook rather than a plain CopyButton+ * because the tooltip is a Tooltip panel here, not a `title`, and a trigger may carry only+ * one of the two — the glyph swap and the live region are the ones copy-button.tsx owns.+ */+ const { copied, flash: flashCopy } = useCopied();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);+ // ----------------------------------------------------------------------- context menus+ // One hook per surface, not per row: each carries a long-press timer, and the tree draws+ // hundreds of rows — twice over while a closing subtree animates out. The row a gesture+ // landed on is resolved from the event instead, and held here for as long as its menu is up.+ const treeMenu = useRowContextMenu();+ const [treeMenuTarget, setTreeMenuTarget] = useState<FileMenuTarget | null>(null);+ const previewMenu = useRowContextMenu();+ /** The selection the preview's menu was opened over; null when there was none inside it. */+ const [menuSelection, setMenuSelection] = useState<PreviewSelection | null>(null);+ const previewBodyRef = useRef<HTMLDivElement | null>(null);+ /** The directory the menu's own picker uploads into (the toolbar's picker always means the current one). */+ const menuUploadDir = useRef("");+ const menuUploadRef = useRef<HTMLInputElement | null>(null);// Mirrors for the async flows and stable callbacks below, which must read the latest// value without re-creating themselves on every change.@@ -431,6 +635,8 @@ export function WorkspaceBrowser({currentDirRef.current = currentDir;const previewRef = useRef(preview);previewRef.current = preview;+ const richViewRef = useRef(richView);+ richViewRef.current = richView;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. */@@ -469,6 +675,12 @@ export function WorkspaceBrowser({setUploading(null);setPendingUpload(null);setSaving(false);+ // An open menu points at a path in the Session that just left; its actions would run+ // against this one.+ treeMenu.close();+ previewMenu.close();+ setTreeMenuTarget(null);+ setMenuSelection(null);previewSeq++;}@@ -641,10 +853,10 @@ export function WorkspaceBrowser({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 && kind === "md" && content.length > HIGHLIGHT_LIMIT && nonce === previewSeq) {+ // Oversized Markdown defaults to the source view: feeding the whole block to remark is a+ // main-thread cost the highlighting worker does nothing about (see MD_RENDER_LIMIT). The+ // reader can still switch to the rendered view, which makes it their informed choice.+ if (!refresh && kind === "md" && content.length > MD_RENDER_LIMIT && nonce === previewSeq) {setRichView("source");}present({@@ -751,6 +963,99 @@ export function WorkspaceBrowser({[promptDiscard, discardEditor],);+ /**+ * Puts one of the two file actions on screen and starts reading the file's current version.+ *+ * The dialog opens first and the version lands in it: waiting for a round trip before showing+ * anything would make a menu click feel broken. A dirty editor is asked about before either,+ * through the same guard navigation uses — both actions move the file out from under it.+ */+ const beginFileAction = useCallback(+ (path: string, kind: "rename" | "delete") => {+ void navigateGuarded(null, () => {+ const opened: FileActionTarget = { path, version: null, reading: true };+ if (kind === "rename") {+ setRenameDraft(path);+ setRenameTarget(opened);+ } else {+ setRemoveTarget(opened);+ }+ const settle = (version: string | null) => {+ const next = (t: FileActionTarget | null): FileActionTarget | null =>+ t !== null && t.path === path ? { path, version, reading: false } : t;+ if (kind === "rename") setRenameTarget(next);+ else setRemoveTarget(next);+ };+ void fetchFileVersion(api.workspaceFileUrl(sessionIdRef.current, path))+ .then(settle)+ .catch(() => settle(null));+ });+ },+ [navigateGuarded],+ );++ /**+ * Reports the one failure both actions share. Nothing was changed, so this is a toast and not+ * a dialog: there is no decision left to take, only the same action again on the file as it+ * now is.+ */+ const reportFileActionError = (err: unknown, path: string): void => {+ if (err instanceof ApiError && err.code === "file_changed") {+ toastError(S.files.changedBeforeAction(baseName(path)));+ } else if (err instanceof ApiError && err.code === "target_exists") {+ toastError(S.files.renameTargetExists(renameDraft.trim()));+ } else {+ toastError(apiErrorText(err));+ }+ };++ const applyRename = async (): Promise<void> => {+ const target = renameTarget;+ const to = renameDraft.trim();+ if (target === null || target.version === null || fileActionBusy) return;+ if (to === "" || to === target.path) {+ setRenameTarget(null);+ return;+ }+ setFileActionBusy(true);+ try {+ await api.moveWorkspaceFile(sessionIdRef.current, {+ from: target.path,+ to,+ ifVersion: target.version,+ });+ setRenameTarget(null);+ // The file did not stop existing, it moved: the panel follows it rather than emptying.+ if (selectedPath === target.path) {+ setSelectedPath(to);+ setCurrentDir(parentDir(to));+ }+ refreshAll();+ toastSuccess(S.files.renamed(baseName(to)));+ } catch (err) {+ reportFileActionError(err, target.path);+ } finally {+ setFileActionBusy(false);+ }+ };++ const applyDelete = async (): Promise<void> => {+ const target = removeTarget;+ if (target === null || target.version === null || fileActionBusy) return;+ setFileActionBusy(true);+ try {+ await api.deleteWorkspaceFile(sessionIdRef.current, target.path, target.version);+ setRemoveTarget(null);+ if (selectedPath === target.path) setSelectedPath(null);+ refreshAll();+ toastSuccess(S.files.deleted(baseName(target.path)));+ } catch (err) {+ reportFileActionError(err, target.path);+ } finally {+ setFileActionBusy(false);+ }+ };+/*** 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@@ -889,6 +1194,38 @@ export function WorkspaceBrowser({* 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.*/+ /**+ * The search runs on the server, over the whole Workspace — not over the rows the lazy tree+ * happens to have loaded, which made a match reachable only if its ancestors were already+ * open. Debounced because every keystroke would otherwise walk the tree again, and sequenced+ * because a slower answer for a shorter query must not land on top of a newer one.+ */+ useEffect(() => {+ const needle = query.trim();+ if (needle === "") {+ searchSeq.current += 1;+ setSearchResult(null);+ setSearchError(null);+ return;+ }+ const run = (searchSeq.current += 1);+ const timer = setTimeout(() => {+ void api+ .searchWorkspaceFiles(sessionId, needle)+ .then((res) => {+ if (searchSeq.current !== run) return;+ setSearchResult({ hits: res.hits, truncated: res.truncated });+ setSearchError(null);+ })+ .catch((e: unknown) => {+ if (searchSeq.current !== run) return;+ setSearchResult(null);+ setSearchError(apiErrorText(e));+ });+ }, SEARCH_DEBOUNCE_MS);+ return () => clearTimeout(timer);+ }, [query, sessionId]);+const openDirForFilter = useCallback((dir: string) => {setCurrentDir(dir);@@ -898,6 +1235,15 @@ export function WorkspaceBrowser({[loadDir],);+ /** A directory hit is somewhere to go, not something to unfold: opening one leaves the search behind and lands the tree there. */+ const openDirFromSearch = useCallback(+ (dir: string) => {+ setQuery("");+ openDirForFilter(dir);+ },+ [openDirForFilter],+ );+const backToTree = (): void => {void navigateGuarded(null, () => {setSelectedPath(null);@@ -912,8 +1258,8 @@ export function WorkspaceBrowser({};const setWrap = (wrap: boolean): void => {- setEditorWrap(wrap);- writeEditorWrap(wrap);+ setWrapLines(wrap);+ writeWrapLines(wrap);};// ------------------------------------------------------------------------- tree width@@ -1143,6 +1489,165 @@ export function WorkspaceBrowser({if (files.length > 0) void stageUpload(files, currentDirRef.current);};+ /** The menu's own picker: same staging, but into the folder that was right-clicked. */+ const onMenuPick = (e: ChangeEvent<HTMLInputElement>): void => {+ const files = e.target.files ? [...e.target.files] : [];+ e.target.value = "";+ if (files.length > 0) void stageUpload(files, menuUploadDir.current);+ };++ // ------------------------------------------------------------------------ context menus++ const copyPath = (target: FileMenuTarget): void => {+ // A menu row cannot carry the copy button's own at-the-control feedback: the row acts and+ // the panel closes out from under it. A toast is the confirmation that survives that, and+ // it says the same word (sidebar.tsx's copy-id row does the same).+ writeClipboard(target.path);+ toastSuccess(S.common.copied);+ };++ const addToChat = (target: FileMenuTarget): void => {+ onAddReference({+ kind: target.kind,+ path: target.path,+ text: pathReference(target.path, target.kind),+ });+ };++ const uploadInto = (dir: string): void => {+ menuUploadDir.current = dir;+ menuUploadRef.current?.click();+ };++ /** Dismisses the row menu. Every action closes it first, so nothing runs under a panel still on screen. */+ const closeTreeMenu = (): void => {+ treeMenu.close();+ setTreeMenuTarget(null);+ };++ /**+ * The tree's context menu, hung on the whole pane. A gesture that lands between rows — the+ * search box, the empty space below the last row — resolves no target, so nothing is+ * suppressed and the browser's own menu stands, which is what the search box needs to be+ * pasteable into.+ */+ const treeMenuProps = {+ onContextMenu: (e: ReactMouseEvent) => {+ const row = hitRow(e.target);+ if (row === null) return;+ // Before the hook reads it: the anchor for a keyboard-synthesized contextmenu is the+ // row's own box, and the hook measures whatever `rowRef` currently points at.+ treeMenu.rowRef(row.el);+ setTreeMenuTarget({ path: row.path, kind: row.kind });+ treeMenu.rowProps.onContextMenu(e);+ },+ onKeyDown: (e: ReactKeyboardEvent) => {+ if (!isContextMenuKey(e)) return;+ // The roving tab stop is what has focus, so the event's own target is the row the+ // keyboard means — no separate lookup of "the focused row" is needed.+ const row = hitRow(e.target);+ if (row === null) return;+ e.preventDefault();+ treeMenu.rowRef(row.el);+ setTreeMenuTarget({ path: row.path, kind: row.kind });+ const r = row.el.getBoundingClientRect();+ treeMenu.openAt({ top: r.top, bottom: r.bottom, left: r.left, right: r.right });+ },+ onPointerDown: (e: ReactPointerEvent) => {+ // Only a press-and-hold opens from here; a mouse arrives through onContextMenu instead,+ // and running this for every click would re-render the panel on each one.+ if (!isLongPressPointer(e.pointerType)) return;+ const row = hitRow(e.target);+ if (row === null) return;+ treeMenu.rowRef(row.el);+ setTreeMenuTarget({ path: row.path, kind: row.kind });+ treeMenu.rowProps.onPointerDown(e);+ },+ onPointerMove: treeMenu.rowProps.onPointerMove,+ onPointerUp: treeMenu.rowProps.onPointerUp,+ onPointerCancel: treeMenu.rowProps.onPointerCancel,+ // A touch screen replays the held press as a click once the finger lifts, and a tree row's+ // click opens the file or the folder. Swallowed in the capture phase so the row never hears+ // it — the rows themselves know nothing about this menu.+ onClickCapture: (e: ReactMouseEvent) => {+ if (!treeMenu.consumeLongPressClick()) return;+ e.preventDefault();+ e.stopPropagation();+ },+ };++ /**+ * The rendered source lines a preview selection can be measured against — the source view's+ * own, and deliberately none in the rendered Markdown and HTML views. A Markdown body draws+ * code blocks of its own, whose line spans would answer with a line number belonging to some+ * other file; no range at all is the honest reading there.+ */+ const sourceLines = (host: HTMLElement | null): HTMLElement[] => {+ const p = previewRef.current;+ const source = p !== null && (p.kind === "text" || richViewRef.current === "source");+ return source && host !== null ? [...host.querySelectorAll<HTMLElement>(".line")] : [];+ };++ /**+ * The preview's context menu. Its target is always the file on screen, so the only thing to+ * resolve is whether a selection sits inside the preview — read at the gesture, by every+ * gesture that opens the menu, rather than when a row is clicked: focusing the menu can+ * collapse the live selection under it, and a selection read at the previous gesture may+ * since have been collapsed or belong to a file that is no longer open.+ */+ /**+ * Reads the selection the gesture landed on, and puts it back.+ *+ * Both halves are needed. Read, because focusing the menu can collapse the live selection,+ * so what the menu acts on has to be captured before the panel opens. Put back, because+ * that collapse is also visible: a right-click inside selected text would clear the+ * highlight the user made, on a gesture that was only asking what could be done with it.+ */+ const captureMenuSelection = (): void => {+ const host = previewBodyRef.current;+ const selection = readSelection(host, sourceLines(host));+ setMenuSelection(selection);+ if (selection !== null) restoreSelection(selection.range);+ };++ const openPreviewMenu = (e: ReactMouseEvent): void => {+ captureMenuSelection();+ previewMenu.rowProps.onContextMenu(e);+ };++ /** The keyboard's chord opens the same menu, so it re-reads the selection the same way. */+ const previewMenuKeyDown = (e: ReactKeyboardEvent): void => {+ if (isContextMenuKey(e)) captureMenuSelection();+ previewMenu.rowProps.onKeyDown(e);+ };++ /** Same as the row menu's: the preview's own links must not fire on the click a hold replays. */+ const previewMenuClickCapture = (e: ReactMouseEvent): void => {+ if (!previewMenu.consumeLongPressClick()) return;+ e.preventDefault();+ e.stopPropagation();+ };++ const addSelectionToChat = (p: Preview, selection: PreviewSelection): void => {+ onAddReference({+ path: p.path,+ text: selectionBlock({+ path: p.path,+ language: languageForExtension(extOf(p.name)),+ selection: selection.text,+ fromLine: selection.fromLine,+ toLine: selection.toLine,+ }),+ kind: "quote",+ ...(selection.fromLine === undefined || selection.toLine === undefined+ ? {}+ : { fromLine: selection.fromLine, toLine: selection.toLine }),+ });+ // The text stays selected: contributing a quote to the conversation is not an edit to the+ // preview, and losing the highlight would cost the reader their place in the file.+ restoreSelection(selection.range);+ };+// -------------------------------------------------------------------------------- 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,@@ -1194,17 +1699,23 @@ export function WorkspaceBrowser({// ------------------------------------------------------------------------------ renderconst 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 rows = useMemo(+ () => (filter === "" ? flattenTree(listings, expanded) : searchRows(searchResult?.hits ?? [])),+ [listings, expanded, filter, searchResult],+ );const rootListing = listings.get("");+ /**+ * What the path strip names: the open file, or the current directory when none is open.+ * One strip rather than a directory row above a filename row — they are one fact, and the+ * two rows spent a whole line of a panel that can be very narrow saying it twice.+ *+ * visibleCrumbSegments fits tail first, so the file's own name is the last thing to go and+ * the leading directories collapse into a single "…" ahead of it.+ */+ const crumbTarget = selectedPath ?? currentDir;const crumbSegments =- currentDir === "" ? [S.files.root] : [S.files.root, ...currentDir.split("/")];- const crumbPath = currentDir === "" ? S.files.root : `${S.files.root}/${currentDir}`;+ crumbTarget === "" ? [S.files.root] : [S.files.root, ...crumbTarget.split("/")];+ const crumbPath = crumbTarget === "" ? S.files.root : `${S.files.root}/${crumbTarget}`;// 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.@@ -1216,61 +1727,173 @@ export function WorkspaceBrowser({const showTree = narrow ? selectedPath === null : treeVisible;const showPreview = narrow ? selectedPath !== null : true;const canEdit = preview !== null && editor === null && canEditPreview(preview);+ /** The source view is on screen: a text file, or Markdown/HTML with the toggle on Source. */+ const sourceShown =+ preview !== null &&+ (preview.kind === "text" ||+ ((preview.kind === "md" || preview.kind === "html") && richView === "source"));+ /** The file's text is on screen to read or to edit. Both present it the same way, so both take the Wrap toggle. */+ const textShown =+ sourceShown || (preview !== null && editor !== null && editor.path === preview.path);+ /** The upload picker's one name — its accessible name and its tooltip both — carrying the running count while an upload is in flight. */+ const uploadLabel =+ uploading !== null ? S.files.uploading(uploading.done, uploading.total) : S.files.upload;+ /** Likewise for the preview's external link, which folds the sandboxing caveat into its name when there is one. */+ const openInNewTabLabel = previewIsolated+ ? S.files.openInNewTab+ : `${S.files.openInNewTab}: ${S.files.previewNotIsolatedHint}`;const dirLabel = (dir: string): string => (dir === "" ? S.files.root : dir);const tree = (<divref={treePaneRef}+ {...treeMenuProps}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 !== "" && (+ {/* The tree pane's header: the search box, and the two actions that belong to the panel+ rather than to any one file — which is why they are here and not on the path row, where+ everything names the open file. Esc in a non-empty box clears it rather than reaching+ the dock or a dialog above, which is what that key means here. */}+ <div className="flex shrink-0 items-center gap-1 border-b border-gray-100 px-2 py-1.5 dark:border-gray-800">+ <div className="relative min-w-0 flex-1">+ <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 !== "" && (+ <button+ type="button"+ aria-label={S.files.searchClear}+ title={S.files.searchClear}+ onClick={() => setQuery("")}+ className="absolute right-1.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"+ >+ <CloseIcon size={12} />+ </button>+ )}+ </div>+ <Tooltip label={S.files.refresh} placement="bottom" className="shrink-0"><buttontype="button"- 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"+ aria-label={S.files.refresh}+ onClick={refreshAll}+ className={iconActionClass}>- <CloseIcon size={12} />+ <GlyphIcon d={REFRESH_ICON} size={ICON_SIZE.iconButton} /></button>- )}+ </Tooltip>+ {/* The picker's own input carries the name: a label with no text names nothing, and the+ glyph inside it is aria-hidden. While an upload runs the count is all the tooltip has+ left to say it with, so it goes there and the glyph becomes a spinner. */}+ <Tooltip label={uploadLabel} placement="bottom" className="shrink-0">+ <label+ className={`${iconActionClass} cursor-pointer focus-within:ring-2 focus-within:ring-gray-400/30`}+ >+ <HiddenFileInput+ multiple+ onChange={onPick}+ disabled={uploading !== null}+ aria-label={uploadLabel}+ />+ {uploading !== null ? (+ <span className="inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent" />+ ) : (+ <GlyphIcon d={UPLOAD_ICON} size={ICON_SIZE.iconButton} />+ )}+ </label>+ </Tooltip></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} />+ ) : searchError !== null ? (+ <p className="px-3 py-3 text-sm text-red-600 dark:text-red-400">{searchError}</p>+ ) : filter !== "" && searchResult === null ? (+ // No answer for this query yet. An empty list here would read as "nothing matches",+ // which is a different thing and the one answer that must not be guessed.+ <p className="px-3 py-3 text-xs text-gray-400 dark:text-gray-500">{S.files.searching}</p>) : (- <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}- />+ <>+ <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 : openDirFromSearch}+ onOpenFile={openFile}+ />+ {searchResult?.truncated === true && (+ <p className="shrink-0 border-t border-gray-100 px-3 py-1.5 text-[11px] text-gray-400 dark:border-gray-800 dark:text-gray-500">+ {S.files.searchTruncated(searchResult.hits.length)}+ </p>+ )}+ </>+ )}+ {/* The row menu. `contents` keeps this wrapper out of the pane's column: it draws no box+ of its own, the panel is portaled, and the anchor is the point the gesture landed on+ rather than this element (the same shape the sidebar's session row uses). */}+ {treeMenuTarget !== null && (+ <Dropdown+ open={treeMenu.open}+ // The target is not cleared here: a dismiss is not always believed (a touch screen+ // replays the held press as an outside click on the menu that gesture just opened),+ // and unmounting the panel on a dismiss the hook refused would close it anyway. It+ // is cleared where the menu really closes — an action, or the Session switching.+ setOpen={treeMenu.setOpen}+ portal={{ direction: "down", align: "left" }}+ anchorRect={treeMenu.anchor}+ anchorOwner={treeMenu.anchorOwner}+ // A tree row carries no button of its own, so the Dropdown's default return target+ // finds nothing: hand Escape back to the row itself.+ returnFocus={treeMenu.anchorOwner}+ className="contents"+ menuClass="w-max min-w-36 max-w-[calc(100vw-2rem)]"+ button={null}+ >+ <WorkspaceFileMenuRows+ target={treeMenuTarget}+ downloadHref={(path) => api.workspaceFileUrl(sessionId, path, true)}+ downloadName={baseName}+ onCopyPath={(t) => {+ closeTreeMenu();+ copyPath(t);+ }}+ onAddToChat={(t) => {+ closeTreeMenu();+ addToChat(t);+ }}+ onUploadInto={(dir) => {+ closeTreeMenu();+ uploadInto(dir);+ }}+ onRename={(t) => {+ closeTreeMenu();+ beginFileAction(t.path, "rename");+ }}+ onDelete={(t) => {+ closeTreeMenu();+ beginFileAction(t.path, "delete");+ }}+ onClose={closeTreeMenu}+ />+ </Dropdown>)}</div>);@@ -1298,6 +1921,25 @@ export function WorkspaceBrowser({/>);+ /**+ * Soft wrap. One toggle and one remembered answer for the source view and the editor alike —+ * they are the same file seen two ways, and a second preference would let Edit reflow the+ * file under the line the user was aiming at.+ */+ const wrapToggle = textShown && (+ <Tooltip label={S.files.wrapLines} placement="bottom" className="shrink-0">+ <button+ type="button"+ aria-pressed={wrapLines}+ aria-label={S.files.wrapLines}+ onClick={() => setWrap(!wrapLines)}+ className={iconToggleClass(wrapLines)}+ >+ <GlyphIcon d={WRAP_TEXT_ICON} size={ICON_SIZE.iconButton} />+ </button>+ </Tooltip>+ );+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">{(@@ -1323,185 +1965,431 @@ export function WorkspaceBrowser({</div>);+ /**+ * Copy and Edit, floated over the top-right of the file rather than parked in the title row.+ * Both act on the body underneath them — the text on screen — while the row above names the+ * file and carries what leaves it: the view toggle, wrap, the external link and download. The+ * pill keeps its own ground so two glyphs stay legible over whatever is beneath them, and it+ * sits clear of the reserved scrollbar gutter.+ *+ * Always drawn, never hover-revealed: a hover-only control is no control at all on a touch+ * screen, and Edit has no other way in from here.+ */+ const previewFloatingActions = preview !== null &&+ (wrapToggle !== false || canEdit || (sourceShown && preview.content !== undefined)) && (+ <div className="absolute right-4 top-2.5 z-10 flex items-center gap-0.5 rounded-md border border-gray-200 bg-white/85 p-0.5 shadow-sm backdrop-blur-sm dark:border-gray-700 dark:bg-gray-900/85">+ {/* Soft wrap is a property of the surface under the pill, and the editor lays its+ textarea over that same surface — so it rides here in both modes, which is also+ the only place the editor can reach it from. */}+ {wrapToggle}+ {/* Copies the text that was read, which is all of the file unless the preview was cut off. */}+ {sourceShown && preview.content !== undefined && (+ <>+ <Tooltip+ label={copied ? S.common.copied : S.chat.copyCode}+ placement="bottom"+ className="shrink-0"+ >+ <button+ type="button"+ aria-label={S.chat.copyCode}+ onClick={() => flashCopy(preview.content ?? "")}+ className={iconActionClass}+ >+ <CopyCheckGlyph copied={copied} size={ICON_SIZE.iconButton} />+ </button>+ </Tooltip>+ {/* Sibling, not a child: the button's accessible name stays the label, and the+ glyph swap is silent without this region. */}+ <CopiedStatus copied={copied} />+ </>+ )}+ {canEdit && (+ <Tooltip label={S.common.edit} placement="bottom" className="shrink-0">+ <button+ type="button"+ aria-label={S.common.edit}+ onClick={() => void startEdit()}+ className={iconActionClass}+ >+ <GlyphIcon d={FILE_EDIT_ICON} size={ICON_SIZE.iconButton} />+ </button>+ </Tooltip>+ )}+ {/* 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.++ Without a separate preview origin the page opens sandboxed, and the caveat joins+ the name rather than riding a ⚠ beside it: the name is all an icon-only control+ has, and the tooltip shows the same words so the two cannot disagree. The tint is+ a second carrier, never the only one. */}+ {/\.html?$/i.test(preview.name) && (+ <Tooltip label={openInNewTabLabel} placement="bottom" className="shrink-0">+ <a+ href={api.workspaceFilePreviewUrl(sessionId, preview.path)}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={openInNewTabLabel}+ className={`${iconActionClass} ${previewIsolated ? "" : toneInk.attention}`}+ >+ <GlyphIcon d={EXTERNAL_LINK_ICON} size={ICON_SIZE.iconButton} />+ </a>+ </Tooltip>+ )}+ </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 className="relative flex min-h-0 flex-1 flex-col">+ <div className="min-h-0 flex-1">+ <WorkspaceFileEditor+ path={editor.path}+ value={editor.draft}+ wrap={wrapLines}+ onChange={updateDraft}+ onSave={requestSave}+ />+ </div>+ {previewFloatingActions}</div>);}+ const selection = menuSelection;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={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"- />- ) : 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>+ <>+ {/* The floating actions' containing block. A positioned ancestor is required here and+ not optional: an absolute box inside a `static` scroller escapes to the initial+ containing block and gives the whole shell a second scrollbar (styles.css). */}+ <div className="relative flex min-h-0 flex-1 flex-col">+ {/* 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+ ref={(el) => {+ previewBodyRef.current = el;+ // The same element is the menu's keyboard anchor and its scroll owner: a scroll of+ // this box moves the point the panel hangs off.+ previewMenu.rowRef(el);+ }}+ onContextMenu={openPreviewMenu}+ onKeyDown={previewMenuKeyDown}+ onPointerDown={(e) => {+ // Only the press-and-hold path can open the menu from here, and only it is worth+ // walking the rendered lines for: an ordinary click would pay that on every click.+ if (isLongPressPointer(e.pointerType)) captureMenuSelection();+ previewMenu.rowProps.onPointerDown(e);+ }}+ onPointerMove={previewMenu.rowProps.onPointerMove}+ onPointerUp={previewMenu.rowProps.onPointerUp}+ onPointerCancel={previewMenu.rowProps.onPointerCancel}+ onClickCapture={previewMenuClickCapture}+ // Focusable only programmatically, and only so Escape has somewhere to hand focus+ // back to: the menu is anchored at this box, and a div with no tabindex would take+ // none, leaving focus on the body when the panel it was in unmounts. -1 keeps it out+ // of the tab order, and the outline is suppressed because the focus is a handover,+ // not a destination the user chose.+ tabIndex={-1}+ // The source view brings its own padding, and has to: the editor's textarea lies on+ // top of it, and only padding the two layers share keeps the typed text over the+ // highlighted text.+ className={`min-h-0 flex-1 overflow-auto outline-none [scrollbar-gutter:stable] ${+ sourceShown && preview?.content !== undefined ? "" : "p-3"+ }`}+ >+ {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={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"+ />+ ) : 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>+ ) : (+ <SkeletonList rows={6} />+ )+ ) : (+ // 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+ }+ 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={href} target="_blank" rel="noreferrer">+ {children}+ </a>+ );+ }+ 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 text itself, with no box around it — the same surface the editor lays its+ // textarea over, so Edit changes what you can do and nothing about what you see.+ // Wrapping is the Wrap toggle's business here; the message stream's own code+ // blocks still scroll sideways rather than wrap, which is a transcript's answer+ // and not a file viewer's.+ <>+ <CodeSurface+ language={languageForExtension(extOf(p.name))}+ code={p.content}+ highlight+ lineNumbers+ wrap={wrapLines}+ className="text-xs leading-relaxed"+ />+ {p.truncated && (+ <p className="px-3 pb-2 text-xs text-gray-400">… {S.files.previewTruncated}</p>+ )}+ </>+ )) : (- <SkeletonList rows={6} />- )- ) : (- // 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- }- 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={href} target="_blank" rel="noreferrer">- {children}- </a>- );- }- 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 className="text-sm text-gray-500 dark:text-gray-400">+ {S.files.previewUnsupported}+ </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>- )}- </>- )- ) : (- <p className="text-sm text-gray-500 dark:text-gray-400">{S.files.previewUnsupported}</p>- )}- </div>+ </div>+ {previewFloatingActions}+ </div>+ {/* The same menu the file's own tree row offers, plus the selection entry while there is+ one. A right-click inside the HTML or PDF preview never arrives here — those are+ iframes, and nothing on this side of them can hear it — so the menu is what the+ surrounding preview chrome offers. */}+ <Dropdown+ open={previewMenu.open}+ setOpen={previewMenu.setOpen}+ portal={{ direction: "down", align: "left" }}+ anchorRect={previewMenu.anchor}+ anchorOwner={previewMenu.anchorOwner}+ returnFocus={previewMenu.anchorOwner}+ className="contents"+ menuClass="w-max min-w-36 max-w-[calc(100vw-2rem)]"+ button={null}+ >+ <WorkspaceFileMenuRows+ target={{ path: p.path, kind: "file" }}+ downloadHref={(path) => api.workspaceFileUrl(sessionId, path, true)}+ downloadName={baseName}+ onCopyPath={(t) => {+ previewMenu.close();+ copyPath(t);+ }}+ onAddToChat={(t) => {+ previewMenu.close();+ addToChat(t);+ }}+ // Never reached: a preview is always a file, so the upload row is never drawn here.+ onUploadInto={uploadInto}+ onAddSelection={+ selection === null+ ? undefined+ : () => {+ previewMenu.close();+ addSelectionToChat(p, selection);+ }+ }+ onRename={(t) => {+ previewMenu.close();+ beginFileAction(t.path, "rename");+ }}+ onDelete={(t) => {+ previewMenu.close();+ beginFileAction(t.path, "delete");+ }}+ onClose={previewMenu.close}+ />+ </Dropdown>+ </>);};+ /**+ * What the path row offers for the file it names. A draft takes the row over: its two+ * decisions, and the state behind them, are the whole of what the row is for while one is+ * open, and a view toggle would be offering a view the draft is not in. Everything that+ * acts on the text rather than on the file rides the floating pill over it instead.+ */+ const fileRowActions =+ preview !== null &&+ preview.path === selectedPath &&+ (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>+ )}+ {/* Icon buttons, not text ones, so the row is the same height whether or not a draft+ is open: a `Button size="sm"` stands 29px against these 27px, and the header would+ grow by two pixels the moment Edit was pressed. The save keeps no primary tint —+ it opens a confirmation whose own button carries that weight. */}+ <Tooltip label={S.common.cancel} placement="bottom" className="shrink-0">+ <button+ type="button"+ aria-label={S.common.cancel}+ onClick={cancelEdit}+ disabled={saving}+ className={`${iconActionClass} disabled:opacity-40`}+ >+ <CloseIcon size={ICON_SIZE.iconButton} />+ </button>+ </Tooltip>+ <Tooltip+ label={saving ? S.common.saving : S.files.saveTitle}+ placement="bottom"+ className="shrink-0"+ >+ <button+ type="button"+ aria-label={S.common.save}+ onClick={requestSave}+ disabled={saving}+ className={`${iconActionClass} disabled:opacity-40`}+ >+ {saving ? (+ <span className="inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent" />+ ) : (+ <GlyphIcon d={STAT_ICONS.check} size={ICON_SIZE.iconButton} />+ )}+ </button>+ </Tooltip>+ </>+ ) : (+ <>+ {richToggle}+ <Tooltip label={S.files.download} placement="bottom" className="shrink-0">+ <a+ href={api.workspaceFileUrl(sessionId, preview.path, true)}+ download={preview.name}+ aria-label={S.files.download}+ className={iconActionClass}+ >+ <GlyphIcon d={DOWNLOAD_ICON} size={ICON_SIZE.iconButton} />+ </a>+ </Tooltip>+ </>+ ));+const previewPane = (<div className="flex min-h-0 min-w-0 flex-1 flex-col">{selectedPath === null ? (@@ -1518,113 +2406,7 @@ export function WorkspaceBrowser({) : 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>- </>- ) : (- <>- {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>- </>- )}- </div>- {previewBody(preview)}- </>+ previewBody(preview))}</div>);@@ -1637,10 +2419,25 @@ export function WorkspaceBrowser({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. */}+ {/* The panel's one header row: the way back or the tree toggle, the path of whatever is+ open, and what that file offers. It never wraps — the path strip absorbs all of the+ pressure, clipping and collapsing its leading segments, while the actions keep their+ width. Everything that acts on the text rather than on the file is in the floating+ pill over the body, and the panel's own actions (refresh, upload) sit in the tree+ pane's header beside its search box. */}<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 && !showTree && (+ <Tooltip label={S.files.backToList} placement="bottom" className="shrink-0">+ <button+ type="button"+ aria-label={S.files.backToList}+ onClick={backToTree}+ className={iconActionClass}+ >+ <GlyphIcon d={BACK_ICON} size={ICON_SIZE.iconButton} />+ </button>+ </Tooltip>+ )}{!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@@ -1671,35 +2468,34 @@ export function WorkspaceBrowser({{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>+ {crumbFit.visible.map((seg, i) => {+ const last = i === crumbFit.visible.length - 1;+ const { stem, ext } = splitFileName(seg);+ return (+ <Fragment key={`${i}-${seg}`}>+ {(crumbFit.collapsed || i > 0) && (+ <span className="shrink-0 text-gray-300 dark:text-gray-700">/</span>+ )}+ {last ? (+ // The name outranks everything else on the row. It does not shrink, so the+ // directories give way before it does — visibleCrumbSegments only estimates+ // their width, and whatever it gets wrong used to be paid by the name. When+ // the name alone outruns the strip it is the STEM that ellipsizes: the+ // extension is three characters that say what kind of file this is.+ <span className="flex min-w-0 max-w-full shrink-0 items-center font-medium text-gray-700 dark:text-gray-200">+ <span className="min-w-0 truncate">{stem}</span>+ <span className="shrink-0">{ext}</span>+ </span>+ ) : (+ <span className="min-w-0 shrink truncate text-gray-500 dark:text-gray-400">+ {seg}+ </span>+ )}+ </Fragment>+ );+ })}</div>+ {fileRowActions}</div><div className="relative flex min-h-0 flex-1">@@ -1741,6 +2537,19 @@ export function WorkspaceBrowser({)}</div>+ {/* The menu's picker. Not the app's HiddenFileInput: that one stays Tab-focusable because+ a <label> wraps and names it, and this one has no label — it is opened by a menu row+ and must not sit in the tab order as an unnamed control. */}+ <input+ ref={menuUploadRef}+ type="file"+ multiple+ tabIndex={-1}+ aria-hidden+ className="hidden"+ onChange={onMenuPick}+ />+{/* Upload-overwrite confirmation: same-name files in the target directory get replaced. */}<ConfirmModalopen={pendingUpload !== null}@@ -1782,6 +2591,43 @@ export function WorkspaceBrowser({</p></ConfirmModal>+ {/* Rename or move: one field holding the whole Workspace-relative path, so a rename and a+ move are one action rather than two that differ only in how much of the path changed. */}+ <ConfirmModal+ open={renameTarget !== null}+ title={S.files.renameTitle}+ confirmLabel={S.files.renameConfirm}+ confirmDisabled={renameTarget?.version == null || renameDraft.trim() === ""}+ busy={fileActionBusy}+ tone="primary"+ onClose={() => setRenameTarget(null)}+ onConfirm={() => void applyRename()}+ >+ <Input+ label={S.files.renameLabel}+ size="sm"+ value={renameDraft}+ hint={S.files.renameHint}+ autoFocus+ {...noAutofill}+ onChange={(e) => setRenameDraft(e.target.value)}+ />+ <FileActionVersionNote target={renameTarget} />+ </ConfirmModal>+ <ConfirmModal+ open={removeTarget !== null}+ title={S.files.deleteTitle}+ confirmLabel={S.common.delete}+ confirmDisabled={removeTarget?.version == null}+ busy={fileActionBusy}+ onClose={() => setRemoveTarget(null)}+ onConfirm={() => void applyDelete()}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {S.files.deleteBody(removeTarget === null ? "" : baseName(removeTarget.path))}+ </p>+ <FileActionVersionNote target={removeTarget} />+ </ConfirmModal>{/* Write-precondition conflict: the file changed after the editor opened it, so thesave was refused with nothing written. Cancel keeps the draft and the editor. */}<ConfirmModaldiff --git a/packages/web/src/features/chat/workspace-editor.tsx b/packages/web/src/features/chat/workspace-editor.tsxindex 29b7dc8b..356c932a 100644--- a/packages/web/src/features/chat/workspace-editor.tsx+++ b/packages/web/src/features/chat/workspace-editor.tsx@@ -1,15 +1,31 @@/**- * 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.+ * The Files panel's in-place text editor: the same highlighted code surface the source view+ * shows, with a textarea laid over it that holds the caret and the selection and nothing else.+ * The text you see is the surface's; the text you type into has `color: transparent`. So+ * editing a file looks exactly like reading it — same line numbers, same colours, same+ * wrapping — and pressing Edit reflows nothing.+ *+ * The two layers are stacked in a single grid cell (styles.css's `.code-editor`), so the taller+ * one sizes the box and the one scroll container carries both. Nothing is synchronised in JS,+ * which is what makes it impossible for them to drift apart: there is only one scroll position.+ * What they do have to agree on is every metric that decides where a glyph lands — family,+ * size, line height, letter spacing, tab size, padding, wrap mode — and those are stated once,+ * for both layers, in `.code-surface`.+ *+ * 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 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 { useEffect, useRef, useState } from "react";import type { KeyboardEvent as ReactKeyboardEvent } from "react";import { S } from "../../lib/strings";-import { baseName } from "../../lib/workspace-tree";+import { TEXT_PREVIEW_LIMIT, baseName, extOf } from "../../lib/workspace-tree";+import { CodeSurface } from "./code-block";+import { languageForExtension } from "./code-languages";++/** Quiet period before re-highlighting, so a keystroke costs a re-render and not a tokenize. */+const EDIT_HIGHLIGHT_SETTLE_MS = 200;export function WorkspaceFileEditor({path,@@ -29,6 +45,9 @@ export function WorkspaceFileEditor({useEffect(() => {ref.current?.focus();}, []);+ // An IME writes its candidate text into the textarea before it reaches `value`, and the+ // textarea's text is transparent — so the layers swap for the length of the composition.+ const [composing, setComposing] = useState(false);const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>): void => {if ((e.ctrlKey || e.metaKey) && !e.altKey && e.key.toLowerCase() === "s") {@@ -38,22 +57,40 @@ export function WorkspaceFileEditor({};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"}- // font-mono text-xs, not the chat composer's text-base: this is a code surface, where- // fitting a long line without wrapping and seeing indentation line up matters more than- // reading comfort. The two full-height typing surfaces differ because prose and code do.- 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" : ""- }`}- />+ <div+ // The composing flag rides on the scroll box so the CSS can swap the layers without the+ // surface needing to know an IME exists.+ data-composing={composing}+ className="code-editor-host h-full min-h-0 overflow-auto text-xs leading-relaxed"+ >+ <CodeSurface+ language={languageForExtension(extOf(baseName(path)))}+ code={value}+ // The editor colours whatever it can hold: tokenizing runs on a worker, so a large+ // file costs latency on the colours rather than a stalled editor, and a ceiling of its+ // own would only refuse to colour a file for no gain. The bound left is the preview+ // cap, which is all a load can put here; the settle delay keeps a burst of typing from+ // queueing a pass per keystroke.+ highlight={value.length <= TEXT_PREVIEW_LIMIT}+ settleMs={EDIT_HIGHLIGHT_SETTLE_MS}+ lineNumbers+ wrap={wrap}+ className="code-editor"+ >+ <textarea+ ref={ref}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={onKeyDown}+ onCompositionStart={() => setComposing(true)}+ onCompositionEnd={() => setComposing(false)}+ aria-label={S.files.editorLabel(baseName(path))}+ spellCheck={false}+ autoCapitalize="off"+ autoCorrect="off"+ wrap={wrap ? "soft" : "off"}+ />+ </CodeSurface>+ </div>);}diff --git a/packages/web/src/features/chat/workspace-file-menu.tsx b/packages/web/src/features/chat/workspace-file-menu.tsxnew file mode 100644index 00000000..98054e44--- /dev/null+++ b/packages/web/src/features/chat/workspace-file-menu.tsx@@ -0,0 +1,133 @@+/**+ * The Files panel's context-menu body: the rows a secondary click offers, shared by the two+ * surfaces that raise one — a tree row, and the preview of the file a tree row opened. Both+ * act on a single Workspace entry, so both draw the same rows from one place and cannot+ * drift into naming the same action two ways.+ *+ * The two entries that hold for either kind come first — copy the relative path, add a+ * reference to the conversation — and the kind-specific one comes last: a folder takes an+ * upload, a file gives a download. Download is an `<a download>` rather than a button, the+ * same shape the preview header already uses: it is the browser's own save, not a fetch this+ * app has to run.+ *+ * The rows reuse the session row menu's compact styling (see its module header, which already+ * declares itself shared beyond that row), so every overflow menu in the app reads the same.+ */+import { S } from "../../lib/strings";+import { STAT_ICONS } from "../../lib/stat-icons";+import {+ ADD_TO_CHAT_ICON,+ DOWNLOAD_ICON,+ FILE_EDIT_ICON,+ UPLOAD_ICON,+} from "../../components/ui/icons";+import {+ TRASH_ICON,+ overflowMenuDangerClass,+ overflowMenuGlyph,+ overflowMenuRowClass,+} from "../../components/ui/session-row-menu";++/** The one Workspace entry a menu is acting on. */+export interface FileMenuTarget {+ path: string;+ kind: "dir" | "file";+}++export function WorkspaceFileMenuRows({+ target,+ downloadHref,+ downloadName,+ onCopyPath,+ onAddToChat,+ onUploadInto,+ onAddSelection,+ onRename,+ onDelete,+ onClose,+}: {+ target: FileMenuTarget;+ /** The file's download URL; never asked for a directory. */+ downloadHref: (path: string) => string;+ downloadName: (path: string) => string;+ onCopyPath: (target: FileMenuTarget) => void;+ onAddToChat: (target: FileMenuTarget) => void;+ onUploadInto: (dir: string) => void;+ /**+ * Adds the text selected in the preview rather than the whole file. Offered only by the+ * preview, and only while a selection actually sits inside it — a tree row has nothing+ * selected to add.+ */+ onAddSelection?: () => void;+ /**+ * Renames or moves the file — one action, because both are the same write of a new path, and+ * offering them separately would mean asking which one the user meant. Files only: a+ * directory has no version marker, so the precondition that keeps this from overwriting the+ * Agent's work cannot be stated for one.+ */+ onRename?: (target: FileMenuTarget) => void;+ /** Deletes the file, behind a confirmation and the same precondition. */+ onDelete?: (target: FileMenuTarget) => void;+ /** Dismisses the panel. The button rows close through their own handlers; the download link, which acts by navigating, has only this. */+ onClose: () => void;+}) {+ return (+ <>+ <button type="button" className={overflowMenuRowClass} onClick={() => onCopyPath(target)}>+ {overflowMenuGlyph(STAT_ICONS.copy)}+ {S.files.copyPath}+ </button>+ <button type="button" className={overflowMenuRowClass} onClick={() => onAddToChat(target)}>+ {overflowMenuGlyph(ADD_TO_CHAT_ICON)}+ {S.files.addToChat}+ </button>+ {onAddSelection !== undefined && (+ <button type="button" className={overflowMenuRowClass} onClick={onAddSelection}>+ {overflowMenuGlyph(ADD_TO_CHAT_ICON)}+ {S.files.addSelectionToChat}+ </button>+ )}+ {target.kind === "dir" ? (+ <button+ type="button"+ className={overflowMenuRowClass}+ onClick={() => onUploadInto(target.path)}+ >+ {overflowMenuGlyph(UPLOAD_ICON)}+ {S.files.uploadHere}+ </button>+ ) : (+ <>+ <a+ href={downloadHref(target.path)}+ download={downloadName(target.path)}+ onClick={onClose}+ className={overflowMenuRowClass}+ >+ {overflowMenuGlyph(DOWNLOAD_ICON)}+ {S.files.download}+ </a>+ {/* The two that change the Workspace come last, after everything that only reads it,+ and the destructive one is last of all — the furthest row from where the pointer+ lands, in the red every other overflow menu gives a delete. */}+ {onRename !== undefined && (+ <button type="button" className={overflowMenuRowClass} onClick={() => onRename(target)}>+ {overflowMenuGlyph(FILE_EDIT_ICON)}+ {S.files.renameTitle}+ </button>+ )}+ {onDelete !== undefined && (+ <button+ type="button"+ className={overflowMenuDangerClass}+ onClick={() => onDelete(target)}+ >+ {overflowMenuGlyph(TRASH_ICON)}+ {S.common.delete}+ </button>+ )}+ </>+ )}+ </>+ );+}diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsxindex e9466ebe..c2d2bc8e 100644--- a/packages/web/src/features/models/models-page.tsx+++ b/packages/web/src/features/models/models-page.tsx@@ -69,6 +69,7 @@ import { Switch } from "../../components/ui/switch";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { Chevron } from "../../components/ui/chevron";import { GlyphIcon } from "../../components/ui/glyph-icon";+import { EXTERNAL_LINK_ICON } from "../../components/ui/icons";import { ProviderLogo } from "../../components/ui/provider-logo";import { SkeletonList } from "../../components/ui/skeleton";import { EmptyState } from "../../components/ui/empty-state";@@ -179,8 +180,6 @@ const TRASH_ICON ="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m3 0l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7m4 4v6m4-6v6";const KEY_ICON ="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4";-const EXTERNAL_LINK_ICON =- "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3";/** Arrow entering a door: authorize with the provider and come back with a key. */const SIGN_IN_ICON = "M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4M10 17l5-5-5-5M15 12H3";diff --git a/packages/web/src/features/skills/skill-icon-view.tsx b/packages/web/src/features/skills/skill-icon-view.tsxindex 4e05d77e..7dec1947 100644--- a/packages/web/src/features/skills/skill-icon-view.tsx+++ b/packages/web/src/features/skills/skill-icon-view.tsx@@ -12,6 +12,7 @@* rendered inline once it passes sanitizeSkillIcon (stroke uses currentColor, following text* color).*/+import { useMemo } from "react";import { GlyphIcon } from "../../components/ui/glyph-icon";import { BOOK_ICON } from "../chat/skill-use";import { sanitizeSkillIcon } from "./skill-icon";@@ -65,13 +66,17 @@ export function SkillIcon({className?: string;}) {const safe = sanitizeSkillIcon(icon);- if (!safe) return <GlyphIcon d={fallback} size={size} className={className} />;+ // Held stable across renders: React compares this prop by object identity and re-sets+ // `innerHTML` whenever it differs, so a literal in the JSX rebuilds the markup on every render+ // (see test/inner-html-stability.test.ts).+ const markup = useMemo(() => (safe ? { __html: safe } : undefined), [safe]);+ if (markup === undefined) return <GlyphIcon d={fallback} size={size} className={className} />;return (<spanaria-hiddenstyle={{ width: size, height: size }}className={`block shrink-0 [&>svg]:block [&>svg]:h-full [&>svg]:w-full ${className}`}- dangerouslySetInnerHTML={{ __html: safe }}+ dangerouslySetInnerHTML={markup}/>);}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 162237f5..4cc59efd 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1949,7 +1949,7 @@ Scenarios:removeImage: "Remove image",openAgents: "Agents panel",/** Panel switcher (chat toolbar top-right): the "create" dropdown and its pin toggles. */- workspacePanel: "Workspace",+ workspacePanel: "Files",filesInMessage: (n: number) => `${n} ${n === 1 ? "file" : "files"}`,imagesInMessage: (n: number) => `${n} ${n === 1 ? "image" : "images"}`,openPreview: "Click to preview",@@ -2512,6 +2512,11 @@ Scenarios:title: "Files",upload: "Upload",download: "Download",+ /** Row / preview context menu: the two entries both kinds carry, then the kind-specific one. */+ copyPath: "Copy relative path",+ addToChat: "Add to conversation",+ addSelectionToChat: "Add selection to conversation",+ uploadHere: "Upload here",openInNewTab: "Open in new tab",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.",@@ -2534,7 +2539,7 @@ Scenarios:`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",- htmlRendered: "Rendered",+ htmlRendered: "Preview",htmlSource: "Source",backToList: "Back to list",/** The tree pane: its accessible name and the toolbar toggle's two states. */@@ -2546,14 +2551,18 @@ Scenarios:/** 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",+ searchNoMatch: "No matches in the Workspace",+ /** The walk is server-side and covers the whole Workspace, so it is not instant on a large one. */+ searching: "Searching…",+ /** The server stopped at its cap: what is listed is the shallowest matches, not all of them. */+ searchTruncated: (n: number): string => `Too many matches — showing the first ${n}`,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",+ /** Soft-wrap toggle, shared by the source view and the editor: off means long lines scroll sideways. */+ wrapLines: "Wrap",unsaved: "Unsaved changes",saveTitle: "Save (Ctrl+S / ⌘S)",saveConfirmTitle: "Save file",@@ -2571,6 +2580,26 @@ Scenarios:changedOnDisk: "Changed on disk",changedOnDiskHint:"This file has been rewritten since you opened it — saving replaces that version with yours.",+ /** Rename and move are one action: both write the file to a new Workspace-relative path. */+ /** The composer chip's remove button, for whatever the Files panel staged there. */+ removeReference: "Remove reference",+ renameTitle: "Rename or move",+ renameLabel: "New path",+ renameHint:+ "Relative to the Workspace root; a directory in the path that does not exist is created",+ renameConfirm: "Move",+ renameTargetExists: (path: string): string => `${path} already exists, so nothing was changed.`,+ renamed: (name: string): string => `Moved to ${name}`,+ deleteTitle: "Delete file",+ deleteBody: (name: string): string => `Delete ${name}? It does not go to a trash folder.`,+ deleted: (name: string): string => `Deleted ${name}`,+ /** Both actions read the file's current version first; until it lands there is nothing to refuse an overwrite with. */+ actionVersionReading: "Reading this file's current version…",+ actionVersionFailed:+ "This file's current version could not be read, so the action is not offered.",+ /** The version precondition refused it: the Agent wrote the file while the question was on screen. */+ changedBeforeAction: (name: string): string =>+ `${name} was rewritten while you were deciding, most likely by the Agent during its turn, so nothing was changed. Refresh and try again.`,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.`,diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 4e726ca3..9ca3d313 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1920,7 +1920,7 @@ Benchmark:statsLabel: "统计信息",removeImage: "移除图片",openAgents: "智能体面板",- workspacePanel: "工作区",+ workspacePanel: "文件浏览",/** File summary card at the end of a message (Codex-style): title, inline preview action, and collapsed row. */filesInMessage: (n: number) => `${n} 个文件`,imagesInMessage: (n: number) => `${n} 张图片`,@@ -2472,6 +2472,11 @@ Benchmark:title: "文件",upload: "上传",download: "下载",+ /** Row / preview context menu: the two entries both kinds carry, then the kind-specific one. */+ copyPath: "复制相对路径",+ addToChat: "添加到对话",+ addSelectionToChat: "将选中内容添加到对话",+ uploadHere: "上传到此文件夹",openInNewTab: "新页面打开",previewNotIsolatedHint:"当前访问地址无法提供独立预览源,页面将以沙箱模式打开:localStorage、Cookie 与第三方 embed 不可用。经 127.0.0.1 或 localhost 访问,或配置 PENGUIN_PREVIEW_ORIGIN 即可解除。",@@ -2493,7 +2498,7 @@ Benchmark:overwriteConfirm: (n: number): string => `目标目录已存在以下 ${n} 个同名文件,上传将覆盖:`,loadFailed: "加载失败",previewTruncated: "内容过大,预览已截断,请下载查看完整文件",- htmlRendered: "渲染视图",+ htmlRendered: "预览",htmlSource: "源码",backToList: "返回列表",/** The tree pane: its accessible name and the toolbar toggle's two states. */@@ -2505,14 +2510,18 @@ Benchmark:/** The search box above the tree; it reaches only as far as the lazy tree has been loaded. */searchPlaceholder: "搜索文件",searchClear: "清除搜索",- searchNoMatch: "已加载的目录中没有匹配项",+ searchNoMatch: "Workspace 中没有匹配项",+ /** The walk is server-side and covers the whole Workspace, so it is not instant on a large one. */+ searching: "搜索中…",+ /** The server stopped at its cap: what is listed is the shallowest matches, not all of them. */+ searchTruncated: (n: number): string => `匹配项过多,仅显示最靠前的 ${n} 条`,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: "自动换行",+ /** Soft-wrap toggle, shared by the source view and the editor: off means long lines scroll sideways. */+ wrapLines: "自动换行",unsaved: "有未保存的修改",saveTitle: "保存(Ctrl+S / ⌘S)",saveConfirmTitle: "保存文件",@@ -2526,6 +2535,24 @@ Benchmark:/** The file was rewritten (by the Agent, most likely) while the editor was open on it. */changedOnDisk: "磁盘上已变更",changedOnDiskHint: "该文件在你打开之后已被重写,保存会用你的版本覆盖它。",+ /** Rename and move are one action: both write the file to a new Workspace-relative path. */+ /** The composer chip's remove button, for whatever the Files panel staged there. */+ removeReference: "移除引用",+ renameTitle: "重命名 / 移动",+ renameLabel: "新的路径",+ renameHint: "相对 Workspace 根目录;路径中不存在的目录会自动创建",+ renameConfirm: "移动",+ renameTargetExists: (path: string): string => `${path} 已存在,未做改动。`,+ renamed: (name: string): string => `已移动到 ${name}`,+ deleteTitle: "删除文件",+ deleteBody: (name: string): string => `删除 ${name}?该文件不会进入回收站。`,+ deleted: (name: string): string => `已删除 ${name}`,+ /** Both actions read the file's current version first; until it lands there is nothing to refuse an overwrite with. */+ actionVersionReading: "正在读取该文件的当前版本…",+ actionVersionFailed: "读不到该文件的当前版本,因此不执行此操作。",+ /** The version precondition refused it: the Agent wrote the file while the question was on screen. */+ changedBeforeAction: (name: string): string =>+ `${name} 在你决定期间被改写(多半是 Agent 在本轮写入的),因此未做任何改动。刷新后可重试。`,conflictTitle: "文件在磁盘上已变更",conflictBody: (name: string): string =>`${name} 在你打开之后被重写(多半是 Agent 本轮写的),本次没有保存任何内容。可以用你的版本覆盖它,也可以继续编辑、先把需要的内容取出来——两种选择都会保留你的文本。`,diff --git a/packages/web/src/lib/workspace-tree.ts b/packages/web/src/lib/workspace-tree.tsindex 1cff6da4..da664cce 100644--- a/packages/web/src/lib/workspace-tree.ts+++ b/packages/web/src/lib/workspace-tree.ts@@ -11,10 +11,13 @@* - 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.+ * - the persisted preferences (tree visibility, tree width, soft wrap) and the+ * unsaved-changes decision;+ * - what the panel's "add to conversation" puts in the composer — the `@path` reference,+ * the fenced block a preview selection becomes, and where each of them may be spliced+ * into a draft that is already half typed.*/-import type { WorkspaceFileEntry } from "@prismshadow/penguin-server/api";+import type { WorkspaceFileEntry, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";import { joinWorkspacePath } from "./file-path";import type { FileTreeRow } from "./file-tree";@@ -184,30 +187,32 @@ export function flattenTree(listings: Listings, expanded: ReadonlySet<string>):}/**- * 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.+ * The rows a whole-Workspace search draws: one per hit the server returned, flat, each naming+ * its full path rather than its base name.*- * 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.+ * Flat because there is no tree to place them in — a hit can sit in a directory the lazy tree+ * has never listed, and the hits are already ordered shallowest first, so nesting them would+ * mean loading every ancestor of every hit to draw scaffolding nobody asked for. The full path+ * because the base name is the part the reader just typed; where the file *is* is the answer+ * they are looking for.+ *+ * Every row is depth 0 and closed: a directory hit is somewhere to go, not something to unfold+ * in a list that is not a tree.*/-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)),- );+export function searchRows(hits: readonly WorkspaceSearchHit[]): TreeRow[] {+ return hits.map((hit, index) => ({+ path: hit.path,+ name: hit.path,+ kind: hit.kind,+ depth: 0,+ posInSet: index + 1,+ setSize: hits.length,+ expanded: false,+ loaded: hit.kind === "file",+ empty: false,+ sizeBytes: hit.sizeBytes,+ mtime: hit.mtime,+ }));}// -------------------------------------------------------------------------- breadcrumbs@@ -372,7 +377,7 @@ export function looksLikeText(bytes: Uint8Array): boolean {// ------------------------------------------------------------------------------ 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;+export const TEXT_PREVIEW_LIMIT = 1024 * 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;@@ -426,6 +431,7 @@ export interface TreePreferenceStorage {/** 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";+/** Soft wrap, shared by the source view and the editor (see parseWrapLines on why one value, and on the key's name). */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). */@@ -480,25 +486,130 @@ export function writeTreeWidth(width: number, storage?: TreePreferenceStorage):}}-/** 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;+/**+ * Tolerant parse of the soft-wrap preference: ON unless an explicit off spelling is stored.+ * Wrapping is what a reader wants of a file — a line that runs off the right edge has to be+ * chased to be read — and the same file being edited should not reflow on the way in.+ *+ * One value for both the source view and the editor, deliberately. They are the same file+ * seen two ways, and Edit swaps them in place: a separate preference would let pressing Edit+ * reflow the whole file and carry the line you were aiming at off the screen. The stored key+ * still reads `editorWrap` because the editor had the toggle first and a rename would silently+ * discard everyone's answer.+ */+export function parseWrapLines(raw: string | null): boolean {+ if (raw === null) return true;const value = raw.trim().toLowerCase();- return value === "1" || value === "true" || value === "on" || value === "yes";+ return !(value === "0" || value === "false" || value === "off" || value === "no");}-export function readEditorWrap(storage?: TreePreferenceStorage): boolean {+export function readWrapLines(storage?: TreePreferenceStorage): boolean {try {- return parseEditorWrap((storage ?? localStorage).getItem(EDITOR_WRAP_KEY));+ return parseWrapLines((storage ?? localStorage).getItem(EDITOR_WRAP_KEY));} catch {- return false;+ return true;}}-export function writeEditorWrap(wrap: boolean, storage?: TreePreferenceStorage): void {+export function writeWrapLines(wrap: boolean, storage?: TreePreferenceStorage): void {try {(storage ?? localStorage).setItem(EDITOR_WRAP_KEY, wrap ? "1" : "0");} catch {/* best-effort persistence (quota limits / private browsing) */}}++// -------------------------------------------------------------- composer references++/**+ * Something the Files panel hands the composer: what it points at, and the text the message+ * carries once it is sent.+ *+ * The text is deliberately kept out of the textarea. What the panel contributes is a whole+ * thing — a file, a directory, a quoted range — and the draft is where the person is writing;+ * splicing the one into the other buries what they were saying under what they were pointing+ * at. The composer shows a chip naming it instead, the same shape `/agent` and `/skill` already+ * stage their picks in.+ */+export interface ComposerReference {+ /** Which glyph the chip wears, and what its label means. */+ kind: "file" | "dir" | "quote";+ /** Workspace-relative path: the chip's label comes from its last segment, its tooltip from the whole. */+ path: string;+ /** What goes into the message. */+ text: string;+ /** 1-based and inclusive, on a `quote` whose place in the file could be resolved. */+ fromLine?: number;+ toLine?: number;+}++/**+ * A file name split for display: the stem, and the extension with its dot still on it.+ *+ * Only a real extension counts. A leading dot is part of the name — `.gitignore` is all stem —+ * and a name with no dot has no extension at all. Splitting it lets the stem ellipsize while the+ * extension stays: the extension is the shortest part and says what kind of thing this is, so it+ * is the last thing worth losing when the row runs out of room.+ */+export function splitFileName(name: string): { stem: string; ext: string } {+ const dot = name.lastIndexOf(".");+ return dot > 0 ? { stem: name.slice(0, dot), ext: name.slice(dot) } : { stem: name, ext: "" };+}++/**+ * A line range as `:12` or `:12-18` — the `file:line` form every editor and stack trace uses, which+ * is why it is written the same way in both languages and read the same way by the model.+ */+export function lineSuffix(fromLine: number, toLine: number): string {+ return fromLine === toLine ? `:${fromLine}` : `:${fromLine}-${toLine}`;+}++/**+ * The `@`-prefixed reference a Workspace entry inserts into the composer. The trailing+ * slash on a directory is the only thing in the string that says it is one; nothing parses+ * these — the `@` is there for the reader, not for a mention mechanism.+ */+export function pathReference(path: string, kind: "dir" | "file"): string {+ return kind === "dir" ? `@${path}/` : `@${path}`;+}++/** The longest run of backticks anywhere in `text`. */+function longestBacktickRun(text: string): number {+ let longest = 0;+ let run = 0;+ for (const ch of text) {+ if (ch !== "`") {+ run = 0;+ continue;+ }+ run += 1;+ if (run > longest) longest = run;+ }+ return longest;+}++/**+ * The fenced block a preview selection inserts: a `@path` header carrying the line range,+ * then the selection verbatim. The fence is opened one backtick longer than the longest run+ * the selection itself contains, so a selection that carries fences still nests correctly.+ * The selected text is neither trimmed nor re-indented — the block is what was on screen.+ */+export function selectionBlock({+ path,+ language,+ selection,+ fromLine,+ toLine,+}: {+ path: string;+ language: string;+ selection: string;+ /** 1-based and inclusive. Both are omitted where the selection's place in the file cannot be resolved — a guessed range would be a lie, so the header then carries the path alone. */+ fromLine?: number;+ toLine?: number;+}): string {+ const range = fromLine === undefined || toLine === undefined ? "" : lineSuffix(fromLine, toLine);+ const fence = "`".repeat(Math.max(3, longestBacktickRun(selection) + 1));+ const body = selection.endsWith("\n") ? selection : `${selection}\n`;+ return `@${path}${range}\n${fence}${language}\n${body}${fence}`;+}diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex e851d184..4c219aa0 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -590,18 +590,134 @@color: inherit;padding: 0;}-/* Shiki code block (features/chat/code-block.tsx): the outer component provides its own chrome (rounded- border + language label header), so this resets the inner pre's border/background/radius — overriding- both .md-body pre's styles and Shiki's own inline background colors (!important beats inline style), with- the dark background left to the outer dark:bg-*. Not scoped to .md-body: the Files preview's source view- isn't inside a markdown container. Dark text is overridden via the dual-theme inline variable- --shiki-dark, so switching themes doesn't require re-highlighting. */-.code-block pre {+/* The code surface (features/chat/code-block.tsx's CodeSurface) — the code itself, with no box+ around it. This resets the inner pre's border/background/radius, overriding both .md-body+ pre's styles and Shiki's own inline background colours (!important beats inline style); the+ background belongs to whatever the surface was dropped into. Not scoped to .md-body: the+ Files panel's source view is not inside a markdown container. Dark text is overridden via+ the dual-theme inline variable --shiki-dark, so switching themes never re-highlights.++ The metrics are stated once, for the pre AND for a textarea laid over it: the Files panel's+ editor is a transparent-text textarea on top of this very surface, and the two only stay in+ register while every value that decides where a glyph lands — family, size, line height,+ letter spacing, tab size, padding, wrap mode — is the same in both. Size and line height are+ inherited so one wrapper sets them for both layers. */+.code-surface :is(pre, textarea) {margin: 0;border: 0;border-radius: 0;background: transparent !important;+ /* The message code block's own padding, kept to the pixel so this refactor leaves the+ transcript exactly where it was; the Files panel's two layers only need to agree. */padding: 0.625rem 0.75rem;+ font-size: inherit;+ line-height: inherit;+ letter-spacing: normal;+ tab-size: 4;+ @apply font-mono;+}+.code-surface pre {+ @apply text-gray-800 dark:text-gray-200;+}+/* Wrapping is the file viewer's answer, never the message stream's: a transcript's code block+ scrolls sideways (see CodeBlock), and only a caller that asked for `wrap` gets this. Both+ layers need the textarea's own UA rule spelled out, because that is the one they must match. */+.code-wrap :is(pre, textarea) {+ white-space: pre-wrap;+ overflow-wrap: break-word;+}+.code-nowrap :is(pre, textarea) {+ white-space: pre;+ overflow-wrap: normal;+}+/* Grown to its content so a horizontal scroll has something to scroll, and so the sticky gutter+ below can travel the whole width — a sticky box cannot go past its containing block, which+ would otherwise be only as wide as the visible strip. */+.code-nowrap pre {+ min-width: max-content;+}++/* Line numbers. A counter over the per-line elements both rendering paths produce — Shiki's own+ `.line` wrappers and the same wrappers the unhighlighted fallback splits into — so the+ highlighter needs no changes and the two paths cannot disagree.++ The lines are blocks here (highlighter.ts strips the newlines Shiki puts between them), which+ is what makes the gutter survive wrapping: `padding-left` reserves the gutter on every visual+ row, and the negative `text-indent` pulls only the FIRST row back into it, so a wrapped line's+ continuation rows line up under its own code instead of under its number. The code therefore+ starts at exactly `--code-gutter` on every row, which is all an overlaid textarea has to+ match — it indents by that much and needs no per-line rule of its own.++ The number is generated content and `user-select: none`, so dragging across the code selects+ the code alone; the copy affordances are unaffected either way, since they copy the string the+ component was given and never the DOM. */+.code-lines pre {+ counter-reset: code-line;+}+.code-lines .line {+ display: block;+ counter-increment: code-line;+ padding-left: var(--code-gutter, 4ch);+ text-indent: calc(-1 * var(--code-gutter, 4ch));+}+.code-lines textarea {+ padding-left: calc(0.75rem + var(--code-gutter, 4ch));+}+.code-lines .line::before {+ content: counter(code-line);+ position: sticky;+ left: 0;+ display: inline-block;+ width: var(--code-gutter, 4ch);+ padding-right: 1.25ch;+ text-align: right;+ text-indent: 0;+ user-select: none;+ -webkit-user-select: none;+ @apply bg-white text-gray-400;+}+/* The dark half is spelled out rather than applied as a `dark:` variant: that variant appends+ its `:where(.dark, .dark *)` to the END of the selector, which for a pseudo-element is+ invalid CSS and is dropped without a word — the same reason the Shiki theme overrides below+ are written this way. */+html.dark .code-lines .line::before {+ @apply bg-gray-950 text-gray-600;+}++/* The editor's two layers, stacked in one grid cell so the taller of them sizes the box and a+ single scroll container moves both — no scroll syncing in JS, and so nothing to drift. The+ textarea keeps a visible caret over transparent text and must not scroll on its own. */+.code-editor {+ display: grid;+ min-height: 100%;+}+.code-editor > * {+ grid-area: 1 / 1;+}+.code-editor textarea {+ overflow: hidden;+ resize: none;+ color: transparent;+ outline: none;+ @apply caret-gray-900 dark:caret-gray-100;+}+/* The dark half is a rule of its own for the same reason as the gutter's above: a `dark:`+ variant appends its `:where(.dark, .dark *)` to the END of the selector, which after a+ pseudo-element is invalid CSS and is dropped from the build without a word. */+.code-editor textarea::selection {+ @apply bg-sky-200;+}+html.dark .code-editor textarea::selection {+ @apply bg-sky-500/40;+}+/* While an IME is composing, the candidate text lives only in the textarea's own rendering — it+ has not reached `value` on every platform — so the layers swap: the code layer steps aside and+ the textarea shows its own text, underline and all, until the composition commits. */+.code-editor-host[data-composing="true"] textarea {+ @apply text-gray-800 dark:text-gray-200;+}+.code-editor-host[data-composing="true"] .code-editor > :not(textarea) {+ visibility: hidden;}html.dark .shiki,html.dark .shiki span {diff --git a/packages/web/test/highlighter-worker.test.ts b/packages/web/test/highlighter-worker.test.tsnew file mode 100644index 00000000..b840efcd--- /dev/null+++ b/packages/web/test/highlighter-worker.test.ts@@ -0,0 +1,55 @@+/**+ * Highlighting must stay off the main thread, and the engine must stay out of the main bundle.+ *+ * Tokenizing is linear in the size of the input and runs to completion once it starts, so the+ * viewer's responsiveness depends on it happening in a worker. Two edits would quietly undo that+ * without failing a build or looking wrong in review: calling the engine directly from a+ * component, and turning the client's fallback `await import(…)` into a static import — which+ * bundles a second ~147KB copy of Shiki into the entry chunk for every reader whose worker works,+ * the very cost the split exists to avoid.+ *+ * vitest runs node-only here (`environment: "node"`, no jsdom), so this asserts against the+ * source text rather than a running worker.+ */+import { readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "../src");+const CHAT = join(SRC, "features/chat");++/** Every `.ts`/`.tsx` under src/, as [path relative to src, source text]. */+function sources(dir: string, rel = ""): Array<[string, string]> {+ const out: Array<[string, string]> = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const next = join(dir, entry.name);+ const label = rel === "" ? entry.name : `${rel}/${entry.name}`;+ if (entry.isDirectory()) out.push(...sources(next, label));+ else if (/\.tsx?$/.test(entry.name)) out.push([label, readFileSync(next, "utf8")]);+ }+ return out;+}++describe("the highlighting worker", () => {+ it("is what the client talks to", () => {+ const client = readFileSync(join(CHAT, "highlighter.ts"), "utf8");+ // `new URL(…, import.meta.url)` is the form Vite resolves into a bundled worker chunk; a+ // bare string path builds without complaint and 404s at runtime.+ expect(client).toMatch(+ /new Worker\(\s*new URL\("\.\/highlighter\.worker\.ts", import\.meta\.url\)/,+ );+ });++ it("owns the only static import of the engine", () => {+ const importers = sources(SRC)+ .filter(([, src]) => /^import\s(?!type\s)[^;]*from "[^"]*highlighter-core"/m.test(src))+ .map(([path]) => path);+ expect(importers).toEqual(["features/chat/highlighter.worker.ts"]);+ });++ it("leaves the client's own use of the engine dynamic, as its fallback", () => {+ const client = readFileSync(join(CHAT, "highlighter.ts"), "utf8");+ expect(client).toMatch(/await import\("\.\/highlighter-core"\)/);+ });+});diff --git a/packages/web/test/inner-html-stability.test.ts b/packages/web/test/inner-html-stability.test.tsnew file mode 100644index 00000000..3114949a--- /dev/null+++ b/packages/web/test/inner-html-stability.test.ts@@ -0,0 +1,57 @@+/**+ * `dangerouslySetInnerHTML` must be handed a value that keeps its identity across renders.+ *+ * React compares that prop by object identity, not by the markup inside it, and re-sets+ * `innerHTML` whenever the two differ. A fresh `{ __html }` literal in the JSX is therefore a+ * new object on every render, so every render of the surrounding component destroys and+ * rebuilds every node in the block — even when the markup is byte-identical.+ *+ * Two things break when that happens, and neither is visible in a screenshot. A text selection+ * the reader made inside the block is anchored to those nodes: replacing them collapses the live+ * Range, so a selection cannot survive so much as a sibling's state change — which is what made+ * the Files panel's "add selection to conversation" unable to keep its own highlight. And the+ * highlighted body is re-parsed by the browser on every keystroke that re-renders a streaming+ * transcript, for markup that did not change.+ *+ * vitest runs node-only here (`environment: "node"`, no jsdom), so this asserts against the+ * source text rather than a rendered DOM.+ */+import { readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "../src");++/** Every `.tsx` under src/, as [path relative to src, source text]. */+function sources(dir: string, rel = ""): Array<[string, string]> {+ const out: Array<[string, string]> = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const next = join(dir, entry.name);+ const label = rel === "" ? entry.name : `${rel}/${entry.name}`;+ if (entry.isDirectory()) out.push(...sources(next, label));+ else if (entry.name.endsWith(".tsx")) out.push([label, readFileSync(next, "utf8")]);+ }+ return out;+}++describe("dangerouslySetInnerHTML", () => {+ it("is never given an object literal built in the JSX", () => {+ // `dangerouslySetInnerHTML={{ __html: … }}` — the inline form, which is a new object every+ // render. The value has to come from a memo (or any other stable reference) instead.+ const inline = sources(SRC)+ .filter(([, src]) => /dangerouslySetInnerHTML=\{\{/.test(src))+ .map(([path]) => path);+ expect(inline).toEqual([]);+ });++ it("is used in exactly the two places that own untrusted markup", () => {+ // A third site is not forbidden, but it is worth noticing: each one is a place sanitisation+ // has to be argued, and each one carries the identity rule above.+ const users = sources(SRC)+ .filter(([, src]) => src.includes("dangerouslySetInnerHTML"))+ .map(([path]) => path)+ .sort();+ expect(users).toEqual(["features/chat/code-block.tsx", "features/skills/skill-icon-view.tsx"]);+ });+});diff --git a/packages/web/test/workspace-tree.test.ts b/packages/web/test/workspace-tree.test.tsindex 85de87d0..0972742c 100644--- a/packages/web/test/workspace-tree.test.ts+++ b/packages/web/test/workspace-tree.test.ts@@ -1,13 +1,16 @@/*** Files panel logic (lib/workspace-tree.ts): the tree's rows from lazily loaded listings,- * the search box's filter over them, where a drop lands, the narrow-layout+ * the rows a whole-Workspace search draws, 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.+ * nothing), the preferences' tolerant parses, when leaving the editor has to ask, and what+ * the panel's "add to conversation" puts in the composer.*/import { describe, expect, it } from "vitest";-import type { WorkspaceFileEntry } from "@prismshadow/penguin-server/api";+import type { WorkspaceFileEntry, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";import {+ type ComposerReference,+ type Listings,PREVIEW_MIN_WIDTH,TREE_LAYOUT_MIN_WIDTH,TREE_MIN_WIDTH,@@ -17,7 +20,7 @@ import {defaultTreeWidth,dropTargetDir,expandTo,- filterTreeRows,+ searchRows,flattenTree,isDirty,isNarrowLayout,@@ -25,23 +28,26 @@ import {maxTreeWidth,needsDiscardConfirm,parentDir,- parseEditorWrap,+ parseWrapLines,parseTreeVisible,parseTreeWidth,+ pathReference,previewKindFor,- readEditorWrap,+ readWrapLines,readTreeVisible,readTreeWidth,+ selectionBlock,+ splitFileName,+ lineSuffix,sortEntries,upsertEntry,utf8Complete,visibleCrumbSegments,withExpanded,- writeEditorWrap,+ writeWrapLines,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 => ({@@ -176,22 +182,34 @@ describe("layout", () => {});});-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"]);+describe("searchRows", () => {+ const hits: WorkspaceSearchHit[] = [+ { path: "notes.md", kind: "file", sizeBytes: 12, mtime: "2026-09-11T00:00:00.000Z" },+ { path: "a/deep", kind: "dir", sizeBytes: 0, mtime: "2026-09-11T00:00:01.000Z" },+ { path: "a/deep/notes.md", kind: "file", sizeBytes: 34, mtime: "2026-09-11T00:00:02.000Z" },+ ];++ it("names each hit by its whole path, because where it is is the part the query did not say", () => {+ // The base name is what the reader just typed; two hits called notes.md are told apart+ // only by the directory in front of them.+ expect(searchRows(hits).map((r) => r.name)).toEqual(["notes.md", "a/deep", "a/deep/notes.md"]);+ expect(searchRows(hits).map((r) => r.path)).toEqual(["notes.md", "a/deep", "a/deep/notes.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("draws a flat list, not a tree: every row is depth 0 and closed", () => {+ // A hit can live in a directory the lazy tree never listed, so there is nothing to nest it+ // under; an open directory row here would promise children the panel cannot draw.+ const rows = searchRows(hits);+ expect(rows.every((r) => r.depth === 0)).toBe(true);+ expect(rows.every((r) => !r.expanded)).toBe(true);+ expect(rows.map((r) => r.posInSet)).toEqual([1, 2, 3]);+ expect(rows.every((r) => r.setSize === 3)).toBe(true);});- 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([]);+ it("carries the size and time the row renderer shows, so a hit reads like a tree entry", () => {+ expect(searchRows(hits).map((r) => r.sizeBytes)).toEqual([12, 0, 34]);+ expect(searchRows(hits)[2]?.mtime).toBe("2026-09-11T00:00:02.000Z");+ expect(searchRows([])).toEqual([]);});});@@ -328,24 +346,24 @@ describe("tree width preference", () => {});});-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);+describe("soft wrap preference", () => {+ it("wraps unless an explicit off value is stored, so a stored answer survives the new default", () => {+ expect(parseWrapLines(null)).toBe(true);+ expect(parseWrapLines("garbage")).toBe(true);+ expect(parseWrapLines("1")).toBe(true);+ expect(parseWrapLines("0")).toBe(false);+ expect(parseWrapLines(" FALSE ")).toBe(false);});- it("round-trips through storage and reads as off when storage throws", () => {+ it("round-trips through storage and reads as on 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();+ expect(readWrapLines(storage)).toBe(true);+ writeWrapLines(false, storage);+ expect(readWrapLines(storage)).toBe(false);+ writeWrapLines(true, storage);+ expect(readWrapLines(storage)).toBe(true);+ expect(readWrapLines(brokenPreferences)).toBe(true);+ expect(() => writeWrapLines(false, brokenPreferences)).not.toThrow();});});@@ -369,3 +387,88 @@ describe("tree visibility preference", () => {expect(() => writeTreeVisible(false, brokenPreferences)).not.toThrow();});});++describe("splitFileName", () => {+ it("keeps the extension whole so it can outlive a truncated stem", () => {+ expect(splitFileName("workspace-browser.tsx")).toEqual({+ stem: "workspace-browser",+ ext: ".tsx",+ });+ expect(splitFileName("archive.tar.gz")).toEqual({ stem: "archive.tar", ext: ".gz" });+ });++ it("treats a leading dot as part of the name, and a name with no dot as all stem", () => {+ // `.gitignore` is not an extension on an empty name: splitting it there would ellipsize to+ // nothing and leave the row showing only a dot.+ expect(splitFileName(".gitignore")).toEqual({ stem: ".gitignore", ext: "" });+ expect(splitFileName("Makefile")).toEqual({ stem: "Makefile", ext: "" });+ expect(splitFileName("src")).toEqual({ stem: "src", ext: "" });+ });+});++describe("lineSuffix", () => {+ it("writes a range the way an editor and a stack trace do", () => {+ expect(lineSuffix(12, 18)).toBe(":12-18");+ expect(lineSuffix(7, 7)).toBe(":7");+ });+});++describe("composer references", () => {+ it("marks a directory with a trailing slash and leaves a file bare", () => {+ expect(pathReference("src/lib/tree.ts", "file")).toBe("@src/lib/tree.ts");+ expect(pathReference("src/lib", "dir")).toBe("@src/lib/");+ });+});++describe("what the panel hands the composer is a reference, not text for the draft", () => {+ const block = selectionBlock({+ path: "src/app.ts",+ language: "ts",+ selection: "const x = 1;",+ fromLine: 3,+ toLine: 3,+ });++ it("carries the text it will send and the file it came from", () => {+ // The chip shows the path; the block is what the message carries. Keeping the two on one+ // object is what lets the composer show one and send the other.+ const reference: ComposerReference = {+ kind: "quote",+ path: "src/app.ts",+ text: block,+ fromLine: 3,+ toLine: 3,+ };+ expect(reference.text).toContain("@src/app.ts:3");+ expect(reference.text).toContain("const x = 1;");+ expect(reference.path).toBe("src/app.ts");+ });++ it("still fences the quotation, so the composer could not have shown it as a line of the draft", () => {+ // The reason this is a chip at all: what it carries is a multi-line block, and splicing a+ // block into a half-typed sentence buries the sentence.+ expect(block.split("\n").length).toBeGreaterThan(2);+ expect(block).toMatch(/```/);+ });++ it("carries a file and a directory the same way, each naming its own kind", () => {+ // All three kinds go through one channel, so the composer has one chip to draw and the+ // panel has no second path that could put text in the draft again.+ const file: ComposerReference = {+ kind: "file",+ path: "src/app.ts",+ text: pathReference("src/app.ts", "file"),+ };+ const dir: ComposerReference = {+ kind: "dir",+ path: "src/lib",+ text: pathReference("src/lib", "dir"),+ };+ expect(file.text).toBe("@src/app.ts");+ expect(dir.text).toBe("@src/lib/");+ expect([file.kind, dir.kind]).toEqual(["file", "dir"]);+ // Neither carries a line range: a whole entry has no lines to name.+ expect(file.fromLine).toBeUndefined();+ expect(dir.fromLine).toBeUndefined();+ });+});diff --git a/packages/web/vite.config.ts b/packages/web/vite.config.tsindex 8011ff6b..a6d64528 100644--- a/packages/web/vite.config.ts+++ b/packages/web/vite.config.ts@@ -67,6 +67,10 @@ function katexWoff2Only(): Plugin {export default defineConfig({plugins: [react(), tailwindcss(), katexWoff2Only()],+ // The highlighting worker loads its themes and each grammar with a dynamic import, so its+ // bundle has to be code-split — and Vite's default worker format, IIFE, cannot be. Without this+ // the build fails outright rather than shipping something subtly wrong, which is the good case.+ worker: { format: "es" },server: {// Fixed PenguinHarness dev port (stands alone — vite configs cannot import core TS,// so the numbers are literals here; the allocation table lives in core's internal/ports.ts).