A local-first multi-agent app development platform, built on PenguinHarness
refactor(ui,web): W7 — files, the app shell and the dock move into the UI package (#906)
Yaowei Zheng685c6af2fba5
diff --git a/changelog/unreleased/2026-09-30-ui-migration-w7.md b/changelog/unreleased/2026-09-30-ui-migration-w7.mdnew file mode 100644index 00000000..d7c7cf97--- /dev/null+++ b/changelog/unreleased/2026-09-30-ui-migration-w7.md@@ -0,0 +1,39 @@+# Files, the app shell and the dock move into the shared UI package++- **Date:** 2026-09-30+- **Type:** refactor+- **Scope:** `ui`, `web`, `ui-gallery`++[中文版](2026-09-30-ui-migration-w7.zh.md)++W7 of the UI-package migration lifts the app's frame into `@prismshadow/penguin-ui`: the Files panel, the window with its sidebar and rail, and the dock. The containers keep their paths and their behaviour in the Web App.++## What moved++- **Files:** `FileTree`, `FileBrowser`, the file menu's rows, the in-place editor, and the Files panel's `TreePane`, `PreviewPane`, `DropOverlay` and `Breadcrumbs`. The pointer drag moves too, with the new `ResizeHandle` and `SplitPane`, which now carry the Files panel's split and both dock resizers.+- **Shell:** `AppShell`, `Rail`, `MobileTopBar`, `SidebarFrame` and `SessionRow`. The sidebar's page links are `NavRow`s, and a conversation's menu rows are `MenuItem`s.+- **Dock:** `DockFrame`, `DockTabs`, `DockPicker`, `PanelsToolbar`, and the floating launcher's `LauncherBall` and `LauncherFan`.++## Details++- The terminal's own light/dark palette stays in the Web App: it sits outside the token system by design.+- The launcher keeps its sizes. Its caption stays 13 px and now follows the text-size setting.+- The dock's tabs are a proper tab list (`role="tab"`).+- The nav column's hover and selected fills are washes of the text colour, and company mode's channel, desk and Temporary rows use them too.++## Visible changes in the default theme (Primer)++- **Sidebar and rails:**+ - Page links in the sidebar are one step lighter at rest (gray-600 → gray-500) and truncate instead of wrapping.+ - Rows sit 1 px closer.+ - A conversation's time is 12 px.+- **Files panel:**+ - Its split handle takes the info tone.+ - The floating pill and the chat drop veil lose their blur.+ - File sizes and the truncation note are 12 px.+- **Dock:**+ - Its handles use the same info tone.+ - The picker's shortcuts are key caps.+ - The bottom handle's cursor is `row-resize`.+ - On touch, the maximise button draws the registry's corner brackets, one pixel further out than before.+- **Dark mode:** the nav column's fill is the muted surface (#1a1a1a → #202020).diff --git a/changelog/unreleased/2026-09-30-ui-migration-w7.zh.md b/changelog/unreleased/2026-09-30-ui-migration-w7.zh.mdnew file mode 100644index 00000000..16bda2a5--- /dev/null+++ b/changelog/unreleased/2026-09-30-ui-migration-w7.zh.md@@ -0,0 +1,39 @@+# 文件、应用外壳与停靠面板迁入共享 UI 包++- **Date:** 2026-09-30+- **Type:** refactor+- **Scope:** `ui`, `web`, `ui-gallery`++[English](2026-09-30-ui-migration-w7.md)++UI 包迁移的 W7 把应用的框架拆分进 `@prismshadow/penguin-ui`:文件面板、带侧栏与图标栏的窗口,以及停靠面板。各容器的路径与行为保留在 Web App。++## 迁入的内容++- **文件**:`FileTree`、`FileBrowser`、文件菜单的行、原地编辑器,以及文件面板的 `TreePane`、`PreviewPane`、`DropOverlay`、`Breadcrumbs`。指针拖动随之迁入,并新增 `ResizeHandle` 与 `SplitPane`,现用于文件面板的分隔条与停靠面板的两个拖动条。+- **外壳**:`AppShell`、`Rail`、`MobileTopBar`、`SidebarFrame`、`SessionRow`;侧栏的页面链接改为 `NavRow`,对话的菜单行改为 `MenuItem`。+- **停靠面板**:`DockFrame`、`DockTabs`、`DockPicker`、`PanelsToolbar`,以及浮动启动器的 `LauncherBall` 与 `LauncherFan`。++## 细节++- 终端自身的明暗调色板留在 Web App:它按设计处在令牌体系之外。+- 启动器尺寸不变;说明文字保持 13 px,并随字号设置缩放。+- 停靠面板的标签改为标准的标签列表(`role="tab"`)。+- 导航列的悬停与选中底色改为文字色的淡填充,公司模式的频道行、工位行与「临时」分组的行同样采用。++## 通用主题下可见的变化++- **侧栏与图标栏**:+ - 侧栏的页面链接静止时浅一级(gray-600 → gray-500),过长时截断而不换行。+ - 各行间距收紧 1 px。+ - 对话的时间为 12 px。+- **文件面板**:+ - 分隔条取信息色调。+ - 浮动按钮组与对话区的拖放遮罩不再模糊。+ - 文件大小与截断提示为 12 px。+- **停靠面板**:+ - 拖动条同样取信息色调。+ - 选择面板的快捷键改为键帽样式。+ - 底部拖动条的光标为 `row-resize`。+ - 触屏上的最大化按钮改用图标注册表的四角括号,比原先向外多出 1 px。+- **深色模式**:导航列的底色改为次级表面(#1a1a1a → #202020)。diff --git a/packages/ui-gallery/src/library/boards/files.tsx b/packages/ui-gallery/src/library/boards/files.tsxindex a0d94038..cd64c3ab 100644--- a/packages/ui-gallery/src/library/boards/files.tsx+++ b/packages/ui-gallery/src/library/boards/files.tsx@@ -1,14 +1,47 @@-/** 文件: the app's FileTree over a demo workspace, and the read-only FileBrowser previewing its README. */+/**+ * 文件: the file tree over a demo workspace, the read-only file browser previewing its README,+ * the Files panel's two panes with the draggable split between them, the path strip at a width+ * that folds it, the file menu's rows for a file and a folder, the in-place editor and the two+ * shapes of drop feedback.+ */import { useState } from "react";-import { FileBrowser } from "../../../../web/src/components/ui/file-browser";-import type { FileBrowserPreview } from "../../../../web/src/components/ui/file-browser";-import { FileTree } from "../../../../web/src/components/ui/file-tree";-import type { TreeToggle } from "../../../../web/src/components/ui/file-tree";-import type { FileTreeRow } from "../../../../web/src/lib/file-tree";+import {+ Breadcrumbs,+ DropOverlay,+ FileBrowser,+ FileTree,+ GlyphIcon,+ ICONS,+ IconButton,+ PreviewPane,+ SplitPane,+ TreePane,+ WorkspaceFileEditor,+ WorkspaceFileMenuRows,+ menuPanelClass,+} from "@prismshadow/penguin-ui";+import type {+ FileBrowserPreview,+ FileTreeRow,+ PreviewView,+ TreeToggle,+} from "@prismshadow/penguin-ui";import { BoardGroup } from "../../foundations/shared";import { useGallery } from "../../state";import { DEMO_OPEN_DIRS, DEMO_TREE, demoSize, flattenTree } from "../demo-tree";+/** The demo's source file: code, the same in every language. */+const DEMO_SOURCE = `import { bm25 } from "./embed";++export function search(query: string, limit = 5) {+ return bm25(query).slice(0, limit);+}+`;++/** The drop feedback's glyph, the paperclip the app passes (its attachment mark). */+const PAPERCLIP_GLYPH =+ "M21.4 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.2-9.19a4 4 0 0 1 5.65 5.66l-9.19 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48";+function formatSize(bytes: number): string {return bytes >= 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${bytes} B`;}@@ -39,6 +72,12 @@ export function FilesBoard() {const t = S.library.files;const tree = useDemoTree();const browser = useDemoTree();+ const panel = useDemoTree();+ const [query, setQuery] = useState("");+ const [treeWidth, setTreeWidth] = useState(200);+ const [wrap, setWrap] = useState(false);+ const [draft, setDraft] = useState(DEMO_SOURCE);+const preview: FileBrowserPreview | null =browser.selected === null? null@@ -48,6 +87,30 @@ export function FilesBoard() {kind: browser.selected.endsWith(".md") ? "md" : "text",content: browser.selected === "README.md" ? t.readme : `// ${browser.selected}\n`,};++ const panelView: PreviewView =+ panel.selected === null+ ? { kind: "empty", title: t.selectFile }+ : panel.selected.endsWith(".md")+ ? { kind: "markdown", text: panel.selected === "README.md" ? t.readme : "" }+ : {+ kind: "source",+ code: panel.selected === "src/rag.ts" ? DEMO_SOURCE : `// ${panel.selected}\n`,+ language: "typescript",+ wrap,+ };+ const crumbs = [t.root, ...(panel.selected ?? "").split("/").filter((part) => part !== "")];+ const menuLabels = {+ copyPath: t.copyPath,+ addToChat: t.addToChat,+ addSelectionToChat: t.addSelection,+ uploadHere: t.uploadHere,+ download: t.download,+ rename: t.rename,+ delete: t.delete,+ };+ const noop = () => undefined;+return (<div className="gf-board"><BoardGroup title={t.tree}>@@ -76,6 +139,10 @@ export function FilesBoard() {headerFallback={t.header}preview={preview}emptyPreview={t.emptyPreview}+ emptyDirLabel={t.emptyDir}+ truncatedLabel={t.truncated}+ unsupportedLabel={t.unsupported}+ downloadLabel={t.download}treeMaxHeight={40}previewHeight={40}onToggleDir={browser.toggle}@@ -83,6 +150,125 @@ export function FilesBoard() {/></div></BoardGroup>+ <BoardGroup title={t.panel} aside={t.panelHint}>+ {/* The panel as the dock draws it: the path row, then the tree and the preview on a+ split whose handle drags (and steps with the arrow keys once focused). */}+ <div className="lib-box flex flex-col" style={{ height: 360 }}>+ <div className="flex shrink-0 items-center gap-1 border-b border-line px-2 py-1.5">+ <Breadcrumbs className="flex-1" items={crumbs.map((label) => ({ label }))} />+ </div>+ <SplitPane+ className="min-h-0 flex-1"+ size={treeWidth}+ min={160}+ max={320}+ label={t.treeWidth}+ onResize={setTreeWidth}+ first={+ <TreePane search={{ value: query, onChange: setQuery, placeholder: t.search }}>+ <FileTree+ rows={panel.rows}+ label={t.treeLabel}+ selectedPath={panel.selected}+ toggled={panel.toggled}+ emptyLabel={t.emptyDir}+ className="min-h-0 flex-1 overflow-auto"+ onToggleDir={panel.toggle}+ onOpenFile={panel.setSelected}+ />+ </TreePane>+ }+ second={+ <PreviewPane+ view={panelView}+ actions={+ panelView.kind === "source" && (+ <IconButton label={t.wrap} size="sm" onClick={() => setWrap(!wrap)}>+ <GlyphIcon d={ICONS.wrapText} />+ </IconButton>+ )+ }+ />+ }+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.crumbs} aside={t.crumbsHint}>+ <div className="lib-box" data-narrow>+ <div className="flex px-2 py-1.5">+ <Breadcrumbs+ className="flex-1"+ items={[t.root, "corpus", "claude-code-docs", "reference", "hooks-guide.md"].map(+ (label) => ({ label }),+ )}+ />+ </div>+ </div>+ </BoardGroup>+ <BoardGroup title={t.menu}>+ <div className="lib-row items-start">+ <div className="lib-stack">+ <span className="lib-caption">{t.menuFile}</span>+ <div className={`${menuPanelClass} w-56`}>+ <WorkspaceFileMenuRows+ target={{ path: "src/rag.ts", kind: "file" }}+ labels={menuLabels}+ downloadHref={() => "#"}+ downloadName={(path) => path.split("/").pop() ?? path}+ onCopyPath={noop}+ onAddToChat={noop}+ onUploadInto={noop}+ onAddSelection={noop}+ onRename={noop}+ onDelete={noop}+ onClose={noop}+ />+ </div>+ </div>+ <div className="lib-stack">+ <span className="lib-caption">{t.menuFolder}</span>+ <div className={`${menuPanelClass} w-56`}>+ <WorkspaceFileMenuRows+ target={{ path: "src", kind: "dir" }}+ labels={menuLabels}+ downloadHref={() => "#"}+ downloadName={(path) => path}+ onCopyPath={noop}+ onAddToChat={noop}+ onUploadInto={noop}+ onClose={noop}+ />+ </div>+ </div>+ </div>+ </BoardGroup>+ <BoardGroup title={t.editor}>+ <div className="lib-box" style={{ height: 180 }}>+ <WorkspaceFileEditor+ path="src/rag.ts"+ value={draft}+ label={t.editorLabel("rag.ts")}+ wrap={wrap}+ onChange={setDraft}+ onSave={noop}+ />+ </div>+ </BoardGroup>+ <BoardGroup title={t.drop}>+ <div className="lib-row items-start">+ <div className="lib-box relative w-72" style={{ height: 200 }}>+ <DropOverlay+ variant="veil"+ glyph={PAPERCLIP_GLYPH}+ title={t.dropAttach}+ description={t.dropAttachHint}+ />+ </div>+ <div className="lib-box relative w-72" style={{ height: 200 }}>+ <DropOverlay variant="frame" glyph={PAPERCLIP_GLYPH} title={t.dropUpload("src")} />+ </div>+ </div>+ </BoardGroup></div>);}diff --git a/packages/ui-gallery/src/library/demo-tree.ts b/packages/ui-gallery/src/library/demo-tree.tsindex 0b5d3d4a..0895db23 100644--- a/packages/ui-gallery/src/library/demo-tree.ts+++ b/packages/ui-gallery/src/library/demo-tree.ts@@ -3,7 +3,7 @@* from it: every visible entry in order, with its depth, its position in its directory and, for* a directory, whether it is open — pure, so the flattening is unit-tested.*/-import type { FileTreeRow } from "../../../web/src/lib/file-tree";+import type { FileTreeRow } from "@prismshadow/penguin-ui";export interface DemoEntry {name: string;diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.tsindex ff4b8d1f..82ca8eb4 100644--- a/packages/ui-gallery/src/strings-en.ts+++ b/packages/ui-gallery/src/strings-en.ts@@ -453,7 +453,11 @@ export const en: GalleryStrings = {title: "Avatars",description: "The user and agent avatars at their sizes, and a stack of them.",},- files: { title: "Files", description: "The file tree and the read-only file browser." },+ files: {+ title: "Files",+ description:+ "The file tree and the read-only file browser; the Files panel's tree and preview panes with the draggable split between them, the path strip, the file menu, the editor and the drop feedback.",+ },content: {title: "Content",description:@@ -917,8 +921,37 @@ export const en: GalleryStrings = {header: "docs-expert",emptyPreview: "Pick a file on the left to preview it.",emptyDir: "Empty directory",+ root: ".",readme:"# Docs Expert\n\nBuilds a BM25 index over `corpus/` and answers questions about the Claude Code docs.\n\n- `src/rag.ts` — retrieval\n- `test/` — cases",+ truncated: "File too large; preview truncated, download for the full file",+ unsupported: "Preview not supported for this type; download instead",+ download: "Download",+ panel: "Files panel",+ panelHint:+ "The tree beside the preview: the draggable split, the path strip and the actions over the preview",+ search: "Search files",+ treeWidth: "Resize the file tree",+ selectFile: "Select a file to preview",+ wrap: "Wrap lines",+ crumbs: "Path strip",+ crumbsHint:+ "When the path does not fit, its leading parts fold into one “…”; the file name gives way last",+ menu: "File menu",+ menuFile: "File",+ menuFolder: "Folder",+ copyPath: "Copy relative path",+ addToChat: "Add to conversation",+ addSelection: "Add selection to conversation",+ uploadHere: "Upload here",+ rename: "Rename or move",+ delete: "Delete",+ editor: "Editor",+ editorLabel: (name: string) => `Editing ${name}`,+ drop: "Drop feedback",+ dropAttach: "Drop files to attach",+ dropAttachHint: "Images and files are added to the message draft",+ dropUpload: (dir: string) => `Drop to upload into ${dir}`,},content: {headings: "Headings",diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.tsindex b03e0d53..11509348 100644--- a/packages/ui-gallery/src/strings.ts+++ b/packages/ui-gallery/src/strings.ts@@ -447,7 +447,11 @@ export const zh = {"统计图的基础:所有图表共用的绘图原语、当前主题的图表令牌,以及建立在它们之上的每一种图表——环形图、环形仪表、图例、趋势与用量柱、请求与成功率、迷你折线、轨迹时间线。",},avatars: { title: "头像", description: "用户头像与智能体头像的各个尺寸,以及头像组。" },- files: { title: "文件", description: "文件树与只读文件浏览器。" },+ files: {+ title: "文件",+ description:+ "文件树与只读文件浏览器,文件面板的树栏、预览栏与可拖动的分隔条,路径条、文件菜单、编辑器与拖放反馈。",+ },content: {title: "内容",description: "标题与文字角色、行内代码、Markdown 正文、代码块与代码面,以及差异视图。",@@ -879,8 +883,35 @@ export const zh = {header: "docs-expert",emptyPreview: "选择左侧的文件预览。",emptyDir: "空目录",+ root: ".",readme:"# Docs Expert\n\n从 `corpus/` 建立 BM25 索引,回答关于 Claude Code 文档的问题。\n\n- `src/rag.ts` — 检索\n- `test/` — 用例",+ truncated: "内容过大,预览已截断,请下载查看完整文件",+ unsupported: "该类型不支持预览,请下载查看",+ download: "下载",+ panel: "文件面板",+ panelHint: "树与预览两栏:可拖动的分隔条、路径条与预览上的操作条",+ search: "搜索文件",+ treeWidth: "调整文件树宽度",+ selectFile: "选择一个文件以预览",+ wrap: "自动换行",+ crumbs: "路径条",+ crumbsHint: "放不下时,开头的几段收进一个「…」,文件名最后让位",+ menu: "文件菜单",+ menuFile: "文件",+ menuFolder: "文件夹",+ copyPath: "复制相对路径",+ addToChat: "添加到对话",+ addSelection: "将选中内容添加到对话",+ uploadHere: "上传到此文件夹",+ rename: "重命名 / 移动",+ delete: "删除",+ editor: "编辑器",+ editorLabel: (name: string) => `编辑 ${name}`,+ drop: "拖放反馈",+ dropAttach: "松开以添加附件",+ dropAttachHint: "图片与文件将添加到输入框",+ dropUpload: (dir: string) => `松开即上传到 ${dir}`,},content: {headings: "标题",diff --git a/packages/ui/src/components/content/code-block/code-languages.ts b/packages/ui/src/components/content/code-block/code-languages.tsindex ddd34ef9..9a948616 100644--- a/packages/ui/src/components/content/code-block/code-languages.ts+++ b/packages/ui/src/components/content/code-block/code-languages.ts@@ -119,6 +119,17 @@ export function languageForExtension(ext: string): string {return LANGUAGE_BY_EXTENSION.get(ext.toLowerCase()) ?? PLAIN_TEXT_LANGUAGE;}+/**+ * The language a file's name says it is written in: from its extension, or from the whole name+ * when it has none (`Makefile`), a leading dot included (`.env`). A path works as well as a name:+ * only its last segment is read.+ */+export function languageForFileName(name: string): string {+ const base = name.slice(name.lastIndexOf("/") + 1);+ const dot = base.lastIndexOf(".");+ return languageForExtension(dot >= 0 ? base.slice(dot + 1) : base);+}+/*** Fence info string / language prop -> the id to highlight with, or undefined when nothing here* covers it (the caller then renders the code unhighlighted). An empty language means andiff --git a/packages/web/src/lib/frontmatter.ts b/packages/ui/src/components/content/prose/frontmatter.tssimilarity index 50%rename from packages/web/src/lib/frontmatter.tsrename to packages/ui/src/components/content/prose/frontmatter.tsindex e5b571db..501a1251 100644--- a/packages/web/src/lib/frontmatter.ts+++ b/packages/ui/src/components/content/prose/frontmatter.ts@@ -1,8 +1,9 @@/**- * Frontmatter helpers shared by the memory views (agents settings tab, chat side panel).+ * A Markdown document's leading frontmatter block, which a reader shows as metadata of its own+ * (a memory's fields, a Skill's card) rather than as text.*//** The body without its frontmatter block: callers render the metadata fields themselves, so rendering the raw YAML too would only repeat them. */export function bodyWithoutFrontmatter(content: string): string {- return content.replace(/^\ufeff?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");+ return content.replace(/^?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");}diff --git a/packages/ui/src/components/content/prose/prose.tsx b/packages/ui/src/components/content/prose/prose.tsxindex e851f5e2..684b0e8a 100644--- a/packages/ui/src/components/content/prose/prose.tsx+++ b/packages/ui/src/components/content/prose/prose.tsx@@ -150,8 +150,9 @@ const SETTLED_COMPONENTS: Components = {};/**- * The settled map, for a read-only Markdown surface that keeps the code-block chrome and swaps- * only the link and image adapters (the shared file browser).+ * The settled map, for a read-only Markdown surface that renders through react-markdown itself+ * and keeps the code-block chrome. A surface that only swaps the link and image adapters (the+ * file browser) passes them to `Md` instead.*/export const SETTLED_MD_COMPONENTS: Components = SETTLED_COMPONENTS;diff --git a/packages/web/src/features/chat/workspace-editor.tsx b/packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsxsimilarity index 54%rename from packages/web/src/features/chat/workspace-editor.tsxrename to packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsxindex 20a50784..51e4c775 100644--- a/packages/web/src/features/chat/workspace-editor.tsx+++ b/packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsx@@ -5,44 +5,58 @@* 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 (`.code-editor` in the UI package's prose.css),- * 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`.+ * The two layers are stacked in a single grid cell (prose.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 the `editor.save` shortcut (⌘S / Ctrl+S by default) 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.+ * No spell-check or autocorrect, and the save shortcut saves (the caller's binding, ⌘S / Ctrl+S+ * when it names none) — the browser's own "save page" default is suppressed while the focus is+ * here. Long lines scroll sideways, as code should, unless the Wrap toggle soft-wraps them; the+ * toggle, Save and Cancel all live in the panel's preview header, and this component owns only+ * the text.*/import { useEffect, useRef, useState } from "react";import type { KeyboardEvent as ReactKeyboardEvent } from "react";-import { CodeSurface, languageForExtension } from "@prismshadow/penguin-ui";-import { S } from "../../lib/strings";-import { isShortcut } from "../../lib/shortcuts/match";-import { currentPlatform } from "../../lib/shortcuts/platform";-import { keymap } from "../../lib/shortcuts/store";-import { TEXT_PREVIEW_LIMIT, baseName, extOf } from "../../lib/workspace-tree";+import { CodeSurface } from "../code-block/code-block";+import { languageForFileName } from "../code-block/code-languages";/** Quiet period before re-highlighting, so a keystroke costs a re-render and not a tokenize. */const EDIT_HIGHLIGHT_SETTLE_MS = 200;+/** Ctrl+S or ⌘S without Alt: the save key when the caller names no binding. */+function isDefaultSaveKey(event: KeyboardEvent): boolean {+ return (event.ctrlKey || event.metaKey) && !event.altKey && event.key.toLowerCase() === "s";+}+export function WorkspaceFileEditor({path,value,+ label,wrap,+ highlight = true,onChange,onSave,+ isSaveKey = isDefaultSaveKey,}: {+ /** The file being edited: its name picks the highlighting language. */path: string;value: string;+ /** The textarea's accessible name ("Editing notes.md"). */+ label: string;/** Soft-wrap long lines instead of scrolling sideways (the preview header's toggle). */wrap: boolean;+ /**+ * Colour the text. Tokenizing runs on a worker, so a large file costs latency on the colours+ * rather than a stalled editor; the caller bounds it only by what a load can put here.+ */+ highlight?: boolean;onChange: (next: string) => void;onSave: () => void;+ /** Whether a keydown is the save shortcut; the app passes the user's binding. */+ isSaveKey?: (event: KeyboardEvent) => boolean;}) {const ref = useRef<HTMLTextAreaElement | null>(null);useEffect(() => {@@ -53,7 +67,7 @@ export function WorkspaceFileEditor({const [composing, setComposing] = useState(false);const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>): void => {- if (isShortcut(e.nativeEvent, keymap(), "editor.save", currentPlatform())) {+ if (isSaveKey(e.nativeEvent)) {// A held chord repeats: every repeat is kept from the browser (Save Page), one save runs.e.preventDefault();if (!e.repeat) onSave();@@ -68,14 +82,10 @@ export function WorkspaceFileEditor({className="code-editor-host h-full min-h-0 overflow-auto text-xs leading-relaxed"><CodeSurface- language={languageForExtension(extOf(baseName(path)))}+ language={languageForFileName(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}+ highlight={highlight}+ // The settle delay keeps a burst of typing from queueing a pass per keystroke.settleMs={EDIT_HIGHLIGHT_SETTLE_MS}lineNumberswrap={wrap}@@ -88,7 +98,7 @@ export function WorkspaceFileEditor({onKeyDown={onKeyDown}onCompositionStart={() => setComposing(true)}onCompositionEnd={() => setComposing(false)}- aria-label={S.files.editorLabel(baseName(path))}+ aria-label={label}spellCheck={false}autoCapitalize="off"autoCorrect="off"diff --git a/packages/ui/src/components/files/drop-overlay/drop-overlay.tsx b/packages/ui/src/components/files/drop-overlay/drop-overlay.tsxnew file mode 100644index 00000000..4fb071c0--- /dev/null+++ b/packages/ui/src/components/files/drop-overlay/drop-overlay.tsx@@ -0,0 +1,61 @@+/**+ * DropOverlay: what a region shows while files are dragged over it — the feedback that letting+ * go here does something, and what.+ *+ * Two shapes. `veil` washes the whole region and centres a dashed card on it, with a title and a+ * line under it: the conversation column, where a drop attaches files to the message being+ * written. `frame` rings the region in a dashed frame and pins a label at its foot: the Files+ * panel, where the label names the folder the files will land in, and the rows under the frame+ * stay visible because a folder row is itself a target.+ *+ * Pure feedback, never a target: `pointer-events-none`, so the drag's hit test keeps seeing the+ * real element underneath (which is how a folder row can be the one the files land in), and+ * `aria-hidden` — it exists only during a pointer drag, and the accessible way in is the region's+ * own upload control. It is positioned `absolute inset-0`, so its region is its nearest+ * positioned ancestor, and it fades in once when it appears.+ */+import { ICON_SIZE } from "../../../icon-scale";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";++/** The card's glyph in the veil: it anchors the card on its own, larger than any row's mark. */+const VEIL_GLYPH_PX = 28;++export interface DropOverlayProps {+ /** `veil` over a whole column, `frame` around a panel whose rows stay visible. */+ variant?: "veil" | "frame";+ /** What letting go does (the veil's heading, the frame's label). */+ title: string;+ /** The veil's line under the title: what is accepted, and how. */+ description?: string;+ /** The mark leading the text, as 24×24 path data. */+ glyph: string;+}++export function DropOverlay({ variant = "veil", title, description, glyph }: DropOverlayProps) {+ if (variant === "frame") {+ return (+ <div+ aria-hidden+ className="anim-fade pointer-events-none absolute inset-0 z-20 flex items-end justify-center p-3"+ >+ <div className="absolute inset-1 rounded-lg border-2 border-dashed border-fg-subtle bg-canvas/40" />+ <div className="relative flex items-center gap-2 rounded-md border border-line-emphasis bg-surface/95 px-3 py-1.5 text-xs font-medium text-fg shadow-sm">+ <GlyphIcon d={glyph} size={ICON_SIZE.rowLead} className="text-fg-subtle" />+ <span className="truncate">{title}</span>+ </div>+ </div>+ );+ }+ return (+ <div+ aria-hidden+ className="anim-fade pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-canvas/70 p-6"+ >+ <div className="flex flex-col items-center gap-2 rounded-xl border-2 border-dashed border-fg-subtle bg-surface/80 px-10 py-8 text-center">+ <GlyphIcon d={glyph} size={VEIL_GLYPH_PX} className="text-fg-subtle" />+ <p className="text-base font-medium text-fg">{title}</p>+ {description !== undefined && <p className="text-xs text-fg-muted">{description}</p>}+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/ui/file-browser.tsx b/packages/ui/src/components/files/file-browser/file-browser.tsxsimilarity index 74%rename from packages/web/src/components/ui/file-browser.tsxrename to packages/ui/src/components/files/file-browser/file-browser.tsxindex d4d710fb..5f3dbd7f 100644--- a/packages/web/src/components/ui/file-browser.tsx+++ b/packages/ui/src/components/files/file-browser/file-browser.tsx@@ -1,40 +1,33 @@/**- * The read-only file browser: the shared `FileTree` in an aside on the left, one preview pane- * on the right. The plugin detail Modal and the Benchmark case dialog are both this, so files- * that cannot be edited are read the same way wherever they are met — the Workspace files- * panel draws the same tree, with its own editing, HTML sandbox and selection machinery- * around it.+ * The read-only file browser: a `FileTree` in an aside on the left, one preview pane on the+ * right. The Web App's plugin detail Modal and its Benchmark case dialog are both this, so files+ * that cannot be edited are read the same way wherever they are met — the Workspace files panel+ * draws the same tree, with its own editing, HTML sandbox and selection machinery around it.** What this owns is the layout and the preview: the two panes, their scroll caps, the header* line naming what is open with its Download link, and how each kind of file is drawn —- * markdown through the chat markdown pipeline, text through the code block, an image and a- * PDF from their own URLs.+ * Markdown through the shared pipeline (`Md`), text through the code block, an image and a PDF+ * from their own URLs.** What the host owns is where the files come from: how the rows are produced (the plugin* groups a listing it already holds, the case dialog lists one directory per level as it is- * opened), how a preview's content is fetched, and what a relative markdown reference points+ * opened), how a preview's content is fetched, and what a relative Markdown reference points* at. A row's `path` is the only identifier here — it is what the tree highlights, what* `onOpenFile` hands back and what the header prints — so a host whose paths are not unique- * on their own (the case dialog's two materials) prefixes them itself.+ * on their own (the case dialog's two materials) prefixes them itself. The words are the host's+ * too: the four this draws on its own arrive as props.*/import { useMemo } from "react";import type { CSSProperties, ReactNode } from "react";-import ReactMarkdown from "react-markdown";import type { Components } from "react-markdown";-import {- CodeBlock,- REHYPE_PLUGINS,- REMARK_PLUGINS,- SETTLED_MD_COMPONENTS,- SkeletonList,- languageForExtension,-} from "@prismshadow/penguin-ui";-import { bodyWithoutFrontmatter } from "../../lib/frontmatter";-import type { FileTreeRow } from "../../lib/file-tree";-import { S } from "../../lib/strings";-import { extOf, previewKindFor } from "../../lib/workspace-tree";-import { FileTree } from "./file-tree";-import type { TreeToggle } from "./file-tree";+import { CodeBlock } from "../../content/code-block/code-block";+import { languageForFileName } from "../../content/code-block/code-languages";+import { bodyWithoutFrontmatter } from "../../content/prose/frontmatter";+import { Md } from "../../content/prose/prose";+import { SkeletonList } from "../../feedback/skeleton/skeleton";+import { FileTree } from "../file-tree/file-tree";+import type { TreeToggle } from "../file-tree/file-tree";+import type { FileTreeRow } from "../file-tree/tree-rows";/** A reference naming a scheme of its own (`https:`, `mailto:`) points outside the browsed files. */const EXTERNAL_REF_RE = /^[a-z][a-z0-9+.-]*:/i;@@ -52,18 +45,6 @@ const DEFAULT_PREVIEW_HEIGHT = 50;/** How a read-only preview draws a file. */export type FileBrowserPreviewKind = "text" | "md" | "image" | "pdf" | "unsupported";-/**- * How a file previews here, from its name: the Workspace panel's own classification, minus the- * two answers a read-only browser cannot give. HTML reads as its source, since rendering it- * would need the panel's sandboxed frame; a name that says nothing reads as unsupported, since- * nobody here is reading the first bytes to find out.- */-export function previewKindOf(name: string): FileBrowserPreviewKind {- const kind = previewKindFor(name);- if (kind === "html") return "text";- return kind === "unknown" ? "unsupported" : kind;-}-/** The file in the preview pane, and everything it takes to draw it. */export interface FileBrowserPreview {/** The tree row path of the previewed file (what `selectedPath` highlights). */@@ -81,29 +62,7 @@ export interface FileBrowserPreview {downloadUrl?: string;}-export function FileBrowser<Row extends FileTreeRow>({- rows,- treeLabel,- selectedPath,- loadingDirs,- toggled = null,- rowTrailing,- treeLoading = false,- treeError = null,- headerFallback,- headerPath,- preview,- emptyPreview,- stripFrontmatter = false,- resolveRef,- treeWidth = DEFAULT_TREE_WIDTH,- treeMaxHeight = DEFAULT_TREE_MAX_HEIGHT,- previewHeight = DEFAULT_PREVIEW_HEIGHT,- minHeight,- className = "",- onToggleDir,- onOpenFile,-}: {+export interface FileBrowserProps<Row extends FileTreeRow> {rows: readonly Row[];/** The tree's accessible name. */treeLabel: string;@@ -125,10 +84,18 @@ export function FileBrowser<Row extends FileTreeRow>({preview: FileBrowserPreview | null;/** The preview body while nothing is selected. */emptyPreview: string;+ /** What an open directory holding nothing says in place of its children. */+ emptyDirLabel: string;+ /** The note under a preview that stopped short of the whole file. */+ truncatedLabel: string;+ /** The preview body for a file this browser cannot draw. */+ unsupportedLabel: string;+ /** The header's download link. */+ downloadLabel: string;/** Markdown: drop a leading frontmatter block before rendering. */stripFrontmatter?: boolean;/**- * What a relative markdown reference points at: the URL to load an image from, and the tree+ * What a relative Markdown reference points at: the URL to load an image from, and the tree* path a link opens in place. Called only for a reference that is neither an in-page anchor* nor a scheme of its own; null leaves the reference as the file wrote it.*/@@ -144,7 +111,35 @@ export function FileBrowser<Row extends FileTreeRow>({className?: string;onToggleDir: (dir: string) => void;onOpenFile: (path: string) => void;-}) {+}++export function FileBrowser<Row extends FileTreeRow>({+ rows,+ treeLabel,+ selectedPath,+ loadingDirs,+ toggled = null,+ rowTrailing,+ treeLoading = false,+ treeError = null,+ headerFallback,+ headerPath,+ preview,+ emptyPreview,+ emptyDirLabel,+ truncatedLabel,+ unsupportedLabel,+ downloadLabel,+ stripFrontmatter = false,+ resolveRef,+ treeWidth = DEFAULT_TREE_WIDTH,+ treeMaxHeight = DEFAULT_TREE_MAX_HEIGHT,+ previewHeight = DEFAULT_PREVIEW_HEIGHT,+ minHeight,+ className = "",+ onToggleDir,+ onOpenFile,+}: FileBrowserProps<Row>) {// The sizes ride in as custom properties rather than as classes: a media query decides where// each one applies (the tree column exists only from `md` up), which an inline style cannot// say, and a class name composed at runtime is one Tailwind never sees to generate.@@ -156,8 +151,10 @@ export function FileBrowser<Row extends FileTreeRow>({} as CSSProperties;/**- * The markdown adapters, rebuilt only when the host's resolver changes: react-markdown takes- * these as element types, so a fresh map every render would remount the whole body.+ * The Markdown adapters, rebuilt only when the host's resolver changes: react-markdown takes+ * these as element types, so a fresh map every render would remount the whole body. `Md`+ * keeps its own fenced-code adapter underneath; the link and image ones are replaced by ones+ * that know the browsed files.*/const markdownComponents = useMemo<Components>(() => {/** What a reference of the file's own points at; null for an external or unresolved one. */@@ -165,10 +162,7 @@ export function FileBrowser<Row extends FileTreeRow>({if (EXTERNAL_REF_RE.test(ref)) return null;return resolveRef?.(ref) ?? null;};- // The chat's settled adapters underneath (the code-block chrome for fenced code), with the- // link and image adapters replaced by ones that know the browsed files.return {- ...SETTLED_MD_COMPONENTS,img: ({ src, alt }) => {const resolved = typeof src === "string" ? target(src) : null;const url = resolved === null ? src : resolved.url;@@ -214,7 +208,7 @@ export function FileBrowser<Row extends FileTreeRow>({/** The note under a preview that stopped short of the whole file. */const truncatedNote = (p: FileBrowserPreview): ReactNode => {if (p.truncated !== true) return null;- return <p className="mt-2 text-xs text-gray-400">{S.files.previewTruncated}</p>;+ return <p className="mt-2 text-xs text-fg-subtle">{truncatedLabel}</p>;};const previewBody = (): ReactNode => {@@ -223,17 +217,19 @@ export function FileBrowser<Row extends FileTreeRow>({// either, so the pane waits with the tree rather than announcing an empty browser; a// listing that failed is done waiting, and the host's empty text says what happened.if (treeLoading && treeError === null) return <SkeletonList rows={8} />;- return <p className="text-sm text-gray-400">{emptyPreview}</p>;+ return <p className="text-sm text-fg-subtle">{emptyPreview}</p>;}if (preview.loading === true) return <SkeletonList rows={8} />;- if (preview.error !== undefined) return <p className="text-sm text-red-500">{preview.error}</p>;+ if (preview.error !== undefined) {+ return <p className="text-sm text-tone-danger-fg">{preview.error}</p>;+ }if (preview.kind === "image") {return (<imgsrc={preview.url}alt={preview.name}loading="lazy"- className="max-w-full rounded-md border border-gray-200 dark:border-gray-800"+ className="max-w-full rounded-md border border-line"/>);}@@ -242,7 +238,7 @@ export function FileBrowser<Row extends FileTreeRow>({<iframesrc={preview.url}title={preview.name}- className="h-[50vh] w-full rounded-md border border-gray-200 dark:border-gray-800"+ className="h-[50vh] w-full rounded-md border border-line"/>);}@@ -250,14 +246,11 @@ export function FileBrowser<Row extends FileTreeRow>({const text = preview.content ?? "";return (<>- <div className="md-body text-sm text-gray-800 dark:text-gray-100">- <ReactMarkdown- remarkPlugins={REMARK_PLUGINS}- rehypePlugins={REHYPE_PLUGINS}+ <div className="md-body text-sm text-fg">+ <Md+ text={stripFrontmatter ? bodyWithoutFrontmatter(text) : text}components={markdownComponents}- >- {stripFrontmatter ? bodyWithoutFrontmatter(text) : text}- </ReactMarkdown>+ /></div>{truncatedNote(preview)}</>@@ -268,7 +261,7 @@ export function FileBrowser<Row extends FileTreeRow>({return (<><CodeBlock- language={languageForExtension(extOf(preview.name))}+ language={languageForFileName(preview.name)}code={code}highlight={code.length <= HIGHLIGHT_LIMIT}/>@@ -276,19 +269,21 @@ export function FileBrowser<Row extends FileTreeRow>({</>);}- return <p className="text-sm text-gray-500 dark:text-gray-400">{S.files.previewUnsupported}</p>;+ return <p className="text-sm text-fg-muted">{unsupportedLabel}</p>;};return (<divstyle={sizes}- className={`grid min-h-[var(--fb-min-height)] grid-cols-1 overflow-hidden rounded-md border border-gray-200 md:grid-cols-[var(--fb-tree-width)_minmax(0,1fr)] dark:border-gray-800 ${className}`}+ className={`grid min-h-[var(--fb-min-height)] grid-cols-1 overflow-hidden rounded-md border border-line md:grid-cols-[var(--fb-tree-width)_minmax(0,1fr)] ${className}`}>{/* Both panes scroll on their own inside fixed heights, so whatever the host draws abovethe browser stays put while a file is read. */}- <aside className="border-b border-gray-200 bg-gray-50/60 md:border-b-0 md:border-r dark:border-gray-800 dark:bg-gray-950/30">+ <aside className="border-b border-line bg-surface-inset/60 md:border-b-0 md:border-r"><div className="max-h-44 overflow-y-auto md:max-h-[var(--fb-tree-max-height)]">- {treeError !== null && <p className="px-3 py-2 text-xs text-red-500">{treeError}</p>}+ {treeError !== null && (+ <p className="px-3 py-2 text-xs text-tone-danger-fg">{treeError}</p>+ )}{/* A `tree` with no `treeitem` in it is not one: while the listing is in flight, orwhen it failed or held nothing, the aside carries the skeleton or the error andno tree at all. */}@@ -301,7 +296,7 @@ export function FileBrowser<Row extends FileTreeRow>({loadingDirs={loadingDirs}toggled={toggled}rowTrailing={rowTrailing}- emptyLabel={S.files.empty}+ emptyLabel={emptyDirLabel}onToggleDir={onToggleDir}onOpenFile={onOpenFile}/>@@ -310,17 +305,17 @@ export function FileBrowser<Row extends FileTreeRow>({</aside><section className="min-w-0">- <div className="flex min-h-11 flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-800">+ <div className="flex min-h-11 flex-wrap items-center gap-2 border-b border-line px-3 py-2"><div className="min-w-0 flex-1">- <p className="truncate font-mono text-xs text-gray-500">{headerLine()}</p>+ <p className="truncate font-mono text-xs text-fg-muted">{headerLine()}</p></div>{preview !== null && preview.downloadUrl !== undefined && (<ahref={preview.downloadUrl}download={preview.name}- className="rounded-md px-2.5 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"+ className="rounded-control px-2.5 py-1 text-xs font-medium text-fg-muted transition-colors duration-150 hover:bg-line-muted hover:text-fg">- {S.files.download}+ {downloadLabel}</a>)}</div>diff --git a/packages/ui/src/components/files/file-tree/file-tree.css b/packages/ui/src/components/files/file-tree/file-tree.cssnew file mode 100644index 00000000..92ce9b16--- /dev/null+++ b/packages/ui/src/components/files/file-tree/file-tree.css@@ -0,0 +1,46 @@+/* FileTree: a directory's rows grow out of, and shrink back into, its row. Grid tracks rather+ than height so the closed state needs no measurement; the inner box clips. Under reduced+ motion the keyframes are off and each class rests at its own end state — open at 1fr,+ closing at 0fr — and the tree drops a closed group on a timer. Matches the chevron's 200ms+ rotation. */+.tree-group {+ display: grid;+ grid-template-rows: 1fr;+}+.tree-group > div {+ min-height: 0;+ overflow: hidden;+}+.tree-group-open {+ animation: tree-group-open 200ms ease-out;+}+.tree-group-close {+ grid-template-rows: 0fr;+ animation: tree-group-close 200ms ease-in;+}+@keyframes tree-group-open {+ from {+ grid-template-rows: 0fr;+ }+ to {+ grid-template-rows: 1fr;+ }+}+@keyframes tree-group-close {+ from {+ grid-template-rows: 1fr;+ }+ to {+ grid-template-rows: 0fr;+ }+}++/* No motion: the gallery's switch on the root, then the user's system preference. */+:root[data-motion="reduced"] :is(.tree-group-open, .tree-group-close) {+ animation: none;+}+@media (prefers-reduced-motion: reduce) {+ :is(.tree-group-open, .tree-group-close) {+ animation: none;+ }+}diff --git a/packages/web/src/components/ui/file-tree.tsx b/packages/ui/src/components/files/file-tree/file-tree.tsxsimilarity index 86%rename from packages/web/src/components/ui/file-tree.tsxrename to packages/ui/src/components/files/file-tree/file-tree.tsxindex 94625def..52a63388 100644--- a/packages/web/src/components/ui/file-tree.tsx+++ b/packages/ui/src/components/files/file-tree/file-tree.tsx@@ -1,13 +1,13 @@/**- * The app's file tree: one row per entry on screen, indented by depth, a chevron and a folder- * glyph on directories, a page glyph on files. Clicking a directory opens or closes it,- * clicking a file hands it to the caller.+ * The file tree: one row per entry on screen, indented by depth, a chevron and a folder glyph on+ * directories, a page glyph on files. Clicking a directory opens or closes it, clicking a file+ * hands it to the caller.*- * The caller brings the rows (`lib/file-tree.ts` states their shape) and nothing else about how- * they were produced: the Workspace panel lists one directory per level as it is opened, the- * plugin browser groups a listing it already holds. What this owns is the drawing and the- * interaction — indentation, glyphs, the selected and hover treatment, the ARIA tree semantics- * and the keyboard walk.+ * The caller brings the rows (tree-rows.ts states their shape) and nothing else about how they+ * were produced: the Workspace panel lists one directory per level as it is opened, the plugin+ * browser groups a listing it already holds. What this owns is the drawing and the interaction —+ * indentation, glyphs, the selected and hover treatment, the ARIA tree semantics and the+ * keyboard walk.** Keyboard: the WAI-ARIA tree pattern with a roving tab stop — one row is in the tab order* (the focused one, else the selected one, else the first), arrows move between rows and@@ -21,18 +21,22 @@* text is not the whole of what it means — the handbook's pinned index.** The rows stay one flat list; what nests is the drawing. An open directory's descendants go- * in a `role="group"` box whose height is animated, so a subtree grows out of its directory's- * row and shrinks back into it. Only the directory the caller says was just toggled animates,- * so a re-render, a filter or an unrelated commit animates nothing. Closing is the awkward- * half: the rows are gone from `rows` by the time the view hears about it, so the view keeps- * the last committed rows and re-renders the closed directory's own descendants, inert, for+ * in a `role="group"` box whose height is animated (file-tree.css), so a subtree grows out of its+ * directory's row and shrinks back into it. Only the directory the caller says was just toggled+ * animates, so a re-render, a filter or an unrelated commit animates nothing. Closing is the+ * awkward half: the rows are gone from `rows` by the time the view hears about it, so the view+ * keeps the last committed rows and re-renders the closed directory's own descendants, inert, for* as long as the shrink lasts.*/import { useEffect, useRef, useState } from "react";import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";-import { Chevron, GlyphIcon, ICONS, ICON_SIZE } from "@prismshadow/penguin-ui";-import { subtreeEnd, treeKeyStep } from "../../lib/file-tree";-import type { FileTreeRow } from "../../lib/file-tree";+import { ICON_SIZE } from "../../../icon-scale";+import { Chevron } from "../../icons/chevron/chevron";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { ICONS } from "../../icons/icons";+import { subtreeEnd, treeKeyStep } from "./tree-rows";+import type { FileTreeRow } from "./tree-rows";+import "./file-tree.css";/** Left padding of a depth-0 row, in px; deeper rows add `TREE_INDENT_PX` per level. */const TREE_PAD_PX = 6;@@ -45,8 +49,8 @@ const CHEVRON_COL_PX = 14;/*** How long a closing subtree is kept on screen when its animation never reports back. Under- * `prefers-reduced-motion` the keyframes are off, so no `animationend` ever arrives and this- * timer is the only thing that drops the retained rows. Comfortably past the 200ms shrink.+ * reduced motion the keyframes are off, so no `animationend` ever arrives and this timer is the+ * only thing that drops the retained rows. Comfortably past the 200ms shrink.*/const CLOSE_FALLBACK_MS = 260;@@ -57,23 +61,7 @@ export interface TreeToggle {serial: number;}-export function FileTree<Row extends FileTreeRow>({- rows,- label,- selectedPath,- loadingDirs,- dropTargetDir = null,- scrollTo = null,- toggled = null,- rowTitle,- rowLabel,- rowTrailing,- emptyLabel,- className = "",- children,- onToggleDir,- onOpenFile,-}: {+export interface FileTreeProps<Row extends FileTreeRow> {rows: readonly Row[];/** The tree's accessible name. */label: string;@@ -87,7 +75,7 @@ export function FileTree<Row extends FileTreeRow>({scrollTo?: { path: string } | null;/** The directory last opened or closed, whose subtree animates. Null: nothing to animate. */toggled?: TreeToggle | null;- /** A row's `title` tooltip; the path by default. */+ /** A row's tooltip; the path by default. */rowTitle?: (row: Row) => string;/*** A row's accessible name, for the row whose visible text leaves out what the row means — the@@ -106,7 +94,25 @@ export function FileTree<Row extends FileTreeRow>({children?: ReactNode;onToggleDir: (dir: string) => void;onOpenFile: (path: string) => void;-}) {+}++export function FileTree<Row extends FileTreeRow>({+ rows,+ label,+ selectedPath,+ loadingDirs,+ dropTargetDir = null,+ scrollTo = null,+ toggled = null,+ rowTitle,+ rowLabel,+ rowTrailing,+ emptyLabel,+ className = "",+ children,+ onToggleDir,+ onOpenFile,+}: FileTreeProps<Row>) {const containerRef = useRef<HTMLDivElement | null>(null);const [focused, setFocused] = useState<string | null>(null);@@ -234,21 +240,21 @@ export function FileTree<Row extends FileTreeRow>({aria-label={rowLabel?.(row)}{...(retained ? {} : { onClick: () => activate(row), onFocus: () => setFocused(row.path) })}style={{ paddingLeft: TREE_PAD_PX + row.depth * TREE_INDENT_PX }}- className={`flex cursor-pointer select-none items-center gap-1.5 py-1 pr-2 text-sm outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/60 ${+ className={`flex cursor-pointer select-none items-center gap-1.5 py-1 pr-2 text-sm outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-fg-subtle/60 ${dropHere- ? "bg-sky-50 ring-2 ring-inset ring-sky-500/60 dark:bg-sky-950/40"+ ? "bg-tone-info-bg ring-2 ring-inset ring-tone-info-emphasis/60": selected- ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-800/50"+ ? "bg-line-muted text-fg"+ : "text-fg hover:bg-surface-muted"} ${loading ? "opacity-60" : ""}`}>- <span className="flex w-3.5 shrink-0 justify-center text-gray-400" aria-hidden>+ <span className="flex w-3.5 shrink-0 justify-center text-fg-subtle" aria-hidden>{row.kind === "dir" && <Chevron open={row.expanded} size={ICON_SIZE.chevronDense} />}</span><GlyphIcond={row.kind === "dir" ? (row.expanded ? ICONS.folderOpen : ICONS.folder) : ICONS.file}size={ICON_SIZE.rowLead}- className="text-gray-400"+ className="text-fg-subtle"/><span className="min-w-0 flex-1 truncate">{row.name}</span>{rowTrailing?.(row)}@@ -260,7 +266,7 @@ export function FileTree<Row extends FileTreeRow>({const renderEmptyLine = (row: Row): ReactNode => (<pkey={`empty:${row.path}`}- className="py-1 pr-2 text-xs text-gray-400"+ className="py-1 pr-2 text-xs text-fg-subtle"style={{ paddingLeft: TREE_PAD_PX + (row.depth + 1) * TREE_INDENT_PX + CHEVRON_COL_PX }}>{emptyLabel}diff --git a/packages/web/src/lib/file-tree.ts b/packages/ui/src/components/files/file-tree/tree-rows.tssimilarity index 100%rename from packages/web/src/lib/file-tree.tsrename to packages/ui/src/components/files/file-tree/tree-rows.tsdiff --git a/packages/ui/src/components/files/preview-pane/preview-pane.tsx b/packages/ui/src/components/files/preview-pane/preview-pane.tsxnew file mode 100644index 00000000..0755281c--- /dev/null+++ b/packages/ui/src/components/files/preview-pane/preview-pane.tsx@@ -0,0 +1,200 @@+/**+ * PreviewPane: the Files panel's right-hand column — what a chosen file looks like. An image+ * (click to zoom), a PDF in the browser's own viewer, Markdown as reading text, source as the+ * highlighted code surface, a note for a file it cannot draw; an empty state while nothing is+ * chosen, and a skeleton while the file is on its way.+ *+ * The caller decides what the file is and fetches it; this draws the `view` it is handed. An+ * embedded page (the panel's sandboxed HTML preview) arrives as an `embed` node, because the+ * sandbox and the page's origin are the caller's security decision, not a drawing one.+ *+ * Two things float with the body. `actions` is a small pill pinned over its top-right corner —+ * the controls that act on the text underneath (wrap, copy, edit) rather than on the file —+ * always drawn, never hover-revealed, since a hover-only control is no control on a touch screen.+ * `editor` replaces the body while the file is being edited; the pill stays, because the editor+ * lays its text over the same surface and still wraps by the same toggle.+ *+ * The body is the scroll box, and `bodyRef` / `bodyProps` reach it: the caller's context menu+ * hangs off it (the gestures, the keyboard chord, the anchor it returns focus to). It is focusable+ * only programmatically (`tabIndex={-1}`), so Escape has somewhere to hand focus back to.+ */+import type { HTMLAttributes, Key, ReactNode, Ref } from "react";+import type { Components } from "react-markdown";+import { CodeSurface } from "../../content/code-block/code-block";+import { Prose } from "../../content/prose/prose";+import { EmptyState } from "../../feedback/empty-state/empty-state";+import { SkeletonList } from "../../feedback/skeleton/skeleton";+import { ZoomableImage } from "../../overlays/lightbox/lightbox";++/** What the pane draws. */+export type PreviewView =+ /** Nothing chosen: an empty state, with an action (showing a hidden tree) when there is one. */+ | { kind: "empty"; title: string; action?: ReactNode }+ /** A file is chosen and on its way: the whole pane waits. */+ | { kind: "opening" }+ /** Part of the file's view is still loading (a page's source fetched on demand). */+ | { kind: "loading" }+ | { kind: "error"; message: string }+ /** `reloadKey` remounts the image when the file is re-read under the same URL. */+ | { kind: "image"; src: string; alt: string; reloadKey?: Key }+ | { kind: "pdf"; src: string; title: string; reloadKey?: Key }+ /** An embedded page the caller frames itself, with its own sandbox. */+ | { kind: "embed"; node: ReactNode }+ /**+ * Markdown as reading text. `components` swaps element adapters (images and links that know+ * where the file lives); `truncatedNote` says the file was cut short.+ */+ | { kind: "markdown"; text: string; components?: Components; truncatedNote?: string }+ /** Source on the code surface — the same surface the editor lays its textarea over. */+ | {+ kind: "source";+ code: string;+ language: string;+ wrap: boolean;+ truncatedNote?: string;+ }+ | { kind: "unsupported"; message: string };++export interface PreviewPaneProps {+ view: PreviewView;+ /** The pill over the body's top-right corner; omitted, no pill. */+ actions?: ReactNode;+ /** The editor, drawn in place of the body while the file is edited. */+ editor?: ReactNode;+ /** The body's context menu (its portal), drawn after the body. */+ menu?: ReactNode;+ bodyRef?: Ref<HTMLDivElement>;+ /** Handlers on the body — the caller's context-menu gestures. */+ bodyProps?: Omit<HTMLAttributes<HTMLDivElement>, "className" | "tabIndex" | "children">;+ className?: string;+}++/** Whether a slot was given something to draw: `cond && node` hands over `false` when it was not. */+const given = (node: ReactNode): boolean => node !== undefined && node !== null && node !== false;++/** The small print under a preview that stopped short of the whole file. */+function TruncatedNote({ note, source }: { note: string | undefined; source: boolean }) {+ if (note === undefined) return null;+ return <p className={`text-xs text-fg-subtle ${source ? "px-3 pb-2" : "mt-1"}`}>… {note}</p>;+}++/** The body's content for a view that has one. */+function viewBody(view: PreviewView): ReactNode {+ switch (view.kind) {+ case "loading":+ return <SkeletonList rows={6} />;+ case "error":+ return <p className="text-sm text-tone-danger-fg">{view.message}</p>;+ case "image":+ return (+ <ZoomableImage+ key={view.reloadKey}+ src={view.src}+ alt={view.alt}+ className="max-w-full rounded-md border border-line"+ />+ );+ case "pdf":+ return (+ <iframe+ key={view.reloadKey}+ src={view.src}+ title={view.title}+ className="h-full min-h-[60vh] w-full rounded-md border border-line"+ />+ );+ case "embed":+ return view.node;+ case "markdown":+ return (+ <>+ <Prose+ text={view.text}+ className="text-base leading-relaxed text-fg"+ components={view.components}+ />+ <TruncatedNote note={view.truncatedNote} source={false} />+ </>+ );+ case "source":+ return (+ <>+ <CodeSurface+ language={view.language}+ code={view.code}+ highlight+ lineNumbers+ wrap={view.wrap}+ className="text-xs leading-relaxed"+ />+ <TruncatedNote note={view.truncatedNote} source />+ </>+ );+ case "unsupported":+ return <p className="text-sm text-fg-muted">{view.message}</p>;+ default:+ return null;+ }+}++export function PreviewPane({+ view,+ actions,+ editor,+ menu,+ bodyRef,+ bodyProps,+ className = "",+}: PreviewPaneProps) {+ const pill = given(actions) && (+ <div className="absolute right-4 top-2.5 z-10 flex items-center gap-1 rounded-md border border-line bg-surface p-1 shadow-sm">+ {actions}+ </div>+ );++ let content: ReactNode;+ if (view.kind === "empty") {+ content = <EmptyState title={view.title} action={view.action} />;+ } else if (view.kind === "opening") {+ content = <SkeletonList rows={6} />;+ } else if (given(editor)) {+ content = (+ <div className="relative flex min-h-0 flex-1 flex-col">+ <div className="min-h-0 flex-1">{editor}</div>+ {pill}+ </div>+ );+ } else {+ content = (+ <>+ {/* The pill's 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. */}+ <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). 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. */}+ <div+ {...bodyProps}+ ref={bodyRef}+ tabIndex={-1}+ className={`min-h-0 flex-1 overflow-auto outline-none [scrollbar-gutter:stable] ${+ view.kind === "source" ? "" : "p-3"+ }`}+ >+ {viewBody(view)}+ </div>+ {pill}+ </div>+ {menu}+ </>+ );+ }++ return <div className={`flex min-h-0 min-w-0 flex-1 flex-col ${className}`}>{content}</div>;+}diff --git a/packages/ui/src/components/files/tree-pane/tree-pane.tsx b/packages/ui/src/components/files/tree-pane/tree-pane.tsxnew file mode 100644index 00000000..9ebb2c63--- /dev/null+++ b/packages/ui/src/components/files/tree-pane/tree-pane.tsx@@ -0,0 +1,95 @@+/**+ * TreePane: the Files panel's left-hand column — the file tree under a header holding its search+ * box and the panel's own actions (refresh, upload). The actions are the caller's: they belong to+ * the panel rather than to any one file, which is why they sit here and not on the path row,+ * where everything names the open file.+ *+ * The body is the first of: the listing's failure, a skeleton while the first listing is on its+ * way, a waiting line (a search whose answer has not arrived — an empty tree there would read as+ * "nothing matches", the one answer that must not be guessed), and otherwise the tree itself with+ * an optional footnote under it (a search that was cut short).+ *+ * The pane takes the caller's handlers on its root (`...rest`): the tree's context menu hangs off+ * the whole pane and resolves the row under the pointer itself, so a gesture between rows — the+ * search box, the space below the last row — reaches nothing and the browser's own menu stands.+ * `menu` is that menu's portal, drawn in every state.+ */+import type { HTMLAttributes, ReactNode } from "react";+import { SkeletonList } from "../../feedback/skeleton/skeleton";+import { SearchInput } from "../../forms/search-input/search-input";++export interface TreePaneSearch {+ value: string;+ onChange: (value: string) => void;+ /** The box's placeholder, which is also its accessible name. */+ placeholder: string;+ /** The clear button's name; the interface's "Clear search" by default. */+ clearLabel?: string;+}++export interface TreePaneProps extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {+ search: TreePaneSearch;+ /** The header's actions, after the search box. */+ actions?: ReactNode;+ /** The listing failed: said in place of the tree. */+ error?: string | null;+ /** The first listing is on its way. */+ loading?: boolean;+ /** Waiting for an answer that decides what the tree shows: said in place of it. */+ pending?: string | null;+ /** Small print under the tree. */+ note?: string | null;+ /** The context menu's portal. */+ menu?: ReactNode;+ /** The tree. */+ children?: ReactNode;+}++export function TreePane({+ search,+ actions,+ error = null,+ loading = false,+ pending = null,+ note = null,+ menu,+ children,+ className = "",+ ...rest+}: TreePaneProps) {+ return (+ <div {...rest} className={`flex min-h-0 flex-1 flex-col ${className}`}>+ {/* Esc in a non-empty box clears it rather than reaching the dock or a dialog above, which+ is what that key means here (SearchInput). */}+ <div className="flex shrink-0 items-center gap-1 border-b border-line-muted px-2 py-1.5">+ <SearchInput+ variant="panel"+ className="min-w-0 flex-1"+ value={search.value}+ onChange={search.onChange}+ placeholder={search.placeholder}+ aria-label={search.placeholder}+ clearLabel={search.clearLabel}+ />+ {actions}+ </div>+ {error !== null ? (+ <p className="px-3 py-3 text-sm text-tone-danger-fg">{error}</p>+ ) : loading ? (+ <SkeletonList rows={6} />+ ) : pending !== null ? (+ <p className="px-3 py-3 text-xs text-fg-subtle">{pending}</p>+ ) : (+ <>+ {children}+ {note !== null && (+ <p className="shrink-0 border-t border-line-muted px-3 py-1.5 text-xs text-fg-subtle">+ {note}+ </p>+ )}+ </>+ )}+ {menu}+ </div>+ );+}diff --git a/packages/web/src/features/chat/workspace-file-menu.tsx b/packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsxsimilarity index 78%rename from packages/web/src/features/chat/workspace-file-menu.tsxrename to packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsxindex 9934eed1..820983c9 100644--- a/packages/web/src/features/chat/workspace-file-menu.tsx+++ b/packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsx@@ -7,15 +7,14 @@* 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+ * same shape the preview header already uses: it is the browser's own save, not a fetch the* app has to run.*- * The rows are the UI package's Menu rows at the small density, the one every overflow and- * context menu in the app uses, so they read the same as the Session row's menu.+ * The rows are the Menu rows at the small density, the one every overflow and context menu in+ * the app uses, so they read the same as the Session row's menu.*/-import { ICONS, Menu, MenuItem } from "@prismshadow/penguin-ui";-import { S } from "../../lib/strings";-import { STAT_ICONS } from "../../lib/stat-icons";+import { ICONS } from "../../icons/icons";+import { Menu, MenuItem } from "../../overlays/menu/menu";/** The one Workspace entry a menu is acting on. */export interface FileMenuTarget {@@ -23,8 +22,20 @@ export interface FileMenuTarget {kind: "dir" | "file";}+/** The rows' words, from the caller's dictionary. */+export interface WorkspaceFileMenuLabels {+ copyPath: string;+ addToChat: string;+ addSelectionToChat: string;+ uploadHere: string;+ download: string;+ rename: string;+ delete: string;+}+export function WorkspaceFileMenuRows({target,+ labels,downloadHref,downloadName,onCopyPath,@@ -36,6 +47,7 @@ export function WorkspaceFileMenuRows({onClose,}: {target: FileMenuTarget;+ labels: WorkspaceFileMenuLabels;/** The file's download URL; never asked for a directory. */downloadHref: (path: string) => string;downloadName: (path: string) => string;@@ -52,7 +64,7 @@ export function WorkspaceFileMenuRows({* 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.+ * agent's work cannot be stated for one.*/onRename?: (target: FileMenuTarget) => void;/** Deletes the file, behind a confirmation and the same precondition. */@@ -62,34 +74,30 @@ export function WorkspaceFileMenuRows({}) {return (<Menu density="sm">- <MenuItem- glyph={STAT_ICONS.copy}- label={S.files.copyPath}- onSelect={() => onCopyPath(target)}- />+ <MenuItem glyph={ICONS.copy} label={labels.copyPath} onSelect={() => onCopyPath(target)} /><MenuItemglyph={ICONS.messagePlus}- label={S.files.addToChat}+ label={labels.addToChat}onSelect={() => onAddToChat(target)}/>{onAddSelection !== undefined && (<MenuItemglyph={ICONS.messagePlus}- label={S.files.addSelectionToChat}+ label={labels.addSelectionToChat}onSelect={onAddSelection}/>)}{target.kind === "dir" ? (<MenuItemglyph={ICONS.upload}- label={S.files.uploadHere}+ label={labels.uploadHere}onSelect={() => onUploadInto(target.path)}/>) : (<><MenuItemglyph={ICONS.download}- label={S.files.download}+ label={labels.download}href={downloadHref(target.path)}download={downloadName(target.path)}onSelect={onClose}@@ -100,14 +108,14 @@ export function WorkspaceFileMenuRows({{onRename !== undefined && (<MenuItemglyph={ICONS.penLine}- label={S.files.renameTitle}+ label={labels.rename}onSelect={() => onRename(target)}/>)}{onDelete !== undefined && (<MenuItemglyph={ICONS.trash}- label={S.common.delete}+ label={labels.delete}dangeronSelect={() => onDelete(target)}/>diff --git a/packages/ui/src/components/icons/chevron/chevron.tsx b/packages/ui/src/components/icons/chevron/chevron.tsxindex 955ba462..f64e7081 100644--- a/packages/ui/src/components/icons/chevron/chevron.tsx+++ b/packages/ui/src/components/icons/chevron/chevron.tsx@@ -7,6 +7,8 @@* It is a component rather than a registry entry because the rotation is part of the mark, and* this file is where the de-slop rules let a transform transition live.*/+import { ChevronDown } from "../marks/marks";+export function Chevron({open,size = 14,@@ -33,3 +35,27 @@ export function Chevron({</svg>);}++/**+ * The caret of a vertical fold: it points down while what it folds away is hidden and turns over+ * to point up once it shows — the sidebar's page-nav toggle, a slim bar under the rows it folds.+ * It is the form control's fixed-grid caret (`ChevronDown`), turned here because this is the file+ * where a transform may transition.+ */+export function ChevronFlip({+ up,+ size = 12,+ className = "",+}: {+ /** What the toggle folds is showing: the caret points up, the way it will fold. */+ up: boolean;+ size?: number;+ className?: string;+}) {+ return (+ <ChevronDown+ size={size}+ className={`transition-transform duration-200 ${up ? "rotate-180" : ""} ${className}`}+ />+ );+}diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.tsindex af7f52a1..8829ff87 100644--- a/packages/ui/src/components/icons/icons.ts+++ b/packages/ui/src/components/icons/icons.ts@@ -134,6 +134,11 @@ export const ICONS = {* it sits level with the other marks of a stats row.*/clockCompact: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0-14v5l3 2",+ /**+ * A clock read backwards (lucide history): the face opens into an arrow turning back. Going+ * back to where the reader was, which a bare clock face — "ordered by time" — does not say.+ */+ history: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5M12 7v5l4 2",/** A calendar (lucide calendar): two rings, the header rule and the page. */calendar:"M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z",@@ -261,6 +266,13 @@ export const ICONS = {chevronLeft: "M15 18l-6-6 6-6",/** The same chevron pointing right: the next page. */chevronRight: "M9 18l6-6-6-6",+ /**+ * A chevron pointing left at an upright bar on the left edge: fold a column away against that+ * edge — the sidebar collapsing to its rail.+ */+ chevronLeftPipe: "M15 6l-6 6 6 6M4 4v16",+ /** The mirror: a chevron pointing right at a bar on the right edge, unfolding the column. */+ chevronRightPipe: "M9 6l6 6-6 6M20 4v16",/*** An arrow pointing left, centred in the box: head and shaft span the same width, where* `arrowLeft`'s head sits left of centre. With its mirror, a pair that steps back and forward@@ -276,6 +288,11 @@ export const ICONS = {panelBottom: "M4 5h16v14H4zM4 14h16",/** A window with a right pane. */panelRight: "M4 5h16v14H4zM14 5v14",+ /**+ * A pane with an arrow escaping its top-right corner: this moves out into a window of its own.+ * A different drawing from `externalLink`, whose arrow leaves from the pane's edge.+ */+ boxArrowOut: "M14 4h6v6M20 4l-8 8M10 6H5a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5",/** Four square tiles of two heights. */tiles: "M3 3h7v9H3zM14 3h7v5h-7zM14 12h7v9h-7zM3 16h7v5H3z",/** Four rounded tiles of two heights (lucide layout-dashboard). */@@ -296,6 +313,10 @@ export const ICONS = {"M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8 7v7M12 7v4M16 7v9",/** Bars of three heights on a baseline. */barChart: "M4 20V10m6 10V4m6 16v-7m4 7H2",+ /** Three full-width lines (lucide menu): the phone's button that opens the navigation drawer. */+ menu: "M4 6h16M4 12h16M4 18h16",+ /** Three sliders on their tracks (lucide sliders-horizontal): a list's display options. */+ slidersHorizontal: "M21 5h-7M10 5H3M21 12h-9M8 12H3M21 19h-5M12 19H3M14 2v6M8 9v6M16 16v6",// --- Status -------------------------------------------------------------------------------diff --git a/packages/ui/src/components/layout/resize-handle/resize-handle.tsx b/packages/ui/src/components/layout/resize-handle/resize-handle.tsxnew file mode 100644index 00000000..8b0a8c75--- /dev/null+++ b/packages/ui/src/components/layout/resize-handle/resize-handle.tsx@@ -0,0 +1,153 @@+/**+ * ResizeHandle: the bar a pointer drags to resize the box beside it — the edge between two+ * columns, or a panel's own edge — drawn in the info tone while it is pointed at and while it is+ * held, and transparent otherwise.+ *+ * The handle reports the pointer and nothing else: every move of a drag hands the caller the+ * native event, and the caller turns its position into a size against its own box (the tree+ * column's left edge, the dock's right edge, a ratio of the page column). That is what lets one+ * bar serve boxes that measure themselves differently. `SplitPane` is the two-column case with+ * that arithmetic done.+ *+ * Two placements. By default the bar is a layout sibling of the box it resizes and costs+ * `RESIZE_HANDLE_PX` of the row, so the boxes on either side always add up to their container.+ * With `edge`, it is an overlay straddling its positioned parent's start or end edge and costs+ * nothing — for a box whose own size is animated, where a sibling would leave a bare strip+ * behind while it collapses.+ *+ * Keyboard: given `onStep`, the bar joins the tab order as a focusable separator reporting its+ * `value` between `min` and `max`, and the arrow keys along its axis step the size. Without it the+ * bar is pointer-only, as a panel edge that also resizes from its own settings is. A double click+ * runs `onReset` (back to the default size) where the caller offers one.+ */+import { useState } from "react";+import type { HTMLAttributes, KeyboardEvent } from "react";+import { usePointerDrag } from "./use-pointer-drag";++/** The bar's thickness in px (`w-1.5` / `h-1.5`): what a layout-sibling handle costs its row. */+export const RESIZE_HANDLE_PX = 6;++/** One arrow-key step, in px: coarse enough to get somewhere, fine enough to land. */+export const RESIZE_STEP_PX = 16;++/** The overlay placements: which edge of the positioned parent the bar straddles, by axis. */+const EDGE_CLASS = {+ x: {+ start: "absolute inset-y-0 -left-[3px] z-20 w-1.5",+ end: "absolute inset-y-0 -right-[3px] z-20 w-1.5",+ },+ y: {+ start: "absolute inset-x-0 -top-[3px] z-20 h-1.5",+ end: "absolute inset-x-0 -bottom-[3px] z-20 h-1.5",+ },+} as const;++export interface ResizeHandleProps extends Omit<+ HTMLAttributes<HTMLDivElement>,+ "children" | "role" | "tabIndex" | "onResize" | "onDoubleClick" | "onKeyDown" | "onPointerDown"+> {+ /**+ * The axis the bar moves along: `x` is an upright bar dragged left and right (between two+ * columns), `y` a flat bar dragged up and down (above a bottom panel).+ */+ axis: "x" | "y";+ /** The bar's accessible name, and its tooltip. */+ label: string;+ /** Every pointer move of a drag, as the native event; the caller measures it against its box. */+ onResize: (event: PointerEvent) => void;+ /** A drag began: a caller that animates the box's size turns that off until it ends. */+ onResizeStart?: () => void;+ /** A drag ended: `committed` on a release (persist the size here, once per drag), not on a cancel. */+ onResizeEnd?: (committed: boolean) => void;+ /** A double click: back to the default size. */+ onReset?: () => void;+ /** The size the bar controls, in px, and its bounds — reported to assistive technology. */+ value?: number;+ min?: number;+ max?: number;+ /**+ * An arrow key along the axis, as the px to move by: positive is right (`x`) or down (`y`).+ * Given, the bar is focusable.+ */+ onStep?: (delta: number) => void;+ /** px per arrow key; `RESIZE_STEP_PX` by default. */+ step?: number;+ /** Straddle the positioned parent's start or end edge instead of taking a place in the row. */+ edge?: "start" | "end";+}++export function ResizeHandle({+ axis,+ label,+ onResize,+ onResizeStart,+ onResizeEnd,+ onReset,+ value,+ min,+ max,+ onStep,+ step = RESIZE_STEP_PX,+ edge,+ className = "",+ ...rest+}: ResizeHandleProps) {+ const [dragging, setDragging] = useState(false);++ const dragProps = usePointerDrag<object>({+ threshold: 0,+ begin: (event) => {+ event.preventDefault(); // no text selection while the bar is dragged+ setDragging(true);+ onResizeStart?.();+ return {};+ },+ onMove: (event) => onResize(event),+ onEnd: () => {+ setDragging(false);+ onResizeEnd?.(true);+ },+ onCancel: () => {+ setDragging(false);+ onResizeEnd?.(false);+ },+ });++ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {+ if (onStep === undefined) return;+ const back = axis === "x" ? "ArrowLeft" : "ArrowUp";+ const forward = axis === "x" ? "ArrowRight" : "ArrowDown";+ const delta = event.key === back ? -step : event.key === forward ? step : 0;+ if (delta === 0) return;+ event.preventDefault();+ onStep(delta);+ };++ const placement =+ edge === undefined+ ? axis === "x"+ ? "w-1.5 shrink-0"+ : "h-1.5 shrink-0"+ : EDGE_CLASS[axis][edge];++ return (+ <div+ {...rest}+ role="separator"+ // The bar's own orientation, which is across the axis it moves along.+ aria-orientation={axis === "x" ? "vertical" : "horizontal"}+ aria-label={label}+ aria-valuenow={value}+ aria-valuemin={min}+ aria-valuemax={max}+ data-tooltip={label}+ tabIndex={onStep === undefined ? undefined : 0}+ {...dragProps}+ onKeyDown={onKeyDown}+ onDoubleClick={onReset}+ className={`${placement} ${axis === "x" ? "cursor-col-resize" : "cursor-row-resize"} outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-fg-subtle/60 ${+ dragging ? "bg-tone-info-emphasis/60" : "bg-transparent hover:bg-tone-info-emphasis/40"+ } ${className}`}+ />+ );+}diff --git a/packages/ui/src/components/layout/resize-handle/split-pane.tsx b/packages/ui/src/components/layout/resize-handle/split-pane.tsxnew file mode 100644index 00000000..0bbbf8c9--- /dev/null+++ b/packages/ui/src/components/layout/resize-handle/split-pane.tsx@@ -0,0 +1,131 @@+/**+ * SplitPane: two columns side by side with a `ResizeHandle` between them — the leading one at a+ * width the caller keeps, the trailing one taking the rest. The Files panel's tree beside its+ * preview is one.+ *+ * The caller owns the width and its preference: `onResize` hands back each new width during a+ * drag (and per arrow key), already brought within `min`–`max` and rounded, and `onResizeEnd` the+ * width to keep once the gesture is over — once per drag, not per frame, which is when a caller+ * writes its stored preference.+ *+ * `collapsed` slides the leading column (with its handle) out of the container's start edge and+ * back. Both keep their own width inside a clipping window whose width is what moves, so the+ * column never reflows while it travels, and the trailing column takes the room it leaves. The+ * slide runs on the theme's layout motion (`data-layout-motion`), and only for the length of the+ * slide: the window's width also follows every drag of the handle, and a transition left on would+ * make the column trail a fifth of a second behind the pointer. A collapsed column is `inert` —+ * a column at zero width is not somewhere to tab into.+ */+import { useEffect, useRef, useState } from "react";+import type { ReactNode, TransitionEvent } from "react";+import { RESIZE_HANDLE_PX, ResizeHandle } from "./resize-handle";++/**+ * How long a slide may keep the layout motion on when its `transitionend` never arrives — under+ * reduced motion there is no transition at all. Comfortably past every theme's layout duration.+ */+const SLIDE_FALLBACK_MS = 400;++export interface SplitPaneProps {+ /** The leading column's width, in px. */+ size: number;+ min: number;+ max: number;+ /** A new width during a drag or per arrow key, within `min`–`max`. */+ onResize: (size: number) => void;+ /** The width to keep, once a drag or an arrow key is done with. */+ onResizeEnd?: (size: number) => void;+ /** The handle's accessible name and tooltip. */+ label: string;+ /** Slide the leading column out; it stays mounted, with everything it holds. */+ collapsed?: boolean;+ /** The leading column's content; it fills the column's height. */+ first: ReactNode;+ /** The trailing column: a flex item that takes the rest of the row. */+ second: ReactNode;+ className?: string;+}++export function SplitPane({+ size,+ min,+ max,+ onResize,+ onResizeEnd,+ label,+ collapsed = false,+ first,+ second,+ className = "",+}: SplitPaneProps) {+ const firstRef = useRef<HTMLDivElement | null>(null);+ // The width last handed out, which is what a release keeps: the `size` prop may still be a+ // render behind the pointer when the release lands.+ const requested = useRef(size);+ requested.current = size;++ // Armed in the render that flips `collapsed`, so the width change and the motion rule land in+ // the same commit and the transition starts from where the window was.+ const [sliding, setSliding] = useState(false);+ const [shownCollapsed, setShownCollapsed] = useState(collapsed);+ if (shownCollapsed !== collapsed) {+ setShownCollapsed(collapsed);+ setSliding(true);+ }+ useEffect(() => {+ if (!sliding) return;+ const timer = window.setTimeout(() => setSliding(false), SLIDE_FALLBACK_MS);+ return () => window.clearTimeout(timer);+ }, [sliding, collapsed]);++ const clamp = (px: number): number => Math.min(max, Math.max(min, Math.round(px)));+ const request = (px: number): number => {+ const next = clamp(px);+ requested.current = next;+ onResize(next);+ return next;+ };++ const onSlideEnd = (event: TransitionEvent<HTMLDivElement>): void => {+ if (event.target === event.currentTarget && event.propertyName === "width") setSliding(false);+ };++ return (+ <div className={`flex min-h-0 ${className}`}>+ <div+ aria-hidden={collapsed}+ inert={collapsed}+ style={{ width: collapsed ? 0 : size + RESIZE_HANDLE_PX }}+ {...(sliding ? { "data-layout-motion": "" } : {})}+ onTransitionEnd={onSlideEnd}+ className="flex min-h-0 shrink-0 overflow-hidden"+ >+ <div+ ref={firstRef}+ style={{ width: size }}+ className="flex min-h-0 shrink-0 flex-col border-r border-line"+ >+ {first}+ </div>+ <ResizeHandle+ axis="x"+ label={label}+ value={size}+ min={min}+ max={max}+ // Against the column's own left edge rather than an accumulated delta, so a drag that+ // outruns the bounds comes back in step instead of offset by however far it overshot.+ onResize={(event) => {+ const rect = firstRef.current?.getBoundingClientRect();+ if (rect) request(event.clientX - rect.left);+ }}+ onResizeEnd={(committed) => {+ if (committed) onResizeEnd?.(requested.current);+ }}+ onStep={(delta) => onResizeEnd?.(request(size + delta))}+ />+ </div>+ {second}+ </div>+ );+}diff --git a/packages/web/src/features/dock/use-pointer-drag.ts b/packages/ui/src/components/layout/resize-handle/use-pointer-drag.tssimilarity index 87%rename from packages/web/src/features/dock/use-pointer-drag.tsrename to packages/ui/src/components/layout/resize-handle/use-pointer-drag.tsindex 8101f641..96a5ee30 100644--- a/packages/web/src/features/dock/use-pointer-drag.ts+++ b/packages/ui/src/components/layout/resize-handle/use-pointer-drag.ts@@ -1,8 +1,8 @@/**- * Shared pointer-drag state machine for the dock's gestures (header move, tab drag, boundary- * resize) and the context gauge's threshold cutter: a movement threshold separating taps from- * drags, and latest-callback refs so `onEnd` never sees stale state. Spread the returned props- * on the gesture's surface.+ * The pointer-drag state machine every drag gesture in the app shares — a resize handle, the+ * dock's header move and tab drag, a canvas pan, a gauge's threshold cutter: a movement threshold+ * separating taps from drags, and latest-callback refs so `onEnd` never sees stale state. Spread+ * the returned props on the gesture's surface.** The press is taken on the element; everything after it runs on WINDOW listeners. An* element-bound `pointermove` stops arriving the moment pointer capture is lost — a control@@ -14,6 +14,7 @@* keeps a fast pull from selecting text or scrolling the page under it; losing it costs nothing.*/import { useEffect, useMemo, useRef } from "react";+import type { PointerEvent as ReactPointerEvent } from "react";interface DragState<T> {payload: T;@@ -26,9 +27,9 @@ interface DragState<T> {release: () => void;}-export function usePointerDrag<T>(options: {+export interface PointerDragOptions<T> {/** Resolves the drag payload from the initial event; null refuses the gesture. */- begin: (event: React.PointerEvent<HTMLElement>) => T | null;+ begin: (event: ReactPointerEvent<HTMLElement>) => T | null;/** px of movement that turns the press into a drag (0 = immediately). */threshold?: number;/** Movement, as the native event: the gesture is tracked on the window, not on the element. */@@ -37,7 +38,11 @@ export function usePointerDrag<T>(options: {onEnd?: (payload: T, dragged: boolean) => void;/** Abandoned gesture (pointercancel): clear visuals, apply nothing. */onCancel?: () => void;-}) {+}++export function usePointerDrag<T>(options: PointerDragOptions<T>): {+ onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;+} {const latest = useRef(options);latest.current = options;const state = useRef<DragState<T> | null>(null);@@ -48,7 +53,7 @@ export function usePointerDrag<T>(options: {return useMemo(() => ({- onPointerDown: (event: React.PointerEvent<HTMLElement>) => {+ onPointerDown: (event: ReactPointerEvent<HTMLElement>) => {if (event.button !== 0) return;// A second press while a gesture is live (another finger, a release the window never// saw): abandon the old one rather than leave its visuals stuck.diff --git a/packages/ui/src/components/navigation/breadcrumbs/breadcrumbs.tsx b/packages/ui/src/components/navigation/breadcrumbs/breadcrumbs.tsxnew file mode 100644index 00000000..0e61c7eb--- /dev/null+++ b/packages/ui/src/components/navigation/breadcrumbs/breadcrumbs.tsx@@ -0,0 +1,95 @@+/**+ * Breadcrumbs: a path on one row that never wraps — the Files panel's header names the open file+ * or folder this way. When the path outgrows the row, its leading items collapse into a single+ * "…" (crumb-fit.ts decides how many fit, from the strip's own measured width), so whatever+ * shares the row keeps its place. The last item is where the path ends and outranks the rest: it+ * does not shrink, so the items before it give way first, and when it alone outruns the strip its+ * stem ellipsizes while its extension stays.+ *+ * The strip measures the space it is given, never its own content: give it `flex-1` (a zero+ * basis) beside the row's other controls, and it reports the width they leave over, with no+ * feedback loop. Until the first measurement it shows the whole path — a "…" for one frame on a+ * path that fits would read as a flicker.+ *+ * An item with `onClick` is a button that goes there; without, the item is read out and nothing+ * more — the Files panel's path is not navigable, because the tree beside it is what navigates.+ * `title` is the strip's tooltip: the whole path, however much of it is on screen.+ */+import { Fragment, useLayoutEffect, useRef, useState } from "react";+import { CRUMB_ELLIPSIS, crumbItemWidth, splitFileName, visibleCrumbSegments } from "./crumb-fit";++export interface BreadcrumbItem {+ label: string;+ /** Go to this item; omitted, the item is text. */+ onClick?: () => void;+}++export function Breadcrumbs({+ items,+ title,+ className = "",+}: {+ items: readonly BreadcrumbItem[];+ /** The strip's tooltip — the whole path. */+ title?: string;+ className?: string;+}) {+ const ref = useRef<HTMLDivElement | null>(null);+ const [width, setWidth] = useState(0);++ useLayoutEffect(() => {+ const el = ref.current;+ if (!el) return;+ const measure = () => setWidth(Math.round(el.getBoundingClientRect().width));+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ const fit = visibleCrumbSegments(+ items.map((item) => item.label),+ width > 0 ? width : Number.POSITIVE_INFINITY,+ crumbItemWidth,+ );+ // The fit keeps a tail, so the items on screen are the last `visible.length` of them.+ const shown = items.slice(items.length - fit.visible.length);++ return (+ <div+ ref={ref}+ data-tooltip={title}+ className={`flex min-w-0 items-center gap-1 overflow-hidden px-1 text-sm ${className}`}+ >+ {fit.collapsed && <span className="shrink-0 text-fg-subtle">{CRUMB_ELLIPSIS}</span>}+ {shown.map((item, i) => {+ const last = i === shown.length - 1;+ const text = last ? (+ // The stem gives way before the extension, which says what kind of file this is.+ <span className="flex min-w-0 max-w-full shrink-0 items-center font-medium text-fg">+ <span className="min-w-0 truncate">{splitFileName(item.label).stem}</span>+ <span className="shrink-0">{splitFileName(item.label).ext}</span>+ </span>+ ) : (+ <span className="min-w-0 shrink truncate text-fg-muted">{item.label}</span>+ );+ return (+ <Fragment key={`${i}-${item.label}`}>+ {(fit.collapsed || i > 0) && <span className="shrink-0 text-line-emphasis">/</span>}+ {item.onClick === undefined ? (+ text+ ) : (+ <button+ type="button"+ onClick={item.onClick}+ className={`flex min-w-0 items-center rounded-sm transition-colors duration-150 hover:text-fg ${last ? "max-w-full shrink-0" : "shrink"}`}+ >+ {text}+ </button>+ )}+ </Fragment>+ );+ })}+ </div>+ );+}diff --git a/packages/ui/src/components/navigation/breadcrumbs/crumb-fit.ts b/packages/ui/src/components/navigation/breadcrumbs/crumb-fit.tsnew file mode 100644index 00000000..36b85c71--- /dev/null+++ b/packages/ui/src/components/navigation/breadcrumbs/crumb-fit.ts@@ -0,0 +1,72 @@+/**+ * How much of a path a one-row breadcrumb strip can show — pure, so the fit is unit-tested:+ * which trailing items fit across the strip, an estimate of an item's rendered width to fit them+ * by, and how a file name splits so that its stem gives way before its extension.+ */++/** The single item a run of dropped leading items collapses into. */+export const CRUMB_ELLIPSIS = "…";++/** What of a path the strip can show: the trailing items that fit, and whether anything was dropped ahead of them. */+export interface CrumbLayout {+ visible: string[];+ collapsed: boolean;+}++/**+ * Which items fit across `availablePx`, tail first. The last item — where the path ends — is+ * always kept, however long it is; leading items are taken while they fit and the rest collapse+ * into one ellipsis item, so whatever shares the row is never pushed onto a second one.+ * `measure` gives a rendered item's width in px, ellipsis item included, which is what lets a+ * test state a fixed per-character width.+ */+export function visibleCrumbSegments(+ segments: readonly string[],+ availablePx: number,+ measure: (text: string) => number,+): CrumbLayout {+ if (segments.length === 0) return { visible: [], collapsed: false };+ const last = segments.length - 1;+ const visible = [segments[last]!];+ let used = measure(segments[last]!);+ for (let i = last - 1; i >= 0; i -= 1) {+ // Taking this item still leaves an ellipsis ahead of it unless it is the first one, so the+ // ellipsis is priced into every step but the last.+ const ellipsis = i > 0 ? measure(CRUMB_ELLIPSIS) : 0;+ const width = measure(segments[i]!);+ if (used + width + ellipsis > availablePx) break;+ visible.unshift(segments[i]!);+ used += width;+ }+ return { visible, collapsed: visible.length < segments.length };+}++/**+ * An item's rendered width, approximated: the strip has no text metrics to measure against, so+ * one character at the strip's text size costs CRUMB_CHAR_PX (a wide character — CJK, full-width+ * punctuation — two of those) and the item itself costs its gap plus the separator drawn before+ * it. Erring wide is the safe direction: it collapses one item early rather than letting the row+ * outgrow its space.+ */+const CRUMB_CHAR_PX = 7;+const CRUMB_ITEM_PX = 16;+const WIDE_CHAR_RE = /[ᄀ-ᅟ⺀-가-힣豈-︰--⦆¢-₩]/;++export function crumbItemWidth(text: string): number {+ let cells = 0;+ for (const ch of text) cells += WIDE_CHAR_RE.test(ch) ? 2 : 1;+ return CRUMB_ITEM_PX + cells * CRUMB_CHAR_PX;+}++/**+ * 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: "" };+}diff --git a/packages/ui/src/components/navigation/dock-tabs/dock-tabs.tsx b/packages/ui/src/components/navigation/dock-tabs/dock-tabs.tsxnew file mode 100644index 00000000..bdd88c7d--- /dev/null+++ b/packages/ui/src/components/navigation/dock-tabs/dock-tabs.tsx@@ -0,0 +1,172 @@+/**+ * A dock's tab strip: pill tabs, each a glyph, a name and an always-visible ×, in a row that+ * scrolls sideways once the tabs outgrow it.+ *+ * The strip is a tab list: each tab's select button is the `role="tab"`, so the selected tab's+ * marker is the theme's to draw through the `ui-underline-nav` hook (Primer draws none; the pill's+ * fill is the mark). The × is a sibling of the select button, never nested in it — a button inside+ * a button is invalid and unclickable — with a slot of its own after the name: crowded tabs shrink+ * by truncating the name while the glyph and the × keep their width, so the close target stays+ * where the pointer expects it.+ *+ * The strip keeps the shown tab in view (a half-clipped active tab reads as a stray × at the+ * strip's edge), and a wheel over it scrolls it sideways. What a drag does to the tabs is the+ * caller's: it spreads its pointer handlers on the strip and reads the tabs back by their+ * `data-tab-id`, which is why the strip's node can be shared through `stripRef`.+ */+import { useEffect, useRef } from "react";+import type { HTMLAttributes, ReactNode, RefObject } from "react";+import { CloseIcon } from "../../icons/marks/marks";+import { Dot } from "../../icons/dot/dot";++export interface DockTabItem {+ /** Stable id: the tab's `data-tab-id`, and what `onSelect` / `onClose` receive. */+ key: string;+ label: string;+ /** The hover hint; the label when omitted (a terminal's names its shell and directory). */+ title?: string;+ glyph: ReactNode;+ /** An attention dot beside the name (a pending approval behind the tab). */+ badge?: boolean;+ /** The ×'s verb: its tooltip, and with the label its accessible name. */+ closeLabel: string;+ /** The shortcut that runs the same close, named after the verb in the ×'s tooltip. */+ closeShortcut?: string;+ /** A terminal tab keeps its shell's id on the node, for the strip's drag and for tests. */+ terminalId?: string;+}++export interface DockTabButtonProps {+ tab: DockTabItem;+ active: boolean;+ /** A finger is the pointer: the pill and its × grow to targets a finger can land in. */+ coarse?: boolean;+ onSelect: () => void;+ onClose: () => void;+}++/** One pill in the strip: the select button (the tab) and its ×, side by side. */+export function DockTabButton({+ tab,+ active,+ coarse = false,+ onSelect,+ onClose,+}: DockTabButtonProps) {+ return (+ <div+ data-testid="dock-tab"+ data-tab-id={tab.key}+ {...(tab.terminalId !== undefined ? { "data-terminal-id": tab.terminalId } : {})}+ data-active={active}+ className={`flex ${coarse ? "h-8" : "h-6"} max-w-44 items-center rounded-md pr-0.5 transition-colors duration-150 ${+ active ? "bg-line-muted text-fg" : "text-fg-muted hover:bg-line-muted hover:text-fg"+ }`}+ >+ <button+ type="button"+ role="tab"+ aria-selected={active}+ data-tooltip={tab.title ?? tab.label}+ onClick={onSelect}+ className="flex h-full min-w-0 flex-1 items-center gap-1.5 pl-2 pr-1 text-left text-xs"+ >+ <span aria-hidden className="shrink-0">+ {tab.glyph}+ </span>+ <span className="min-w-0 truncate">{tab.label}</span>+ {tab.badge === true && <Dot tone="attention" />}+ </button>+ <button+ type="button"+ data-tooltip={+ tab.closeShortcut !== undefined+ ? `${tab.closeLabel} (${tab.closeShortcut})`+ : tab.closeLabel+ }+ aria-label={`${tab.closeLabel}: ${tab.label}`}+ data-testid="dock-tab-close"+ onClick={onClose}+ className={`flex ${coarse ? "h-6 w-6" : "h-4 w-4"} shrink-0 items-center justify-center rounded-sm text-fg-subtle transition-colors duration-150 hover:bg-line-emphasis hover:text-fg`}+ >+ <CloseIcon size={10} />+ </button>+ </div>+ );+}++export interface DockTabsProps extends Omit<HTMLAttributes<HTMLDivElement>, "onSelect"> {+ tabs: readonly DockTabItem[];+ /** The shown tab's key; null while nothing is shown. */+ active: string | null;+ onSelect: (key: string) => void;+ onClose: (key: string) => void;+ /** A finger is the pointer: larger pills and × targets (the glyphs keep their size). */+ coarse?: boolean;+ /** The strip's node, for a caller that hit-tests its tabs during a drag. */+ stripRef?: RefObject<HTMLDivElement | null>;+}++export function DockTabs({+ tabs,+ active,+ onSelect,+ onClose,+ coarse = false,+ stripRef,+ className = "",+ ...rest+}: DockTabsProps) {+ const ownRef = useRef<HTMLDivElement | null>(null);+ const ref = stripRef ?? ownRef;++ // The shown tab keeps itself in view: with many tabs the strip scrolls. It follows the shown+ // tab and the strip's lineup, not every render — a re-render for a new title must not pull a+ // strip the user scrolled back to the shown tab.+ const lineup = tabs.map((tab) => tab.key).join("\n");+ useEffect(() => {+ if (active === null) return;+ ref.current+ ?.querySelector(`[data-tab-id="${CSS.escape(active)}"]`)+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });+ }, [active, lineup, ref]);++ // A wheel over the strip scrolls it sideways (there is no vertical axis to scroll, and a+ // trackpad's deltaX works too). A native non-passive listener: React's synthetic onWheel is+ // passive, so preventDefault there cannot stop the page handling the event.+ useEffect(() => {+ const strip = ref.current;+ if (!strip) return;+ const onWheel = (event: WheelEvent): void => {+ const delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;+ if (delta === 0 || strip.scrollWidth <= strip.clientWidth) return;+ event.preventDefault();+ strip.scrollLeft += delta;+ };+ strip.addEventListener("wheel", onWheel, { passive: false });+ return () => strip.removeEventListener("wheel", onWheel);+ }, [ref]);++ return (+ <div+ ref={ref}+ role="tablist"+ data-testid="dock-tab-strip"+ {...rest}+ // overflow-y-hidden: only the horizontal axis scrolls, so a theme's marker drawn just below+ // a tab cannot make the strip scroll vertically.+ className={`ui-underline-nav flex min-w-0 items-center gap-1 overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden ${className}`}+ >+ {tabs.map((tab) => (+ <DockTabButton+ key={tab.key}+ tab={tab}+ active={tab.key === active}+ coarse={coarse}+ onSelect={() => onSelect(tab.key)}+ onClose={() => onClose(tab.key)}+ />+ ))}+ </div>+ );+}diff --git a/packages/ui/src/components/navigation/group-header/group-header.tsx b/packages/ui/src/components/navigation/group-header/group-header.tsxindex 60da0571..46859726 100644--- a/packages/ui/src/components/navigation/group-header/group-header.tsx+++ b/packages/ui/src/components/navigation/group-header/group-header.tsx@@ -14,6 +14,7 @@import type { DragEvent as ReactDragEvent, ReactNode } from "react";import { useUiStrings } from "../../../strings";import { Chevron } from "../../icons/chevron/chevron";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";import { ICON_SIZE } from "../../../icon-scale";/** A folder toggle's and a "more" row's shape: a dense, muted row with a chevron column. */@@ -160,6 +161,7 @@ export function GroupHeader({open,onToggle,icon,+ glyph,label,uppercase = false,muted = false,@@ -175,8 +177,14 @@ export function GroupHeader({}: {open: boolean;onToggle: () => void;- /** The leading visual (an avatar, a folder glyph), sized by the caller. */- icon: ReactNode;+ /** The leading visual the caller sized: an avatar, which says who the group is. */+ icon?: ReactNode;+ /**+ * The leading glyph as a registry path (a folder, a calendar), drawn at the header's glyph rung+ * in the subtle ink. It repeats what the label says, so it is decorative (`ui-icon-decor`, role+ * `group`): a theme may recolour or drop it. Takes the place of `icon`.+ */+ glyph?: string;label: string;/** A group label rather than a name whose casing matters: set on the eyebrow rung. */uppercase?: boolean;@@ -219,7 +227,16 @@ export function GroupHeader({{...(title !== undefined ? { "data-tooltip": title } : {})}className="flex min-w-0 flex-1 items-center gap-1 self-stretch rounded px-1 py-0.5 text-left transition-colors duration-150 hover:bg-fg/5">- {icon}+ {glyph !== undefined ? (+ <GlyphIcon+ d={glyph}+ size={ICON_SIZE.groupHeaderGlyph}+ decor="group"+ className="text-fg-subtle"+ />+ ) : (+ icon+ )}<spanclassName={`min-w-0 truncate ${uppercase ? "ui-eyebrow" : "text-xs font-semibold"} ${ink}`}>diff --git a/packages/ui/src/components/navigation/nav-list/nav-list.tsx b/packages/ui/src/components/navigation/nav-list/nav-list.tsxindex 2aa4de96..ef780a3c 100644--- a/packages/ui/src/components/navigation/nav-list/nav-list.tsx+++ b/packages/ui/src/components/navigation/nav-list/nav-list.tsx@@ -1,8 +1,8 @@/**- * A navigation list and its rows: the rail of a paged dialog, a settings rail, and (later) the- * sidebar's page links and the dock's picker. A row is a glyph, a label and an optional trailing- * badge; the current row takes a solid fill and `aria-current="page"`, the others a lighter fill- * under the pointer.+ * A navigation list and its rows: the rail of a paged dialog, a settings rail, the sidebar's page+ * links, and (later) the dock's picker. A row is a glyph, a label and an optional trailing badge;+ * the current row takes a solid fill and `aria-current="page"`, the others a lighter fill under the+ * pointer.** `NavList` is the named `<nav>`. Vertical, its rows stack at the rail's width; responsive, it is* a horizontal strip that scrolls sideways below the `sm` breakpoint and a vertical rail from it@@ -12,7 +12,13 @@* `NavRow` is a button by default (a rail that switches panes), a link with `href`. The glyph is* decoration — the label beside it already says what it says — so it carries the* `ui-icon-decor` hook with the `nav` role, and a theme may recolour or drop it. A label is text,- * never mono. A router link takes the row's look through {@link navRowClass}.+ * never mono. A router's link draws the row through `renderLink`, which hands it the row's+ * classes, state and content; an element the row does not draw at all takes the row's look+ * through {@link navRowClass}.+ *+ * A row on the app's navigation column (`surface="muted"`) sits on the muted surface, where a+ * surface step would not show: its hover and its selection are thin washes of the ink instead+ * ({@link NAV_FILL}), which every other row on that column reads too.*/import { createContext, useContext } from "react";import type { ReactNode } from "react";@@ -24,6 +30,23 @@ export type NavListOrientation = "vertical" | "responsive";/** `md` for a rail or a sidebar (the default); `sm` for a dense list inside a panel. */export type NavRowDensity = "sm" | "md";+/**+ * What a row sits on: `default`, a page or a dialog; `muted`, the app's navigation column, whose+ * own fill is the muted surface.+ */+export type NavSurface = "default" | "muted";++/**+ * The fills of a row on the navigation column's muted surface: a wash of the ink under the+ * pointer and a slightly heavier one on the selected row. The column's page rows, its+ * conversation rows, the rail's entries and the column's own controls all take these two, so one+ * hover and one selection hold across the column.+ */+export const NAV_FILL = {+ hover: "hover:bg-fg/5",+ selected: "bg-fg/7",+} as const;+const NavOrientationContext = createContext<NavListOrientation>("vertical");export interface NavListProps {@@ -65,31 +88,59 @@ const GLYPH_SIZE: Record<NavRowDensity, number> = {sm: ICON_SIZE.inlineGlyph,};+/** The selected and resting looks, per surface. */+const STATE: Record<NavSurface, { active: string; rest: string }> = {+ default: {+ active: "bg-line-muted font-medium text-fg",+ rest: "text-fg-muted hover:bg-surface-muted hover:text-fg",+ },+ muted: {+ active: `${NAV_FILL.selected} font-medium text-fg`,+ rest: `text-fg-muted ${NAV_FILL.hover} hover:text-fg`,+ },+};+/**- * A row's classes, for an element the row cannot render itself (a router's link). The width- * follows the list: full in a vertical rail, the label's own in a horizontal strip, which keeps- * every row whole rather than squeezing their labels.+ * A row's classes, for an element the row cannot render itself. The width follows the list: full+ * in a vertical rail, the label's own in a horizontal strip, which keeps every row whole rather+ * than squeezing their labels.*/export function navRowClass({active = false,disabled = false,density = "md",orientation = "vertical",+ surface = "default",}: {active?: boolean;disabled?: boolean;density?: NavRowDensity;orientation?: NavListOrientation;+ surface?: NavSurface;} = {}): string {const width = orientation === "responsive" ? "shrink-0 sm:w-full" : "w-full";const state = disabled? "cursor-not-allowed text-fg-subtle": active- ? "bg-line-muted font-medium text-fg"- : "text-fg-muted hover:bg-surface-muted hover:text-fg";+ ? STATE[surface].active+ : STATE[surface].rest;return `flex ${width} items-center whitespace-nowrap rounded-md text-left transition-colors duration-150 ${DENSITY[density]} ${state}`;}+/**+ * What a row hands `renderLink`: everything its own `<a>` would carry, for the caller's link+ * element to spread onto itself (a router's link takes `href` as its destination).+ */+export interface NavRowLinkProps {+ href: string;+ className: string;+ "aria-current"?: "page";+ "aria-label"?: string;+ "data-tooltip"?: string;+ onClick?: () => void;+ children: ReactNode;+}+export interface NavRowProps {label: ReactNode;/** A 24×24 line path drawn on the row's glyph rung, or a mark the caller sizes. Decorative. */@@ -101,8 +152,12 @@ export interface NavRowProps {/** Nowhere to go right now: muted, no hover fill, not focusable as a link. */disabled?: boolean;density?: NavRowDensity;+ /** The surface the row sits on: `muted` on the app's navigation column. */+ surface?: NavSurface;/** Renders a link to this address instead of a button. */href?: string;+ /** With `href`: draws the link through the caller's own element (a router's) instead of `<a>`. */+ renderLink?: (link: NavRowLinkProps) => ReactNode;onClick?: () => void;/** The accessible name, when the badge adds to what the label says. */ariaLabel?: string;@@ -118,14 +173,16 @@ export function NavRow({active = false,disabled = false,density = "md",+ surface = "default",href,+ renderLink,onClick,ariaLabel,tooltip,className = "",}: NavRowProps) {const orientation = useContext(NavOrientationContext);- const classes = `${navRowClass({ active, disabled, density, orientation })} ${className}`;+ const classes = `${navRowClass({ active, disabled, density, orientation, surface })} ${className}`;const current = active && !disabled ? ("page" as const) : undefined;const named = {...(ariaLabel !== undefined ? { "aria-label": ariaLabel } : {}),@@ -144,11 +201,28 @@ export function NavRow({);if (href !== undefined) {// A link with nowhere to go keeps its place in the list but leaves the tab order.- return disabled ? (- <span role="link" aria-disabled="true" {...named} className={classes}>- {content}- </span>- ) : (+ if (disabled) {+ return (+ <span role="link" aria-disabled="true" {...named} className={classes}>+ {content}+ </span>+ );+ }+ if (renderLink !== undefined) {+ return (+ <>+ {renderLink({+ href,+ className: classes,+ ...(current !== undefined ? { "aria-current": current } : {}),+ ...named,+ ...(onClick !== undefined ? { onClick } : {}),+ children: content,+ })}+ </>+ );+ }+ return (<a href={href} aria-current={current} onClick={onClick} {...named} className={classes}>{content}</a>diff --git a/packages/ui/src/components/shell/app-shell/app-shell.tsx b/packages/ui/src/components/shell/app-shell/app-shell.tsxnew file mode 100644index 00000000..a43e340b--- /dev/null+++ b/packages/ui/src/components/shell/app-shell/app-shell.tsx@@ -0,0 +1,58 @@+/**+ * The app window: the navigation column beside the main column, and a dock column on the right+ * when the caller has one. It carries the `ui-shell` hook, so a theme may paint a field behind the+ * window, float the main column or rule the columns apart; the columns are its `nav`, `main` and+ * `dock` slots, and the selected row inside the navigation column is the one marked+ * `aria-current="page"`.+ *+ * The navigation column is hidden below `md` — a phone reaches the same content in a drawer,+ * opened from the `MobileTopBar` at the top of the main column — and folds to the rail's width+ * when `navCollapsed`. The fold animates the column's width through the theme's layout motion+ * (`data-layout-motion`), the one property this box may animate at all: the column is in flow, so+ * the main column reflows beside it rather than being slid over, and a transform, a `will-change`+ * or an opacity below 1 would each make it a stacking context and trap the menus the column opens.+ * Its content is laid out at the width it will keep and clipped by the column, so it never+ * reflows mid-fold: the rail sits at its final width from the first frame while the column closes+ * around it, and the pinned sidebar is uncovered left to right.+ *+ * Nothing in the window is fixed or transformed: chrome that makes a stacking context would trap+ * the overlays the columns open.+ */+import type { ReactNode } from "react";++export interface AppShellProps {+ /** The navigation column: the pinned sidebar, or the rail while the column is folded. */+ nav: ReactNode;+ /** Fold the navigation column to the rail's width. */+ navCollapsed?: boolean;+ /** The main column: the mobile top bar, any window-wide notice, the page. */+ children: ReactNode;+ /** A column docked on the right, when the caller has one. */+ dock?: ReactNode;+ /** Layers mounted beside the columns rather than in one: dialogs, the phone's drawer. */+ overlays?: ReactNode;+}++export function AppShell({ nav, navCollapsed = false, children, dock, overlays }: AppShellProps) {+ const width = navCollapsed ? "w-12" : "w-64 lg:w-72";+ return (+ <div className="ui-shell flex h-full">+ <aside+ data-slot="nav"+ data-layout-motion+ className={`hidden shrink-0 overflow-hidden border-r border-line bg-surface-muted md:block ${width}`}+ >+ <div className={`h-full ${width}`}>{nav}</div>+ </aside>+ <div data-slot="main" className="flex min-w-0 flex-1 flex-col">+ {children}+ </div>+ {dock !== undefined && (+ <div data-slot="dock" className="flex shrink-0 flex-col border-l border-line">+ {dock}+ </div>+ )}+ {overlays}+ </div>+ );+}diff --git a/packages/ui/src/components/shell/dock-frame/dock-frame.tsx b/packages/ui/src/components/shell/dock-frame/dock-frame.tsxnew file mode 100644index 00000000..e6941b41--- /dev/null+++ b/packages/ui/src/components/shell/dock-frame/dock-frame.tsx@@ -0,0 +1,160 @@+/**+ * A dock surface's frame: the header (the tab strip, a spacer, the action cluster) above the+ * shown tab's body, in a box that opens from an edge of the page — the bottom (a full-width+ * band) or the right (a column beside the conversation).+ *+ * The frame never unmounts to hide: a closed dock stays in the tree at size 0 and inert, so the+ * bodies inside keep their scroll, their drill-down and their unsaved text, and `data-open` says+ * what is on screen. Its size is the caller's, in pixels: `size` is what the box shows (0 while+ * collapsed or before the entrance), `contentSize` the settled size its content lays out at, so+ * while the box animates past intermediate sizes nothing inside reflows — text does not squeeze+ * and a terminal does not refit its grid on every frame. The animation is the theme's layout+ * motion, off while a drag resizes or a flip must land at once.+ *+ * The border belongs to the open state only: with border-box sizing a collapsed dock would still+ * paint its 1px, leaving a hairline where nothing is. The resize handle is the caller's too, shown+ * only while open: an overlay straddling the bottom dock's top edge (it costs no height), and a+ * layout sibling before the right dock (it must cost real width, so the conversation measures+ * the same under every surface).+ */+import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode, Ref } from "react";++export type DockEdge = "right" | "bottom";++/** A small square header button: the dock's add, detach, move and hide controls. */+export function DockHeaderButton({+ label,+ coarse = false,+ children,+ className = "",+ ...rest+}: Omit<ButtonHTMLAttributes<HTMLButtonElement>, "aria-label"> & {+ /** The accessible name and the tooltip. */+ label: string;+ /**+ * A finger is the pointer: a 24px box is a comfortable mouse target and a poor finger one, so+ * the box grows while the glyph inside keeps its size.+ */+ coarse?: boolean;+ children: ReactNode;+}) {+ return (+ <button+ type="button"+ data-tooltip={label}+ aria-label={label}+ {...rest}+ className={`flex ${coarse ? "h-8 w-8" : "h-6 w-6"} shrink-0 items-center justify-center rounded-sm text-fg-subtle transition-colors duration-150 hover:bg-line-muted hover:text-fg ${className}`}+ >+ {children}+ </button>+ );+}++export interface DockFrameProps {+ position: DockEdge;+ /** False while the dock collapses on its way out: it stays mounted at size 0, inert. */+ open: boolean;+ /** The box's size on screen (px): the bottom dock's height, the right dock's width. */+ size: number;+ /** The settled size the content lays out at (px), whatever the box is passing through. */+ contentSize: number;+ /** Whether a change of `size` animates. */+ animate: boolean;+ /** The tab strip (`DockTabs`). */+ tabs: ReactNode;+ /** The header's right-hand cluster, evenly spaced, ending in the dock's hide button. */+ actions: ReactNode;+ /**+ * Pointer handlers on the header, for a caller that lets the header drag the whole dock.+ * `movable` shows the grab cursor for it.+ */+ headerProps?: HTMLAttributes<HTMLElement>;+ movable?: boolean;+ /** The shown tab's body, or the picker while the dock has no tabs. */+ children: ReactNode;+ /** The resize handle, rendered only while open. */+ handle?: ReactNode;+ /** Layers that belong to the dock but float over the page (a drag overlay, a confirmation). */+ overlays?: ReactNode;+ /** The box's node: the resize handle measures it, and a drop preview finds it. */+ rootRef?: Ref<HTMLDivElement>;+}++export function DockFrame({+ position,+ open,+ size,+ contentSize,+ animate,+ tabs,+ actions,+ headerProps,+ movable = false,+ children,+ handle,+ overlays,+ rootRef,+}: DockFrameProps) {+ const header = (+ <header+ data-testid="dock-header"+ {...headerProps}+ className={`flex shrink-0 items-center gap-2 border-b border-line px-2 py-1.5 text-xs ${+ movable ? "cursor-grab select-none" : ""+ }`}+ >+ {tabs}+ <span className="min-w-0 flex-1" />+ <div className="flex shrink-0 items-center gap-1.5">{actions}</div>+ </header>+ );++ if (position === "bottom") {+ return (+ <div+ ref={rootRef}+ data-testid="dock"+ data-position="bottom"+ data-open={open}+ data-layout-motion={animate ? "" : undefined}+ style={{ height: size }}+ inert={!open}+ className={`relative flex w-full shrink-0 flex-col overflow-hidden bg-canvas ${+ open ? "border-t border-line" : ""+ }`}+ >+ {open && handle}+ <div style={{ height: contentSize }} className="flex min-h-0 shrink-0 flex-col">+ {header}+ {children}+ </div>+ {overlays}+ </div>+ );+ }++ return (+ <>+ {open && handle}+ <div+ ref={rootRef}+ data-testid="dock"+ data-position="right"+ data-open={open}+ data-layout-motion={animate ? "" : undefined}+ style={{ width: size }}+ inert={!open}+ className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden bg-canvas ${+ open ? "border-l border-line" : ""+ }`}+ >+ <div style={{ width: contentSize }} className="flex min-h-0 flex-1 flex-col">+ {header}+ {children}+ </div>+ {overlays}+ </div>+ </>+ );+}diff --git a/packages/ui/src/components/shell/dock-picker/dock-picker.tsx b/packages/ui/src/components/shell/dock-picker/dock-picker.tsxnew file mode 100644index 00000000..f99f4e3e--- /dev/null+++ b/packages/ui/src/components/shell/dock-picker/dock-picker.tsx@@ -0,0 +1,58 @@+/**+ * The body of an open dock that has no tabs yet: a centred list of what can open there, one row+ * per choice — a glyph and a name, and the key caps of a shortcut that does the same thing.+ * The bottom surface lays its choices out in a wrapping row; the right one stacks them.+ */+import type { HTMLAttributes, ReactNode } from "react";+import { ICON_GAP } from "../../../icon-scale";+import { Kbd } from "../../actions/kbd/kbd";++export interface DockPickerChoice {+ /** Stable id: the row's test id is `dock-pick-<key>`. */+ key: string;+ label: string;+ glyph: ReactNode;+ /** A shortcut that makes the same choice, as the platform names its keys (`["Ctrl", "`"]`). */+ keys?: readonly string[];+ onChoose: () => void;+}++export interface DockPickerProps extends HTMLAttributes<HTMLDivElement> {+ choices: readonly DockPickerChoice[];+ /** A row of choices (the bottom surface) instead of a list (the right one). */+ horizontal: boolean;+}++export function DockPicker({ choices, horizontal, className = "", ...rest }: DockPickerProps) {+ return (+ <div+ data-testid="dock-picker"+ {...rest}+ className={`flex min-h-0 flex-1 items-center justify-center overflow-y-auto p-4 ${className}`}+ >+ <div+ className={+ horizontal+ ? "flex max-w-full flex-wrap items-center justify-center gap-1"+ : "flex w-60 flex-col gap-1"+ }+ >+ {choices.map((choice) => (+ <button+ key={choice.key}+ type="button"+ data-testid={`dock-pick-${choice.key}`}+ onClick={choice.onChoose}+ className={`flex items-center ${ICON_GAP.menu} rounded-md px-3 py-2 text-left text-sm text-fg-muted transition-colors duration-150 hover:bg-line-muted hover:text-fg`}+ >+ <span className="shrink-0 text-fg-muted">{choice.glyph}</span>+ <span className={`min-w-0 truncate ${choice.keys === undefined ? "" : "flex-1"}`}>+ {choice.label}+ </span>+ {choice.keys !== undefined && <Kbd keys={choice.keys} />}+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/components/shell/launcher/launcher.tsx b/packages/ui/src/components/shell/launcher/launcher.tsxnew file mode 100644index 00000000..3564e087--- /dev/null+++ b/packages/ui/src/components/shell/launcher/launcher.tsx@@ -0,0 +1,195 @@+/**+ * The floating launcher: a round, translucent ball floating over the conversation, with a short+ * caption hanging under it, and the fan of round entries it opens onto an arc around itself.+ *+ * The ball is quiet at rest (translucent, a little faded) and clear while it is pointed at,+ * focused, open or dragged. The caption is the one name on screen: it reads out whatever is+ * pointed at, so the entries are glyphs alone and nothing carries a tooltip. It is the visible+ * readout only — every button carries its own accessible name — so it is hidden from assistive+ * technology and never folded into the ball's name.+ *+ * Every entry's box sits on the ball's centre; its place on the arc is its own `x` / `y` offset,+ * carried as `--fan-x` / `--fan-y` into the resting transform and the entrance's end state, so+ * with the animation dropped (reduced motion) an entry still stands on the arc. The entrance runs+ * down the arc from the top with a short stagger; the fold runs all at once.+ *+ * What the launcher is for, where it sits, how it drags and springs, and what an entry opens are+ * the caller's: these draw the ball and the fan from what they are given.+ */+import type { ButtonHTMLAttributes, CSSProperties, ReactNode, Ref } from "react";+import { Dot } from "../../icons/dot/dot";++/** Gap between the ball and its caption (px); the pill takes the rest of the caption height. */+const CAPTION_GAP = 4;+/**+ * Delay between one entry's entrance and the next, the topmost entry first (ms). Short enough+ * that the ring arrives as one shape rather than as a trickle of circles.+ */+const FAN_STAGGER_MS = 16;++export interface LauncherBallProps extends Omit<+ ButtonHTMLAttributes<HTMLButtonElement>,+ "children" | "aria-label"+> {+ /** The ball's diameter (px). */+ size: number;+ /** The height reserved under the ball for the caption, the gap included (px). */+ captionHeight: number;+ /** The ball's face: the resting mark, or the mark of what is pointed at. */+ glyph: ReactNode;+ /** The readout under the ball. */+ caption: string;+ /** The ball's accessible name. */+ label: string;+ /** Clear rather than quiet: the fan is open, or the ball is being dragged. */+ lit: boolean;+ dragging: boolean;+ /** An attention dot on the ball (a pending approval); the caller folds it into `label`. */+ badge?: boolean;+ buttonRef?: Ref<HTMLButtonElement>;+}++export function LauncherBall({+ size,+ captionHeight,+ glyph,+ caption,+ label,+ lit,+ dragging,+ badge = false,+ buttonRef,+ className = "",+ style,+ ...rest+}: LauncherBallProps) {+ return (+ <button+ ref={buttonRef}+ type="button"+ {...rest}+ aria-label={label}+ data-testid="dock-launcher-ball"+ style={{ ...style, width: size, height: size }}+ className={`ui-glass anim-pop relative flex touch-none select-none items-center justify-center rounded-full border border-line/80 text-fg-muted shadow-sm backdrop-blur-md transition-[background-color,color,opacity,box-shadow] duration-150 hover:bg-surface/95 hover:text-fg hover:opacity-100 hover:shadow-lg focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${+ lit ? "bg-surface/95 text-fg opacity-100" : "bg-surface/75 opacity-80"+ } ${dragging ? "cursor-grabbing" : "cursor-pointer"} ${className}`}+ >+ {glyph}+ {/* A small pill on the same glass, with no ink of its own, so it follows the ball's resting+ and clear ink. 13px in every theme: the caption belongs to the ball's fixed geometry,+ not to the text around it, and the code rung is the contract's 13px. Its height is the+ caller's reserved one, so the caption and the room kept for it cannot drift apart. */}+ <span+ aria-hidden+ className="ui-glass pointer-events-none absolute left-1/2 -translate-x-1/2 whitespace-nowrap rounded-md border border-line/80 bg-surface/85 px-2 py-0.5 text-[length:var(--ui-text-code-size)] font-medium leading-5 shadow-sm backdrop-blur-md transition-colors duration-150"+ style={{ top: size + CAPTION_GAP, height: captionHeight - CAPTION_GAP }}+ >+ {caption}+ </span>+ {badge && (+ // The ring is the page's fill, cutting the dot out of the ball's edge.+ <span+ aria-hidden+ className="absolute right-0.5 top-0.5 flex rounded-full ring-2 ring-canvas"+ >+ <Dot tone="attention" size="md" />+ </span>+ )}+ </button>+ );+}++export interface LauncherFanEntry {+ key: string;+ /** The entry's accessible name; the caption reads it out while the entry is pointed at. */+ label: string;+ glyph: ReactNode;+ /** An attention dot on the entry. */+ badge?: boolean;+ testId?: string;+ /** The entry's centre as an offset from the ball's centre (px). */+ x: number;+ y: number;+ onChoose: () => void;+}++export interface LauncherFanProps {+ /** In arc order, top to bottom: the DOM order is the visual order. */+ entries: readonly LauncherFanEntry[];+ /** "closing" plays the fold; the owner unmounts the fan once it has run. */+ phase: "open" | "closing";+ /** An entry's diameter (px). */+ entrySize: number;+ /** The group's accessible name. */+ label: string;+ /** The pointer or focus arrived on an entry. */+ onPoint: (key: string) => void;+ /** The pointer or focus left an entry. */+ onLeave: (key: string) => void;+ /** The group's node: a caller walking the entries with the arrow keys reads them from it. */+ fanRef?: Ref<HTMLDivElement>;+}++/**+ * The arc of entries, on a zero-size anchor at the ball's centre: the entries are placed by their+ * own transforms, so nothing here may size or clip the arc.+ */+export function LauncherFan({+ entries,+ phase,+ entrySize,+ label,+ onPoint,+ onLeave,+ fanRef,+}: LauncherFanProps) {+ return (+ <div+ ref={fanRef}+ role="group"+ aria-label={label}+ data-testid="dock-launcher-fan"+ className="absolute left-1/2 top-1/2 h-0 w-0"+ >+ {entries.map((entry, index) => (+ <button+ key={entry.key}+ type="button"+ data-testid={entry.testId}+ aria-label={entry.label}+ onClick={entry.onChoose}+ onMouseEnter={() => onPoint(entry.key)}+ onMouseLeave={() => onLeave(entry.key)}+ onFocus={() => onPoint(entry.key)}+ onBlur={() => onLeave(entry.key)}+ className={`ui-glass absolute flex items-center justify-center rounded-full border border-line/80 bg-surface/90 text-fg-muted shadow-sm backdrop-blur-md transition-colors duration-150 hover:bg-surface hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${+ phase === "closing" ? "launcher-fan-out" : "launcher-fan-in"+ }`}+ style={+ {+ width: entrySize,+ height: entrySize,+ left: -entrySize / 2,+ top: -entrySize / 2,+ transform: "translate(var(--fan-x), var(--fan-y))",+ animationDelay: phase === "closing" ? "0ms" : `${index * FAN_STAGGER_MS}ms`,+ "--fan-x": `${entry.x.toFixed(1)}px`,+ "--fan-y": `${entry.y.toFixed(1)}px`,+ } as CSSProperties+ }+ >+ {entry.glyph}+ {entry.badge === true && (+ <span+ aria-hidden+ className="absolute -right-0.5 -top-0.5 flex rounded-full ring-2 ring-canvas"+ >+ <Dot tone="attention" size="sm" />+ </span>+ )}+ </button>+ ))}+ </div>+ );+}diff --git a/packages/ui/src/components/shell/mobile-top-bar/mobile-top-bar.tsx b/packages/ui/src/components/shell/mobile-top-bar/mobile-top-bar.tsxnew file mode 100644index 00000000..d64b8337--- /dev/null+++ b/packages/ui/src/components/shell/mobile-top-bar/mobile-top-bar.tsx@@ -0,0 +1,43 @@+/**+ * The phone's top bar: a thin strip at the top of the main column, below `md` only, holding the+ * button that opens the navigation drawer and the product's name. The navigation column itself is+ * hidden at that width (`AppShell`), so this button is the way to everything the column lists.+ *+ * The button is named by the caller for what the drawer lists; a badge on its corner (an update+ * dot) says something is waiting inside, and `menuHint` names it — in the accessible name too, so+ * the caller folds it into `menuLabel` as well.+ */+import type { ReactNode } from "react";+import { ICON_SIZE } from "../../../icon-scale";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { ICONS } from "../../icons/icons";++export interface MobileTopBarProps {+ /** The product's name beside the button. */+ title: ReactNode;+ /** The drawer button's accessible name: what the drawer lists. */+ menuLabel: string;+ /** A hint on the button, for what its badge means. */+ menuHint?: string;+ /** A mark on the button's corner (an update dot). */+ menuBadge?: ReactNode;+ onMenu: () => void;+}++export function MobileTopBar({ title, menuLabel, menuHint, menuBadge, onMenu }: MobileTopBarProps) {+ return (+ <header className="flex h-12 shrink-0 items-center gap-2 border-b border-line bg-canvas px-2 md:hidden">+ <button+ type="button"+ aria-label={menuLabel}+ {...(menuHint !== undefined ? { "data-tooltip": menuHint } : {})}+ onClick={onMenu}+ className="relative flex h-9 w-9 items-center justify-center rounded-md text-fg-muted transition-colors duration-150 hover:bg-line-muted hover:text-fg"+ >+ <GlyphIcon d={ICONS.menu} size={ICON_SIZE.sectionMark} />+ {menuBadge}+ </button>+ <span className="text-sm font-semibold">{title}</span>+ </header>+ );+}diff --git a/packages/ui/src/components/shell/panels-toolbar/panels-toolbar.tsx b/packages/ui/src/components/shell/panels-toolbar/panels-toolbar.tsxnew file mode 100644index 00000000..b519c22a--- /dev/null+++ b/packages/ui/src/components/shell/panels-toolbar/panels-toolbar.tsx@@ -0,0 +1,60 @@+/**+ * The toolbar's dock switcher: one icon toggle per dock edge, each pulling its dock open or+ * putting it away. A toggle is `aria-expanded` while its dock is on screen, and may carry an+ * attention dot for something waiting inside that dock. Everything a dock holds — its tabs, its+ * add menu, its picker — lives on the dock itself, so this stays a row of toggles.+ */+import type { HTMLAttributes } from "react";+import { ICON_SIZE } from "../../../icon-scale";+import { Dot } from "../../icons/dot/dot";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";++export interface PanelsToolbarToggle {+ /** Stable id: the toggle's test id is `dock-toggle-<key>`. */+ key: string;+ /** The accessible name, and the tooltip when `tooltip` is absent. */+ label: string;+ /** The tooltip, when it says more than the name (the name with its shortcut). */+ tooltip?: string;+ /** The glyph's path, from the icon registry. */+ glyph: string;+ /** The dock is on screen. */+ active: boolean;+ /** An attention dot beside the glyph (a pending approval inside that dock). */+ badge?: boolean;+ onToggle: () => void;+}++export interface PanelsToolbarProps extends HTMLAttributes<HTMLDivElement> {+ toggles: readonly PanelsToolbarToggle[];+}++export function PanelsToolbar({ toggles, className = "", ...rest }: PanelsToolbarProps) {+ return (+ <div+ data-testid="panels-toolbar"+ {...rest}+ className={`flex shrink-0 items-center gap-1 ${className}`}+ >+ {toggles.map((toggle) => (+ <button+ key={toggle.key}+ type="button"+ aria-expanded={toggle.active}+ onClick={toggle.onToggle}+ data-tooltip={toggle.tooltip ?? toggle.label}+ aria-label={toggle.label}+ data-testid={`dock-toggle-${toggle.key}`}+ className={`relative flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${+ toggle.active+ ? "bg-line-muted text-fg"+ : "text-fg-muted hover:bg-line-muted hover:text-fg"+ }`}+ >+ <GlyphIcon d={toggle.glyph} size={ICON_SIZE.iconButton} />+ {toggle.badge === true && <Dot tone="attention" />}+ </button>+ ))}+ </div>+ );+}diff --git a/packages/ui/src/components/shell/rail/rail.tsx b/packages/ui/src/components/shell/rail/rail.tsxnew file mode 100644index 00000000..4608b4a4--- /dev/null+++ b/packages/ui/src/components/shell/rail/rail.tsx@@ -0,0 +1,201 @@+/**+ * The folded navigation column: a 48px strip of icon entries in place of the pinned sidebar. The+ * head holds the entries that stay put (the unfold button, a mode toggle), the middle is a+ * `<nav>` of entries that scrolls on its own when the window is too short for them, and the foot+ * holds the account's avatar. The scrollbar is hidden: at this width it would cost a third of the+ * strip.+ *+ * An entry is an icon with no visible label, so it carries its name as `aria-label` and the same+ * words in the styled `Tooltip` beside it — never also a native `title`, which would stack a+ * second, slower hint under the first. A selected entry (`active`) takes the column's selected+ * wash; a toggle (`pressed`) takes it while on. An entry with nowhere to go keeps its place,+ * muted, with nothing to click or tab to. A router's link draws a link entry through+ * `renderLink`, as a `NavRow` does.+ */+import type { ReactNode, Ref } from "react";+import { ICON_SIZE } from "../../../icon-scale";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { NAV_FILL } from "../../navigation/nav-list/nav-list";+import type { NavRowLinkProps } from "../../navigation/nav-list/nav-list";+import { Tooltip } from "../../overlays/tooltip/tooltip";++/**+ * An entry's square: the selected wash when `active`, the same wash under the pointer otherwise,+ * and a muted glyph with no fill when `disabled`. For an element the rail does not draw itself (a+ * row another module renders onto the rail).+ */+export function railItemClass({+ active = false,+ disabled = false,+}: {+ active?: boolean;+ disabled?: boolean;+} = {}): string {+ const state = disabled+ ? "cursor-not-allowed text-fg-muted opacity-40"+ : active+ ? `${NAV_FILL.selected} text-fg`+ : "text-fg-muted hover:bg-fg/7 hover:text-fg";+ return `relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 ${state}`;+}++export interface RailProps {+ /** The entries above the scrolling list: the unfold button, a mode toggle. */+ head?: ReactNode;+ /** The entries: the rail's `<nav>`, which scrolls when the window is short. */+ children?: ReactNode;+ /** Below the list: the account's avatar. */+ foot?: ReactNode;+ /** The list's accessible name, when the entries need one beyond their own. */+ label?: string;+}++export function Rail({ head, children, foot, label }: RailProps) {+ return (+ <div className="flex h-full flex-col items-center gap-1 py-2.5">+ {head}+ <nav+ {...(label !== undefined ? { "aria-label": label } : {})}+ className="mt-1 flex min-h-0 flex-1 flex-col items-center gap-1 overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"+ >+ {children}+ </nav>+ {foot}+ </div>+ );+}++export interface RailItemProps {+ /** The entry's accessible name. */+ label: string;+ /** The hint beside it; the name when omitted. */+ tooltip?: string;+ /** The glyph's path, from the icon registry. */+ glyph: string;+ /** The entry is where the reader is: the selected wash (and `aria-current` on a link). */+ active?: boolean;+ /** A toggle: `aria-pressed`, and the selected wash while on. */+ pressed?: boolean;+ /** Nowhere to go right now: muted, no hover fill, not focusable. */+ disabled?: boolean;+ /** A mark on the entry's corner: an update dot, a count. */+ badge?: ReactNode;+ /** A link to this address instead of a button. */+ href?: string;+ /** With `href`: draws the link through the caller's own element (a router's). */+ renderLink?: (link: NavRowLinkProps) => ReactNode;+ onClick?: () => void;+ /** Extra classes on the entry's place in the column (`shrink-0` for a head entry). */+ className?: string;+}++export function RailItem({+ label,+ tooltip,+ glyph,+ active = false,+ pressed,+ disabled = false,+ badge,+ href,+ renderLink,+ onClick,+ className,+}: RailItemProps) {+ const classes = railItemClass({ active: active || pressed === true, disabled });+ const mark = (+ <>+ <GlyphIcon d={glyph} size={ICON_SIZE.sectionMark} />+ {badge}+ </>+ );+ let entry: ReactNode;+ if (href !== undefined && disabled) {+ entry = (+ <span role="link" aria-label={label} aria-disabled="true" className={classes}>+ {mark}+ </span>+ );+ } else if (href !== undefined) {+ const link: NavRowLinkProps = {+ href,+ className: classes,+ ...(active ? { "aria-current": "page" as const } : {}),+ "aria-label": label,+ ...(onClick !== undefined ? { onClick } : {}),+ children: mark,+ };+ entry =+ renderLink !== undefined ? (+ renderLink(link)+ ) : (+ <a+ href={href}+ aria-current={link["aria-current"]}+ aria-label={label}+ onClick={onClick}+ className={classes}+ >+ {mark}+ </a>+ );+ } else {+ entry = (+ <button+ type="button"+ aria-label={label}+ aria-pressed={pressed}+ disabled={disabled}+ onClick={onClick}+ className={classes}+ >+ {mark}+ </button>+ );+ }+ return (+ <Tooltip label={tooltip ?? label} {...(className !== undefined ? { className } : {})}>+ {entry}+ </Tooltip>+ );+}++/** A hairline between two runs of entries (the pages, then an organization's channels). */+export function RailDivider() {+ return <span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-line" />;+}++/**+ * The account's button at the rail's foot: the avatar, which opens the account menu. It keeps the+ * entries' 32px square as its target and draws nothing of its own around the avatar, which is the+ * pinned sidebar's tile at the sidebar's size — the two states swap outright, so a tile that+ * changed size between them would pop on every fold.+ */+export function RailAccountButton({+ label,+ expanded,+ onClick,+ buttonRef,+ children,+}: {+ label: string;+ /** The menu it opens is showing. */+ expanded: boolean;+ onClick: () => void;+ buttonRef?: Ref<HTMLButtonElement>;+ children: ReactNode;+}) {+ return (+ <button+ ref={buttonRef}+ type="button"+ aria-label={label}+ aria-haspopup="menu"+ aria-expanded={expanded}+ onClick={onClick}+ className="flex h-8 w-8 shrink-0 items-center justify-center"+ >+ {children}+ </button>+ );+}diff --git a/packages/ui/src/components/shell/session-row/session-row.tsx b/packages/ui/src/components/shell/session-row/session-row.tsxnew file mode 100644index 00000000..e88a0f17--- /dev/null+++ b/packages/ui/src/components/shell/session-row/session-row.tsx@@ -0,0 +1,366 @@+/**+ * A conversation's row in the sidebar's list, and the hover actions it shares with the other+ * conversation rows.+ *+ * The row is the title — with an agent's avatar before it where the group does not name the+ * agent — the marks of its standing arrangements, its live state and its waiting approvals, and a+ * trailing slot that swaps what it shows: the compact last-active time at rest, and on hover or+ * focus the direct actions and the "more" button that opens the whole set as a menu. The same+ * menu opens at the pointer on a right-click, from the keyboard with Shift+F10, and on touch with+ * a press-and-hold (`useRowContextMenu`, whose handlers the row spreads); a hold's replayed click+ * does not also open the conversation. Both panels go through the dropdown's body portal, so the+ * sidebar's scroller cannot clip them.+ *+ * Every mark after the title names itself, in a hint and in visually hidden text, which is what+ * lets the standing ones recede to the subtle ink: pinned, relayed to a messaging channel,+ * scheduled to run on its own, and work still running in the background. The live state (a+ * turning hourglass, the compress mark, the unread dot) has one reserved box, kept empty when+ * there is nothing to show, so the title never re-flows as a run starts, finishes and is read.+ *+ * The title is the caller's to draw, with the classes the row hands `renderTitle`: the row+ * decides the ink and the weight, the caller its own truncation — the app's line reveals a+ * clipped tail by scrolling it while the row is hovered or focused, keyed on the row's+ * `data-title-reveal`. The trailing slot's width is fixed per language (`timeSlot`), so the marks+ * that end the title sit at one x from row to row, and the hover actions are anchored to its right+ * edge so every row's icons form one column.+ */+import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";+import { ICON_SIZE } from "../../../icon-scale";+import {+ ActivityIcon,+ BackgroundTasksMark,+ ScheduleMark,+} from "../../icons/activity-icon/activity-icon";+import type { ActivityIconState } from "../../icons/activity-icon/activity-icon";+import { AgentAvatar } from "../../icons/avatars/agent-avatar";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { ICONS } from "../../icons/icons";+import { NAV_FILL } from "../../navigation/nav-list/nav-list";+import { Dropdown } from "../../overlays/dropdown/dropdown";+import { MenuItem } from "../../overlays/menu/menu";+import type { AnchorRect } from "../../overlays/portal-panel/context-menu";+import { useRowContextMenu } from "../../overlays/portal-panel/use-row-context-menu";++/** One thing a row can do to what it stands for, as its hover button or its menu row draw it. */+export interface RowActionItem {+ /** Stable within the row. */+ id: string;+ /** The label in the row's current state: the menu row's words, the hover button's name. */+ label: string;+ /** The glyph's path, from the icon registry. */+ glyph: string;+ /** Destructive: the danger ink on the menu row and on the hover button's hover. */+ danger?: boolean;+ onSelect: () => void;+}++/** A hover button's glyph: a notch under the icon-button rung, sized to the row's 24px buttons. */+const ACTION_GLYPH = 14;++/**+ * The hover buttons: the reveal is gated on pointer events exactly as on opacity, because an+ * invisible button still takes taps, and on a touch screen — where `hover:` never matches — these+ * are invisible for the whole session. Keyboard focus is unaffected by `pointer-events`, so Tab+ * still reaches them, and revealing one re-arms its click. `focus` rather than `focus-visible`:+ * the time they swap with hides on plain focus-within, and the two must agree or the slot goes+ * blank.+ */+const HOVER_BUTTON =+ "pointer-events-none flex h-6 w-6 shrink-0 items-center justify-center rounded-sm text-fg-subtle opacity-0 transition-[color,opacity] duration-150 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100";++/**+ * A row's hover affordance: its direct actions as icon buttons that fade in over the row's end,+ * then the "more" button that opens the row's menu anchored at its own box, so every menu action+ * is one visible click away rather than right-click only. Hover and focus only — desktop — since+ * a touch screen reaches the same menu by holding the row. The row that holds them carries the+ * `group` scope.+ */+export function RowHoverActions({+ actions,+ moreLabel,+ onMore,+}: {+ actions: readonly RowActionItem[];+ /** The "more" button's name and hint. */+ moreLabel: string;+ /** Opens the row's menu anchored at the "more" button's own box. */+ onMore: (anchor: AnchorRect) => void;+}) {+ const openMore = (e: ReactMouseEvent<HTMLButtonElement>) => {+ const r = e.currentTarget.getBoundingClientRect();+ onMore({ top: r.top, bottom: r.bottom, left: r.left, right: r.right });+ };+ return (+ <>+ {actions.map((action) => (+ <button+ key={action.id}+ type="button"+ data-tooltip={action.label}+ aria-label={action.label}+ onClick={action.onSelect}+ className={`${HOVER_BUTTON} ${+ action.danger === true ? "hover:text-tone-danger-fg" : "hover:text-fg"+ }`}+ >+ <GlyphIcon d={action.glyph} size={ACTION_GLYPH} />+ </button>+ ))}+ <button+ type="button"+ data-tooltip={moreLabel}+ aria-label={moreLabel}+ aria-haspopup="menu"+ onClick={openMore}+ className={`${HOVER_BUTTON} hover:text-fg`}+ >+ {/* Hairline-stroke dots vanish at this size, so the ellipsis is drawn filled: the stroke+ rides on top of the fill, landing the dots at the other glyphs' weight. */}+ <GlyphIcon d={ICONS.ellipsis} size={ACTION_GLYPH} filled />+ </button>+ </>+ );+}++/** A standing arrangement's mark after the title: the glyph, its hint, and its words for a reader. */+function RowMark({ glyph, label }: { glyph: string; label: string }) {+ return (+ <span data-tooltip={label} className="shrink-0 text-fg-subtle">+ <GlyphIcon d={glyph} size={ICON_SIZE.rowMark} />+ <span className="sr-only">{label}</span>+ </span>+ );+}++/** The live state's box: its glyph, or the same box empty, so the title never re-flows. */+function StatusSlot({+ activity,+}: {+ activity: { state: ActivityIconState; label: string } | null;+}) {+ if (activity === null) return <span aria-hidden="true" className="block h-3 w-3 shrink-0" />;+ return <ActivityIcon activity={activity.state} label={activity.label} />;+}++export interface SessionRowProps {+ /** The conversation's id, written on the row's button for tests and for the app to find it. */+ sessionId: string;+ /** Draws the title line with the classes the row hands over (its ink and weight). */+ renderTitle: (className: string) => ReactNode;+ /** The open conversation: the selected wash and the title's medium weight. */+ active?: boolean;+ /** Archived: the title recedes to the subtle ink. */+ archived?: boolean;+ /** The conversation's agent, as a small avatar before the title (where its group is not the agent). */+ agent?: { id: string; name: string };+ /** Pinned to the top of its list: the pin mark, named by this. */+ pinnedLabel?: string;+ /** Relayed to a messaging channel: the paper plane, named by this (the channel's name). */+ relayLabel?: string;+ /** A scheduled task will run it: the alarm clock, named by this. */+ scheduledLabel?: string;+ /** Background work it owns is still running: the pulse, named by `label`; none at a count of 0. */+ background?: { count: number; label: string };+ /** Its live state; null (or omitted) keeps the box empty. */+ activity?: { state: ActivityIconState; label: string } | null;+ /** Approvals waiting: the count in the attention ink, its hint; none at a count of 0. */+ approvals?: { count: number; label: string };+ /** The compact last-active time at rest; "" draws none. */+ time: string;+ /**+ * The width the trailing slot reserves, fixed per language: `wide` where the longest compact+ * time runs longer ("12月31日", "59 分钟前"), `narrow` otherwise ("Nov 30").+ */+ timeSlot?: "narrow" | "wide";+ /** The direct actions the hover reveals, before the "more" button. */+ hoverActions: readonly RowActionItem[];+ /** The whole set, in the menu the "more" button, a right-click, Shift+F10 or a hold opens. */+ menuActions: readonly RowActionItem[];+ /** The "more" button's name and hint. */+ moreLabel: string;+ onOpen: () => void;+ /** Manual order: the row can be dragged (the caller wires the handlers). */+ draggable?: boolean;+ /** While another row is dragged over this one: the edge the drop would land on. */+ dropEdge?: "above" | "below" | null;+ onDragStart?: (e: ReactDragEvent) => void;+ onDragEnd?: () => void;+ onDragOver?: (e: ReactDragEvent) => void;+ onDragLeave?: () => void;+ onDrop?: (e: ReactDragEvent) => void;+}++export function SessionRow({+ sessionId,+ renderTitle,+ active = false,+ archived = false,+ agent,+ pinnedLabel,+ relayLabel,+ scheduledLabel,+ background,+ activity = null,+ approvals,+ time,+ timeSlot = "narrow",+ hoverActions,+ menuActions,+ moreLabel,+ onOpen,+ draggable = false,+ dropEdge = null,+ onDragStart,+ onDragEnd,+ onDragOver,+ onDragLeave,+ onDrop,+}: SessionRowProps) {+ const ctx = useRowContextMenu();+ /** A hover button closes an open menu before it acts. */+ const fromHover = (action: RowActionItem): RowActionItem => ({+ ...action,+ onSelect: () => {+ ctx.close();+ action.onSelect();+ },+ });+ /**+ * A menu row hands focus back to the row before acting: the panel unmounts under the reader,+ * and the menu is the only keyboard route to some actions, so a Shift+F10 → Enter reader would+ * otherwise land on the page's body and lose their place in the list. An action that opens a+ * dialog takes focus from there as usual.+ */+ const fromMenu = (action: RowActionItem) => () => {+ ctx.returnFocus()?.focus();+ ctx.close();+ action.onSelect();+ };+ const titleInk = active ? "font-medium text-fg" : archived ? "text-fg-subtle" : "text-fg/80";+ return (+ <li+ className="relative"+ {...(draggable+ ? { draggable: true, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }+ : {})}+ >+ {/* The drop line: a thin accent rule on the edge a dragged row would land on. */}+ {dropEdge !== null && (+ <div+ aria-hidden+ className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-accent ${+ dropEdge === "above" ? "-top-px" : "-bottom-px"+ }`}+ />+ )}+ <div+ data-title-reveal+ ref={ctx.rowRef}+ // Right-click, Shift+F10 and press-and-hold open the row's menu; the browser's own menu+ // is suppressed on this row only. select-none keeps a held press from raising the text+ // selection callout on touch instead of the menu.+ {...ctx.rowProps}+ className={`group flex select-none items-center rounded-md pr-1 transition-colors duration-150 ${+ draggable ? "cursor-grab " : ""+ }${active ? NAV_FILL.selected : NAV_FILL.hover}`}+ >+ <button+ type="button"+ data-testid="session-row"+ data-session-id={sessionId}+ // A press-and-hold that opened the menu must not also open the conversation: touch+ // screens replay the held press as a click once the finger lifts.+ onClick={() => {+ if (ctx.consumeLongPressClick()) return;+ onOpen();+ }}+ className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left"+ >+ {agent !== undefined && (+ <span data-tooltip={agent.name} className="flex shrink-0 items-center">+ <AgentAvatar+ id={agent.id}+ name={agent.name}+ size={ICON_SIZE.rowLead}+ className="rounded-sm"+ />+ {/* The avatar is hidden from assistive technology and the hint serves pointers only:+ the agent's name reaches everyone else as hidden text inside the row's button. */}+ <span className="sr-only">{agent.name}</span>+ </span>+ )}+ {renderTitle(`min-w-0 flex-1 font-sans text-sm ${titleInk}`)}+ {pinnedLabel !== undefined && <RowMark glyph={ICONS.pin} label={pinnedLabel} />}+ {relayLabel !== undefined && <RowMark glyph={ICONS.paperPlane} label={relayLabel} />}+ {scheduledLabel !== undefined && (+ <ScheduleMark label={scheduledLabel} size={ICON_SIZE.rowMark} />+ )}+ {background !== undefined && background.count > 0 && (+ <BackgroundTasksMark label={background.label} size={ICON_SIZE.rowMark} />+ )}+ <StatusSlot activity={activity} />+ {/* A numeral in the attention ink, with no pill: a filled chip beside the title reads as+ a second button. */}+ {approvals !== undefined && approvals.count > 0 && (+ <span+ data-tooltip={approvals.label}+ className="shrink-0 text-xs font-semibold tabular-nums text-tone-attention-fg"+ >+ {approvals.count}+ </span>+ )}+ </button>+ {/* The trailing slot: the time at rest, the hover actions over it. Its width is fixed so+ the marks before it hold one x from row to row; the actions are a constant-width+ group anchored at its right edge, so their glyphs form one column; the swap is an+ opacity handoff (the actions precede the time, so the peer rule can reach it). */}+ <div+ className={`relative flex h-6 shrink-0 items-center justify-end ${+ timeSlot === "wide" ? "w-[4.5rem]" : "w-14"+ }`}+ >+ <div className="peer absolute right-0 top-1/2 flex -translate-y-1/2 items-center">+ <RowHoverActions+ actions={hoverActions.map(fromHover)}+ moreLabel={moreLabel}+ onMore={ctx.openAt}+ />+ </div>+ {time !== "" && (+ <span+ aria-hidden+ className="pointer-events-none whitespace-nowrap px-1 text-right text-xs tabular-nums text-fg-subtle transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0"+ >+ {time}+ </span>+ )}+ </div>+ {/* The menu. `contents` keeps this wrapper out of the row's layout: the panel is+ portaled, and its anchor is the point the gesture landed on (or the "more" button's+ box), not this element. */}+ <Dropdown+ open={ctx.open}+ setOpen={ctx.setOpen}+ portal={{ direction: "down", align: "left" }}+ anchorRect={ctx.anchor}+ anchorOwner={ctx.anchorOwner}+ returnFocus={ctx.returnFocus}+ className="contents"+ menuClass="w-36"+ button={null}+ >+ {menuActions.map((action) => (+ <MenuItem+ key={action.id}+ density="sm"+ glyph={action.glyph}+ label={action.label}+ danger={action.danger === true}+ onSelect={fromMenu(action)}+ />+ ))}+ </Dropdown>+ </div>+ </li>+ );+}diff --git a/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx b/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsxnew file mode 100644index 00000000..34defd60--- /dev/null+++ b/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx@@ -0,0 +1,311 @@+/**+ * The pinned sidebar's frame: one column, top to bottom — an optional mode switch, the switcher+ * row (the fold button and the Project or organization switcher), one pinned entry, the scroll+ * area, and the account row at the foot. The pieces the scroll area is built from are here too:+ * the page nav that folds away under a slim toggle, the list's header with its label and its+ * controls, the controls themselves, and the switcher's and the account's buttons.+ *+ * The page nav and the list scroll together, so the nav rides up as the list is scrolled: the+ * scroll area is the column's only shrinkable block, and a column of fixed chrome taller than a+ * short window would push the document into a second scrollbar. The area is its own containing+ * block (`relative`), so an absolutely placed descendant (a row's visually hidden name) scrolls+ * with it rather than stretching the document, and it clips sideways (`overflow-x-clip`) so a+ * pixel of horizontal overflow never turns into a scrollbar under the list.+ *+ * Everything on the column sits on its muted surface, so a hover and a selection are the column's+ * washes of the ink (`NAV_FILL`). The frame paints no background of its own: the column that holds+ * it does (`AppShell`'s navigation slot, or the phone's drawer).+ */+import type { ReactNode, Ref } from "react";+import { ICON_SIZE } from "../../../icon-scale";+import { ChevronFlip } from "../../icons/chevron/chevron";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { ICONS } from "../../icons/icons";+import { ChevronDown } from "../../icons/marks/marks";+import { Text } from "../../content/typography/typography";+import { NAV_FILL } from "../../navigation/nav-list/nav-list";++/**+ * A list-header control's glyph: one step under the icon-button rung, since the control's square+ * is the dense 24px one and its glyph sits beside a small label.+ */+const CONTROL_GLYPH = 14;++export interface SidebarFrameProps {+ /** Above everything: a mode switch, in a group named by its `label`. */+ modeSwitch?: { label: string; control: ReactNode };+ /** The switcher row's content: the Project or organization switcher. */+ switcher: ReactNode;+ /**+ * The fold button at the start of the switcher row; drawn only when given. `tooltip` says more+ * than the name when it has more to say (the name with its shortcut).+ */+ collapse?: { label: string; tooltip?: string; onClick: () => void };+ /**+ * The one entry pinned under the switcher ("New chat"). Without one the column keeps the gap the+ * scroll area below depends on.+ */+ pinned?: ReactNode;+ /** The scroll area: the page nav and the list. */+ children?: ReactNode;+ /** The account row at the foot: the account menu's trigger. */+ account: ReactNode;+ /** Layers the column opens (its dialogs), mounted after it. */+ overlays?: ReactNode;+ /** The column's node: a caller that must know whether the column is on screen reads it. */+ rootRef?: Ref<HTMLDivElement>;+}++export function SidebarFrame({+ modeSwitch,+ switcher,+ collapse,+ pinned,+ children,+ account,+ overlays,+ rootRef,+}: SidebarFrameProps) {+ return (+ <div ref={rootRef} className="flex h-full w-full flex-col">+ {modeSwitch !== undefined && (+ <div className="shrink-0 px-2 pt-2" role="group" aria-label={modeSwitch.label}>+ {modeSwitch.control}+ </div>+ )}+ <div className="flex shrink-0 items-center gap-1 px-2 pt-2">+ {collapse !== undefined && (+ <button+ type="button"+ data-tooltip={collapse.tooltip ?? collapse.label}+ aria-label={collapse.label}+ onClick={collapse.onClick}+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-fg-subtle transition-colors duration-150 hover:bg-fg/7 hover:text-fg"+ >+ <GlyphIcon d={ICONS.chevronLeftPipe} size={ICON_SIZE.sectionMark} />+ </button>+ )}+ {switcher}+ </div>+ {/* The gap to the scroll area is this block's own bottom padding, not padding inside the+ scroller: padding there belongs to the scrolled content and slides away with it, and a+ scrolled nav row would end up flush against the pinned entry. */}+ {pinned === undefined ? (+ <div className="shrink-0 pb-2" />+ ) : (+ <div className="shrink-0 px-2 pb-2 pt-2">{pinned}</div>+ )}+ <div className="relative min-h-0 flex-1 overflow-y-auto overflow-x-clip px-2 pb-2">+ {children}+ </div>+ <div className="shrink-0 border-t border-line p-2">{account}</div>+ {overlays}+ </div>+ );+}++/**+ * The page nav: its rows in a group that folds away, and under them a slim, full-width toggle+ * whose caret points up while the rows show (fold them) and down once they are folded (the way+ * back). The fold slides: the group's row track tweens between `0fr` and `1fr` under the theme's+ * layout motion while the rows fade, and the list below glides up with it. The rows stay mounted+ * for the tween but turn inert while folded, so a zero-height row is never focusable or+ * clickable. The toggle's resting band is the column's one fill at rest: it reads as the seam+ * between the nav and the list below it.+ */+export function SidebarNavGroup({+ collapsed,+ onToggle,+ expandLabel,+ collapseLabel,+ children,+}: {+ collapsed: boolean;+ onToggle: () => void;+ /** The toggle's name while the rows are folded. */+ expandLabel: string;+ /** The toggle's name while they show. */+ collapseLabel: string;+ children: ReactNode;+}) {+ const label = collapsed ? expandLabel : collapseLabel;+ return (+ <nav className="space-y-px">+ <div+ data-layout-motion+ className={`grid ${collapsed ? "grid-rows-[0fr]" : "grid-rows-[1fr]"}`}+ >+ <div className="overflow-hidden" inert={collapsed}>+ <div+ className={`space-y-px transition-opacity duration-200 ${+ collapsed ? "opacity-0" : "opacity-100"+ }`}+ >+ {children}+ </div>+ </div>+ </div>+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={!collapsed}+ aria-label={label}+ data-tooltip={label}+ className={`flex h-4 w-full items-center justify-center rounded-md ${NAV_FILL.selected} text-fg-subtle transition-colors duration-150 hover:bg-fg/10 hover:text-fg`}+ >+ <ChevronFlip up={!collapsed} />+ </button>+ </nav>+ );+}++/**+ * The list's header: its group label on the left, its controls on the right. Searching, the+ * header becomes the search field in place — the label's column closes while the controls'+ * column takes the whole row under the theme's layout motion, and the field inside grows leftward+ * over the label's place — so a search costs no extra row.+ */+export function SidebarListHeader({+ label,+ searching = false,+ children,+}: {+ /** The group label naming the list below. */+ label: string;+ /** The search field is open in the controls' column. */+ searching?: boolean;+ /** The controls, or the open search field and the controls after it. */+ children: ReactNode;+}) {+ return (+ <div+ data-layout-motion+ className={`mt-3 grid items-center px-1 pt-2 ${+ searching ? "grid-cols-[0fr_1fr]" : "grid-cols-[1fr_1fr]"+ }`}+ >+ <Text+ as="span"+ variant="eyebrow"+ className={`min-w-0 overflow-hidden whitespace-nowrap px-1 transition-opacity duration-200 ${+ searching ? "opacity-0" : "opacity-100"+ }`}+ >+ {label}+ </Text>+ <div className="flex min-w-0 items-center justify-end gap-px">{children}</div>+ </div>+ );+}++/**+ * A control's square on the list header (search, list options, create): the subtle glyph, the+ * column's hover wash, and the selected wash while `active` (its menu or picker is open). For a+ * trigger another module draws (a picker's own button).+ */+export function sidebarControlClass(active = false): string {+ return `flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors duration-150 ${+ active ? `${NAV_FILL.selected} text-fg` : `text-fg-subtle ${NAV_FILL.hover} hover:text-fg`+ }`;+}++/** An icon control on the list header, named by its hint. */+export function SidebarControl({+ label,+ tooltip,+ glyph,+ active = false,+ onClick,+ "aria-haspopup": hasPopup,+ "aria-expanded": expanded,+}: {+ /** The accessible name, and the hint when `tooltip` is absent. */+ label: string;+ /** The hint, when it says more than the name (the name with its shortcut). */+ tooltip?: string;+ /** A registry path, drawn at the header's small rung, or a mark the caller sized. */+ glyph: string | ReactNode;+ /** Its menu or picker is open. */+ active?: boolean;+ onClick: () => void;+ "aria-haspopup"?: "menu";+ "aria-expanded"?: boolean;+}) {+ return (+ <button+ type="button"+ data-tooltip={tooltip ?? label}+ aria-label={label}+ aria-haspopup={hasPopup}+ aria-expanded={expanded}+ onClick={onClick}+ className={sidebarControlClass(active)}+ >+ {typeof glyph === "string" ? <GlyphIcon d={glyph} size={CONTROL_GLYPH} /> : glyph}+ </button>+ );+}++/** The switcher's trigger: the current Project's name, full width, and the caret. */+export function SidebarSwitcherButton({+ label,+ onClick,+}: {+ label: ReactNode;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-base font-semibold transition-colors duration-150 hover:bg-fg/7"+ >+ <span className="min-w-0 flex-1 truncate font-sans text-left">{label}</span>+ <span className="text-fg-subtle">+ <ChevronDown />+ </span>+ </button>+ );+}++/**+ * The account row's trigger at the column's foot: the avatar, the account's name and an optional+ * role after it. The menu it opens is the caller's.+ */+export function SidebarAccountButton({+ avatar,+ name,+ role,+ expanded,+ onClick,+ label,+ hint,+}: {+ avatar: ReactNode;+ name: ReactNode;+ /** A short role after the name ("Admin"). */+ role?: string;+ /** The account menu is open. */+ expanded: boolean;+ onClick: () => void;+ /** The accessible name, when a hint adds to what the name says. */+ label?: string;+ /** A hint on hover and focus (what the avatar's badge means). */+ hint?: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-haspopup="menu"+ aria-expanded={expanded}+ {...(hint !== undefined ? { "data-tooltip": hint } : {})}+ {...(label !== undefined ? { "aria-label": label } : {})}+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-fg/7"+ >+ {avatar}+ <span className="min-w-0 flex-1 truncate font-sans text-sm font-medium">{name}</span>+ {role !== undefined && <span className="text-xs text-fg-subtle">{role}</span>}+ </button>+ );+}diff --git a/packages/ui/src/hooks.ts b/packages/ui/src/hooks.tsindex d6c5aa10..cd391896 100644--- a/packages/ui/src/hooks.ts+++ b/packages/ui/src/hooks.ts@@ -15,7 +15,8 @@* | hook | the job | anatomy the recipes rely on |* | ------------------ | -------------------------------------------------------- | ----------------------------------------------------- |* | `ui-glass` | a transient layer over content: menus, popovers, the | — |- * | | modal card, the floating composer, a sticky page header | |+ * | | modal card, the floating composer and launcher, a sticky | |+ * | | page header | |* | | hosts: `ComposerCard` and its `SlashMenu`, `Modal`, | |* | | `Dropdown`, the selects, popovers and tooltips | |* | `ui-eyebrow` | a group label naming the items below it (never directly | — |@@ -28,8 +29,10 @@* | `ui-frame` | a ruled box with a head, a body, a foot and panes | children carry `data-slot="head" \| "body" \| "foot" \| "pane"` |* | | hosts: the transcript's cards, the code block, `Card`, | |* | | a framed `Table` | |- * | `ui-underline-nav` | the selected-tab marker of a tab bar | items `[role="tab"]`, selected by `aria-selected="true"` |+ * | `ui-underline-nav` | the selected-tab marker of a tab bar (a page's tabs, a | items `[role="tab"]`, selected by `aria-selected="true"` |+ * | | dock's tab strip) | |* | `ui-shell` | the app window: a navigation column beside a main column | children carry `data-slot="nav" \| "main"` (a right column may carry `"dock"`); the selected nav row is `[aria-current="page"]` |+ * | | host: `AppShell` | |* | `ui-icon-decor` | an icon that says nothing its label does not already say | on the icon itself (or the element holding only it); optional `data-role="nav" \| "group" \| "menu" \| "empty"` |* | | hosts: the icon renderers' call sites, `NavRow`'s glyph | |* | `ui-tree` | a container whose rows nest | rows carry `data-depth="0"…"8"`, the last row of a level `data-last="true"`; a row's children may follow it in a `data-branch` element carrying the children's `data-depth` |diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 09840f8d..774a0006 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -187,3 +187,39 @@ export * from "./components/forms/tag-input/tag-input";// W6-C — the company channel: a sender's run of messages and its bubbles.export * from "./components/chat/channel-bubble/channel-bubble";++// W7-A — files: the pointer-drag machine with the resize handle and the split pane built on it,+// the file tree and its row logic, the read-only file browser, the Files panel's tree and preview+// panes, the drop overlay, the file menu's rows, the in-place editor, the breadcrumbs and their+// fit, and the frontmatter helper the Markdown readers share.+export * from "./components/layout/resize-handle/use-pointer-drag";+export * from "./components/layout/resize-handle/resize-handle";+export * from "./components/layout/resize-handle/split-pane";+export * from "./components/files/file-tree/tree-rows";+export * from "./components/files/file-tree/file-tree";+export * from "./components/files/file-browser/file-browser";+export * from "./components/files/tree-pane/tree-pane";+export * from "./components/files/preview-pane/preview-pane";+export * from "./components/files/drop-overlay/drop-overlay";+export * from "./components/files/workspace-file-menu/workspace-file-menu";+export * from "./components/content/workspace-file-editor/workspace-file-editor";+export * from "./components/navigation/breadcrumbs/crumb-fit";+export * from "./components/navigation/breadcrumbs/breadcrumbs";+export * from "./components/content/prose/frontmatter";++// W7-C — the dock: its tab strip, its frame and header buttons, the picker of an empty dock, the+// toolbar's dock toggles, and the floating launcher's ball and fan.+export * from "./components/navigation/dock-tabs/dock-tabs";+export * from "./components/shell/dock-frame/dock-frame";+export * from "./components/shell/dock-picker/dock-picker";+export * from "./components/shell/panels-toolbar/panels-toolbar";+export * from "./components/shell/launcher/launcher";++// W7-B — the shell: the app window and its columns, the folded rail, the phone's top bar, the+// pinned sidebar's frame with its nav fold, list header and controls, and the conversation row+// with the hover actions it shares.+export * from "./components/shell/app-shell/app-shell";+export * from "./components/shell/rail/rail";+export * from "./components/shell/mobile-top-bar/mobile-top-bar";+export * from "./components/shell/sidebar-frame/sidebar-frame";+export * from "./components/shell/session-row/session-row";diff --git a/packages/ui/test/app-shell.test.ts b/packages/ui/test/app-shell.test.tsnew file mode 100644index 00000000..feed28ce--- /dev/null+++ b/packages/ui/test/app-shell.test.ts@@ -0,0 +1,164 @@+/**+ * The app window (src/components/shell/app-shell/), the folded rail (rail/) and the phone's top+ * bar (mobile-top-bar/): the shell's slots are the ones its theme recipes select on, its column+ * folds under the theme's layout motion, and every icon-only entry carries its name and a styled+ * hint rather than a native title.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ICONS } from "../src/components/icons/icons";+import type { NavRowLinkProps } from "../src/components/navigation/nav-list/nav-list";+import { NAV_FILL } from "../src/components/navigation/nav-list/nav-list";+import { AppShell } from "../src/components/shell/app-shell/app-shell";+import { MobileTopBar } from "../src/components/shell/mobile-top-bar/mobile-top-bar";+import {+ Rail,+ RailAccountButton,+ RailDivider,+ RailItem,+ railItemClass,+} from "../src/components/shell/rail/rail";+import { classTokens, renderStatic } from "../src/testing";++const text = (value: string) => createElement("span", null, value);++describe("AppShell", () => {+ const shell = (props: Partial<Parameters<typeof AppShell>[0]> = {}) =>+ renderStatic(+ createElement(AppShell, {+ nav: text("Sidebar"),+ children: text("Page"),+ ...props,+ }),+ );++ it("is the ui-shell window with its nav and main slots, and a dock slot only when docked", () => {+ const html = shell();+ expect(html).toMatch(/^<div class="ui-shell flex h-full"><aside data-slot="nav"/);+ expect(html).toContain(+ '<div data-slot="main" class="flex min-w-0 flex-1 flex-col"><span>Page</span></div>',+ );+ expect(html).not.toContain('data-slot="dock"');+ expect(shell({ dock: text("Dock") })).toContain('data-slot="dock"');+ });++ it("folds the navigation column's width under the theme's layout motion", () => {+ const open = shell();+ expect(open).toContain('data-layout-motion="true"');+ expect(classTokens(open)).toEqual(+ expect.arrayContaining(["w-64", "lg:w-72", "md:block", "hidden"]),+ );+ const folded = shell({ navCollapsed: true });+ expect(classTokens(folded)).toContain("w-12");+ expect(classTokens(folded)).not.toContain("w-64");+ expect(classTokens(open).filter((t) => t.startsWith("transition"))).toEqual([]);+ });++ it("mounts its overlays beside the columns, in no slot", () => {+ const html = shell({ overlays: text("Dialog") });+ expect(html).toMatch(/<span>Page<\/span><\/div><span>Dialog<\/span><\/div>$/);+ });+});++describe("MobileTopBar", () => {+ it("is the phone's bar, its drawer button named by the caller and hinted only with a badge", () => {+ const plain = renderStatic(+ createElement(MobileTopBar, {+ title: "PenguinHarness",+ menuLabel: "Sessions",+ onMenu: () => {},+ }),+ );+ expect(classTokens(plain)).toContain("md:hidden");+ expect(plain).toContain('aria-label="Sessions"');+ expect(plain).not.toContain("data-tooltip");+ expect(plain).toContain('<span class="text-sm font-semibold">PenguinHarness</span>');+ const badged = renderStatic(+ createElement(MobileTopBar, {+ title: "PenguinHarness",+ menuLabel: "Sessions · Update available",+ menuHint: "Update available",+ menuBadge: createElement("i", { "aria-hidden": true }),+ onMenu: () => {},+ }),+ );+ expect(badged).toContain(+ 'aria-label="Sessions · Update available" data-tooltip="Update available"',+ );+ expect(badged).toContain('<i aria-hidden="true"></i></button>');+ });+});++describe("Rail", () => {+ it("scrolls its entries in a nav, the head and foot staying put", () => {+ const html = renderStatic(+ createElement(Rail, { head: text("head"), foot: text("foot"), children: text("entry") }),+ );+ expect(html).toMatch(+ /<span>head<\/span><nav class="[^"]*overflow-y-auto[^"]*"><span>entry<\/span><\/nav><span>foot<\/span>/,+ );+ });++ it("names an icon entry and hints it with the styled tooltip, never a native title", () => {+ const html = renderStatic(+ createElement(RailItem, { label: "New chat", glyph: ICONS.penLine, onClick: () => {} }),+ );+ expect(html).toContain('<button type="button" aria-label="New chat"');+ expect(html).not.toContain("title=");+ });++ it("presses a toggle and fills a selected entry with the column's wash", () => {+ const pressed = renderStatic(+ createElement(RailItem, { label: "Company", glyph: ICONS.building, pressed: true }),+ );+ expect(pressed).toContain('aria-pressed="true"');+ expect(railItemClass({ active: true })).toContain(NAV_FILL.selected);+ expect(railItemClass()).not.toContain(` ${NAV_FILL.selected}`);+ expect(railItemClass({ disabled: true })).toContain("cursor-not-allowed");+ });++ it("hands a link entry to the router, the current page marked, and parks a dead one", () => {+ const seen: NavRowLinkProps[] = [];+ renderStatic(+ createElement(RailItem, {+ label: "Models",+ glyph: ICONS.chip,+ href: "/models",+ active: true,+ renderLink: (link: NavRowLinkProps) => {+ seen.push(link);+ return createElement("a", { href: link.href }, link.children);+ },+ }),+ );+ expect(seen[0]).toMatchObject({+ href: "/models",+ "aria-current": "page",+ "aria-label": "Models",+ });+ const dead = renderStatic(+ createElement(RailItem, {+ label: "Overview",+ glyph: ICONS.dashboard,+ href: "",+ disabled: true,+ }),+ );+ expect(dead).toContain('<span role="link" aria-label="Overview" aria-disabled="true"');+ });++ it("rules runs of entries apart and opens the account menu from a named square", () => {+ expect(renderStatic(createElement(RailDivider))).toBe(+ '<span aria-hidden="true" class="my-0.5 h-px w-5 shrink-0 bg-line"></span>',+ );+ const account = renderStatic(+ createElement(RailAccountButton, {+ label: "Ada",+ expanded: false,+ onClick: () => {},+ children: text("A"),+ }),+ );+ expect(account).toContain('aria-label="Ada" aria-haspopup="menu" aria-expanded="false"');+ });+});diff --git a/packages/ui/test/breadcrumbs.test.ts b/packages/ui/test/breadcrumbs.test.tsnew file mode 100644index 00000000..acbe9118--- /dev/null+++ b/packages/ui/test/breadcrumbs.test.ts@@ -0,0 +1,101 @@+/**+ * The breadcrumbs (src/components/navigation/breadcrumbs): which trailing items fit a one-row+ * strip and the width an item is priced at, how a file name splits so its stem gives way first,+ * and the strip itself — the whole path before it has measured anything, the last item split,+ * and a button only for an item that goes somewhere.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { Breadcrumbs } from "../src/components/navigation/breadcrumbs/breadcrumbs";+import {+ crumbItemWidth,+ splitFileName,+ visibleCrumbSegments,+} from "../src/components/navigation/breadcrumbs/crumb-fit";+import { renderStatic } from "../src/testing";++describe("visibleCrumbSegments", () => {+ /** A fixed advance per character, so the fit is arithmetic rather than a font. */+ const measure = (text: string): number => text.length * 10;++ it("shows the whole path when it fits", () => {+ expect(visibleCrumbSegments(["root", "aa", "bb"], 1000, measure)).toEqual({+ visible: ["root", "aa", "bb"],+ collapsed: false,+ });+ expect(visibleCrumbSegments([], 1000, measure)).toEqual({ visible: [], collapsed: false });+ });++ it("drops leading segments until the rest fit, pricing in the ellipsis they become", () => {+ // "cc" 20 + "bb" 20 + the ellipsis still ahead of them 10 = 50, within 60; "aa" would+ // make it 70.+ expect(visibleCrumbSegments(["root", "aa", "bb", "cc"], 60, measure)).toEqual({+ visible: ["bb", "cc"],+ collapsed: true,+ });+ // At 100 the first segment fits too, and with nothing left ahead of it there is no+ // ellipsis to pay for.+ expect(visibleCrumbSegments(["root", "aa", "bb", "cc"], 100, measure)).toEqual({+ visible: ["root", "aa", "bb", "cc"],+ collapsed: false,+ });+ });++ it("always keeps the last item, however little room there is", () => {+ expect(visibleCrumbSegments(["root", "aa", "bb"], 0, measure)).toEqual({+ visible: ["bb"],+ collapsed: true,+ });+ });++ it("prices a wide character at two narrow ones", () => {+ expect(crumbItemWidth("文档") - crumbItemWidth("")).toBe(+ crumbItemWidth("docs") - crumbItemWidth(""),+ );+ });+});++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("Breadcrumbs", () => {+ it("shows the whole path until it has a width to fit it to, the last item split", () => {+ const html = renderStatic(+ createElement(Breadcrumbs, {+ items: [{ label: "." }, { label: "src" }, { label: "rag.ts" }],+ title: "./src/rag.ts",+ }),+ );+ expect(html).toContain('data-tooltip="./src/rag.ts"');+ expect(html).not.toContain("…");+ expect(html.match(/>\/<\/span>/g)).toHaveLength(2);+ expect(html).toContain(">rag</span><span");+ expect(html).toContain(">.ts</span>");+ expect(html).not.toContain("<button");+ });++ it("makes an item that goes somewhere a button", () => {+ const html = renderStatic(+ createElement(Breadcrumbs, {+ items: [{ label: "Workspace", onClick: () => undefined }, { label: "notes" }],+ }),+ );+ expect(html.match(/<button type="button"/g)).toHaveLength(1);+ expect(html).toMatch(/<button[^>]*>.*>Workspace<\/span><\/button>/);+ });+});diff --git a/packages/ui/test/code-block.test.ts b/packages/ui/test/code-block.test.tsindex 30ca714a..e1c95df0 100644--- a/packages/ui/test/code-block.test.ts+++ b/packages/ui/test/code-block.test.ts@@ -20,6 +20,7 @@ import {LANGUAGE_LOADERS,PLAIN_TEXT_LANGUAGE,languageForExtension,+ languageForFileName,resolveLanguage,} from "../src/components/content/code-block/code-languages";import { DEFAULT_UI_STRINGS, UiStringsProvider } from "../src/strings";@@ -128,6 +129,13 @@ describe("the language tables", () => {expect(languageForExtension("unknown")).toBe(PLAIN_TEXT_LANGUAGE);});+ it("read a file's language from its name, or its whole name when it has no extension", () => {+ expect(languageForFileName("src/rag.TS")).toBe(languageForExtension("ts"));+ expect(languageForFileName("notes/build.sh")).toBe("shellscript");+ expect(languageForFileName("Makefile")).toBe(languageForExtension("makefile"));+ expect(languageForFileName("dir.d/README")).toBe(PLAIN_TEXT_LANGUAGE);+ });+it("never resolve a prototype key", () => {expect(resolveLanguage("constructor")).toBeUndefined();expect(languageForExtension("__proto__")).toBe(PLAIN_TEXT_LANGUAGE);diff --git a/packages/ui/test/dock-frame.test.ts b/packages/ui/test/dock-frame.test.tsnew file mode 100644index 00000000..edbc6b57--- /dev/null+++ b/packages/ui/test/dock-frame.test.ts@@ -0,0 +1,68 @@+/**+ * DockFrame (src/components/shell/dock-frame/dock-frame.tsx): a dock that hides at size 0+ * rather than unmounting, lays its content out at the settled size, and animates only through+ * the theme's layout motion.+ */+import { createElement } from "react";+import type { ComponentProps } from "react";+import { describe, expect, it } from "vitest";+import { DockFrame, DockHeaderButton } from "../src/components/shell/dock-frame/dock-frame";+import { classTokens, renderStatic } from "../src/testing";++const handle = createElement("div", { "data-testid": "handle" });++const render = (props: Partial<ComponentProps<typeof DockFrame>> = {}) =>+ renderStatic(+ createElement(DockFrame, {+ position: "bottom",+ open: true,+ size: 240,+ contentSize: 240,+ animate: true,+ tabs: "TABS",+ actions: createElement(DockHeaderButton, { label: "Hide the dock", children: "×" }),+ handle,+ children: "BODY",+ ...props,+ }),+ );++describe("DockFrame", () => {+ it("says what is on screen, and animates through the layout-motion attribute only", () => {+ const html = render();+ expect(html).toMatch(/^<div data-testid="dock" data-position="bottom" data-open="true"/);+ expect(html).toContain('data-layout-motion=""');+ expect(html).toContain('style="height:240px"');+ expect(html).not.toMatch(/transition-\[/);+ expect(render({ animate: false })).not.toContain("data-layout-motion");+ });++ it("keeps a closed dock in the tree at size 0, inert, with no border and no handle", () => {+ const html = render({ open: false, size: 0 });+ expect(html).toContain('data-open="false"');+ expect(html).toContain("inert");+ expect(html).toContain('style="height:0"');+ expect(html).not.toContain("border-t");+ expect(html).not.toContain('data-testid="handle"');+ // The content still lays out at the settled size.+ expect(html).toContain('style="height:240px"');+ expect(html).toContain("BODY");+ });++ it("puts the right dock's handle before the dock, where it costs real width", () => {+ const html = render({ position: "right", size: 360, contentSize: 360 });+ expect(html).toMatch(+ /^<div data-testid="handle"><\/div><div data-testid="dock" data-position="right"/,+ );+ expect(html).toContain('style="width:360px"');+ expect(classTokens(html)).toEqual(+ expect.arrayContaining(["bg-canvas", "border-l", "border-line"]),+ );+ });++ it("names a header button and gives it the tooltip", () => {+ const html = render();+ expect(html).toContain('data-tooltip="Hide the dock" aria-label="Hide the dock"');+ expect(html).toContain('data-testid="dock-header"');+ });+});diff --git a/packages/ui/test/dock-picker.test.ts b/packages/ui/test/dock-picker.test.tsnew file mode 100644index 00000000..ec654079--- /dev/null+++ b/packages/ui/test/dock-picker.test.ts@@ -0,0 +1,42 @@+/**+ * DockPicker (src/components/shell/dock-picker/dock-picker.tsx): an empty dock's choices, laid+ * out as a list or a row, with a shortcut as key caps.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { DockPicker } from "../src/components/shell/dock-picker/dock-picker";+import { classTokens, renderStatic } from "../src/testing";++describe("DockPicker", () => {+ const render = (horizontal: boolean) =>+ renderStatic(+ createElement(DockPicker, {+ horizontal,+ choices: [+ { key: "agents", label: "Agents", glyph: "A", onChoose: () => {} },+ {+ key: "terminal",+ label: "Terminal",+ glyph: "T",+ keys: ["Ctrl", "`"],+ onChoose: () => {},+ },+ ],+ }),+ );++ it("renders one button per choice, and a shortcut as key caps", () => {+ const html = render(false);+ expect(html).toContain('data-testid="dock-pick-agents"');+ expect(html).toContain('data-testid="dock-pick-terminal"');+ expect(html.match(/<button/g)).toHaveLength(2);+ expect(html).toContain("<kbd");+ expect(html).toMatch(/>Ctrl<\/kbd><kbd[^>]*>`<\/kbd>/);+ });++ it("stacks the choices on the right dock and wraps them in a row on the bottom one", () => {+ expect(classTokens(render(false))).toEqual(expect.arrayContaining(["flex-col", "w-60"]));+ expect(classTokens(render(true))).toEqual(expect.arrayContaining(["flex-wrap"]));+ expect(classTokens(render(true))).not.toContain("flex-col");+ });+});diff --git a/packages/ui/test/dock-tabs.test.ts b/packages/ui/test/dock-tabs.test.tsnew file mode 100644index 00000000..6dff92f1--- /dev/null+++ b/packages/ui/test/dock-tabs.test.ts@@ -0,0 +1,79 @@+/**+ * DockTabs (src/components/navigation/dock-tabs/dock-tabs.tsx): a dock's tab strip — a tab list+ * on the underline hook, whose pills hold a select button and a sibling ×.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { DockTabs } from "../src/components/navigation/dock-tabs/dock-tabs";+import type { DockTabItem } from "../src/components/navigation/dock-tabs/dock-tabs";+import { classTokens, renderStatic } from "../src/testing";++const TABS: DockTabItem[] = [+ { key: "workspace", label: "Files", glyph: "F", closeLabel: "Close tab" },+ {+ key: "terminal:t1",+ label: "1: zsh",+ title: "zsh — /repo",+ glyph: "T",+ badge: true,+ closeLabel: "Kill shell",+ closeShortcut: "Ctrl+W",+ terminalId: "t1",+ },+];++const render = (active: string | null = "workspace") =>+ renderStatic(+ createElement(DockTabs, { tabs: TABS, active, onSelect: () => {}, onClose: () => {} }),+ );++describe("DockTabs", () => {+ it("is a tab list on the underline hook, with exactly the shown tab selected", () => {+ const html = render();+ expect(html).toMatch(+ /^<div role="tablist" data-testid="dock-tab-strip" class="ui-underline-nav /,+ );+ expect(html.match(/role="tab"/g)).toHaveLength(2);+ expect(html.match(/aria-selected="true"/g)).toHaveLength(1);+ expect(html).toContain('data-tab-id="workspace" data-active="true"');+ expect(render(null)).not.toContain('aria-selected="true"');+ });++ it("keeps the × a sibling of the select button, never nested in it", () => {+ const html = render();+ expect(html).not.toMatch(/<button[^>]*>(?:(?!<\/button>).)*<button/);+ expect(html.match(/data-testid="dock-tab-close"/g)).toHaveLength(2);+ });++ it("names each × after its tab, with the shortcut in the tooltip only", () => {+ const html = render();+ expect(html).toContain('aria-label="Close tab: Files"');+ expect(html).toContain('aria-label="Kill shell: 1: zsh"');+ expect(html).toContain('data-tooltip="Kill shell (Ctrl+W)"');+ expect(html).toContain('data-tooltip="zsh — /repo"');+ expect(html).toContain('data-terminal-id="t1"');+ });++ it("grows the pills and the × targets under a finger", () => {+ const coarse = renderStatic(+ createElement(DockTabs, {+ tabs: TABS,+ active: "workspace",+ coarse: true,+ onSelect: () => {},+ onClose: () => {},+ }),+ );+ expect(classTokens(render())).toEqual(expect.arrayContaining(["h-6", "h-4", "w-4"]));+ expect(classTokens(coarse)).toEqual(expect.arrayContaining(["h-8", "h-6", "w-6"]));+ expect(classTokens(coarse)).not.toContain("h-4");+ });++ it("marks a tab's badge with the attention dot, in tokens", () => {+ const html = render();+ expect(html.match(/bg-tone-attention-emphasis/g)).toHaveLength(1);+ expect(classTokens(html)).toEqual(+ expect.arrayContaining(["bg-line-muted", "text-fg-muted", "text-fg-subtle"]),+ );+ });+});diff --git a/packages/ui/test/file-browser.test.ts b/packages/ui/test/file-browser.test.tsnew file mode 100644index 00000000..50e35db6--- /dev/null+++ b/packages/ui/test/file-browser.test.ts@@ -0,0 +1,95 @@+/**+ * The read-only file browser (src/components/files/file-browser/file-browser.tsx): the tree+ * beside one preview, every word it draws on its own from the caller, and Markdown through the+ * shared reader with its frontmatter dropped on request.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { FileBrowser } from "../src/components/files/file-browser/file-browser";+import type {+ FileBrowserPreview,+ FileBrowserProps,+} from "../src/components/files/file-browser/file-browser";+import type { FileTreeRow } from "../src/components/files/file-tree/tree-rows";+import { classTokens, renderStatic } from "../src/testing";++const ROWS: FileTreeRow[] = [+ {+ path: "SKILL.md",+ name: "SKILL.md",+ kind: "file",+ depth: 0,+ posInSet: 1,+ setSize: 1,+ expanded: false,+ loaded: true,+ empty: false,+ },+];++const render = (+ preview: FileBrowserPreview | null,+ extra: Partial<FileBrowserProps<FileTreeRow>> = {},+) =>+ renderStatic(+ createElement(FileBrowser<FileTreeRow>, {+ rows: ROWS,+ treeLabel: "Plugin files",+ selectedPath: preview?.path ?? null,+ headerFallback: "docs-expert",+ preview,+ emptyPreview: "Nothing selected",+ emptyDirLabel: "Nothing here",+ truncatedLabel: "Cut short",+ unsupportedLabel: "Cannot show this",+ downloadLabel: "Save",+ onToggleDir: () => undefined,+ onOpenFile: () => undefined,+ ...extra,+ }),+ );++describe("FileBrowser", () => {+ it("names the tree and the header from the caller while nothing is open", () => {+ const html = render(null);+ expect(html).toContain('role="tree" aria-label="Plugin files"');+ expect(html).toContain(">docs-expert</p>");+ expect(html).toContain(">Nothing selected</p>");+ });++ it("says the caller's words for a cut-short file, an unsupported one and the download", () => {+ const cut = render({+ path: "notes.txt",+ name: "notes.txt",+ kind: "text",+ content: "a",+ truncated: true,+ downloadUrl: "/files/notes.txt",+ });+ expect(cut).toContain(">Cut short</p>");+ expect(cut).toContain('download="notes.txt"');+ expect(cut).toContain(">Save</a>");+ const odd = render({ path: "blob.bin", name: "blob.bin", kind: "unsupported" });+ expect(odd).toContain(">Cannot show this</p>");+ });++ it("reads Markdown in the reading box, dropping frontmatter when asked", () => {+ const md: FileBrowserPreview = {+ path: "SKILL.md",+ name: "SKILL.md",+ kind: "md",+ content: "---\nname: docs\n---\n# Docs Expert\n",+ };+ const stripped = render(md, { stripFrontmatter: true });+ expect(stripped).toContain("md-body");+ expect(stripped).toContain("Docs Expert</h1>");+ expect(stripped).not.toContain("name: docs");+ expect(render(md)).toContain("name: docs");+ });++ it("frames itself in tokens", () => {+ const html = render(null);+ expect(classTokens(html)).toEqual(expect.arrayContaining(["border-line", "rounded-md"]));+ expect(html).not.toMatch(/gray-|red-|dark:/);+ });+});diff --git a/packages/web/test/file-tree.test.ts b/packages/ui/test/file-tree-rows.test.tssimilarity index 89%rename from packages/web/test/file-tree.test.tsrename to packages/ui/test/file-tree-rows.test.tsindex 98ad1447..971b5e05 100644--- a/packages/web/test/file-tree.test.ts+++ b/packages/ui/test/file-tree-rows.test.ts@@ -1,11 +1,12 @@/**- * The shared file tree's DOM-free logic (lib/file-tree.ts): where a row's subtree ends in the- * flat row list, and the keyboard step over those rows — the WAI-ARIA tree pattern's up/down- * move, right to open a directory or step into it, left to close it or step out to its parent.+ * The file tree's DOM-free logic (src/components/files/file-tree/tree-rows.ts): where a row's+ * subtree ends in the flat row list, and the keyboard step over those rows — the WAI-ARIA tree+ * pattern's up/down move, right to open a directory or step into it, left to close it or step out+ * to its parent.*/import { describe, expect, it } from "vitest";-import { subtreeEnd, treeKeyStep } from "../src/lib/file-tree";-import type { FileTreeRow } from "../src/lib/file-tree";+import { subtreeEnd, treeKeyStep } from "../src/components/files/file-tree/tree-rows";+import type { FileTreeRow } from "../src/components/files/file-tree/tree-rows";const baseName = (path: string): string => path.slice(path.lastIndexOf("/") + 1);diff --git a/packages/ui/test/file-tree.test.ts b/packages/ui/test/file-tree.test.tsnew file mode 100644index 00000000..c8d0bd5a--- /dev/null+++ b/packages/ui/test/file-tree.test.ts@@ -0,0 +1,91 @@+/**+ * The file tree (src/components/files/file-tree/file-tree.tsx): the WAI-ARIA tree shape over the+ * caller's flat rows, the attributes a caller's hit test resolves a row by, an open directory's+ * children nested in a group, the caller's words for an empty directory, and inks from tokens.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { FileTree } from "../src/components/files/file-tree/file-tree";+import type { FileTreeRow } from "../src/components/files/file-tree/tree-rows";+import { classTokens, renderStatic } from "../src/testing";++const row = (+ path: string,+ kind: "dir" | "file",+ depth: number,+ posInSet: number,+ setSize: number,+ extra: Partial<FileTreeRow> = {},+): FileTreeRow => ({+ path,+ name: path.slice(path.lastIndexOf("/") + 1),+ kind,+ depth,+ posInSet,+ setSize,+ expanded: false,+ loaded: kind === "file",+ empty: false,+ ...extra,+});++const ROWS: FileTreeRow[] = [+ row("src", "dir", 0, 1, 3, { expanded: true, loaded: true }),+ row("src/rag.ts", "file", 1, 1, 2),+ row("src/empty", "dir", 1, 2, 2, { expanded: true, loaded: true, empty: true }),+ row("docs", "dir", 0, 2, 3),+ row("README.md", "file", 0, 3, 3),+];++const render = (props: Partial<Parameters<typeof FileTree<FileTreeRow>>[0]> = {}) =>+ renderStatic(+ createElement(FileTree<FileTreeRow>, {+ rows: ROWS,+ label: "Workspace",+ selectedPath: "src/rag.ts",+ emptyLabel: "Empty directory",+ onToggleDir: () => undefined,+ onOpenFile: () => undefined,+ ...props,+ }),+ );++describe("FileTree", () => {+ it("is a named tree whose rows state their level, place in their set and state", () => {+ const html = render();+ expect(html).toContain('role="tree" aria-label="Workspace"');+ expect(html.match(/role="treeitem"/g)).toHaveLength(ROWS.length);+ expect(html).toContain(+ 'aria-level="2" aria-posinset="1" aria-setsize="2" aria-selected="true"',+ );+ expect(html).toMatch(/aria-selected="false" aria-expanded="true"[^>]*data-tree-path="src"/);+ expect(html).toContain('data-tree-path="README.md" data-tree-kind="file"');+ // The selected row is the one tab stop.+ expect(html.match(/tabindex="0"/g)).toHaveLength(1);+ expect(html).toMatch(/tabindex="0"[^>]*data-tree-path="src\/rag.ts"/);+ });++ it("nests an open directory's rows in a named group, and says an empty one is empty", () => {+ const html = render();+ expect(html).toContain('role="group" aria-label="src"');+ expect(html).toContain('role="group" aria-label="empty"');+ expect(html).toContain(">Empty directory</p>");+ // A closed directory draws no group.+ expect(html).not.toContain('aria-label="docs"');+ });++ it("rings the folder a drag would drop into in the info tone, and takes every ink from tokens", () => {+ const html = render({ dropTargetDir: "docs" });+ const tokens = classTokens(html);+ expect(tokens).toEqual(+ expect.arrayContaining(["bg-tone-info-bg", "ring-tone-info-emphasis/60", "text-fg"]),+ );+ expect(html).not.toMatch(/gray-|sky-|dark:/);+ });++ it("shows the caller's empty state in place of rows when there are none", () => {+ const html = render({ rows: [], children: createElement("p", null, "No files") });+ expect(html).toContain(">No files</p>");+ expect(html).not.toContain("treeitem");+ });+});diff --git a/packages/ui/test/files-panes.test.ts b/packages/ui/test/files-panes.test.tsnew file mode 100644index 00000000..985edf79--- /dev/null+++ b/packages/ui/test/files-panes.test.ts@@ -0,0 +1,130 @@+/**+ * The Files panel's panes and its drop feedback (src/components/files): the tree pane's header+ * and the one state its body says, the preview pane's views with the pill and the editor over+ * the body, and the drop overlay as pure, hidden feedback in its two shapes.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { DropOverlay } from "../src/components/files/drop-overlay/drop-overlay";+import { PreviewPane } from "../src/components/files/preview-pane/preview-pane";+import type {+ PreviewPaneProps,+ PreviewView,+} from "../src/components/files/preview-pane/preview-pane";+import { TreePane } from "../src/components/files/tree-pane/tree-pane";+import type { TreePaneProps } from "../src/components/files/tree-pane/tree-pane";+import { classTokens, renderStatic } from "../src/testing";++const search = { value: "", onChange: () => undefined, placeholder: "Search files" };+const tree = createElement("div", { role: "tree" }, "rows");++describe("TreePane", () => {+ it("heads the tree with its search box, named by its placeholder, and the caller's actions", () => {+ const html = renderStatic(+ createElement(TreePane, {+ search,+ actions: createElement("button", { type: "button" }, "Refresh"),+ children: tree,+ }),+ );+ expect(html).toContain('placeholder="Search files"');+ expect(html).toContain('aria-label="Search files"');+ expect(html.indexOf("Search files")).toBeLessThan(html.indexOf(">Refresh<"));+ expect(html).toContain('role="tree"');+ });++ it("says the first of: a failure, a first load, a pending search — and only then the tree", () => {+ const pane = (props: Partial<TreePaneProps>) =>+ renderStatic(createElement(TreePane, { search, children: tree, ...props }));+ const failed = pane({ error: "Could not list", loading: true, pending: "Searching…" });+ expect(failed).toContain(">Could not list</p>");+ expect(failed).not.toContain("rows");+ expect(classTokens(failed)).toContain("text-tone-danger-fg");+ expect(pane({ loading: true, pending: "Searching…" })).not.toContain("Searching…");+ const waiting = pane({ pending: "Searching…" });+ expect(waiting).toContain(">Searching…</p>");+ expect(waiting).not.toContain('role="tree"');+ const cut = pane({ note: "Showing the first 200" });+ expect(cut).toContain('role="tree"');+ expect(cut).toContain(">Showing the first 200</p>");+ });+});++describe("PreviewPane", () => {+ const pane = (view: PreviewView, props: Partial<PreviewPaneProps> = {}) =>+ renderStatic(createElement(PreviewPane, { view, ...props }));++ it("shows the empty state's title and action while nothing is chosen", () => {+ const html = pane({+ kind: "empty",+ title: "Select a file to preview",+ action: createElement("button", { type: "button" }, "Show tree"),+ });+ expect(html).toContain(">Select a file to preview</p>");+ expect(html).toContain(">Show tree</button>");+ });++ it("sets source flush on the code surface, and pads every other body", () => {+ const source = pane({ kind: "source", code: "let a = 1;", language: "ts", wrap: false });+ expect(source).toContain('tabindex="-1"');+ expect(source).not.toMatch(/tabindex="-1" class="[^"]*\bp-3\b/);+ const unsupported = pane({ kind: "unsupported", message: "No preview for this type" });+ expect(unsupported).toMatch(/tabindex="-1" class="[^"]*\bp-3\b/);+ expect(unsupported).toContain(">No preview for this type</p>");+ });++ it("notes a cut-short file under the text", () => {+ const html = pane({+ kind: "source",+ code: "x",+ language: "text",+ wrap: true,+ truncatedNote: "Preview truncated",+ });+ expect(html).toContain(">… Preview truncated</p>");+ });++ it("pins the caller's actions in a pill over the body, and keeps them over the editor", () => {+ const actions = createElement("button", { type: "button" }, "Wrap");+ const view: PreviewView = { kind: "source", code: "x", language: "text", wrap: false };+ const reading = pane(view, { actions });+ expect(reading).toContain(">Wrap</button>");+ expect(classTokens(reading)).toEqual(+ expect.arrayContaining(["absolute", "right-4", "top-2.5", "bg-surface", "border-line"]),+ );+ const editing = pane(view, {+ actions,+ editor: createElement("textarea", { "aria-label": "Editing a" }),+ });+ expect(editing).toContain('aria-label="Editing a"');+ expect(editing).toContain(">Wrap</button>");+ // The editor replaces the body, so the body's own box is gone.+ expect(editing).not.toContain('tabindex="-1"');+ });+});++describe("DropOverlay", () => {+ it("is hidden, pointer-transparent feedback carrying the caller's words", () => {+ const veil = renderStatic(+ createElement(DropOverlay, {+ glyph: "M0 0h24",+ title: "Drop files to attach",+ description: "Images and files are added to the message draft",+ }),+ );+ expect(veil).toMatch(/^<div aria-hidden="true" class="[^"]*pointer-events-none/);+ expect(veil).toContain(">Drop files to attach</p>");+ expect(veil).toContain(">Images and files are added to the message draft</p>");+ expect(classTokens(veil)).toEqual(expect.arrayContaining(["border-dashed", "z-50"]));+ });++ it("frames a panel with its label at the foot", () => {+ const frame = renderStatic(+ createElement(DropOverlay, { variant: "frame", glyph: "M0 0h24", title: "Drop into src" }),+ );+ expect(frame).toMatch(/^<div aria-hidden="true" class="[^"]*pointer-events-none/);+ expect(frame).toContain(">Drop into src</span>");+ expect(classTokens(frame)).toEqual(expect.arrayContaining(["items-end", "z-20"]));+ expect(frame).not.toMatch(/gray-|white|dark:|backdrop-blur/);+ });+});diff --git a/packages/web/test/frontmatter.test.ts b/packages/ui/test/frontmatter.test.tssimilarity index 75%rename from packages/web/test/frontmatter.test.tsrename to packages/ui/test/frontmatter.test.tsindex ea8444eb..9bf7f5ac 100644--- a/packages/web/test/frontmatter.test.ts+++ b/packages/ui/test/frontmatter.test.ts@@ -1,11 +1,11 @@/**- * frontmatter.ts unit tests: stripping the leading YAML block from a memory file's content,- * shared by the agent-settings memory tab and the chat Memory panel. The cases that matter are- * the ones a hand-written topic file actually produces — no block, an unterminated block, CRLF,- * a BOM, and a `---` rule further down the body.+ * The frontmatter helper (src/components/content/prose/frontmatter.ts): stripping the leading YAML+ * block from a Markdown file's content, shared by the memory views and the file browser. The cases+ * that matter are the ones a hand-written topic file actually produces — no block, an unterminated+ * block, CRLF, a BOM, and a `---` rule further down the body.*/import { describe, expect, it } from "vitest";-import { bodyWithoutFrontmatter } from "../src/lib/frontmatter";+import { bodyWithoutFrontmatter } from "../src/components/content/prose/frontmatter";describe("bodyWithoutFrontmatter", () => {it("strips a well-formed block and keeps the body verbatim", () => {diff --git a/packages/ui/test/group-header.test.ts b/packages/ui/test/group-header.test.tsindex 5372be2e..e9ac55e4 100644--- a/packages/ui/test/group-header.test.ts+++ b/packages/ui/test/group-header.test.ts@@ -52,6 +52,20 @@ describe("GroupHeader", () => {expect(classTokens(header(true, true))).not.toContain("uppercase");expect(classTokens(header(true, false))).not.toContain("ui-eyebrow");});++ it("draws a registry glyph as the header's decorative mark, in the subtle ink", () => {+ const html = inZh(+ createElement(GroupHeader, {+ open: true,+ onToggle: () => {},+ glyph: "M3 7h18",+ label: "repo",+ }),+ );+ expect(html).toMatch(+ /<svg [^>]*class="block shrink-0 ui-icon-decor text-fg-subtle" data-role="group"/,+ );+ });});describe("FolderSection and MoreRow", () => {diff --git a/packages/ui/test/hooks.test.ts b/packages/ui/test/hooks.test.tsindex 9df599dc..4c70ddd8 100644--- a/packages/ui/test/hooks.test.ts+++ b/packages/ui/test/hooks.test.ts@@ -71,15 +71,15 @@ const APPENDIX_A = [* it exists: the last test below fails on a host no scanned file declares.** Glass is for the layers that float over the page (the composer card and its slash list, dialogs,- * menus, popovers, tooltips); the eyebrow and display rungs for the sidebar's list label and the page titles; live- * marks for the spinner, a pulsing state dot, the machines page's working marks and the caret of- * a reply still streaming in; frames for the transcript's cards, the code block, the page's cards- * and a table that is its own box; the shell for the app layout; a decorative icon for the rows- * and headers whose label already says what the icon says (sidebar rows and group headers, a nav- * row's glyph in a rail, a menu row's glyph, a tab, an empty state) — a session row is not a host,- * its avatar and marks carry information; a tree for a file tree and a work group's steps; a field- * for a settings row; activity for the transcript's work in progress (the work group's header, a- * tool call, the thinking row).+ * menus, popovers, tooltips, the floating launcher); the eyebrow and display rungs for the+ * sidebar's list label and the page titles; live marks for the spinner, a pulsing state dot, the+ * machines page's working marks and the caret of a reply still streaming in; frames for the+ * transcript's cards, the code block, the page's cards and a table that is its own box; the shell+ * for the app window; a decorative icon for the rows and headers whose label already says what the+ * icon says (a nav row's glyph in the sidebar or a rail, a group header's, a menu row's glyph, a+ * tab, an empty state) — a session row is not a host, its avatar and marks carry information; a+ * tree for a file tree and a work group's steps; a field for a settings row; activity for the+ * transcript's work in progress (the work group's header, a tool call, the thinking row).*/const HOSTS: Readonly<Record<string, readonly string[]>> = {// The composer's card and the slash list that opens over it (W6) float with the menus.@@ -94,23 +94,28 @@ const HOSTS: Readonly<Record<string, readonly string[]>> = {"Tooltip","TooltipLayer","TooltipPanel",+ // The floating launcher (W7): its ball and caption, and the fan's entries, float over the+ // conversation with content moving underneath.+ "LauncherBall",+ "LauncherFan",],- // `Text` carries it for its eyebrow role (W5), the one door a group label takes in new code.- "ui-eyebrow": ["Sidebar", "GroupHeader", "PagedDialog", "Text"],+ // `Text` carries it for its eyebrow role (W7), the one door a group label takes in new code —+ // the sidebar's list label among them (W7).+ "ui-eyebrow": ["GroupHeader", "PagedDialog", "Text"],// The page titles are `PageHeader`'s; the draft view's hero writes its own."ui-display": ["Heading", "PageHeader", "EmptyState", "DraftView"],"ui-live": ["Spinner", "Dot", "Stepper", "MachineCard", "ProgressBar", "StreamingCaret"],// The transcript's cards (the tool call, the work group, the changes card at a Task's foot) and// the code block, and the page-level boxes (W4): the card and a table that is its own box."ui-frame": ["ToolCallCard", "WorkGroup", "ChangesCard", "CodeBlock", "Card", "Table"],- "ui-underline-nav": ["Tabs"],- "ui-shell": ["AppLayout"],+ // The page tab bar, and a dock's tab strip (W7).+ "ui-underline-nav": ["Tabs", "DockTabs"],+ // The app window (W7: the package's shell; the web's layout route renders it).+ "ui-shell": ["AppShell"],"ui-icon-decor": ["GlyphIcon",- "Sidebar","NavRow","SettingsDialog",- "MenuItemGlyph","MenuItem","GroupHeader","Tabs",diff --git a/packages/ui/test/launcher.test.ts b/packages/ui/test/launcher.test.tsnew file mode 100644index 00000000..908c21a3--- /dev/null+++ b/packages/ui/test/launcher.test.ts@@ -0,0 +1,93 @@+/**+ * LauncherBall and LauncherFan (src/components/shell/launcher/launcher.tsx): the floating ball+ * with its caption, and the arc of entries it opens.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { LauncherBall, LauncherFan } from "../src/components/shell/launcher/launcher";+import { classTokens, renderStatic } from "../src/testing";++const ball = (props: { lit?: boolean; badge?: boolean } = {}) =>+ renderStatic(+ createElement(LauncherBall, {+ size: 56,+ captionHeight: 30,+ glyph: "G",+ caption: "Shortcuts",+ label: "Open the workbench",+ lit: props.lit ?? false,+ dragging: false,+ badge: props.badge,+ }),+ );++describe("LauncherBall", () => {+ it("is named by its label, with the caption shown but hidden from assistive technology", () => {+ const html = ball();+ expect(html).toContain('aria-label="Open the workbench"');+ expect(html).toMatch(/<span aria-hidden="true" class="ui-glass [^"]*"[^>]*>Shortcuts<\/span>/);+ });++ it("keeps the product's geometry: the ball's size, and the caption in the reserved room", () => {+ const html = ball();+ expect(html).toContain('style="width:56px;height:56px"');+ expect(html).toContain('style="top:60px;height:26px"');+ expect(classTokens(html)).toContain("text-[length:var(--ui-text-code-size)]");+ });++ it("is quiet at rest and clear when lit, on the glass hook", () => {+ expect(classTokens(ball())).toEqual(expect.arrayContaining(["ui-glass", "opacity-80"]));+ expect(classTokens(ball({ lit: true }))).toEqual(+ expect.arrayContaining(["opacity-100", "text-fg"]),+ );+ });++ it("carries the attention dot only when asked", () => {+ expect(ball()).not.toContain("bg-tone-attention-emphasis");+ expect(ball({ badge: true })).toContain("bg-tone-attention-emphasis");+ });+});++describe("LauncherFan", () => {+ const fan = (phase: "open" | "closing") =>+ renderStatic(+ createElement(LauncherFan, {+ phase,+ entrySize: 46,+ label: "Panels",+ onPoint: () => {},+ onLeave: () => {},+ entries: [+ { key: "a", label: "Agents", glyph: "A", x: 0, y: -112, onChoose: () => {} },+ {+ key: "b",+ label: "Files",+ glyph: "B",+ x: -112,+ y: 0,+ testId: "open-b",+ onChoose: () => {},+ },+ ],+ }),+ );++ it("is a named group of named entries, each placed on the arc by its offset", () => {+ const html = fan("open");+ expect(html).toMatch(/^<div role="group" aria-label="Panels"/);+ expect(html).toContain('aria-label="Agents"');+ expect(html).toContain('data-testid="open-b"');+ expect(html).toContain("--fan-x:-112.0px;--fan-y:0.0px");+ expect(html).toContain("width:46px;height:46px;left:-23px;top:-23px");+ });++ it("staggers the entrance down the arc and folds all at once", () => {+ const open = fan("open");+ expect(open).toContain("launcher-fan-in");+ expect(open).toContain("animation-delay:0ms");+ expect(open).toContain("animation-delay:16ms");+ const closing = fan("closing");+ expect(closing).toContain("launcher-fan-out");+ expect(closing).not.toContain("animation-delay:16ms");+ });+});diff --git a/packages/ui/test/panels-toolbar.test.ts b/packages/ui/test/panels-toolbar.test.tsnew file mode 100644index 00000000..710b5c77--- /dev/null+++ b/packages/ui/test/panels-toolbar.test.ts@@ -0,0 +1,43 @@+/**+ * PanelsToolbar (src/components/shell/panels-toolbar/panels-toolbar.tsx): the toolbar's dock+ * toggles, each saying whether its dock is open.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { PanelsToolbar } from "../src/components/shell/panels-toolbar/panels-toolbar";+import { renderStatic } from "../src/testing";++describe("PanelsToolbar", () => {+ it("says which docks are open, and dots only the toggle that asks for it", () => {+ const html = renderStatic(+ createElement(PanelsToolbar, {+ toggles: [+ {+ key: "bottom",+ label: "Bottom dock",+ glyph: "M0 0h1",+ active: false,+ onToggle: () => {},+ },+ {+ key: "right",+ label: "Right dock",+ tooltip: "Right dock (Ctrl+Alt+R)",+ glyph: "M0 0h1",+ active: true,+ badge: true,+ onToggle: () => {},+ },+ ],+ }),+ );+ expect(html).toContain('data-testid="panels-toolbar"');+ expect(html).toMatch(/aria-expanded="false"[^>]*aria-label="Bottom dock"/);+ expect(html).toMatch(/aria-expanded="true"[^>]*aria-label="Right dock"/);+ expect(html).toContain('data-testid="dock-toggle-right"');+ // The tooltip may add the shortcut; the name stays the label alone.+ expect(html).toContain('data-tooltip="Right dock (Ctrl+Alt+R)" aria-label="Right dock"');+ expect(html).toContain('data-tooltip="Bottom dock" aria-label="Bottom dock"');+ expect(html.match(/bg-tone-attention-emphasis/g)).toHaveLength(1);+ });+});diff --git a/packages/ui/test/resize-handle.test.ts b/packages/ui/test/resize-handle.test.tsnew file mode 100644index 00000000..3b981232--- /dev/null+++ b/packages/ui/test/resize-handle.test.ts@@ -0,0 +1,102 @@+/**+ * The resize family (src/components/layout/resize-handle): the handle is a named separator in the+ * info tone that joins the tab order only when it can step, and the split pane lays its leading+ * column and handle in a window that slides shut when collapsed.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import {+ RESIZE_HANDLE_PX,+ ResizeHandle,+} from "../src/components/layout/resize-handle/resize-handle";+import { SplitPane } from "../src/components/layout/resize-handle/split-pane";+import { classTokens, renderStatic } from "../src/testing";++const noop = () => undefined;++describe("ResizeHandle", () => {+ it("is a separator named by its label, across the axis it moves along", () => {+ const html = renderStatic(+ createElement(ResizeHandle, { axis: "x", label: "Resize the file tree", onResize: noop }),+ );+ expect(html).toContain('role="separator"');+ expect(html).toContain('aria-orientation="vertical"');+ expect(html).toContain('aria-label="Resize the file tree"');+ expect(html).toContain('data-tooltip="Resize the file tree"');+ // Pointer-only without a step: not in the tab order, and no value to report.+ expect(html).not.toContain("tabindex");+ expect(html).not.toContain("aria-valuenow");+ const y = renderStatic(+ createElement(ResizeHandle, { axis: "y", label: "Resize", onResize: noop }),+ );+ expect(y).toContain('aria-orientation="horizontal"');+ expect(classTokens(y)).toContain("cursor-row-resize");+ });++ it("reports its value and joins the tab order when it can step", () => {+ const html = renderStatic(+ createElement(ResizeHandle, {+ axis: "x",+ label: "Resize",+ onResize: noop,+ value: 220,+ min: 160,+ max: 400,+ onStep: noop,+ }),+ );+ expect(html).toContain('aria-valuenow="220"');+ expect(html).toContain('aria-valuemin="160"');+ expect(html).toContain('aria-valuemax="400"');+ expect(html).toContain('tabindex="0"');+ });++ it("draws in the info tone, as a row sibling or straddling an edge", () => {+ const inline = classTokens(+ renderStatic(createElement(ResizeHandle, { axis: "x", label: "Resize", onResize: noop })),+ );+ expect(inline).toEqual(expect.arrayContaining(["w-1.5", "shrink-0", "cursor-col-resize"]));+ expect(inline).toContain("hover:bg-tone-info-emphasis/40");+ expect(inline).not.toContain("absolute");+ const edge = classTokens(+ renderStatic(+ createElement(ResizeHandle, { axis: "y", label: "Resize", onResize: noop, edge: "start" }),+ ),+ );+ expect(edge).toEqual(expect.arrayContaining(["absolute", "-top-[3px]", "h-1.5"]));+ });+});++describe("SplitPane", () => {+ const render = (collapsed: boolean) =>+ renderStatic(+ createElement(SplitPane, {+ size: 220,+ min: 160,+ max: 400,+ label: "Resize the file tree",+ onResize: noop,+ collapsed,+ first: createElement("p", null, "tree"),+ second: createElement("p", null, "preview"),+ }),+ );++ it("gives the leading column its width, and the window that width plus the handle", () => {+ const html = render(false);+ expect(html).toContain(`style="width:${220 + RESIZE_HANDLE_PX}px"`);+ expect(html).toContain('style="width:220px"');+ expect(html).toContain('aria-valuenow="220"');+ expect(html).toContain('tabindex="0"');+ expect(html.indexOf(">tree<")).toBeLessThan(html.indexOf(">preview<"));+ expect(classTokens(html)).toEqual(expect.arrayContaining(["border-r", "border-line"]));+ });++ it("slides the column shut when collapsed, keeping it mounted but out of reach", () => {+ const html = render(true);+ expect(html).toContain('style="width:0"');+ expect(html).toContain('aria-hidden="true"');+ expect(html).toContain("inert");+ expect(html).toContain(">tree<");+ });+});diff --git a/packages/ui/test/session-row.test.ts b/packages/ui/test/session-row.test.tsnew file mode 100644index 00000000..cd7bc0e8--- /dev/null+++ b/packages/ui/test/session-row.test.ts@@ -0,0 +1,167 @@+/**+ * The sidebar's conversation row and its hover actions (src/components/shell/session-row/): a+ * button that opens the conversation, the title drawn by the caller in the row's ink, marks that+ * each name themselves, one reserved box for the live state, and a trailing slot whose time gives+ * way to the hover actions. The row's menu mounts only while open, which a static render never+ * is; what its wiring must keep doing is pinned against the source.+ */+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ICONS } from "../src/components/icons/icons";+import { NAV_FILL } from "../src/components/navigation/nav-list/nav-list";+import { RowHoverActions, SessionRow } from "../src/components/shell/session-row/session-row";+import type { SessionRowProps } from "../src/components/shell/session-row/session-row";+import { classTokens, renderStatic } from "../src/testing";+import { SRC_DIR } from "./helpers/paths";++const SOURCE = readFileSync(join(SRC_DIR, "components/shell/session-row/session-row.tsx"), "utf8");++const action = (id: string, label: string, danger = false) => ({+ id,+ label,+ glyph: ICONS.archive,+ danger,+ onSelect: () => {},+});++const row = (props: Partial<SessionRowProps> = {}) =>+ renderStatic(+ createElement(SessionRow, {+ sessionId: "s-1",+ renderTitle: (className: string) => createElement("span", { className }, "Fix the build"),+ time: "3 分钟前",+ hoverActions: [action("archive", "归档")],+ menuActions: [action("rename", "重命名"), action("delete", "删除", true)],+ moreLabel: "更多",+ onOpen: () => {},+ ...props,+ }),+ );++describe("SessionRow", () => {+ it("is a list item whose button opens the conversation, under the title-reveal hook", () => {+ const html = row();+ expect(html).toMatch(/^<li class="relative">/);+ expect(html).toContain('data-title-reveal="true"');+ expect(html).toContain('data-testid="session-row" data-session-id="s-1"');+ });++ it("hands the title its ink: medium on the open row, subtle when archived, near-full at rest", () => {+ expect(row({ active: true })).toContain(+ 'class="min-w-0 flex-1 font-sans text-sm font-medium text-fg"',+ );+ expect(row({ archived: true })).toContain(+ 'class="min-w-0 flex-1 font-sans text-sm text-fg-subtle"',+ );+ expect(row()).toContain('class="min-w-0 flex-1 font-sans text-sm text-fg/80"');+ });++ it("fills the open row with the column's selected wash and the others with its hover", () => {+ expect(classTokens(row({ active: true }))).toContain(NAV_FILL.selected);+ expect(classTokens(row())).toContain(NAV_FILL.hover);+ expect(classTokens(row())).not.toContain(NAV_FILL.selected);+ });++ it("names every standing mark in words, from the caller's labels", () => {+ const html = row({+ pinnedLabel: "已置顶",+ relayLabel: "飞书远程控制",+ scheduledLabel: "定时任务",+ background: { count: 2, label: "2 个后台任务" },+ approvals: { count: 3, label: "3 个待审批" },+ agent: { id: "coder", name: "Coder" },+ });+ expect(html).toContain('<span class="sr-only">已置顶</span>');+ expect(html).toContain('<span class="sr-only">飞书远程控制</span>');+ expect(html).toContain('<span class="sr-only">Coder</span>');+ expect(html).toContain('role="img" aria-label="定时任务"');+ expect(html).toContain('role="img" aria-label="2 个后台任务"');+ expect(html).toMatch(+ /data-tooltip="3 个待审批" class="[^"]*tabular-nums text-tone-attention-fg">3</,+ );+ });++ it("draws no background mark and no approval count at zero", () => {+ const html = row({+ background: { count: 0, label: "0 个后台任务" },+ approvals: { count: 0, label: "0 个待审批" },+ });+ expect(html).not.toContain("0 个后台任务");+ expect(html).not.toContain("0 个待审批");+ });++ it("keeps the live state's box whether or not it holds a glyph", () => {+ expect(row()).toContain('<span aria-hidden="true" class="block h-3 w-3 shrink-0"></span>');+ const running = row({ activity: { state: "running", label: "运行中" } });+ expect(running).toContain('role="status" aria-label="运行中"');+ expect(running).not.toContain("block h-3 w-3 shrink-0");+ });++ it("reserves a trailing slot per language, its time on the small rung", () => {+ expect(classTokens(row())).toContain("w-14");+ expect(classTokens(row({ timeSlot: "wide" }))).toContain("w-[4.5rem]");+ const tokens = classTokens(row());+ expect(tokens).toContain("text-xs");+ expect(tokens).not.toContain("text-[11px]");+ expect(row()).toContain(">3 分钟前</span>");+ expect(row({ time: "" })).not.toContain("tabular-nums text-fg-subtle transition-opacity");+ });++ it("offers the hover actions and the menu's pointer entry, never the menu rows while closed", () => {+ const html = row();+ expect(html).toContain('aria-label="归档"');+ expect(html).toContain('aria-label="更多" aria-haspopup="menu"');+ expect(html).not.toContain("重命名");+ });++ it("drags only under manual order, with the drop line on the edge it would land on", () => {+ expect(row()).not.toContain('draggable="true"');+ const dragged = row({ draggable: true, dropEdge: "below" });+ expect(dragged).toMatch(/^<li class="relative" draggable="true">/);+ expect(classTokens(dragged)).toEqual(+ expect.arrayContaining(["cursor-grab", "-bottom-px", "bg-accent"]),+ );+ });++ it("wires all three menu openers and names the anchor's owner", () => {+ expect(SOURCE).toContain("{...ctx.rowProps}");+ expect(SOURCE).toContain("ctx.consumeLongPressClick()");+ expect(SOURCE).toContain("anchorOwner={ctx.anchorOwner}");+ // A menu row hands focus back to the row before it acts.+ expect(SOURCE).toMatch(/ctx\.returnFocus\(\)\?\.focus\(\);\s*ctx\.close\(\);/);+ });+});++describe("RowHoverActions", () => {+ const html = renderStatic(+ createElement(RowHoverActions, {+ actions: [action("archive", "Archive"), action("delete", "Delete", true)],+ moreLabel: "More",+ onMore: () => {},+ }),+ );++ it("gates taps exactly as it gates sight, on hover and on focus", () => {+ const tokens = classTokens(html);+ expect(tokens).toEqual(+ expect.arrayContaining([+ "pointer-events-none",+ "opacity-0",+ "group-hover:pointer-events-auto",+ "group-hover:opacity-100",+ "focus:pointer-events-auto",+ "focus:opacity-100",+ ]),+ );+ expect(tokens).not.toContain("focus-visible:opacity-100");+ expect(tokens).not.toContain("transition-all");+ });++ it("names each button, and gives only the destructive one the danger ink", () => {+ expect(html).toContain('data-tooltip="Archive" aria-label="Archive"');+ expect(html.match(/hover:text-tone-danger-fg/g)).toHaveLength(1);+ expect(html).toContain('data-tooltip="More" aria-label="More" aria-haspopup="menu"');+ });+});diff --git a/packages/ui/test/sidebar-frame.test.ts b/packages/ui/test/sidebar-frame.test.tsnew file mode 100644index 00000000..bb33fd21--- /dev/null+++ b/packages/ui/test/sidebar-frame.test.ts@@ -0,0 +1,217 @@+/**+ * The pinned sidebar's frame and its pieces (src/components/shell/sidebar-frame/), and the page+ * row on the navigation column (NavRow on the muted surface): one column whose scroll area is the+ * only block that shrinks, a page nav that folds under its toggle, a list header whose label is+ * the eyebrow rung, and the column's washes in place of surface steps.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ICONS } from "../src/components/icons/icons";+import { NAV_FILL, NavRow, navRowClass } from "../src/components/navigation/nav-list/nav-list";+import type { NavRowLinkProps } from "../src/components/navigation/nav-list/nav-list";+import {+ SidebarAccountButton,+ SidebarControl,+ SidebarFrame,+ SidebarListHeader,+ SidebarNavGroup,+ sidebarControlClass,+} from "../src/components/shell/sidebar-frame/sidebar-frame";+import { classTokens, renderStatic } from "../src/testing";++const frame = (props: Partial<Parameters<typeof SidebarFrame>[0]> = {}) =>+ renderStatic(+ createElement(SidebarFrame, {+ switcher: createElement("span", null, "Project"),+ account: createElement("span", null, "Account"),+ children: createElement("span", null, "List"),+ ...props,+ }),+ );++describe("SidebarFrame", () => {+ it("stacks the switcher, the scroll area and the account row, only the scroll area shrinking", () => {+ const html = frame();+ expect(html).toMatch(/^<div class="flex h-full w-full flex-col">/);+ expect(html).toContain(+ '<div class="relative min-h-0 flex-1 overflow-y-auto overflow-x-clip px-2 pb-2"><span>List</span></div>',+ );+ expect(html).toContain(+ '<div class="shrink-0 border-t border-line p-2"><span>Account</span></div>',+ );+ });++ it("keeps the gap under the switcher with no pinned entry, and pads the one it has", () => {+ expect(frame()).toContain('<div class="shrink-0 pb-2"></div>');+ expect(frame({ pinned: createElement("span", null, "New chat") })).toContain(+ '<div class="shrink-0 px-2 pb-2 pt-2"><span>New chat</span></div>',+ );+ });++ it("names the mode switch's group and the fold button from the caller's words", () => {+ const html = frame({+ modeSwitch: { label: "工作模式", control: createElement("span", null, "switch") },+ collapse: { label: "收起侧栏", onClick: () => {} },+ });+ expect(html).toContain('role="group" aria-label="工作模式"');+ expect(html).toContain('data-tooltip="收起侧栏" aria-label="收起侧栏"');+ expect(frame()).not.toContain("aria-label");+ });++ it("paints no background of its own: the column holding it does", () => {+ expect(classTokens(frame()).filter((t) => t.startsWith("bg-"))).toEqual([]);+ });+});++describe("SidebarNavGroup", () => {+ const group = (collapsed: boolean) =>+ renderStatic(+ createElement(SidebarNavGroup, {+ collapsed,+ onToggle: () => {},+ expandLabel: "展开",+ collapseLabel: "折叠",+ children: createElement("a", { href: "/agents" }, "Agents"),+ }),+ );++ it("folds under the theme's layout motion, turning the folded rows inert", () => {+ expect(group(false)).toContain('data-layout-motion="true" class="grid grid-rows-[1fr]"');+ expect(group(true)).toContain('class="grid grid-rows-[0fr]"');+ expect(group(true)).toContain('inert=""');+ expect(group(false)).not.toContain("inert");+ expect(classTokens(group(false)).filter((t) => t.startsWith("transition-["))).toEqual([]);+ });++ it("names its toggle by what pressing it does", () => {+ expect(group(false)).toContain('aria-expanded="true" aria-label="折叠" data-tooltip="折叠"');+ expect(group(true)).toContain('aria-expanded="false" aria-label="展开" data-tooltip="展开"');+ });++ it("spaces its rows on the rhythm", () => {+ expect(classTokens(group(false))).toContain("space-y-px");+ expect(classTokens(group(false))).not.toContain("space-y-0.5");+ });+});++describe("SidebarListHeader", () => {+ const header = (searching: boolean) =>+ renderStatic(+ createElement(SidebarListHeader, {+ label: "Sessions",+ searching,+ children: createElement("button", { type: "button" }, "search"),+ }),+ );++ it("sets its label on the eyebrow rung, spelling no case, tracking or size of its own", () => {+ const tokens = classTokens(header(false));+ expect(tokens).toEqual(expect.arrayContaining(["ui-eyebrow", "text-fg-subtle"]));+ for (const own of ["uppercase", "tracking-wide", "text-[11px]"]) {+ expect(tokens).not.toContain(own);+ }+ });++ it("gives the search the label's column under the layout motion", () => {+ expect(header(false)).toContain("grid-cols-[1fr_1fr]");+ expect(header(true)).toContain("grid-cols-[0fr_1fr]");+ expect(header(true)).toContain('data-layout-motion="true"');+ });+});++describe("the column's controls", () => {+ it("name an icon control by its hint, and fill it while its menu is open", () => {+ const html = renderStatic(+ createElement(SidebarControl, {+ label: "List options",+ glyph: ICONS.slidersHorizontal,+ active: true,+ "aria-haspopup": "menu",+ "aria-expanded": true,+ onClick: () => {},+ }),+ );+ expect(html).toContain(+ 'data-tooltip="List options" aria-label="List options" aria-haspopup="menu" aria-expanded="true"',+ );+ expect(sidebarControlClass(true)).toContain(NAV_FILL.selected);+ expect(sidebarControlClass(false)).toContain(NAV_FILL.hover);+ });++ it("open the account menu from a named trigger with the role after the name", () => {+ const html = renderStatic(+ createElement(SidebarAccountButton, {+ avatar: createElement("span", null, "A"),+ name: "Ada",+ role: "Admin",+ expanded: false,+ onClick: () => {},+ }),+ );+ expect(html).toContain('aria-haspopup="menu" aria-expanded="false"');+ expect(html).toContain('<span class="text-xs text-fg-subtle">Admin</span>');+ expect(html).not.toContain("aria-label");+ });+});++describe("NavRow on the navigation column", () => {+ it("takes the column's washes in place of the surface steps", () => {+ const active = navRowClass({ active: true, surface: "muted" });+ expect(active).toContain(NAV_FILL.selected);+ expect(active).not.toContain("bg-line-muted");+ const rest = navRowClass({ surface: "muted" });+ expect(rest).toContain(NAV_FILL.hover);+ expect(rest).not.toContain("hover:bg-surface-muted");+ // The default surface is untouched.+ expect(navRowClass({ active: true })).toContain("bg-line-muted");+ });++ it("hands a router its link: the address, the row's classes and the current page", () => {+ const seen: NavRowLinkProps[] = [];+ const html = renderStatic(+ createElement(NavRow, {+ label: "Agents",+ glyph: ICONS.robot,+ href: "/agents",+ active: true,+ surface: "muted",+ tooltip: "Update available",+ renderLink: (link: NavRowLinkProps) => {+ seen.push(link);+ return createElement(+ "a",+ { href: `#${link.href}`, className: link.className },+ link.children,+ );+ },+ }),+ );+ expect(seen).toHaveLength(1);+ expect(seen[0]).toMatchObject({+ href: "/agents",+ "aria-current": "page",+ "data-tooltip": "Update available",+ });+ expect(seen[0]!.className).toContain(NAV_FILL.selected);+ expect(html).toContain('href="#/agents"');+ expect(html).toContain('data-role="nav"');+ });++ it("keeps a disabled link's place without handing it to the router", () => {+ let called = false;+ const html = renderStatic(+ createElement(NavRow, {+ label: "Overview",+ href: "",+ disabled: true,+ surface: "muted",+ renderLink: () => {+ called = true;+ return null;+ },+ }),+ );+ expect(called).toBe(false);+ expect(html).toMatch(/^<span role="link" aria-disabled="true" class="/);+ });+});diff --git a/packages/ui/test/workspace-file-menu.test.ts b/packages/ui/test/workspace-file-menu.test.tsnew file mode 100644index 00000000..a7493e27--- /dev/null+++ b/packages/ui/test/workspace-file-menu.test.ts@@ -0,0 +1,86 @@+/**+ * The Files panel's file menu rows and its in-place editor: the rows say the caller's words and+ * differ by what the entry is, and the editor's textarea takes its name from the caller over the+ * code surface it shares with the source view.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { WorkspaceFileEditor } from "../src/components/content/workspace-file-editor/workspace-file-editor";+import { WorkspaceFileMenuRows } from "../src/components/files/workspace-file-menu/workspace-file-menu";+import type { FileMenuTarget } from "../src/components/files/workspace-file-menu/workspace-file-menu";+import { renderStatic } from "../src/testing";++const LABELS = {+ copyPath: "Copy relative path",+ addToChat: "Add to conversation",+ addSelectionToChat: "Add selection to conversation",+ uploadHere: "Upload here",+ download: "Download",+ rename: "Rename or move",+ delete: "Delete",+};+const noop = () => undefined;++const rows = (+ target: FileMenuTarget,+ extra: Partial<Parameters<typeof WorkspaceFileMenuRows>[0]> = {},+) =>+ renderStatic(+ createElement(WorkspaceFileMenuRows, {+ target,+ labels: LABELS,+ downloadHref: (path: string) => `/files/${path}?download=1`,+ downloadName: (path: string) => path.slice(path.lastIndexOf("/") + 1),+ onCopyPath: noop,+ onAddToChat: noop,+ onUploadInto: noop,+ onClose: noop,+ ...extra,+ }),+ );++describe("WorkspaceFileMenuRows", () => {+ it("offers a folder an upload, and no download", () => {+ const html = rows({ path: "src", kind: "dir" });+ expect(html).toContain('role="menu"');+ expect(html).toContain(">Copy relative path</span>");+ expect(html).toContain(">Upload here</span>");+ expect(html).not.toContain("Download");+ });++ it("offers a file its download as a link, and its rename and delete last, delete in danger", () => {+ const html = rows(+ { path: "src/rag.ts", kind: "file" },+ { onRename: noop, onDelete: noop, onAddSelection: noop },+ );+ expect(html).toContain('href="/files/src/rag.ts?download=1"');+ expect(html).toContain('download="rag.ts"');+ expect(html).toContain(">Add selection to conversation</span>");+ expect(html).not.toContain("Upload here");+ expect(html.indexOf(">Download<")).toBeLessThan(html.indexOf(">Rename or move<"));+ expect(html.indexOf(">Rename or move<")).toBeLessThan(html.indexOf(">Delete<"));+ expect(html).toMatch(/text-tone-danger-fg[^>]*>(?:(?!<\/button>).)*>Delete</);+ });+});++describe("WorkspaceFileEditor", () => {+ it("names its textarea from the caller and follows the wrap toggle", () => {+ const render = (wrap: boolean) =>+ renderStatic(+ createElement(WorkspaceFileEditor, {+ path: "src/rag.ts",+ value: "export {};",+ label: "Editing rag.ts",+ wrap,+ onChange: noop,+ onSave: noop,+ }),+ );+ const html = render(false);+ expect(html).toContain('aria-label="Editing rag.ts"');+ expect(html).toContain('spellCheck="false"');+ expect(html).toContain('wrap="off"');+ expect(html).toContain("code-editor-host");+ expect(render(true)).toContain('wrap="soft"');+ });+});diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjsindex 5e62e366..da7cee9f 100644--- a/packages/web/e2e/layout.spec.mjs+++ b/packages/web/e2e/layout.spec.mjs@@ -467,8 +467,9 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation",{ timeout: 1000 },);}).toPass({ timeout: 15_000 });- // Active fill = the *unprefixed* bg-gray-200/70 token (the resting state carries hover:bg-gray-200/70, which a bare substring match would also hit).- const ACTIVE_FILL = /(^|\s)bg-gray-200\/70(\s|$)/;+ // Active fill = the *unprefixed* bg-fg/7 token, the navigation column's selected wash (the+ // resting state carries hover:bg-fg/7, which a bare substring match would also hit).+ const ACTIVE_FILL = /(^|\s)bg-fg\/7(\s|$)/;// On a conversation, the entry lights as "you are here" (any non-draft /chat/:id).await expect(rail.getByRole("button", { name: "Last conversation" })).toHaveClass(ACTIVE_FILL);diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex 06cea9e3..b088db54 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -1,17 +1,25 @@/**- * App main layout:- * - >=md: left single-column sidebar (Project / new chat / nav / Session list / user config) + main content;- * - <md: top thin bar (hamburger -> sidebar drawer + brand name) + main content.- * All chrome uses solid backgrounds and avoids stacking contexts (frosted-glass/transform would trap overlay z-index).+ * The app's layout route: the UI package's `AppShell` bound to the app's state.+ * - >=md: the navigation column holds the pinned sidebar (Project / new chat / nav / Session list /+ * user config), or the rail while it is folded, beside the page;+ * - <md: the phone's top bar (the drawer button + the product's name) above the page, and the+ * sidebar in a drawer.+ * The shell's chrome uses solid fills and makes no stacking context (a frosted glass or a+ * transform would trap the menus it opens); the package's components say how.*/import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { NavLink, Outlet, useLocation, useMatch, useNavigate } from "react-router";+import { Outlet, useLocation, useMatch, useNavigate } from "react-router";import {+ AppShell,CloseIcon,Drawer,- GlyphIcon,ICONS,+ MobileTopBar,NoticeStrip,+ Rail,+ RailAccountButton,+ RailDivider,+ RailItem,Tooltip,UpdateDot,UserAvatar,@@ -41,6 +49,7 @@ import {} from "../../features/company/company-nav";import { NEW_CHAT_ICON, Sidebar } from "./sidebar";import { UserMenu } from "./user-menu";+import { isCurrentPath, renderRouterLink } from "./router-link";import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";import { useNewChat } from "../../features/chat/use-new-chat";import { ChangePasswordDialog } from "../account/change-password-dialog";@@ -52,39 +61,23 @@ import { setDockScope } from "../../features/dock/dock-state";import { AppPalette } from "../../features/palette/app-palette";/**- * "Last conversation" glyph, used only by the rail: lucide's history mark — a clock read- * backwards. Deliberately not the bare clock the session list's "most recent" sort option- * wears (group-list.tsx): that one means "ordered by time", this one means "the conversation- * you were last in", and the returning arrow is what says so.- */-const HISTORY_ICON = "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5M12 7v5l4 2";--/**- * Whether the pinned sidebar (or its rail) is on screen: the `<aside>` below is `hidden md:block`,- * and Tailwind's `md` is 768px at the browser's default font size — a media query ignores the- * app's 18px root. Below it the drawer's own sidebar answers the commands while it is open.+ * Whether the pinned sidebar (or its rail) is on screen: the shell's navigation column is+ * `hidden md:block`, and Tailwind's `md` is 768px at the browser's default font size — a media+ * query ignores the app's 18px root. Below it the drawer's own sidebar answers the commands while+ * it is open.*/function pinnedSidebarOnScreen(): boolean {return typeof window !== "undefined" && window.matchMedia("(min-width: 768px)").matches;}-/** Shared look of rail entries (icon buttons and NavLinks alike): solid gray fill when active, gray hover otherwise. `relative` so an entry can anchor an update badge on its corner (no z-index, so it still creates no stacking context). */-const railItemClass = (active: boolean) =>- `relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 ${- active- ? "bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-500 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- }`;-/**- * Collapsed narrow rail: expand button on top; below it, in product-specified order, last- * conversation / new chat / Agents / Skills / Models / Costs / Benchmark; user avatar at the- * bottom, opening the same account menu the pinned sidebar's avatar does. No Logo shown.+ * The folded navigation column: the unfold button on top; below it, in product-specified order,+ * last conversation / new chat / Agents / Skills / Models / Costs / Benchmark; the user avatar at+ * the bottom, opening the same account menu the pinned sidebar's avatar does. No logo.*- * Every entry is an icon with no visible label, so each carries a localized aria-label and- * the same words in a styled Tooltip — never also a native `title`, which would put a second- * tooltip under the first. The entries' own names come from the same strings as the pinned- * nav's, so the rail follows the UI language with it.+ * Every entry is an icon with no visible label, so each carries a localized name and the same+ * words in a styled tooltip (the package's `RailItem`). The entries' names come from the same+ * strings as the pinned nav's, so the rail follows the UI language with it.*/function CollapsedRail({ onExpand }: { onExpand: () => void }) {const { user } = useAuth();@@ -110,6 +103,9 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {if (next === "company") navigate("/org");else if (isOrgRoute(location.pathname)) navigate("/chat");};+ // The move INTO company mode says the mode is a beta: the rail has no room for the pill the+ // expanded sidebar carries, and the suffix belongs on the label that offers the mode, not on+ // the one that leaves it.const companyToggleLabel = inCompany? S.company.switchToDev: `${S.company.switchToCompany} · ${S.company.beta}`;@@ -199,172 +195,123 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {const expandTitle = useShortcutTitle(S.nav.expandSidebar, "sidebar.toggle");return (- <div className="flex h-full flex-col items-center gap-1 py-2.5">- <Tooltip label={expandTitle} className="shrink-0">- <button- type="button"- aria-label={S.nav.expandSidebar}- onClick={onExpand}- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <GlyphIcon d="M9 6l6 6-6 6M20 4v16" size={18} />- </button>- </Tooltip>- {/* The work-mode toggle, the rail's compact form of the sidebar's 开发 | 公司 switch:- one building glyph, pressed while in company mode, the tooltip naming the move a- click makes. Same availability rule as the switch. The move INTO company mode says- the mode is a beta — the rail has no room for the pill the expanded sidebar carries,- and the suffix belongs on the label that offers the mode, not on the one that leaves- it. */}- {company.available && (- <Tooltip label={companyToggleLabel} className="shrink-0">- <button- type="button"- aria-label={companyToggleLabel}- aria-pressed={inCompany}- onClick={toggleMode}- className={railItemClass(inCompany)}- >- <GlyphIcon d={ICONS.building} size={18} />- </button>- </Tooltip>- )}- {/* The entries scroll as one block, like the pinned sidebar's nav + session list: the rail- keeps only the expand control and the account avatar at fixed height, so a window too- short for the icons scrolls them here instead of pushing them out of the rail and- growing the document. Scrollbar hidden — at 48px wide it would cost a third of the- rail's width. */}- <nav className="no-scrollbar mt-1 flex min-h-0 flex-1 flex-col items-center gap-1 overflow-y-auto">- {/* 1. Last conversation: a history mark (a clock read backwards) — the entry goes BACK to- where the user was, which the returning arrow says and a bare clock face does not.- Lit on any non-draft conversation. Dimmed/disabled (tooltip kept) only once the list- has settled with no non-archived Session — while it is still loading the entry keeps- its normal look (no flash) and a click is a graceful no-op. */}- <Tooltip label={S.nav.lastConversation}>- <button- type="button"- aria-label={S.nav.lastConversation}- disabled={!lastSession && !loading}- onClick={openLastSession}- className={- lastSession || loading- ? railItemClass(onConversation)- : "flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-md text-gray-300 dark:text-gray-700"- }- >- <GlyphIcon d={HISTORY_ICON} size={18} />- </button>- </Tooltip>- {/* 2. New chat: shows the same gray active fill while on the draft page (pinned-sidebar- convention). Company mode leaves this slot empty — a channel is made rarely, from- the channel list's own header, and the rail carries no create control of its own. */}- {!inCompany && (- <Tooltip label={S.chat.newSessionMenu}>- <button- type="button"- aria-label={S.chat.newSessionMenu}- onClick={newChat}- className={railItemClass(activeSessionId === DRAFT_SESSION_ID)}- >- <GlyphIcon d={NEW_CHAT_ICON} size={18} />- </button>- </Tooltip>- )}- {/* 3-8. Page entries */}- {pages.map((item) => {- /* Four entries sit on a badge trail — Agents (an outdated kernel), Skills, Models and- the Cost Center. The dot itself is decorative: the tooltip and the accessible name- say what is waiting, and this rail's icons have no visible label, so they carry- both the entry's name and that sentence. */- const note = item.note;- const label = note !== null ? `${item.label} · ${note}` : item.label;- if (item.to === null) {- /* Nowhere to go: the icon keeps its place, muted, with no hover fill and nothing- to click or tab to. The name still stands, so the row is readable. */- return (- <Tooltip key={item.key} label={label}>- <span- role="link"- aria-label={label}- aria-disabled="true"- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-300 dark:text-gray-700"- >- <GlyphIcon d={item.icon} size={18} />- </span>- </Tooltip>- );- }- return (- <Tooltip key={item.key} label={label}>- <NavLink- to={item.to}- aria-label={label}- className={({ isActive }) => railItemClass(isActive)}+ <Rail+ head={+ <>+ <RailItem+ label={S.nav.expandSidebar}+ tooltip={expandTitle}+ glyph={ICONS.chevronRightPipe}+ onClick={onExpand}+ className="shrink-0"+ />+ {/* The work-mode toggle, the rail's compact form of the sidebar's 开发 | 公司 switch:+ one building glyph, pressed while in company mode, the tooltip naming the move a+ click makes. Same availability rule as the switch. */}+ {company.available && (+ <RailItem+ label={companyToggleLabel}+ glyph={ICONS.building}+ pressed={inCompany}+ onClick={toggleMode}+ className="shrink-0"+ />+ )}+ </>+ }+ foot={+ /* The account menu opens here, on the rail, instead of the avatar expanding the sidebar+ first: appearance and Settings, the update row and signing out all stay one click+ away while collapsed. Same component as the pinned sidebar's (user-menu.tsx). */+ <UserMenu+ className="mt-auto shrink-0"+ menuClass="w-56 origin-bottom-left"+ portal={{ direction: "up", align: "left" }}+ anchorRect={menuAnchor}+ anchorOwner={() => avatarRef.current}+ trigger={({ open, toggle }) => (+ /* The tooltip names the same avatar the open menu hangs off, so it stands down+ while the menu is up rather than covering it. */+ <Tooltip label={avatarTooltip} suppressed={open}>+ <RailAccountButton+ buttonRef={avatarRef}+ label={avatarName}+ expanded={open}+ onClick={() => {+ setMenuAnchor(measureMenuAnchor());+ toggle();+ }}>- <GlyphIcon d={item.icon} size={18} />- {note !== null && <UpdateDot />}- </NavLink>+ <UserAvatar+ userId={user?.userId ?? "?"}+ {...(user?.displayName !== undefined ? { displayName: user.displayName } : {})}+ {...(user?.avatar !== undefined ? { avatar: user.avatar } : {})}+ >+ {/* Update reminder, mirroring the pinned sidebar's avatar: the update row sits+ in the menu this opens, and the label above names what is waiting. */}+ {badges.software !== null && <UpdateDot />}+ </UserAvatar>+ </RailAccountButton></Tooltip>- );- })}- {/* The organization's channels, its desks and then its Temporary entries, under the- pages the way they sit under the nav in the pinned sidebar. A hairline says where each- run ends; a channel row carries its own unread count and a desk or an entry its- running dot, since a rail with no labels must still say how much is waiting. */}- {inCompany && navOrg !== null && (- <>- <span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" />- <ChannelRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />- <span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" />- <DeskRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />- <TempSessionRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />- </>- )}- </nav>- {/* The account menu opens here, on the rail, instead of the avatar expanding the sidebar- first: appearance and Settings, the update row and signing out all stay one- click away while collapsed. Same component as the pinned sidebar's (user-menu.tsx). */}- <UserMenu- className="mt-auto shrink-0"- menuClass="w-56 origin-bottom-left"- portal={{ direction: "up", align: "left" }}- anchorRect={menuAnchor}- anchorOwner={() => avatarRef.current}- trigger={({ open, toggle }) => (- /* The tooltip names the same avatar the open menu hangs off, so it stands down while- the menu is up rather than covering it. */- <Tooltip label={avatarTooltip} suppressed={open}>- <button- ref={avatarRef}- type="button"- aria-label={avatarName}- aria-haspopup="menu"- aria-expanded={open}- onClick={() => {- setMenuAnchor(measureMenuAnchor());- toggle();- }}- className="flex h-8 w-8 shrink-0 items-center justify-center"- >- {/* The tile is the pinned sidebar's avatar, at its size, inside a rail-sized hit- box: the two states swap this element outright, so a tile that changed size- between them would pop on every collapse while the box beside it animates- smoothly. The button keeps the rail's 32px square, which is every other- entry's target. */}- <UserAvatar- userId={user?.userId ?? "?"}- {...(user?.displayName !== undefined ? { displayName: user.displayName } : {})}- {...(user?.avatar !== undefined ? { avatar: user.avatar } : {})}- >- {/* Update reminder, mirroring the pinned sidebar's avatar: the update row sits in- the menu this opens, and the label above names what is waiting. */}- {badges.software !== null && <UpdateDot />}- </UserAvatar>- </button>- </Tooltip>- )}+ )}+ />+ }+ >+ {/* 1. Last conversation: a history mark (a clock read backwards) — the entry goes BACK to+ where the user was. Lit on any non-draft conversation. Dimmed/disabled (tooltip kept)+ only once the list has settled with no non-archived Session — while it is still+ loading the entry keeps its normal look (no flash) and a click is a graceful no-op. */}+ <RailItem+ label={S.nav.lastConversation}+ glyph={ICONS.history}+ active={onConversation}+ disabled={!lastSession && !loading}+ onClick={openLastSession}/>- </div>+ {/* 2. New chat: lit while on the draft page (pinned-sidebar convention). Company mode+ leaves this slot empty — a channel is made rarely, from the channel list's own header,+ and the rail carries no create control of its own. */}+ {!inCompany && (+ <RailItem+ label={S.chat.newSessionMenu}+ glyph={NEW_CHAT_ICON}+ active={activeSessionId === DRAFT_SESSION_ID}+ onClick={newChat}+ />+ )}+ {/* 3-8. Page entries. Four sit on a badge trail — Agents (an outdated kernel), Skills,+ Models and the Cost Center. The dot is decorative: this rail's icons have no visible+ label, so the name and the hint carry both the entry and what is waiting. An entry+ with nowhere to go keeps its place, muted, with nothing to click or tab to. */}+ {pages.map((item) => {+ const label = item.note !== null ? `${item.label} · ${item.note}` : item.label;+ return (+ <RailItem+ key={item.key}+ label={label}+ glyph={item.icon}+ href={item.to ?? ""}+ disabled={item.to === null}+ active={item.to !== null && isCurrentPath(item.to, location.pathname)}+ renderLink={renderRouterLink}+ {...(item.note !== null ? { badge: <UpdateDot /> } : {})}+ />+ );+ })}+ {/* The organization's channels, its desks and then its Temporary entries, under the pages+ the way they sit under the nav in the pinned sidebar. A hairline says where each run+ ends; a channel row carries its own unread count and a desk or an entry its running+ dot, since a rail with no labels must still say how much is waiting. */}+ {inCompany && navOrg !== null && (+ <>+ <RailDivider />+ <ChannelRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />+ <RailDivider />+ <DeskRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />+ <TempSessionRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />+ </>+ )}+ </Rail>);}@@ -389,7 +336,7 @@ export function AppLayout() {// browser session, so a dot can be there on a fresh load instead of waiting for someone to// open the sidebar menu. Every other anchor reads the same caches passively.const badges = useUpdateBadges(true);- // The drawer holds the sidebar, so the hamburger is named after what the sidebar lists:+ // The drawer holds the sidebar, so the drawer button is named after what the sidebar lists:// conversations in development mode, channels in company mode.const company = useCompany();const drawerName =@@ -469,143 +416,110 @@ export function AppLayout() {}, [collapsed, inCompany, newChat]);return (- // ui-shell: the app window. A theme may paint a field behind it, float the main column as a- // sheet or rule the columns apart; the navigation column is `nav`, the page column `main`.- <div className="ui-shell flex h-full">- {/* Desktop: single-column sidebar (collapsible to a narrow rail).- Collapsing animates the WIDTH, which is the one animation here that transform cannot- carry: the sidebar is in flow, so the main content reflows beside it rather than- being slid over. Width is also the only property this box may animate at all —- transform, will-change and any opacity below 1 each make it a stacking context and- would trap the z-40 menus the sidebar opens inside it (see the file header).- `prefers-reduced-motion` is answered globally in styles.css, which drops the- transition and leaves the resting width correct.- The panes do NOT cross-fade. Each is rendered at its own final width inside the box- and clipped by it, so neither is ever laid out against a width it will not keep: the- rail sits at its final 48px from the first frame while the box closes around it, and- the pinned sidebar is uncovered left to right instead of reflowing on every frame. */}- <aside- data-slot="nav"- className={`hidden shrink-0 overflow-hidden border-r border-gray-200 bg-gray-50 transition-[width] duration-200 ease-out md:block dark:border-gray-800 dark:bg-gray-900 ${- collapsed ? "w-12" : "w-64 lg:w-72"- }`}- >- <div className={`h-full ${collapsed ? "w-12" : "w-64 lg:w-72"}`}>- {collapsed ? (- <CollapsedRail- onExpand={() => {- setOpenSearchOnExpand(false);- toggleCollapsed();- }}- />- ) : (- <Sidebar- onCollapse={() => {- setOpenSearchOnExpand(false);- toggleCollapsed();- }}- initialSearchOpen={openSearchOnExpand}- />- )}- </div>- </aside>+ <AppShell+ navCollapsed={collapsed}+ nav={+ collapsed ? (+ <CollapsedRail+ onExpand={() => {+ setOpenSearchOnExpand(false);+ toggleCollapsed();+ }}+ />+ ) : (+ <Sidebar+ onCollapse={() => {+ setOpenSearchOnExpand(false);+ toggleCollapsed();+ }}+ initialSearchOpen={openSearchOnExpand}+ />+ )+ }+ overlays={+ <>+ {/* The software-update modal, opened from the sidebar's update row and the draft+ page's version badge alike; mounted here so it outlives both. */}+ <UpdateModal />+ <ChangePasswordDialog+ open={changePasswordOpen}+ onClose={() => setChangePasswordOpen(false)}+ />+ {/* Mobile: the sidebar in a drawer, on the navigation column's own fill. */}+ <Drawer+ open={drawerOpen}+ side="left"+ title={S.appName}+ onClose={() => setDrawerOpen(false)}+ >+ <div className="h-full bg-surface-muted">+ <Sidebar onNavigate={() => setDrawerOpen(false)} />+ </div>+ </Drawer>+ </>+ }+ >+ {/* The outermost menu on a phone: it carries a dot for EITHER trail, so its wording is+ the combined one — naming one of two updates would point at the wrong trail. Both+ trails continue inside the drawer's sidebar (the Agents entry, the user row's update+ entry). */}+ <MobileTopBar+ title={S.appName}+ menuLabel={badges.note !== null ? `${drawerName} · ${badges.note}` : drawerName}+ {...(badges.note !== null ? { menuHint: badges.note } : {})}+ {...(badges.any ? { menuBadge: <UpdateDot /> } : {})}+ onMenu={() => setDrawerOpen(true)}+ />- <div data-slot="main" className="flex min-w-0 flex-1 flex-col">- {/* Mobile: top thin bar (hamburger + brand) */}- <header className="flex h-12 shrink-0 items-center gap-2 border-b border-gray-200 bg-white px-2 md:hidden dark:border-gray-800 dark:bg-gray-950">- {/* The outermost menu on a phone: it carries a dot for EITHER trail, so its wording- is the combined one — naming one of two updates would point at the wrong trail.- Both trails continue inside the drawer's sidebar (the Agents entry, the user- row's update entry). */}+ {/* Initial-password notice banner (seed/admin-set password): disappears once passwordIsInitial clears after a successful change.+ Hidden in desktop mode — the seed password there is random and never shown, so "change it" is meaningless nagging.+ Permanently dismissible via the X on the right (per-user ui_prefs); only rendered once+ hydrated prefs confirm it was never dismissed, so it does not flash-then-vanish on load. */}+ {passwordBannerRelevant && passwordBannerDismissed === false && (+ <NoticeStrip+ tone="attention"+ className="relative flex shrink-0 items-center justify-center gap-3 border-b px-8 py-1.5 text-xs"+ >+ <span>{S.account.initialPasswordBanner}</span><buttontype="button"- aria-label={badges.note !== null ? `${drawerName} · ${badges.note}` : drawerName}- {...(badges.note !== null ? { "data-tooltip": badges.note } : {})}- onClick={() => setDrawerOpen(true)}- className="relative flex h-9 w-9 items-center justify-center rounded-md 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"+ className="shrink-0 font-medium underline underline-offset-2 hover:text-amber-950 dark:hover:text-amber-100"+ onClick={() => setChangePasswordOpen(true)}>- <svg- width="18"- height="18"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.7"- strokeLinecap="round"- aria-hidden- >- <path d="M4 6h16M4 12h16M4 18h16" />- </svg>- {badges.any && <UpdateDot />}+ {S.account.changeNow}</button>- <span className="text-sm font-semibold">{S.appName}</span>- </header>-- {/* Initial-password notice banner (seed/admin-set password): disappears once passwordIsInitial clears after a successful change.- Hidden in desktop mode — the seed password there is random and never shown, so "change it" is meaningless nagging.- Permanently dismissible via the X on the right (per-user ui_prefs); only rendered once- hydrated prefs confirm it was never dismissed, so it does not flash-then-vanish on load. */}- {passwordBannerRelevant && passwordBannerDismissed === false && (- <NoticeStrip- tone="attention"- className="relative flex shrink-0 items-center justify-center gap-3 border-b px-8 py-1.5 text-xs"+ {/* Amber-toned twin of the shared CloseButton (same glyph + aria-label) — its hardcoded+ gray colors would clash here. Flat: hover feedback is icon-color-only (no background+ fill), same hover shades as the change-now link. Absolutely positioned at the right+ edge: near-full-height hit area without growing the banner and without transform (see+ the stacking-context note in the file header); the banner's symmetric px-8 keeps the+ centered text clear. */}+ <button+ type="button"+ aria-label={S.common.close}+ data-tooltip={S.common.close}+ onClick={dismissPasswordBanner}+ className="absolute inset-y-0.5 right-1.5 flex items-center rounded-md px-1 text-amber-500 transition-colors duration-150 hover:text-amber-950 dark:text-amber-400/70 dark:hover:text-amber-100">- <span>{S.account.initialPasswordBanner}</span>- <button- type="button"- className="shrink-0 font-medium underline underline-offset-2 hover:text-amber-950 dark:hover:text-amber-100"- onClick={() => setChangePasswordOpen(true)}- >- {S.account.changeNow}- </button>- {/* Amber-toned twin of the shared CloseButton (same glyph + aria-label) — its hardcoded- gray colors would clash here. Flat: hover feedback is icon-color-only (no background- fill), same hover shades as the change-now link. Absolutely positioned at the right- edge: near-full-height hit area without growing the banner and without transform (see- the stacking-context note in the file header); the banner's symmetric px-8 keeps the- centered text clear. */}- <button- type="button"- aria-label={S.common.close}- data-tooltip={S.common.close}- onClick={dismissPasswordBanner}- className="absolute inset-y-0.5 right-1.5 flex items-center rounded-md px-1 text-amber-500 transition-colors duration-150 hover:text-amber-950 dark:text-amber-400/70 dark:hover:text-amber-100"- >- <CloseIcon size={12} />- </button>- </NoticeStrip>- )}-- <main className="min-h-0 min-w-0 flex-1 overflow-hidden">- <Outlet />- </main>- {/* The docks themselves render inside the chat page (features/dock); the xterm- views live in this pool and are adopted into dock tab bodies by DOM handoff,- so navigating between pages never reconnects a terminal. */}- <TerminalDockRuntime />- {/* Reconciles the shortcut mirror with the account's prefs and carries edits back. */}- <ShortcutRuntime />- {/* The built-in browser's pages (desktop app only): they live here, outside every page,- and are laid over the dock's browser tab by coordinates — a webview moved in the DOM- reloads, so navigating the app must never re-parent one. */}- <BuiltinBrowserLayer />- <AppPalette />- </div>-- {/* The software-update modal, opened from the sidebar's update row and the draft- page's version badge alike; mounted here so it outlives both. */}- <UpdateModal />- <ChangePasswordDialog- open={changePasswordOpen}- onClose={() => setChangePasswordOpen(false)}- />+ <CloseIcon size={12} />+ </button>+ </NoticeStrip>+ )}- {/* Mobile: sidebar drawer */}- <Drawer open={drawerOpen} side="left" title={S.appName} onClose={() => setDrawerOpen(false)}>- <div className="h-full bg-gray-50 dark:bg-gray-900">- <Sidebar onNavigate={() => setDrawerOpen(false)} />- </div>- </Drawer>- </div>+ <main className="min-h-0 min-w-0 flex-1 overflow-hidden">+ <Outlet />+ </main>+ {/* The docks themselves render inside the chat page (features/dock); the xterm+ views live in this pool and are adopted into dock tab bodies by DOM handoff,+ so navigating between pages never reconnects a terminal. */}+ <TerminalDockRuntime />+ {/* Reconciles the shortcut mirror with the account's prefs and carries edits back. */}+ <ShortcutRuntime />+ {/* The built-in browser's pages (desktop app only): they live here, outside every page,+ and are laid over the dock's browser tab by coordinates — a webview moved in the DOM+ reloads, so navigating the app must never re-parent one. */}+ <BuiltinBrowserLayer />+ <AppPalette />+ </AppShell>);}diff --git a/packages/web/src/components/layout/router-link.tsx b/packages/web/src/components/layout/router-link.tsxnew file mode 100644index 00000000..f6e55f0f--- /dev/null+++ b/packages/web/src/components/layout/router-link.tsx@@ -0,0 +1,31 @@+/**+ * The router's side of the shell's link rows: the UI package draws a nav row or a rail entry, and+ * hands its link over through `renderLink`; the app draws that link as the router's `Link`, so a+ * click navigates in place, and says which link is the current page.+ */+import { Link, matchPath } from "react-router";+import type { NavRowLinkProps } from "@prismshadow/penguin-ui";++/** A package row's link as the router's own: the row's classes, state and content, navigating in place. */+export function renderRouterLink(link: NavRowLinkProps) {+ return (+ <Link+ to={link.href}+ className={link.className}+ aria-current={link["aria-current"]}+ aria-label={link["aria-label"]}+ data-tooltip={link["data-tooltip"]}+ onClick={link.onClick}+ >+ {link.children}+ </Link>+ );+}++/**+ * Whether `to` is the page the reader is on: the path itself or anything under it, the rule a+ * router `NavLink` applies by default (so `/agents` stays current on an Agent's own page).+ */+export function isCurrentPath(to: string, pathname: string): boolean {+ return matchPath({ path: to, end: false }, pathname) !== null;+}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 5e356185..b11c0893 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -34,26 +34,27 @@* New chats always enter draft state (/chat/new; a group header's "+" names its group's Agent or* Workspace in route state): Model / Workspace / approval mode are all chosen on the draft input* card, so there's no longer a separate "quick / advanced" pair of new-chat dialogs.- * Color scheme is white/gray-based: active state uses a solid gray fill, running status uses a small color dot, no large blocks of color.+ * The column's look — its frame, page rows, list header, controls and conversation rows — is the+ * UI package's (SidebarFrame, NavRow, SessionRow); this file binds them to the app's state. On the+ * column's muted surface a hover and a selection are washes of the ink (NAV_FILL), and a running+ * status is a small mark, never a block of colour.*/import { useEffect, useMemo, useRef, useState } from "react";import type { DragEvent as ReactDragEvent, ReactNode } from "react";-import { NavLink, useLocation, useMatch, useNavigate } from "react-router";+import { useLocation, useMatch, useNavigate } from "react-router";import type {SessionCategory,SessionCategoryCounts,SessionInfo,} from "@prismshadow/penguin-server/api";import {- ActivityIcon,AgentAvatar,- BackgroundTasksMark,Badge,Button,- ChevronDown,ConfirmModal,Dropdown,FolderSection,+ GlyphIcon,GroupHeader,ICONS,ICON_SIZE,@@ -65,16 +66,23 @@ import {MenuSeparator,Modal,MoreRow,- ScheduleMark,+ NAV_FILL,+ NavRow,SearchInput,Segmented,+ SessionRow,+ SidebarAccountButton,+ SidebarControl,+ SidebarFrame,+ SidebarListHeader,+ SidebarNavGroup,+ SidebarSwitcherButton,SkeletonList,UpdateDot,UserAvatar,toastError,toastInfo,toastSuccess,- useRowContextMenu,} from "@prismshadow/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";@@ -158,12 +166,7 @@ import {orderGroups,saveGroupOrder,} from "../../lib/group-order";-import {- HOVER_ROW_ACTIONS,- SessionRowHoverActions,- SessionRowMenuRows,- contextMenuActions,-} from "../ui/session-row-menu";+import { HOVER_ROW_ACTIONS, contextMenuActions, sessionRowActions } from "../ui/session-row-menu";import type { SessionRowAction } from "../ui/session-row-menu";import { NAV_ICONS } from "../../lib/nav-icons";import {@@ -191,6 +194,7 @@ import type { DraftSessionEntry } from "../../features/chat/draft-sessions";import { prepareNewChatDraft } from "../../features/chat/new-chat";import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";import { UserMenu } from "./user-menu";+import { isCurrentPath, renderRouterLink } from "./router-link";import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";import { pendingScheduleSessions } from "../../features/schedules/schedule-panel-state";import { useProjectSchedules } from "../../features/schedules/schedule-store";@@ -207,7 +211,6 @@ import {parseOrgKey,} from "../../features/company/company-nav";import type { WorkMode } from "../../features/company/company-nav";-import { toneInk } from "../../lib/tone";/** New-chat pencil (the pinned "New chat" button and the collapsed rail share it). */export const NEW_CHAT_ICON = "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";@@ -223,9 +226,6 @@ function EllipsisGlyph({ size = 16 }: { size?: number }) {);}-/** Horizontal sliders (lucide sliders-horizontal), the section header's list-settings menu. */-const SLIDERS_ICON = "M21 5h-7M10 5H3M21 12h-9M8 12H3M21 19h-5M12 19H3M14 2v6M8 9v6M16 16v6";-/*** Private drag payload type of a manual session reorder. Deliberately NOT `text/plain`:* the composer is a controlled textarea with no drop guard, and a native text drop@@ -276,13 +276,12 @@ function AddBadgeIcon({ base, size = 15 }: { base: string; size?: number }) {);}-/** Section-header icon control (search / list settings / create): the grouping-toggle button look — active renders as a pressed fill. */-const headerControlClass = (active: boolean) =>- `flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors duration-150 ${- active- ? "bg-gray-200/70 text-gray-700 dark:bg-gray-800 dark:text-gray-200"- : "text-gray-400 hover:bg-gray-200/50 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800/70 dark:hover:text-gray-300"- }`;+/**+ * A group header's trailing action (new chat, Agent settings): a square on the column's hover+ * wash, the subtle glyph deepening under the pointer.+ */+const GROUP_ACTION_CLASS =+ "flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-fg-subtle transition-colors duration-150 hover:bg-fg/7 hover:text-fg";/*** Collapsed-group and pinned-group persistence (survives a refresh), one storage key@@ -361,19 +360,6 @@ const groupShares = (/** Standing "no Session is scheduled", so the first render has something to hold before any answer. */const NO_SCHEDULED_SESSIONS: ReadonlySet<string> = new Set();-/**- * Session status glyph: a turning hourglass while the Session is busy, a green dot once it has- * finished with a reply the user has not seen, and nothing once that reply has been read — or- * if the Session never ran at all. See sessionActivity.- */-function StatusGlyph({ activity }: { activity: SessionActivity }) {- // Reserve the glyph's box even when there is no glyph: the row is a flex line whose title- // truncates into whatever space is left, so letting the slot collapse would re-flow the title- // of every never-run row (and again the moment its first run starts).- if (activity === null) return <span aria-hidden="true" className="block h-3 w-3 shrink-0" />;- return <ActivityIcon activity={activity} label={sessionActivityLabel(activity)} />;-}-export function Sidebar({onNavigate,onCollapse,@@ -1386,7 +1372,7 @@ export function Sidebar({/** Whether these rows are the group's ACTIVE list (the only rows pinning can reorder). */activeList = false,) => (- <ul className="space-y-0.5">+ <ul className="space-y-px">{rows.map((s) => {// Manual-sort drag wiring (active lists only; never while searching — a filtered// view is not the real order). A drop stays within its own scope AND its own@@ -1453,7 +1439,7 @@ export function Sidebar({: null,};return (- <SessionRow+ <SidebarSessionRowkey={s.sessionId}s={s}active={s.sessionId === activeSessionId}@@ -1791,857 +1777,46 @@ export function Sidebar({note: navNoteFor(badges, `/${key}`),}));- return (- <div ref={rootRef} className="flex h-full w-full flex-col">- {/* The work-mode switch, above the Project switcher: 开发 | 公司. Rendered only while- company mode is available (the admin master switch and the user's own switch both- on); the choice persists per user. The 内测版 tag rides on 公司 — the switch is the- one control that names the mode, so the mark stands on the word it qualifies rather- than somewhere inside the mode it describes. */}- {company.available && (- <div className="shrink-0 px-2 pt-2" role="group" aria-label={S.company.workMode}>- <Segmented- options={[- { value: "dev" as const, label: S.company.modeDev },- {- value: "company" as const,- label: S.company.modeCompany,- badge: { node: <CompanyBetaBadge />, name: S.company.beta },- },- ]}- value={company.workMode}- onChange={switchMode}- cols={2}- />- </div>- )}- {/* Project switcher (+ collapse sidebar); the organization switcher in company mode */}- <div className="flex shrink-0 items-center gap-1 px-2 pt-2">- {onCollapse && (- <button- type="button"- data-tooltip={collapseTitle}- aria-label={S.nav.collapseSidebar}- onClick={onCollapse}- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <Icon d="M15 6l-6 6 6 6M4 4v16" size={18} />- </button>- )}- {inCompany ? (- <OrgSwitcher {...(onNavigate ? { onNavigate } : {})} />- ) : (- <Dropdown- open={projectOpen}- setOpen={setProjectOpen}- className="min-w-0 flex-1"- menuClass="left-0 right-0 top-full mt-1 origin-top"- button={- <button- type="button"- onClick={() => setProjectOpen(!projectOpen)}- className="flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-base font-semibold transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"- >- <span className="min-w-0 flex-1 truncate font-sans text-left">- {currentProject ? projectDisplayName(currentProject) : S.common.loading}- </span>- <span className="text-gray-400">- <ChevronDown />- </span>- </button>- }- >- {/* Plain rows rather than a role="menu": the switcher's Project rows are named- like its trigger, and both are reached as buttons. */}- {projects.map((p) => (- <MenuRadioItem- key={p.projectId}- label={<span className="font-sans">{projectDisplayName(p)}</span>}- trailing={<Badge>{p.role}</Badge>}- checked={p.projectId === currentProject?.projectId}- onSelect={() => {- setCurrentProjectId(p.projectId);- setProjectOpen(false);- }}- />- ))}- <MenuSeparator />- <MenuItem- glyph={ICONS.plus}- label={S.project.create}- onSelect={() => {- setProjectOpen(false);- setCreateProjectOpen(true);- }}- />- {currentProject && (- <MenuItem- glyph={ICONS.gear}- label={S.project.settings}- onSelect={() => {- setProjectOpen(false);- setProjectSettingsOpen(true);- }}- />- )}- </Dropdown>- )}- </div>-- {/* New chat: the only pinned entry besides the Project switcher above and the user row- below. No background fill, the same gray hover/active styling as the nav items,- distinguished only by its position and font-medium; shows the same gray active state- while on the draft page.- The gap to the scroll area below is this block's OWN pb-2, not padding inside the- scroller: padding-top there belongs to the scrollable content and slides away with- it, so a scrolled nav entry ended up flush against this pinned button, the two- labels touching. Outside the scroller the 8px stays put at every scroll offset —- the same text-to-text rhythm two adjacent nav rows have. */}- {/* Company mode pins nothing here: a channel is made rarely, so "New channel" is the- channel list's own header action rather than a permanent row (channel-sidebar.tsx).- The slot still holds its 8px, which is the gap the scroll area below depends on. */}- {inCompany ? (- <div className="shrink-0 pb-2" />- ) : (- <div className="shrink-0 px-2 pb-2 pt-2">- <button- type="button"- data-tooltip={newChatTitle}- onClick={() => newChat()}- className={`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors duration-150 ${- activeSessionId === DRAFT_SESSION_ID- ? "bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"- }`}- >- <span className="ui-icon-decor text-gray-500 dark:text-gray-400" data-role="nav">- <Icon d={NEW_CHAT_ICON} />- </span>- {S.chat.newSessionMenu}- </button>- </div>- )}-- {/* Scroll area: the page nav and the session list scroll together, so the nav rides up- as the list is scrolled. It is the sidebar's only shrinkable block — with the nav- pinned, the column's fixed height (Project switcher + New chat + eight nav entries +- user row ≈ 412px) exceeded a short window, and the overflow, clipped by nothing,- grew the document into a second scrollbar.- relative: the scroller acts as its own containing block, so absolute descendants- (each row's sr-only Agent name) anchor and scroll inside it — anchored to the- initial containing block instead, rows past the fold would bypass this- overflow-y-auto and stretch the **document**, so expanding "More" / a source- folder made the whole page scroll (composer pushed up, blank space below).- overflow-x-clip: the list scrolls one way only. With overflow-y set, a horizontal- overflow of a single pixel — a group header's actions in a theme with wider type or- roomier controls — would otherwise turn into a sideways scrollbar under the list;- nothing here is meant to be reached by scrolling sideways. */}- <div className="relative min-h-0 flex-1 overflow-y-auto overflow-x-clip px-2 pb-2">- <nav className="space-y-0.5">- {/* Expand/collapse SLIDE: grid-template-rows tweens between 0fr and 1fr with the- inner overflow-hidden clipping the rows (the skills/models-page convention) —- the moving clip edge reveals/hides the entries while the toggle button and the- Session list below glide up/down with it; a subtle opacity fade rides along,- both 200ms, moving as one with the chevron flip below. The rows stay mounted- for the tween but go inert while collapsed (zero-height rows must not stay- Tab-focusable or clickable). Transitions fire only on state CHANGES, so a mount- restoring a persisted collapsed state renders collapsed instantly — only user- toggles animate; reduced motion is covered by the global- prefers-reduced-motion override in styles.css. */}- <div- className={`grid transition-[grid-template-rows] duration-200 ease-out ${- navCollapsed ? "grid-rows-[0fr]" : "grid-rows-[1fr]"- }`}- >- <div className="overflow-hidden" inert={navCollapsed}>- <div- className={`space-y-0.5 transition-opacity duration-200 ${- navCollapsed ? "opacity-0" : "opacity-100"- }`}- >- {navItems.map((item) => {- /* Four nav entries sit on a badge trail — Agents (an outdated kernel, fixed on- the Agent settings page two clicks down), Skills, Models and the Cost Center- (each cleared on the page itself). The dot is anchored to the row, not to the- label text (where it would float over whatever follows the word): at the- row's right edge, on the same inset as its horizontal padding, and vertically- centred on the row rather than on the line of text. */- const note = item.note;- if (item.to === null) {- /* Nowhere to go: the row keeps its place and its glyph, muted, with no- hover fill and nothing to click or tab to. */- return (- <span- key={item.key}- role="link"- aria-disabled="true"- className="relative flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-gray-400 dark:text-gray-600"- >- <span- className="ui-icon-decor text-gray-300 dark:text-gray-700"- data-role="nav"- >- <Icon d={item.icon} />- </span>- {item.label}- </span>- );- }- return (- <NavLink- key={item.key}- to={item.to}- onClick={() => onNavigate?.()}- {...(note !== null- ? {- // The row's own label is visible, so the tooltip only adds what- // the dot means; the accessible name keeps that label as its- // prefix. (The collapsed rail's icon-only twin has no visible- // label, so its tooltip carries both.)- title: note,- "aria-label": `${item.label} · ${note}`,- }- : {})}- className={({ isActive }) =>- `relative flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${- isActive- ? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"- }`- }- >- <span- className="ui-icon-decor text-gray-500 dark:text-gray-400"- data-role="nav"- >- <Icon d={item.icon} />- </span>- {item.label}- {note !== null && (- <UpdateDot size="inline" position="right-2.5 top-1/2 -translate-y-1/2" />- )}- </NavLink>- );- })}- </div>- </div>- </div>- {/* Collapse toggle of the page-nav group (智能体 → 评估中心): a slim (h-4)- nav-row-wide button directly under the group's last entry — a centered chevron- pointing UP while expanded (click to collapse) and DOWN while collapsed (the- button stays as the only way back, right under the new-chat boundary once the- entries are hidden). The soft resting band is deliberate — the sidebar's one- exception to flat-at-rest: it makes the strip read as the seam between the- page nav above and the Session list below (the ruled separator it replaces- was rejected as a line under the button); hover deepens it a step further so- it stays clearly interactive. Icon-only, so tooltip + aria carry the name- (GroupHeader's collapse/expand wording). */}- <button- type="button"- onClick={toggleNavGroup}- aria-expanded={!navCollapsed}- aria-label={navCollapsed ? S.nav.expandGroup : S.nav.collapseGroup}- data-tooltip={navCollapsed ? S.nav.expandGroup : S.nav.collapseGroup}- className="flex h-4 w-full items-center justify-center rounded-md bg-gray-200/70 text-gray-400 transition-colors duration-150 hover:bg-gray-300/60 hover:text-gray-700 dark:bg-gray-800/70 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-300"- >- <ChevronDown- size={12}- className={`transition-transform duration-200 ${navCollapsed ? "" : "rotate-180"}`}- />- </button>- </nav>-- {inCompany ? (- navOrg !== null ? (- /* Company mode: the organization's channels, where development mode lists- conversations, and below them its 工位 group — one row per employee's desk. */- <>- <ChannelSidebar- projectId={navOrg.projectId}- orgId={navOrg.orgId}- {...(onNavigate ? { onNavigate } : {})}- />- <OrgSessionGroups- projectId={navOrg.projectId}- orgId={navOrg.orgId}- activeSessionId={activeSessionId}- {...(onNavigate ? { onNavigate } : {})}- />- </>- ) : (- /* No organization to list: the create block, not an empty channel list. */- <NoOrganizationsSidebar {...(onNavigate ? { onNavigate } : {})} />- )- ) : (- <>- {/* Section header: list label + right-aligned controls (icon + tooltip family):- search, list settings (grouping + sort radios — the old inline grouping- toggle relocated into this menu), and the mode-dependent create button (the- created object follows the grouping mode). The search is a mac-style- IN-PLACE expansion — no extra row: the two grid columns tween (the 0fr/1fr- trick, horizontal), the label's column collapsing while the controls column- takes the full width and the field inside grows leftward over the label's- place; the magnifier morphs from toggle button into the field's leading- glyph. No ruled separator at this boundary — see the nav toggle above. */}- <div- className={`mt-3 grid items-center px-1 pt-2 transition-[grid-template-columns] duration-200 ease-out ${- searchOpen ? "grid-cols-[0fr_1fr]" : "grid-cols-[1fr_1fr]"- }`}- >- <span- className={`ui-eyebrow min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${- searchOpen ? "opacity-0" : "opacity-100"- }`}- >- {S.chat.sessionList}- </span>- <div className="flex min-w-0 items-center justify-end gap-0.5">- {searchOpen ? (- /* Expanded field: the magnifier, the input and the clear ×, one bordered- box filling the row (its width rides the column tween). Esc and × both- collapse it and drop the filter, which is why the × stays while it is empty. */- <SearchInput- ref={searchInputRef}- icon- alwaysClearable- autoFocus- className="min-w-0 flex-1"- value={searchQuery}- onChange={setSearchQuery}- onClear={closeSearch}- placeholder={S.chat.searchSessionsPlaceholder}- aria-label={S.chat.searchSessions}- clearLabel={S.chat.searchClear}- />- ) : (- <button- type="button"- data-tooltip={searchTitle}- aria-label={S.chat.searchSessions}- onClick={() => setSearchOpen(true)}- className={headerControlClass(false)}- >- <Icon d={ICONS.search} size={14} />- </button>- )}- <Dropdown- open={listSettingsOpen}- setOpen={setListSettingsOpen}- portal={{ direction: "down", align: "right" }}- menuClass="w-40"- button={- <button- type="button"- data-tooltip={S.chat.listSettings}- aria-label={S.chat.listSettings}- aria-haspopup="menu"- aria-expanded={listSettingsOpen}- onClick={() => setListSettingsOpen(!listSettingsOpen)}- className={headerControlClass(listSettingsOpen)}- >- <Icon d={SLIDERS_ICON} size={14} />- </button>- }- >- <Menu density="sm">- <MenuLabel>{S.chat.groupModeSection}</MenuLabel>- <MenuRadioItem- glyph={GROUP_MODE_ICONS.workspace}- label={S.chat.groupByWorkspace}- checked={groupMode === "workspace"}- onSelect={() => {- setGroupMode("workspace");- setListSettingsOpen(false);- }}- />- <MenuRadioItem- glyph={GROUP_MODE_ICONS.agent}- label={S.chat.groupByAgent}- checked={groupMode === "agent"}- onSelect={() => {- setGroupMode("agent");- setListSettingsOpen(false);- }}- />- <MenuRadioItem- glyph={GROUP_MODE_ICONS.time}- label={S.chat.groupByTime}- checked={groupMode === "time"}- onSelect={() => {- setGroupMode("time");- setListSettingsOpen(false);- }}- />- <MenuSeparator />- <MenuLabel>{S.chat.sortModeSection}</MenuLabel>- {/* Manual order is offered only where a drag can actually happen (see canDrag). */}- {canDrag && (- <MenuRadioItem- glyph={SORT_MODE_ICONS.manual}- label={S.chat.sortManual}- checked={sortMode === "manual"}- onSelect={() => {- setSortMode("manual");- setListSettingsOpen(false);- }}- />- )}- <MenuRadioItem- glyph={SORT_MODE_ICONS.recent}- label={S.chat.sortRecent}- checked={sortMode === "recent"}- onSelect={() => {- setSortMode("recent");- setListSettingsOpen(false);- }}- />- </Menu>- </Dropdown>- {/* Mode-dependent create — 具体新建的对象按分组方式决定, the icon following- suit (folder+ / robot+, a bottom-right plus badge on the entity's glyph):- agent grouping opens the Agents page's existing create dialog (route- state); workspace grouping opens the SAME directory-browse menu the- draft's workspace picker uses — the picked directory registers as a- workspace group immediately, Sessions or not. Time buckets are not- something to create into, so that mode starts a plain new conversation- and wears the compose glyph without a plus badge. */}- {newEntity === "agent" ? (- <button- type="button"- data-tooltip={newEntityLabel}- aria-label={newEntityLabel}- onClick={() => {- navigate("/agents", { state: { create: true } });- onNavigate?.();- }}- className={headerControlClass(false)}- >- <AddBadgeIcon base={NAV_ICONS.agents} />- </button>- ) : newEntity === "chat" ? (- <button- type="button"- data-tooltip={newEntityLabel}- aria-label={newEntityLabel}- onClick={() => newChat()}- className={headerControlClass(false)}- >- <Icon d={NEW_CHAT_ICON} size={ICON_SIZE.iconButton} />- </button>- ) : (- <WorkspaceSelect- // Remount per Project: the picker browses lazily and caches the listing- // for its lifetime, so a long-lived instance would show the PREVIOUS- // Project's directories after a switch — and register that path into the- // new Project's registry.- key={currentProjectId ?? "no-project"}- projectId={currentProjectId ?? ""}- workspace=""- onChange={addWorkspace}- // The sidebar's + is where a workspace is CREATED, so it is where the- // machine is chosen; the draft and settings pickers edit a workspace that- // already has one.- chooseMachine- trigger={(open, toggle) => (- <button- type="button"- data-tooltip={newEntityLabel}- aria-label={newEntityLabel}- aria-expanded={open}- onClick={toggle}- className={headerControlClass(open)}- >- <AddBadgeIcon base={ICONS.folder} />- </button>- )}- />- )}- </div>- </div>-- {/* Parked draft conversations (unsent new chats, newest first): pinned above both- grouping modes — they belong to no Agent or Workspace until sent. Hidden- entirely while there are none; the search filter applies to their titles too. */}- {shownDrafts.length > 0 && (- <div className="pt-2.5">- <GroupHeader- open={searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)}- onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}- icon={- <span- className="ui-icon-decor shrink-0 text-gray-400 dark:text-gray-500"- data-role="group"- >- <Icon d={NEW_CHAT_ICON} size={ICON_SIZE.groupHeaderGlyph} />- </span>- }- label={S.chat.draftGroup}- uppercase- count={shownDrafts.length}- />- {(searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)) && (- <ul className="space-y-0.5">- {shownDrafts.map((entry) => (- <DraftRow- key={entry.id}- entry={entry}- active={entry.id === activeSessionId}- onOpen={() => go(`/chat/${entry.id}`)}- onDelete={() => setDeletingDraft(entry)}- />- ))}- </ul>- )}- </div>- )}-- {groupMode === "agent" ? (- loading && agents.length === 0 ? (- <SkeletonList rows={5} />- ) : (- // While searching: every group renders (paging bypassed), zero-match groups- // hide, and the rest are forced open — a hit inside a collapsed group would- // look like a missing result.- groupsOnPage(orderedAgents).map((agent) => {- const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);- if (searching && groupRows.length === 0) return null;- const parts = partitionSessions(groupRows);- /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */- const foldedOnly = folderOnlyAgents.get(agent.agentId);- const collapsed =- !searching &&- (foldedOnly === undefined- ? collapsedGroups.has(agent.agentId)- : !expandedFolderOnlyGroups.has(agent.agentId));- const pinned = pinnedGroups.has(agent.agentId);- const drag = groupDragProps(agent.agentId, agentGroupSequence);- return (- <GroupBlock key={agent.agentId} dropEdge={drag.dropEdge}>- {/* Group header: collapse toggle (Agent name) + pin + new chat + Agent settings; also the group's drag handle. */}- <GroupHeader- {...drag.header}- open={!collapsed}- onToggle={() => toggleGroup(agent.agentId, foldedOnly !== undefined)}- icon={- <AgentAvatar- id={agent.agentId}- name={agentDisplayName(agent)}- size={18}- className="shrink-0 rounded"- />- }- label={agentDisplayName(agent)}- uppercase- {...(foldedOnly === undefined- ? {}- : {- // An Agent header carries no count otherwise; a folder-only one says- // what it holds, because everything it holds is behind its folders.- count: foldedOnly,- muted: true,- title: S.chat.folderOnlyGroup(foldedOnly),- })}- actions={- <>- <GroupPinButton- pinned={pinned}- onToggle={() => togglePin(agent.agentId)}- />- {/* New chat: enters draft state directly with this group's Agent (all options live on the draft input card) */}- <button- type="button"- data-tooltip={S.chat.newSessionMenu}- aria-label={S.chat.newSessionMenu}- onClick={() => newChat({ agentId: agent.agentId })}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <Icon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />- </button>- <button- type="button"- data-tooltip={S.agent.settings}- aria-label={S.agent.settings}- onClick={() => go(`/agents/${agent.agentId}`)}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <Icon d={ICONS.gear} size={ICON_SIZE.groupHeaderAction} />- </button>- </>- }- />-- {collapsed- ? null- : renderGroupBody(- agent.agentId,- parts,- false,- countsByAgent.get(agent.agentId),- () => [agent.agentId],- )}- </GroupBlock>- );- })- )- ) : null}- {groupMode === "agent" ? groupPagerRow() : null}- {groupMode !== "workspace" ? null : loading && sessions.length === 0 ? (- <SkeletonList rows={5} />- ) : orderedWorkspaceGroups.length === 0 && !searching ? (- <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">- {S.chat.noSessions}- </p>- ) : (- // Same search treatment as agent mode: paging bypassed, zero-match groups hidden, the rest forced open.- groupsOnPage(orderedWorkspaceGroups).map((group) => {- const groupRows = filterRows(group.sessions);- if (searching && groupRows.length === 0) return null;- const parts = partitionSessions(groupRows);- /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */- const foldedOnly = folderOnlyWorkspaceGroups.get(group.key);- const collapsed =- !searching &&- (foldedOnly === undefined- ? collapsedGroups.has(group.key)- : !expandedFolderOnlyGroups.has(group.key));- const pinned = pinnedGroups.has(group.key);- /**- * Header tooltip: the full Workspace path, or — for a folder-only group — the- * sentence that says what the dimmed header and its count mean, which carries that- * same path inside it.- */- const qualifiedPath =- group.fullPath !== null- ? nameOnMachine(group.fullPath, machineNameOf(group.machineId))- : null;- const headerTitle =- foldedOnly === undefined- ? qualifiedPath- : S.chat.folderOnlyGroup(foldedOnly, qualifiedPath ?? undefined);- const drag = groupDragProps(group.key, workspaceGroupSequence);- /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */- const counts = workspaceGroupCounts.get(group.key);- /** Read once so the registry actions below keep the narrowing (null = the merged temp group, which has no single path). */- const fullPath = group.fullPath;- /** The ssh alias qualifying this group's names, or null when it is on this server. */- const machineName = machineNameOf(group.machineId);- const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];- const agentsFor = (category: SessionCategory) => [- ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),- ];- return (- <GroupBlock key={group.key} dropEdge={drag.dropEdge}>- {/* Group header: collapse toggle (folder icon + directory basename + count, full- path in the tooltip; the count = the group's active conversations only, exact- server share, loaded rows win a disagreement — the folders never feed it,- except in a folder-only group, where they are all there is to count) +- pin + new chat in this Workspace; also the group's drag handle. */}- <GroupHeader- {...drag.header}- open={!collapsed}- onToggle={() => toggleGroup(group.key, foldedOnly !== undefined)}- icon={- /* Folder opens and closes with the group */- <span- className="ui-icon-decor shrink-0 text-gray-400 dark:text-gray-500"- data-role="group"- >- <Icon- d={collapsed ? ICONS.folder : ICONS.folderOpen}- size={ICON_SIZE.groupHeaderGlyph}- />- </span>- }- label={nameOnMachine(- group.temp ? S.chat.tempWorkspaces : group.label,- machineName,- )}- count={- foldedOnly !== undefined- ? foldedOnly- : searching- ? parts.active.length- : Math.max(counts?.totals.active ?? 0, parts.active.length)- }- muted={foldedOnly !== undefined}- {...(headerTitle !== null ? { title: headerTitle } : {})}- actions={- <>- <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />- {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the Project's new-chat default, like any other new chat */}- <button- type="button"- data-tooltip={S.chat.newSessionInWorkspace}- aria-label={S.chat.newSessionInWorkspace}- onClick={() =>- newChat({- workspace: fullPath ?? "",- // The machine travels with the path: this group's rows live on it,- // and the same path here is a different directory (or none).- ...(group.machineId ? { machineId: group.machineId } : {}),- })- }- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <Icon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />- </button>- {/* Manually-added (registry-backed) Workspaces only: rename-alias /- remove-from-sidebar overflow, to the right of the "+" (session-- derived groups have no registry entry for these to act on). */}- {fullPath !== null && registeredKeys.has(group.key) && (- <GroupOverflowMenu- onRename={() => openRenameWorkspace(fullPath, group.machineId)}- onDelete={() =>- setDeletingWorkspace({- path: fullPath,- machineId: group.machineId,- label: group.label,- })- }- />- )}- </>- }- />-- {/* A workspace group can span Agents: the group body fans folder loads and "More"- out per category to the Agents whose share of THIS group is non-zero (plus the- Agents already contributing loaded rows) — the active list and each folder- page independently. */}- {collapsed- ? null- : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}- </GroupBlock>- );- })- )}- {groupMode === "workspace" ? groupPagerRow() : null}-- {/* Time mode: last day / last month / earlier, bucketed on each conversation's last- activity — the same stamp the rows' compact timestamps and the recency sort read,- so a row can never sit under a bucket its own timestamp contradicts. Empty buckets- are dropped, and there are at most three, so this mode never paginates its groups.- The buckets span every Agent and every Workspace: a bucket's "More" only reveals- further loaded rows, while fetching the next page and reaching the Subagents /- Scheduled / Archived rows happen once for the whole Project, below. */}- {groupMode !== "time" || timeParts === null ? null : loading &&- sessions.length === 0 ? (- <SkeletonList rows={5} />- ) : (- <>- {timeGroups.map((group) => {- const collapsed = !searching && collapsedGroups.has(group.key);- return (- <div key={group.key} className="pt-2.5">- <GroupHeader- open={!collapsed}- onToggle={() => toggleGroup(group.key)}- icon={- <span- className="ui-icon-decor shrink-0 text-gray-400 dark:text-gray-500"- data-role="group"- >- <Icon d={GROUP_MODE_ICONS.time} size={ICON_SIZE.groupHeaderGlyph} />- </span>- }- label={S.chat.timeGroups[group.bucket]}- uppercase- count={group.sessions.length}- />- {collapsed- ? null- : renderGroupBody(- group.key,- bucketPartition(group.sessions),- true,- undefined,- () => [],- )}- </div>- );- })}-- {/* Empty only when the shared folders below are empty too (renderGroupBody's own- rule): "no Sessions yet" over an "Archived (3)" row would contradict it. */}- {timeGroups.length === 0 && !searching && timeFolders.every((f) => f === null) && (- <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">- {S.chat.noSessions}- </p>- )}-- {/* Whole-list paging: a fetched page lands in whichever bucket its rows' activity- puts them, so the row that pulls one belongs to the list, not to a bucket —- and its label says "conversations" where a bucket's says "more". */}- {!searching &&- timeParts.active.length < projectCounts.active &&- timeMoreAgents.length > 0 && (- <MoreRow- label={S.chat.loadMoreSessions}- ariaLabel={S.chat.loadMoreSessions}- pending={pendingLoads.has(loadKey(TIME_FOLDERS_GROUP_KEY, "active"))}- onClick={() =>- trackedLoadMore(TIME_FOLDERS_GROUP_KEY, "active", timeMoreAgents)- }- className="mt-1"- />- )}-- {/* The shared, Project-wide folders (see timeFolders). */}- <div className="pt-2.5">{timeFolders}</div>- </>- )}-- {/* Quiet no-match line: the search is live and nothing — drafts included — hit. */}- {searching && !hasSearchMatches && (- <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">- {S.chat.searchNoMatches}- </p>- )}- </>- )}- </div>-- {/* Bottom user row: the trigger for the account menu both this sidebar and the- collapsed rail open (user-menu.tsx). */}- <div className="shrink-0 border-t border-gray-200 p-2 dark:border-gray-800">- <UserMenu- menuClass="bottom-full left-0 right-0 mb-1 origin-bottom"- trigger={({ open, toggle }) => (- <button- type="button"- onClick={toggle}- aria-haspopup="menu"- aria-expanded={open}- {...(badges.softwareNote !== null- ? {- // The dot alone is mysterious: name what is waiting on the trigger (hover- // tooltip + accessible name), in the update row's own wording.- "data-tooltip": badges.softwareNote,- "aria-label": `${user?.displayName ?? user?.userId ?? ""} · ${badges.softwareNote}`,- }- : {})}- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"+ /**+ * The account row at the column's foot: the trigger for the account menu both this sidebar and+ * the collapsed rail open (user-menu.tsx).+ */+ const accountRow = (+ <UserMenu+ menuClass="bottom-full left-0 right-0 mb-1 origin-bottom"+ trigger={({ open, toggle }) => (+ <SidebarAccountButton+ expanded={open}+ onClick={toggle}+ // The dot alone is mysterious: name what is waiting on the trigger (hover tooltip ++ // accessible name), in the update row's own wording.+ {...(badges.softwareNote !== null+ ? {+ hint: badges.softwareNote,+ label: `${user?.displayName ?? user?.userId ?? ""} · ${badges.softwareNote}`,+ }+ : {})}+ avatar={+ <UserAvatar+ userId={user?.userId ?? "?"}+ {...(user?.displayName !== undefined ? { displayName: user.displayName } : {})}+ {...(user?.avatar !== undefined ? { avatar: user.avatar } : {})}>- <UserAvatar- userId={user?.userId ?? "?"}- {...(user?.displayName !== undefined ? { displayName: user.displayName } : {})}- {...(user?.avatar !== undefined ? { avatar: user.avatar } : {})}- >- {/* Update reminder: the menu behind this trigger holds the row that acts on- it, and the trigger's tooltip/label above say what it is. */}- {badges.software !== null && <UpdateDot />}- </UserAvatar>- <span className="min-w-0 flex-1 truncate font-sans text-sm font-medium">- {user?.displayName ?? user?.userId}- </span>- {user?.isAdmin && (- <span className="text-xs text-gray-400 dark:text-gray-500">{S.auth.admin}</span>- )}- </button>- )}+ {/* Update reminder: the menu behind this trigger holds the row that acts on it,+ and the trigger's tooltip/label above say what it is. */}+ {badges.software !== null && <UpdateDot />}+ </UserAvatar>+ }+ name={user?.displayName ?? user?.userId}+ {...(user?.isAdmin ? { role: S.auth.admin } : {})}/>- </div>+ )}+ />+ );+ /** The dialogs the column's rows and menus open, mounted after the column. */+ const dialogs = (+ <><CreateProjectDialogopen={createProjectOpen}onClose={() => setCreateProjectOpen(false)}@@ -2795,7 +1970,649 @@ export function Sidebar({: ""}</p></ConfirmModal>- </div>+ </>+ );++ return (+ <SidebarFrame+ rootRef={rootRef}+ // The work-mode switch, above the Project switcher: 开发 | 公司. Rendered only while+ // company mode is available (the admin master switch and the user's own switch both on);+ // the choice persists per user. The 内测版 tag rides on 公司 — the switch is the one+ // control that names the mode, so the mark stands on the word it qualifies rather than+ // somewhere inside the mode it describes.+ {...(company.available+ ? {+ modeSwitch: {+ label: S.company.workMode,+ control: (+ <Segmented+ options={[+ { value: "dev" as const, label: S.company.modeDev },+ {+ value: "company" as const,+ label: S.company.modeCompany,+ badge: { node: <CompanyBetaBadge />, name: S.company.beta },+ },+ ]}+ value={company.workMode}+ onChange={switchMode}+ cols={2}+ />+ ),+ },+ }+ : {})}+ {...(onCollapse+ ? {+ collapse: { label: S.nav.collapseSidebar, tooltip: collapseTitle, onClick: onCollapse },+ }+ : {})}+ switcher={+ // The Project switcher; the organization switcher in company mode.+ inCompany ? (+ <OrgSwitcher {...(onNavigate ? { onNavigate } : {})} />+ ) : (+ <Dropdown+ open={projectOpen}+ setOpen={setProjectOpen}+ className="min-w-0 flex-1"+ menuClass="left-0 right-0 top-full mt-1 origin-top"+ button={+ <SidebarSwitcherButton+ label={currentProject ? projectDisplayName(currentProject) : S.common.loading}+ onClick={() => setProjectOpen(!projectOpen)}+ />+ }+ >+ {/* Plain rows rather than a role="menu": the switcher's Project rows are named+ like its trigger, and both are reached as buttons. */}+ {projects.map((p) => (+ <MenuRadioItem+ key={p.projectId}+ label={<span className="font-sans">{projectDisplayName(p)}</span>}+ trailing={<Badge>{p.role}</Badge>}+ checked={p.projectId === currentProject?.projectId}+ onSelect={() => {+ setCurrentProjectId(p.projectId);+ setProjectOpen(false);+ }}+ />+ ))}+ <MenuSeparator />+ <MenuItem+ glyph={ICONS.plus}+ label={S.project.create}+ onSelect={() => {+ setProjectOpen(false);+ setCreateProjectOpen(true);+ }}+ />+ {currentProject && (+ <MenuItem+ glyph={ICONS.gear}+ label={S.project.settings}+ onSelect={() => {+ setProjectOpen(false);+ setProjectSettingsOpen(true);+ }}+ />+ )}+ </Dropdown>+ )+ }+ // New chat: the only pinned entry besides the switcher above and the account row below,+ // a page row like the nav's (no fill at rest), told apart by its place and its weight, and+ // lit while on the draft page. Company mode pins nothing here: a channel is made rarely,+ // so "New channel" is the channel list's own header action rather than a permanent row+ // (channel-sidebar.tsx).+ {...(inCompany+ ? {}+ : {+ pinned: (+ <NavRow+ surface="muted"+ label={S.chat.newSessionMenu}+ tooltip={newChatTitle}+ glyph={NEW_CHAT_ICON}+ active={activeSessionId === DRAFT_SESSION_ID}+ onClick={() => newChat()}+ className="font-medium"+ />+ ),+ })}+ account={accountRow}+ overlays={dialogs}+ >+ {/* The page nav (智能体 → 评估中心, or the organization's six pages), folded away under+ its slim toggle; the choice persists. Always mounted — the fold animates the rows'+ height to zero and turns them inert. The nav and the session list scroll together. */}+ <SidebarNavGroup+ collapsed={navCollapsed}+ onToggle={toggleNavGroup}+ expandLabel={S.nav.expandGroup}+ collapseLabel={S.nav.collapseGroup}+ >+ {navItems.map((item) => (+ /* Four nav entries sit on a badge trail — Agents (an outdated kernel, fixed on the Agent+ settings page two clicks down), Skills, Models and the Cost Center (each cleared on+ the page itself). The dot is anchored to the row, not to the label text: at the+ row's right edge, on its horizontal padding, vertically centred on the row. The row's+ own label is visible, so the hint only adds what the dot means, and the accessible+ name keeps the label as its prefix. A row with nowhere to go keeps its place and its+ glyph, muted, with nothing to click or tab to. */+ <NavRow+ key={item.key}+ surface="muted"+ label={item.label}+ glyph={item.icon}+ href={item.to ?? ""}+ disabled={item.to === null}+ active={item.to !== null && isCurrentPath(item.to, location.pathname)}+ renderLink={renderRouterLink}+ onClick={() => onNavigate?.()}+ className="relative"+ {...(item.note !== null+ ? {+ ariaLabel: `${item.label} · ${item.note}`,+ tooltip: item.note,+ badge: <UpdateDot size="inline" position="right-2.5 top-1/2 -translate-y-1/2" />,+ }+ : {})}+ />+ ))}+ </SidebarNavGroup>++ {inCompany ? (+ navOrg !== null ? (+ /* Company mode: the organization's channels, where development mode lists+ conversations, and below them its 工位 group — one row per employee's desk. */+ <>+ <ChannelSidebar+ projectId={navOrg.projectId}+ orgId={navOrg.orgId}+ {...(onNavigate ? { onNavigate } : {})}+ />+ <OrgSessionGroups+ projectId={navOrg.projectId}+ orgId={navOrg.orgId}+ activeSessionId={activeSessionId}+ {...(onNavigate ? { onNavigate } : {})}+ />+ </>+ ) : (+ /* No organization to list: the create block, not an empty channel list. */+ <NoOrganizationsSidebar {...(onNavigate ? { onNavigate } : {})} />+ )+ ) : (+ <>+ {/* The list's header: its label and the controls (icon + tooltip family) — search, list+ settings (grouping + sort radios), and the mode-dependent create button (the created+ object follows the grouping mode). The search opens in place, over the label's+ column, so it costs no extra row; the magnifier becomes the field's leading glyph.+ No ruled separator at this boundary — the nav toggle above is the seam. */}+ <SidebarListHeader label={S.chat.sessionList} searching={searchOpen}>+ {searchOpen ? (+ /* Expanded field: the magnifier, the input and the clear ×, one bordered+ box filling the row (its width rides the column tween). Esc and × both+ collapse it and drop the filter, which is why the × stays while it is empty. */+ <SearchInput+ ref={searchInputRef}+ icon+ alwaysClearable+ autoFocus+ className="min-w-0 flex-1"+ value={searchQuery}+ onChange={setSearchQuery}+ onClear={closeSearch}+ placeholder={S.chat.searchSessionsPlaceholder}+ aria-label={S.chat.searchSessions}+ clearLabel={S.chat.searchClear}+ />+ ) : (+ <SidebarControl+ label={S.chat.searchSessions}+ tooltip={searchTitle}+ glyph={ICONS.search}+ onClick={() => setSearchOpen(true)}+ />+ )}+ <Dropdown+ open={listSettingsOpen}+ setOpen={setListSettingsOpen}+ portal={{ direction: "down", align: "right" }}+ menuClass="w-40"+ button={+ <SidebarControl+ label={S.chat.listSettings}+ glyph={ICONS.slidersHorizontal}+ active={listSettingsOpen}+ aria-haspopup="menu"+ aria-expanded={listSettingsOpen}+ onClick={() => setListSettingsOpen(!listSettingsOpen)}+ />+ }+ >+ <Menu density="sm">+ <MenuLabel>{S.chat.groupModeSection}</MenuLabel>+ <MenuRadioItem+ glyph={GROUP_MODE_ICONS.workspace}+ label={S.chat.groupByWorkspace}+ checked={groupMode === "workspace"}+ onSelect={() => {+ setGroupMode("workspace");+ setListSettingsOpen(false);+ }}+ />+ <MenuRadioItem+ glyph={GROUP_MODE_ICONS.agent}+ label={S.chat.groupByAgent}+ checked={groupMode === "agent"}+ onSelect={() => {+ setGroupMode("agent");+ setListSettingsOpen(false);+ }}+ />+ <MenuRadioItem+ glyph={GROUP_MODE_ICONS.time}+ label={S.chat.groupByTime}+ checked={groupMode === "time"}+ onSelect={() => {+ setGroupMode("time");+ setListSettingsOpen(false);+ }}+ />+ <MenuSeparator />+ <MenuLabel>{S.chat.sortModeSection}</MenuLabel>+ {/* Manual order is offered only where a drag can actually happen (see canDrag). */}+ {canDrag && (+ <MenuRadioItem+ glyph={SORT_MODE_ICONS.manual}+ label={S.chat.sortManual}+ checked={sortMode === "manual"}+ onSelect={() => {+ setSortMode("manual");+ setListSettingsOpen(false);+ }}+ />+ )}+ <MenuRadioItem+ glyph={SORT_MODE_ICONS.recent}+ label={S.chat.sortRecent}+ checked={sortMode === "recent"}+ onSelect={() => {+ setSortMode("recent");+ setListSettingsOpen(false);+ }}+ />+ </Menu>+ </Dropdown>+ {/* Mode-dependent create — 具体新建的对象按分组方式决定, the icon following+ suit (folder+ / robot+, a bottom-right plus badge on the entity's glyph):+ agent grouping opens the Agents page's existing create dialog (route+ state); workspace grouping opens the SAME directory-browse menu the+ draft's workspace picker uses — the picked directory registers as a+ workspace group immediately, Sessions or not. Time buckets are not+ something to create into, so that mode starts a plain new conversation+ and wears the compose glyph without a plus badge. */}+ {newEntity === "agent" ? (+ <SidebarControl+ label={newEntityLabel}+ glyph={<AddBadgeIcon base={NAV_ICONS.agents} />}+ onClick={() => {+ navigate("/agents", { state: { create: true } });+ onNavigate?.();+ }}+ />+ ) : newEntity === "chat" ? (+ <SidebarControl+ label={newEntityLabel}+ glyph={<GlyphIcon d={NEW_CHAT_ICON} size={ICON_SIZE.iconButton} />}+ onClick={() => newChat()}+ />+ ) : (+ <WorkspaceSelect+ // Remount per Project: the picker browses lazily and caches the listing+ // for its lifetime, so a long-lived instance would show the PREVIOUS+ // Project's directories after a switch — and register that path into the+ // new Project's registry.+ key={currentProjectId ?? "no-project"}+ projectId={currentProjectId ?? ""}+ workspace=""+ onChange={addWorkspace}+ // The sidebar's + is where a workspace is CREATED, so it is where the+ // machine is chosen; the draft and settings pickers edit a workspace that+ // already has one.+ chooseMachine+ trigger={(open, toggle) => (+ <SidebarControl+ label={newEntityLabel}+ glyph={<AddBadgeIcon base={ICONS.folder} />}+ active={open}+ aria-expanded={open}+ onClick={toggle}+ />+ )}+ />+ )}+ </SidebarListHeader>++ {/* Parked draft conversations (unsent new chats, newest first): pinned above both+ grouping modes — they belong to no Agent or Workspace until sent. Hidden+ entirely while there are none; the search filter applies to their titles too. */}+ {shownDrafts.length > 0 && (+ <div className="pt-2.5">+ <GroupHeader+ open={searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)}+ onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}+ glyph={NEW_CHAT_ICON}+ label={S.chat.draftGroup}+ uppercase+ count={shownDrafts.length}+ />+ {(searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)) && (+ <ul className="space-y-px">+ {shownDrafts.map((entry) => (+ <DraftRow+ key={entry.id}+ entry={entry}+ active={entry.id === activeSessionId}+ onOpen={() => go(`/chat/${entry.id}`)}+ onDelete={() => setDeletingDraft(entry)}+ />+ ))}+ </ul>+ )}+ </div>+ )}++ {groupMode === "agent" ? (+ loading && agents.length === 0 ? (+ <SkeletonList rows={5} />+ ) : (+ // While searching: every group renders (paging bypassed), zero-match groups+ // hide, and the rest are forced open — a hit inside a collapsed group would+ // look like a missing result.+ groupsOnPage(orderedAgents).map((agent) => {+ const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);+ if (searching && groupRows.length === 0) return null;+ const parts = partitionSessions(groupRows);+ /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */+ const foldedOnly = folderOnlyAgents.get(agent.agentId);+ const collapsed =+ !searching &&+ (foldedOnly === undefined+ ? collapsedGroups.has(agent.agentId)+ : !expandedFolderOnlyGroups.has(agent.agentId));+ const pinned = pinnedGroups.has(agent.agentId);+ const drag = groupDragProps(agent.agentId, agentGroupSequence);+ return (+ <GroupBlock key={agent.agentId} dropEdge={drag.dropEdge}>+ {/* Group header: collapse toggle (Agent name) + pin + new chat + Agent settings; also the group's drag handle. */}+ <GroupHeader+ {...drag.header}+ open={!collapsed}+ onToggle={() => toggleGroup(agent.agentId, foldedOnly !== undefined)}+ icon={+ <AgentAvatar+ id={agent.agentId}+ name={agentDisplayName(agent)}+ size={18}+ className="shrink-0 rounded"+ />+ }+ label={agentDisplayName(agent)}+ uppercase+ {...(foldedOnly === undefined+ ? {}+ : {+ // An Agent header carries no count otherwise; a folder-only one says+ // what it holds, because everything it holds is behind its folders.+ count: foldedOnly,+ muted: true,+ title: S.chat.folderOnlyGroup(foldedOnly),+ })}+ actions={+ <>+ <GroupPinButton+ pinned={pinned}+ onToggle={() => togglePin(agent.agentId)}+ />+ {/* New chat: enters draft state directly with this group's Agent (all options live on the draft input card) */}+ <button+ type="button"+ data-tooltip={S.chat.newSessionMenu}+ aria-label={S.chat.newSessionMenu}+ onClick={() => newChat({ agentId: agent.agentId })}+ className={GROUP_ACTION_CLASS}+ >+ <Icon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />+ </button>+ <button+ type="button"+ data-tooltip={S.agent.settings}+ aria-label={S.agent.settings}+ onClick={() => go(`/agents/${agent.agentId}`)}+ className={GROUP_ACTION_CLASS}+ >+ <Icon d={ICONS.gear} size={ICON_SIZE.groupHeaderAction} />+ </button>+ </>+ }+ />++ {collapsed+ ? null+ : renderGroupBody(+ agent.agentId,+ parts,+ false,+ countsByAgent.get(agent.agentId),+ () => [agent.agentId],+ )}+ </GroupBlock>+ );+ })+ )+ ) : null}+ {groupMode === "agent" ? groupPagerRow() : null}+ {groupMode !== "workspace" ? null : loading && sessions.length === 0 ? (+ <SkeletonList rows={5} />+ ) : orderedWorkspaceGroups.length === 0 && !searching ? (+ <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">+ {S.chat.noSessions}+ </p>+ ) : (+ // Same search treatment as agent mode: paging bypassed, zero-match groups hidden, the rest forced open.+ groupsOnPage(orderedWorkspaceGroups).map((group) => {+ const groupRows = filterRows(group.sessions);+ if (searching && groupRows.length === 0) return null;+ const parts = partitionSessions(groupRows);+ /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */+ const foldedOnly = folderOnlyWorkspaceGroups.get(group.key);+ const collapsed =+ !searching &&+ (foldedOnly === undefined+ ? collapsedGroups.has(group.key)+ : !expandedFolderOnlyGroups.has(group.key));+ const pinned = pinnedGroups.has(group.key);+ /**+ * Header tooltip: the full Workspace path, or — for a folder-only group — the+ * sentence that says what the dimmed header and its count mean, which carries that+ * same path inside it.+ */+ const qualifiedPath =+ group.fullPath !== null+ ? nameOnMachine(group.fullPath, machineNameOf(group.machineId))+ : null;+ const headerTitle =+ foldedOnly === undefined+ ? qualifiedPath+ : S.chat.folderOnlyGroup(foldedOnly, qualifiedPath ?? undefined);+ const drag = groupDragProps(group.key, workspaceGroupSequence);+ /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */+ const counts = workspaceGroupCounts.get(group.key);+ /** Read once so the registry actions below keep the narrowing (null = the merged temp group, which has no single path). */+ const fullPath = group.fullPath;+ /** The ssh alias qualifying this group's names, or null when it is on this server. */+ const machineName = machineNameOf(group.machineId);+ const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];+ const agentsFor = (category: SessionCategory) => [+ ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),+ ];+ return (+ <GroupBlock key={group.key} dropEdge={drag.dropEdge}>+ {/* Group header: collapse toggle (folder icon + directory basename + count, full+ path in the tooltip; the count = the group's active conversations only, exact+ server share, loaded rows win a disagreement — the folders never feed it,+ except in a folder-only group, where they are all there is to count) ++ pin + new chat in this Workspace; also the group's drag handle. */}+ <GroupHeader+ {...drag.header}+ open={!collapsed}+ onToggle={() => toggleGroup(group.key, foldedOnly !== undefined)}+ // The folder opens and closes with the group.+ glyph={collapsed ? ICONS.folder : ICONS.folderOpen}+ label={nameOnMachine(+ group.temp ? S.chat.tempWorkspaces : group.label,+ machineName,+ )}+ count={+ foldedOnly !== undefined+ ? foldedOnly+ : searching+ ? parts.active.length+ : Math.max(counts?.totals.active ?? 0, parts.active.length)+ }+ muted={foldedOnly !== undefined}+ {...(headerTitle !== null ? { title: headerTitle } : {})}+ actions={+ <>+ <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />+ {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the Project's new-chat default, like any other new chat */}+ <button+ type="button"+ data-tooltip={S.chat.newSessionInWorkspace}+ aria-label={S.chat.newSessionInWorkspace}+ onClick={() =>+ newChat({+ workspace: fullPath ?? "",+ // The machine travels with the path: this group's rows live on it,+ // and the same path here is a different directory (or none).+ ...(group.machineId ? { machineId: group.machineId } : {}),+ })+ }+ className={GROUP_ACTION_CLASS}+ >+ <Icon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />+ </button>+ {/* Manually-added (registry-backed) Workspaces only: rename-alias /+ remove-from-sidebar overflow, to the right of the "+" (session-+ derived groups have no registry entry for these to act on). */}+ {fullPath !== null && registeredKeys.has(group.key) && (+ <GroupOverflowMenu+ onRename={() => openRenameWorkspace(fullPath, group.machineId)}+ onDelete={() =>+ setDeletingWorkspace({+ path: fullPath,+ machineId: group.machineId,+ label: group.label,+ })+ }+ />+ )}+ </>+ }+ />++ {/* A workspace group can span Agents: the group body fans folder loads and "More"+ out per category to the Agents whose share of THIS group is non-zero (plus the+ Agents already contributing loaded rows) — the active list and each folder+ page independently. */}+ {collapsed+ ? null+ : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}+ </GroupBlock>+ );+ })+ )}+ {groupMode === "workspace" ? groupPagerRow() : null}++ {/* Time mode: last day / last month / earlier, bucketed on each conversation's last+ activity — the same stamp the rows' compact timestamps and the recency sort read,+ so a row can never sit under a bucket its own timestamp contradicts. Empty buckets+ are dropped, and there are at most three, so this mode never paginates its groups.+ The buckets span every Agent and every Workspace: a bucket's "More" only reveals+ further loaded rows, while fetching the next page and reaching the Subagents /+ Scheduled / Archived rows happen once for the whole Project, below. */}+ {groupMode !== "time" || timeParts === null ? null : loading && sessions.length === 0 ? (+ <SkeletonList rows={5} />+ ) : (+ <>+ {timeGroups.map((group) => {+ const collapsed = !searching && collapsedGroups.has(group.key);+ return (+ <div key={group.key} className="pt-2.5">+ <GroupHeader+ open={!collapsed}+ onToggle={() => toggleGroup(group.key)}+ glyph={GROUP_MODE_ICONS.time}+ label={S.chat.timeGroups[group.bucket]}+ uppercase+ count={group.sessions.length}+ />+ {collapsed+ ? null+ : renderGroupBody(+ group.key,+ bucketPartition(group.sessions),+ true,+ undefined,+ () => [],+ )}+ </div>+ );+ })}++ {/* Empty only when the shared folders below are empty too (renderGroupBody's own+ rule): "no Sessions yet" over an "Archived (3)" row would contradict it. */}+ {timeGroups.length === 0 && !searching && timeFolders.every((f) => f === null) && (+ <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">+ {S.chat.noSessions}+ </p>+ )}++ {/* Whole-list paging: a fetched page lands in whichever bucket its rows' activity+ puts them, so the row that pulls one belongs to the list, not to a bucket —+ and its label says "conversations" where a bucket's says "more". */}+ {!searching &&+ timeParts.active.length < projectCounts.active &&+ timeMoreAgents.length > 0 && (+ <MoreRow+ label={S.chat.loadMoreSessions}+ ariaLabel={S.chat.loadMoreSessions}+ pending={pendingLoads.has(loadKey(TIME_FOLDERS_GROUP_KEY, "active"))}+ onClick={() =>+ trackedLoadMore(TIME_FOLDERS_GROUP_KEY, "active", timeMoreAgents)+ }+ className="mt-1"+ />+ )}++ {/* The shared, Project-wide folders (see timeFolders). */}+ <div className="pt-2.5">{timeFolders}</div>+ </>+ )}++ {/* Quiet no-match line: the search is live and nothing — drafts included — hit. */}+ {searching && !hasSearchMatches && (+ <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">+ {S.chat.searchNoMatches}+ </p>+ )}+ </>+ )}+ </SidebarFrame>);}@@ -2818,9 +2635,7 @@ function DraftRow({// Same truncated-title scroll reveal as the session rows (#309).data-title-revealclassName={`group flex items-center rounded-md pr-1 transition-colors duration-150 ${- active- ? "bg-gray-200/70 dark:bg-gray-800"- : "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"+ active ? NAV_FILL.selected : NAV_FILL.hover}`}><button@@ -2831,10 +2646,9 @@ function DraftRow({<TruncatedscrollRevealtext={title}+ // The conversation rows' inks (SessionRow), so a parked draft reads as one of them.className={`min-w-0 flex-1 font-sans text-sm ${- active- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-700 dark:text-gray-300"+ active ? "font-medium text-fg" : "text-fg/80"}`}/></button>@@ -2906,10 +2720,10 @@ function GroupPinButton({ pinned, onToggle }: { pinned: boolean; onToggle: () =>aria-label={S.nav.pinGroup}aria-pressed={pinned}onClick={onToggle}- className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-[opacity,background-color,color] duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200 ${+ className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-[opacity,background-color,color] duration-150 hover:bg-fg/7 hover:text-fg ${pinned- ? "text-gray-500 dark:text-gray-400"- : "text-gray-400 opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100 dark:text-gray-500"+ ? "text-fg-muted"+ : "text-fg-subtle opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100"}`}><Icon d={ICONS.pin} size={ICON_SIZE.groupHeaderAction} />@@ -2918,25 +2732,22 @@ function GroupPinButton({ pinned, onToggle }: { pinned: boolean; onToggle: () =>}/**- * Single Session row: title + pinned indicator + status dot/approval badge, and one- * trailing slot that swaps its content — at rest it shows the compact last-active time,- * on row hover — or on either of them taking focus — it shows archive and delete as- * direct icon buttons.- * That pair is the affordance every release up to v0.2.2 shipped (as icon buttons in- * exactly this slot), restored here: the 0.3 line had replaced it with an ellipsis- * dropdown carrying pin / rename / archive / delete, which cost two clicks for the two- * actions people actually reach for.+ * One conversation row: the package's `SessionRow`, bound to this Session. The row itself — the+ * title with its marks, the trailing slot that swaps the last-active time for archive and the+ * "more" button on hover or focus, and the context menu a right-click, Shift+F10 or a+ * press-and-hold opens — is the package's; this container says which actions each surface+ * carries (session-row-menu.tsx), what each one does, and in which words the marks name+ * themselves.*- * The rest of the set did not disappear — **right-clicking the row** opens all four as a- * context menu at the pointer (useRowContextMenu; also Shift+F10 from the keyboard and- * press-and-hold on touch, since neither hover nor a secondary click exists there). Both- * panels go through the Dropdown body portal so the sidebar scroller can't clip them, and- * both read their action set from session-row-menu.tsx.+ * The hover pair is the affordance every release up to v0.2.2 shipped (archive as a direct icon+ * button), the rest of the set one click further; the full set stays one right-click away.*- * A truncated title scrolls its tail into view while the row is hovered or- * keyboard-focused (#309; Truncated's scrollReveal + data-title-reveal).+ * A truncated title scrolls its tail into view while the row is hovered or keyboard-focused+ * (#309; Truncated's scrollReveal, keyed on the row's `data-title-reveal`). No `title` tooltip+ * comes with it: it would sit over the very text scrolling past underneath. Under+ * prefers-reduced-motion nothing scrolls and the conditional hint returns instead.*/-function SessionRow({+function SidebarSessionRow({s,active,activity,@@ -2975,7 +2786,7 @@ function SessionRow({canPin?: boolean;/** Preformatted compact last-active time ("" hides the slot's resting text). */lastActive: string;- /** Interface language: decides the fixed width the time slot reserves (see the slot's comment). */+ /** Interface language: decides the fixed width the time slot reserves (SessionRow's `timeSlot`). */locale: "zh" | "en";/** Agent display name; when set (workspace mode) a small avatar keeps the Agent context visible on the row. */agentHint?: string;@@ -2995,10 +2806,8 @@ function SessionRow({onDelete: (s: SessionInfo) => void;onToggleArchive: (s: SessionInfo) => void;}) {- const ctx = useRowContextMenu();- /** Run one action on this Session, closing the context menu first if it was open. */+ /** Run one action on this Session (the row has closed its menu first). */const run = (action: SessionRowAction) => {- ctx.close();const handler: Record<SessionRowAction, (x: SessionInfo) => void> = {pin: onTogglePin,rename: onRename,@@ -3015,204 +2824,54 @@ function SessionRow({};handler[action](s);};- /**- * Menu items hand focus back to the row before acting: the panel unmounts under the- * user, and the context menu is the only keyboard route to pin and rename, so a- * Shift+F10 → Enter user would otherwise be dropped onto <body> and lose their place in- * the list. Actions that open a dialog (rename, delete) take focus from there as usual.- */- const runFromMenu = (action: SessionRowAction) => {- ctx.returnFocus()?.focus();- run(action);- };const rowState = { archived: s.archived, pinned };return (- <li- className="relative"- {...(draggable- ? { draggable: true, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }- : {})}- >- {/* Manual-drag drop indicator: a thin accent line on the edge the drop would land on (both themes read it against the row gap). */}- {dropEdge !== null && (- <div- aria-hidden- className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-accent ${- dropEdge === "above" ? "-top-px" : "-bottom-px"- }`}+ <SessionRow+ sessionId={s.sessionId}+ renderTitle={(className) => (+ <Truncated+ scrollReveal+ text={s.title ?? S.chat.defaultSessionTitle}+ className={className}/>)}- <div- // data-title-reveal: hovering the row / keyboard-focusing its button scrolls a- // truncated title's tail into view (the Truncated below; styles.css #309 rules).- data-title-reveal- ref={ctx.rowRef}- // Right-click / Shift+F10 / press-and-hold open the row's context menu. The- // native menu is suppressed inside this handler only — the rest of the app keeps- // the browser's own. select-none keeps a held press from raising the text- // selection callout on touch instead of the menu.- {...ctx.rowProps}- className={`group flex select-none items-center rounded-md pr-1 transition-colors duration-150 ${- draggable ? "cursor-grab " : ""- }${- active- ? "bg-gray-200/70 dark:bg-gray-800"- : "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"- }`}- >- <button- type="button"- data-testid="session-row"- data-session-id={s.sessionId}- // A press-and-hold that opened the context menu must not also open the Session:- // touch screens replay the held press as a click once the finger lifts.- onClick={() => {- if (ctx.consumeLongPressClick()) return;- onOpen(s);- }}- className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left"- >- {agentHint !== undefined && (- <span data-tooltip={agentHint} className="flex shrink-0 items-center">- <AgentAvatar id={s.agentId} name={agentHint} size={14} className="rounded" />- {/* The avatar is aria-hidden and title only serves pointer users: expose the Agent name to keyboard/screen-reader users as visually hidden text inside the row button. */}- <span className="sr-only">{agentHint}</span>- </span>- )}- {/* Truncated titles reveal their full text on row hover / keyboard focus by- scrolling the tail into view (#309; scrollReveal, no-op when the title fits).- No `title` tooltip comes with it: it would sit over the very text scrolling- past underneath. Under prefers-reduced-motion the keyframes are disabled and- nothing scrolls, so the conditional `title` returns there as the pointer-hover- fallback — not as a touch path: mobile browsers do not surface `title` on- long-press. Touch reaches the full text by opening the Session. */}- <Truncated- scrollReveal- text={s.title ?? S.chat.defaultSessionTitle}- className={`min-w-0 flex-1 font-sans text-sm ${- active- ? "font-medium text-gray-900 dark:text-gray-100"- : s.archived- ? "text-gray-400 dark:text-gray-500"- : "text-gray-700 dark:text-gray-300"- }`}- />- {/* Four marks for the row's STANDING arrangements, all in one dim cluster and all in- the `muted` ink: how the row is filed (pinned), where it can be reached from- (messaging relay), whether it runs on its own (a scheduled task) and whether it- owns work that outlives the turn (background tasks). None of them is live work, so- none competes with the status glyph that follows; each names itself in a tooltip- and in sr text, which is what lets them recede this far. */}- {/* Pinned indicator: a dim pin after the title (unpin lives in the row menu). */}- {pinned && canPin && (- <span data-tooltip={S.chat.pinnedSession} className={`shrink-0 ${toneInk.muted}`}>- <Icon d={ICONS.pin} size={ICON_SIZE.rowMark} />- <span className="sr-only">{S.chat.pinnedSession}</span>- </span>- )}- {/* Enabled-messaging indicator: one glyph for every channel, the channel named in- the tooltip and sr text (saved-but-disabled configs stay off the row; the binding- dialog lives in the row menu). */}- {s.messagingChannel !== undefined && (- <span- data-tooltip={S.messaging.enabledIndicator[s.messagingChannel]}- className={`shrink-0 ${toneInk.muted}`}- >- <Icon d={ICONS.paperPlane} size={ICON_SIZE.rowMark} />- <span className="sr-only">{S.messaging.enabledIndicator[s.messagingChannel]}</span>- </span>- )}- {/* Scheduled-task indicator: the row says this conversation will run on its own, and- the schedules panel says how often and what. A paused task, or one past its end- time, draws nothing — nothing more will fire from it, and a mark would be noise. */}- {scheduled && <ScheduleMark label={S.chat.sessionScheduled} size={ICON_SIZE.rowMark} />}- {/* Background work the conversation owns while sitting idle: still running, only- outside the turn, so it reads as live work rather than as a standing arrangement.- The mark leaves with the last task (live via session_background). */}- {background > 0 && (- <BackgroundTasksMark- label={S.chat.backgroundTasks(background)}- size={ICON_SIZE.rowMark}- />- )}- {/* No per-row source tag: subagent / scheduled Sessions live in their own labelled, collapsed folders, so a badge on the title would just repeat the folder. */}- <StatusGlyph activity={activity} />- {/* The count is a numeral in the attention ink, with no pill: a filled chip beside the- title read as a second button and fought every theme's row. */}- {s.pendingApprovalCount > 0 && (- <span- data-tooltip={S.chat.pendingApprovals(s.pendingApprovalCount)}- className={`shrink-0 text-xs font-semibold tabular-nums ${toneInk.attention}`}- >- {s.pendingApprovalCount}- </span>- )}- </button>- {/* Trailing swap slot: resting last-active time / hover-focus archive + delete.- The buttons form a CONSTANT-width group anchored at the slot's right edge —- NOT a whole-slot overlay: the slot's width rides the time string (2 分钟前 vs- 31 分钟前), and slot-centered glyphs landed at a different x per row, so the- icons never formed a vertical column (the user saw them shift with the time's- character count). Right-anchored, every row's icons share one x. The slot's- width is FIXED per language rather than riding the time string: the marks that- end the title button (glyph, background, schedule, approvals) sit against this- slot, so a slot that grew with 「31 分钟前」 and shrank with 「刚刚」 moved them- row by row. Sized for the widest string each language produces — 「12月31日」- and 「59 分钟前」 in zh, "Nov 30" in en — measured at the SMALLEST font tier,- which is the tight one: the slot is in rem and shrinks with the root font,- while the time inside it is a fixed 11px and does not. Never below the hover- pair's own width (two w-6 buttons), so on a row with no time the buttons- still don't overhang the title.- The swap stays a pure opacity handoff: the time hides on row hover- (group-hover) and while a button holds focus (peer-focus-within; the group- precedes the time span so the peer combinator can reach it). */}- <div- className={`relative flex h-6 shrink-0 items-center justify-end ${- locale === "zh" ? "w-[4.5rem]" : "w-14"- }`}- >- {/* No hover pill on these (a fill as wide as the date read ugly); feedback is- the glyph color deepening — red for delete. */}- <div className="peer absolute right-0 top-1/2 flex -translate-y-1/2 items-center">- <SessionRowHoverActions- actions={HOVER_ROW_ACTIONS}- state={rowState}- onRun={run}- onMore={ctx.openAt}- />- </div>- {lastActive !== "" && (- <span- aria-hidden- className="pointer-events-none whitespace-nowrap px-1 text-right text-[11px] tabular-nums text-gray-400 transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0 dark:text-gray-500"- >- {lastActive}- </span>- )}- </div>- {/* The full set, one right-click away (also Shift+F10 / press-and-hold — see- useRowContextMenu). `contents` keeps this wrapper out of the row's flex- layout: it renders no box of its own, the panel is portaled, and the anchor- is the viewport point the gesture landed on rather than this element. */}- <Dropdown- open={ctx.open}- setOpen={ctx.setOpen}- portal={{ direction: "down", align: "left" }}- anchorRect={ctx.anchor}- anchorOwner={ctx.anchorOwner}- returnFocus={ctx.returnFocus}- className="contents"- menuClass="w-36"- button={null}- >- <SessionRowMenuRows- actions={contextMenuActions(canPin)}- state={rowState}- onRun={runFromMenu}- />- </Dropdown>- </div>- </li>+ active={active}+ archived={s.archived}+ {...(agentHint !== undefined ? { agent: { id: s.agentId, name: agentHint } } : {})}+ // Four marks for the row's STANDING arrangements, all in one dim cluster: how the row is+ // filed (pinned — only where pinning reorders anything), where it can be reached from (the+ // messaging relay, named by its channel), whether it runs on its own (a scheduled task still+ // to fire; a paused or ended one draws nothing) and whether it owns work that outlives the+ // turn (background tasks, live via session_background).+ {...(pinned && canPin ? { pinnedLabel: S.chat.pinnedSession } : {})}+ {...(s.messagingChannel !== undefined+ ? { relayLabel: S.messaging.enabledIndicator[s.messagingChannel] }+ : {})}+ {...(scheduled ? { scheduledLabel: S.chat.sessionScheduled } : {})}+ background={{ count: background, label: S.chat.backgroundTasks(background) }}+ activity={+ activity === null ? null : { state: activity, label: sessionActivityLabel(activity) }+ }+ approvals={{+ count: s.pendingApprovalCount,+ label: S.chat.pendingApprovals(s.pendingApprovalCount),+ }}+ time={lastActive}+ // Sized for the widest compact time each language produces — 「12月31日」 and 「59 分钟前」 in+ // zh, "Nov 30" in en.+ timeSlot={locale === "zh" ? "wide" : "narrow"}+ hoverActions={sessionRowActions(HOVER_ROW_ACTIONS, rowState, run)}+ menuActions={sessionRowActions(contextMenuActions(canPin), rowState, run)}+ moreLabel={S.chat.moreActions}+ onOpen={() => onOpen(s)}+ draggable={draggable}+ dropEdge={dropEdge}+ {...(onDragStart ? { onDragStart } : {})}+ {...(onDragEnd ? { onDragEnd } : {})}+ {...(onDragOver ? { onDragOver } : {})}+ {...(onDragLeave ? { onDragLeave } : {})}+ {...(onDrop ? { onDrop } : {})}+ />);}diff --git a/packages/web/src/components/ui/chord-kbd.tsx b/packages/web/src/components/ui/chord-kbd.tsxindex 7e57e47b..c531e5f6 100644--- a/packages/web/src/components/ui/chord-kbd.tsx+++ b/packages/web/src/components/ui/chord-kbd.tsx@@ -10,9 +10,13 @@ import { currentPlatform } from "../../lib/shortcuts/platform";import { keyboardLayout } from "../../lib/shortcuts/store";import type { Chord } from "../../lib/shortcuts/types";-export function ChordKbd({ chord, className = "" }: { chord: Chord; className?: string }) {+/** The chord's keys as `Kbd` takes them: one glyph run on macOS, one key per `+` token elsewhere. */+export function chordKeys(chord: Chord): string[] {const platform = currentPlatform();const label = formatChord(chord, platform, keyboardLayout() ?? undefined);- const keys = platform === "mac" ? [label] : label.split("+");- return <Kbd keys={keys} variant="plain" className={className} />;+ return platform === "mac" ? [label] : label.split("+");+}++export function ChordKbd({ chord, className = "" }: { chord: Chord; className?: string }) {+ return <Kbd keys={chordKeys(chord)} variant="plain" className={className} />;}diff --git a/packages/web/src/components/ui/session-row-menu.tsx b/packages/web/src/components/ui/session-row-menu.tsxindex 3e9d45f1..72bfc008 100644--- a/packages/web/src/components/ui/session-row-menu.tsx+++ b/packages/web/src/components/ui/session-row-menu.tsx@@ -16,37 +16,13 @@* Rename therefore keeps a home: every Session must stay renamable, archivable and* deletable, and paring the hover affordance down would otherwise have dropped rename* off the row entirely.+ *+ * The surfaces themselves are the UI package's (`SessionRow`, `RowHoverActions`, the `MenuItem`+ * rows); this module says which actions they carry and in what words.*/-import type { MouseEvent as ReactMouseEvent } from "react";-import { GlyphIcon, ICONS, menuRowClass, menuRowTone } from "@prismshadow/penguin-ui";-import type { AnchorRect } from "@prismshadow/penguin-ui";+import { ICONS, MenuItem, RowHoverActions } from "@prismshadow/penguin-ui";+import type { AnchorRect, RowActionItem } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";-import { Icon } from "./group-list";--/** Compact overflow-menu row (session row menu + workspace group menu): small text, leading thin-line glyph. */-export const overflowMenuRowClass = `flex items-center gap-2 ${menuRowClass} text-xs ${menuRowTone()}`;--/** The overflow menus' destructive row (delete keeps the red treatment; its glyph inherits the red). */-export const overflowMenuDangerClass = `flex items-center gap-2 ${menuRowClass} text-xs text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40`;--/**- * A menu row's leading glyph. It names the row's subject beside a label that is never dropped,- * so it is decorative (`ui-icon-decor`, role `menu`): a theme may recolour it or leave it out.- * Muted, except on a danger row, where it inherits the row's red.- */-export function MenuItemGlyph({ d, danger = false }: { d: string; danger?: boolean }) {- return (- <span- className={`ui-icon-decor shrink-0 ${danger ? "" : "text-gray-400 dark:text-gray-500"}`}- data-role="menu"- >- <Icon d={d} size={13} />- </span>- );-}--/** The overflow menus' muted leading glyph, for call sites that build their rows inline. */-export const overflowMenuGlyph = (d: string) => <MenuItemGlyph d={d} />;/** One thing a Session row can do to its Session. */export type SessionRowAction = "pin" | "rename" | "copy" | "messaging" | "archive" | "delete";@@ -60,7 +36,7 @@ export interface SessionRowState {/*** The hover affordance's direct actions: archive alone. Everything else — delete* included — lives in the context menu, whose discoverable pointer entry is the- * ellipsis button `SessionRowHoverActions` renders after these (see the module header).+ * ellipsis button the row renders after these (see the module header).*/export const HOVER_ROW_ACTIONS: readonly SessionRowAction[] = ["archive"];@@ -128,6 +104,27 @@ export function sessionRowMenuItem(}}+/**+ * The given actions as the package row's items: each with its label and glyph for the row's+ * state, and `run` as what choosing it does.+ */+export function sessionRowActions(+ actions: readonly SessionRowAction[],+ state: SessionRowState,+ run: (action: SessionRowAction) => void,+): RowActionItem[] {+ return actions.map((action) => {+ const item = sessionRowMenuItem(action, state);+ return {+ id: action,+ label: item.label,+ glyph: item.icon,+ danger: item.danger,+ onSelect: () => run(action),+ };+ });+}+/** The context menu's body: one labelled row per action, in the given order. */export function SessionRowMenuRows({actions,@@ -140,41 +137,25 @@ export function SessionRowMenuRows({}) {return (<>- {actions.map((action) => {- const item = sessionRowMenuItem(action, state);- return (- <button- key={action}- type="button"- className={item.danger ? overflowMenuDangerClass : overflowMenuRowClass}- onClick={() => onRun(action)}- >- <MenuItemGlyph d={item.icon} danger={item.danger} />- {item.label}- </button>- );- })}+ {sessionRowActions(actions, state, onRun).map((item) => (+ <MenuItem+ key={item.id}+ density="sm"+ glyph={item.glyph}+ label={item.label}+ danger={item.danger === true}+ onSelect={item.onSelect}+ />+ ))}</>);}-/** The hover buttons' shared reveal classes (see SessionRowHoverActions on why pointer events are gated with opacity). */-const hoverButtonClass =- "pointer-events-none flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-[opacity,color] duration-150 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100";-/**- * Hover affordance: icon-only buttons that fade in over the row — the direct actions- * (archive), then an ellipsis that opens the row's context menu anchored at itself, so- * every menu action is one visible click away rather than right-click-only. Deliberately- * hover/focus-gated and therefore desktop-only — Tailwind scopes `hover:` behind- * `@media (hover: hover)`, so these never appear on a touch screen, where the same menu- * is reached by holding the row instead.- *- * Which is why they are **pointer-events-gated on exactly the same conditions as their- * opacity**, not just faded out: an invisible button still takes taps, so a bare- * `opacity-0` would leave a phantom tap target sitting over the right end of every row- * for the one class of user who can never see it. Keyboard focus is unaffected by- * `pointer-events`, so Tab still reaches them and revealing them re-arms the click.+ * The hover affordance for a row the package's `SessionRow` does not draw (a company desk+ * row): the direct actions, then the ellipsis that opens the row's context menu anchored at+ * itself. Desktop only, and hidden from taps as well as from sight while it is not revealed —+ * the package's `RowHoverActions` says why.*/export function SessionRowHoverActions({actions,@@ -188,43 +169,11 @@ export function SessionRowHoverActions({/** Opens the row's context menu anchored at the ellipsis button's own box. */onMore: (anchor: AnchorRect) => void;}) {- const openMore = (e: ReactMouseEvent<HTMLButtonElement>) => {- const r = e.currentTarget.getBoundingClientRect();- onMore({ top: r.top, bottom: r.bottom, left: r.left, right: r.right });- };return (- <>- {actions.map((action) => {- const item = sessionRowMenuItem(action, state);- return (- <button- key={action}- type="button"- data-tooltip={item.label}- aria-label={item.label}- onClick={() => onRun(action)}- className={`${hoverButtonClass} ${- item.danger- ? "hover:text-red-600 dark:hover:text-red-400"- : "hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"- }`}- >- <Icon d={item.icon} size={14} />- </button>- );- })}- <button- type="button"- data-tooltip={S.chat.moreActions}- aria-label={S.chat.moreActions}- aria-haspopup="menu"- onClick={openMore}- className={`${hoverButtonClass} hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200`}- >- {/* Hairline-stroke dots vanish at row-glyph size, so the ellipsis is drawn filled: the- stroke rides on top of the fill, landing the dots at the archive glyph's weight. */}- <GlyphIcon d={ICONS.ellipsis} size={14} filled />- </button>- </>+ <RowHoverActions+ actions={sessionRowActions(actions, state, onRun)}+ moreLabel={S.chat.moreActions}+ onMore={onMore}+ />);}diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsxindex 37e1549b..e4d2f48e 100644--- a/packages/web/src/features/agents/memory-tab.tsx+++ b/packages/web/src/features/agents/memory-tab.tsx@@ -54,6 +54,7 @@ import {Textarea,ToggleRow,UploadIcon,+ bodyWithoutFrontmatter,buttonClass,toastError,toastSuccess,@@ -78,8 +79,6 @@ import {} from "./memory-transfer";import type { MemoryImportPlan } from "./memory-transfer";-import { bodyWithoutFrontmatter } from "../../lib/frontmatter";-/** Same breakpoint as the chat page's panels: \u22651024px the view opens as a side Drawer, below it as a bottom Sheet. */const DESKTOP_QUERY = "(min-width: 1024px)";diff --git a/packages/web/src/features/benchmark/benchmark-case-browser.tsx b/packages/web/src/features/benchmark/benchmark-case-browser.tsxindex fbcf532f..3d76cabf 100644--- a/packages/web/src/features/benchmark/benchmark-case-browser.tsx+++ b/packages/web/src/features/benchmark/benchmark-case-browser.tsx@@ -17,7 +17,8 @@ import type {CaseMaterial,WorkspaceFileEntry,} from "@prismshadow/penguin-server/api";-import { Badge } from "@prismshadow/penguin-ui";+import { Badge, FileBrowser } from "@prismshadow/penguin-ui";+import type { FileBrowserPreview, FileTreeRow, TreeToggle } from "@prismshadow/penguin-ui";import * as api from "../../api/endpoints";import { apiErrorText } from "../../lib/api-error";import { joinWorkspacePath } from "../../lib/file-path";@@ -29,13 +30,10 @@ import {baseName,expandTo,parentDir,+ previewKindOf,withExpanded,} from "../../lib/workspace-tree";import type { Listings } from "../../lib/workspace-tree";-import type { FileTreeRow } from "../../lib/file-tree";-import { FileBrowser, previewKindOf } from "../../components/ui/file-browser";-import type { FileBrowserPreview } from "../../components/ui/file-browser";-import type { TreeToggle } from "../../components/ui/file-tree";/** One row of the case tree: a shared tree row, which material it came from, and a file's size. */export interface CaseTreeRow extends FileTreeRow {@@ -366,6 +364,10 @@ export function BenchmarkCaseBrowser({ projectId, benchmarkId, caseSummary, machheaderPath={headerPath()}preview={preview}emptyPreview={S.benchmark.caseFileUnavailable}+ emptyDirLabel={S.files.empty}+ truncatedLabel={S.files.previewTruncated}+ unsupportedLabel={S.files.previewUnsupported}+ downloadLabel={S.files.download}resolveRef={resolveRef}treeWidth={locale === "en" ? 380 : 270}treeMaxHeight={53}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex ec08c8dc..ea0f7ffe 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -162,7 +162,7 @@ import { terminalApiSupported, subscribeTerminals } from "../terminal/terminal-limport { advancePanelTaskScope, createPanelTaskScope } from "./panel-task-scope";import { useSessionDraft } from "./use-session-draft";import { useSessionStream } from "./use-session-stream";-import { PanelsToolbar } from "./panels-toolbar";+import { DockToggles } from "./dock-toggles";import { toneInk } from "../../lib/tone";import { STAT_ICONS } from "../../lib/stat-icons";import { exitedProcessIds, reportableProcessFailure } from "./process-list";@@ -2096,7 +2096,7 @@ export function ChatPage() {placement actions and pin toggles. Every entry is a dock tab (features/dock)— the toolbar reads and drives the dock store directly; this page only feedsthe pending-approval dot. */}- <PanelsToolbar agentsPending={anySubagentPending} />+ <DockToggles agentsPending={anySubagentPending} />{/* Conversation index fallback: exactly when the gutter tick rail can't show(phones without a hover pointer; a desktop window whose gutter a docked paneldiff --git a/packages/web/src/features/chat/context-gauge.tsx b/packages/web/src/features/chat/context-gauge.tsxindex 4383c150..241d8a5b 100644--- a/packages/web/src/features/chat/context-gauge.tsx+++ b/packages/web/src/features/chat/context-gauge.tsx@@ -70,7 +70,14 @@ import { useEffect, useId, useRef, useState } from "react";import type { RefObject } from "react";import { createPortal } from "react-dom";import type { SessionContextResponse } from "@prismshadow/penguin-server/api";-import { ConfirmModal, ContextRing, Input, Legend, usePortalPanel } from "@prismshadow/penguin-ui";+import {+ ConfirmModal,+ ContextRing,+ Input,+ Legend,+ usePointerDrag,+ usePortalPanel,+} from "@prismshadow/penguin-ui";import { getSessionContext } from "../../api/endpoints";import {MIN_COMPACTION_THRESHOLD,@@ -84,7 +91,6 @@ import {} from "../../lib/context";import { formatPercent, humanizeTokens } from "../../lib/format";import { S } from "../../lib/strings";-import { usePointerDrag } from "../dock/use-pointer-drag";import { contextComposition } from "./context-parts";import type { ContextPartKey } from "./context-parts";diff --git a/packages/web/src/features/chat/dock-toggles.tsx b/packages/web/src/features/chat/dock-toggles.tsxnew file mode 100644index 00000000..8d4e5c97--- /dev/null+++ b/packages/web/src/features/chat/dock-toggles.tsx@@ -0,0 +1,65 @@+/**+ * Top-right dock switcher of the chat toolbar (Codex-style): exactly two icon toggles — pull+ * open the bottom dock, pull open the right dock — drawn by the UI package's `PanelsToolbar`+ * and bound here to the dock store. Opening a dock that has no tabs yet lands on its picker+ * (choose what to open there); everything element-specific — the tab strips, each dock's "+"+ * menu, the pickers — lives on the dock surfaces themselves (features/dock).+ *+ * The pending-approval amber dot rides the toggle of the dock that holds the agents tab+ * (the right one while the panel is closed — the default edge panels open on), keeping a+ * nested approval discoverable while the panel is off screen.+ */+import { useSyncExternalStore } from "react";+import { ICONS, PanelsToolbar } from "@prismshadow/penguin-ui";+import type { PanelsToolbarToggle } from "@prismshadow/penguin-ui";+import { S } from "../../lib/strings";+import { useShortcutTitle } from "../../lib/shortcuts/use-keymap";+import {+ dockVersion,+ isDockVisible,+ panelDock,+ subscribeDock,+ toggleDock,+ type DockPosition,+} from "../dock/dock-state";++export interface DockTogglesProps {+ /** A pending approval inside a subagent: amber dot beside the agents tab's dock toggle. */+ agentsPending: boolean;+}++export function DockToggles({ agentsPending }: DockTogglesProps) {+ useSyncExternalStore(subscribeDock, dockVersion);+ // The dot follows the agents tab's dock; with the panel closed it sits on the right+ // toggle — the edge the panel opens on.+ const pendingDock: DockPosition = panelDock("agents") ?? "right";++ const bottomTitle = useShortcutTitle(S.dock.bottomDock, "dock.toggleBottom");+ const rightTitle = useShortcutTitle(S.dock.rightDock, "dock.toggleRight");++ const toggle = (+ position: DockPosition,+ label: string,+ tooltip: string,+ glyph: string,+ ): PanelsToolbarToggle => ({+ key: position,+ label,+ tooltip,+ glyph,+ active: isDockVisible(position),+ badge: agentsPending && pendingDock === position,+ // Hiding a dock keeps every body mounted (dock-panel.tsx renders it at zero size), so a+ // tab holding unsaved work has nothing to lose and nothing to ask.+ onToggle: () => toggleDock(position),+ });++ return (+ <PanelsToolbar+ toggles={[+ toggle("bottom", S.dock.bottomDock, bottomTitle, ICONS.panelBottom),+ toggle("right", S.dock.rightDock, rightTitle, ICONS.panelRight),+ ]}+ />+ );+}diff --git a/packages/web/src/features/chat/drop-zone.tsx b/packages/web/src/features/chat/drop-zone.tsxindex 588cb667..af08fc3d 100644--- a/packages/web/src/features/chat/drop-zone.tsx+++ b/packages/web/src/features/chat/drop-zone.tsx@@ -23,10 +23,11 @@* tested against the region with `contains`, so where the pointer is decides everything and* no state accumulates (see dropRegionAction in lib/file-drop.ts for why that matters).*- * The overlay is pure feedback: `pointer-events-none` (so it never becomes the drag target- * itself and the hit test keeps seeing the real element underneath), `aria-hidden` — it- * exists only during a pointer drag, and the accessible entry point stays the "+" menu —- * and `absolute inset-0` portaled into the region, on the overlay z tier (z-50).+ * The overlay is the UI package's `DropOverlay` veil, pure feedback: `pointer-events-none` (so+ * it never becomes the drag target itself and the hit test keeps seeing the real element+ * underneath), `aria-hidden` — it exists only during a pointer drag, and the accessible entry+ * point stays the "+" menu — and `absolute inset-0` portaled into the region, on the overlay z+ * tier (z-50).** Interplay with the app-shell guard (see lib/file-drop.ts): over the chat area this* component claims the drag — preventDefault on dragover plus a copy cursor — so the guard's@@ -38,7 +39,7 @@import { createContext, useContext, useEffect, useRef, useState } from "react";import type { ReactNode } from "react";import { createPortal } from "react-dom";-import { GlyphIcon } from "@prismshadow/penguin-ui";+import { DropOverlay } from "@prismshadow/penguin-ui";import { dropRegionAction, isFileDrag } from "../../lib/file-drop";import type { DragSignal, DropRegionAction } from "../../lib/file-drop";import { S } from "../../lib/strings";@@ -135,18 +136,12 @@ export function FileDropZone({ onFiles }: { onFiles: (files: File[]) => void })if (!active || !region) return null;return createPortal(- <div- aria-hidden- className="anim-fade pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-white/70 p-6 backdrop-blur-sm dark:bg-gray-950/70"- >- <div className="flex flex-col items-center gap-2 rounded-xl border-2 border-dashed border-gray-400 bg-white/80 px-10 py-8 text-center dark:border-gray-500 dark:bg-gray-900/80">- <GlyphIcon d={PAPERCLIP_ICON} size={28} className="text-gray-400 dark:text-gray-500" />- <p className="text-base font-medium text-gray-800 dark:text-gray-100">- {S.chat.dropFilesTitle}- </p>- <p className="text-xs text-gray-500 dark:text-gray-400">{S.chat.dropFilesDesc}</p>- </div>- </div>,+ <DropOverlay+ variant="veil"+ glyph={PAPERCLIP_ICON}+ title={S.chat.dropFilesTitle}+ description={S.chat.dropFilesDesc}+ />,region,);}diff --git a/packages/web/src/features/chat/memory-view.tsx b/packages/web/src/features/chat/memory-view.tsxindex 7534b050..dbc7d52c 100644--- a/packages/web/src/features/chat/memory-view.tsx+++ b/packages/web/src/features/chat/memory-view.tsx@@ -14,11 +14,17 @@*/import { useEffect, useState } from "react";import type { SessionInfo } from "@prismshadow/penguin-server/api";-import { GlyphIcon, ICONS, ICON_SIZE, Md, SkeletonList } from "@prismshadow/penguin-ui";+import {+ GlyphIcon,+ ICONS,+ ICON_SIZE,+ Md,+ SkeletonList,+ bodyWithoutFrontmatter,+} from "@prismshadow/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { formatRelativeDate } from "../../lib/format";-import { bodyWithoutFrontmatter } from "../../lib/frontmatter";import type { MemoryChangeRow, MemoryLocateTarget } from "../../lib/omni/memory-changes";import { memoryRowKey } from "../../lib/omni/memory-changes";import { useLocale } from "../../state/locale";diff --git a/packages/web/src/features/chat/panels-toolbar.tsx b/packages/web/src/features/chat/panels-toolbar.tsxdeleted file mode 100644index e4cfcdf2..00000000--- a/packages/web/src/features/chat/panels-toolbar.tsx+++ /dev/null@@ -1,74 +0,0 @@-/**- * Top-right dock switcher of the chat toolbar (Codex-style): exactly two icon buttons —- * pull open the bottom dock, pull open the right dock. Opening a dock that has no tabs- * yet lands on its picker (choose what to open there); everything element-specific — the- * tab strips, each dock's "+" menu, the pickers — lives on the dock surfaces themselves- * (features/dock), so this component stays two toggles.- *- * The pending-approval amber dot rides the button of the dock that holds the agents tab- * (the right one while the panel is closed — the default edge panels open on), keeping a- * nested approval discoverable while the panel is off screen.- */-import { useSyncExternalStore } from "react";-import { GlyphIcon, ICONS, ICON_SIZE } from "@prismshadow/penguin-ui";-import { S } from "../../lib/strings";-import { useShortcutTitle } from "../../lib/shortcuts/use-keymap";-import { toneDot } from "../../lib/tone";-import {- dockVersion,- isDockVisible,- panelDock,- subscribeDock,- toggleDock,- type DockPosition,-} from "../dock/dock-state";--export interface PanelsToolbarProps {- /** A pending approval inside a subagent: amber dot beside the agents tab's dock button. */- agentsPending: boolean;-}--const triggerClass = (active: boolean) =>- `relative flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${- active- ? "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"- : "text-gray-500 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- }`;--export function PanelsToolbar({ agentsPending }: PanelsToolbarProps) {- useSyncExternalStore(subscribeDock, dockVersion);- // The dot follows the agents tab's dock; with the panel closed it sits on the right- // button — the edge the panel opens on.- const pendingDock: DockPosition = panelDock("agents") ?? "right";-- const bottomTitle = useShortcutTitle(S.dock.bottomDock, "dock.toggleBottom");- const rightTitle = useShortcutTitle(S.dock.rightDock, "dock.toggleRight");- const toggles: Array<{ position: DockPosition; label: string; title: string; icon: string }> = [- { position: "bottom", label: S.dock.bottomDock, title: bottomTitle, icon: ICONS.panelBottom },- { position: "right", label: S.dock.rightDock, title: rightTitle, icon: ICONS.panelRight },- ];-- return (- <div className="flex shrink-0 items-center gap-1" data-testid="panels-toolbar">- {toggles.map(({ position, label, title, icon }) => (- <button- key={position}- type="button"- aria-expanded={isDockVisible(position)}- // Hiding a dock keeps every body mounted (dock-panel.tsx renders it at zero- // size), so a tab holding unsaved work has nothing to lose and nothing to ask.- onClick={() => toggleDock(position)}- data-tooltip={title}- aria-label={label}- data-testid={`dock-toggle-${position}`}- className={triggerClass(isDockVisible(position))}- >- <GlyphIcon d={icon} size={ICON_SIZE.iconButton} />- {agentsPending && pendingDock === position && (- <span aria-hidden className={`h-1.5 w-1.5 rounded-full ${toneDot.attention}`} />- )}- </button>- ))}- </div>- );-}diff --git a/packages/web/src/features/chat/shortcuts-folder.tsx b/packages/web/src/features/chat/shortcuts-folder.tsxindex 2763df7f..8fff8374 100644--- a/packages/web/src/features/chat/shortcuts-folder.tsx+++ b/packages/web/src/features/chat/shortcuts-folder.tsx@@ -170,7 +170,7 @@ export function ShortcutsFolder({folder's height plus the New-shortcut row. */<div className="mt-0.5 pl-4">{loaded && (- <ul className="space-y-0.5">+ <ul className="space-y-1">{shortcuts.map((shortcut) => (<li key={shortcut.id} className="flex items-center gap-1"><buttondiff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex e0457ddc..ccf17e06 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -29,16 +29,14 @@* 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.+ *+ * This file is the container: it lists, fetches, edits, uploads and guards. What the panel looks+ * like is the UI package's — the tree pane (`TreePane` over `FileTree`), the preview pane+ * (`PreviewPane`, with `WorkspaceFileEditor` in it while a file is edited), the draggable split+ * between them (`SplitPane`), the path strip (`Breadcrumbs`), the drop feedback (`DropOverlay`)+ * and the file menu's rows (`WorkspaceFileMenuRows`).*/-import {- Fragment,- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import type {ChangeEvent,DragEvent as ReactDragEvent,@@ -47,28 +45,29 @@ import type {PointerEvent as ReactPointerEvent,} from "react";import {+ Breadcrumbs,Button,CloseIcon,- CodeSurface,ConfirmModal,CopiedStatus,CopyCheckGlyph,+ DropOverlay,Dropdown,- EmptyState,GlyphIcon,HiddenFileInput,ICONS,ICON_SIZE,Input,- Prose,- SearchInput,- SkeletonList,+ PreviewPane,+ SplitPane,Spinner,Tooltip,- ZoomableImage,+ TreePane,+ WorkspaceFileEditor,+ WorkspaceFileMenuRows,isContextMenuKey,isLongPressPointer,- languageForExtension,+ languageForFileName,noAutofill,toastError,toastInfo,@@ -76,6 +75,12 @@ import {useCopied,useRowContextMenu,} from "@prismshadow/penguin-ui";+import type {+ FileMenuTarget,+ PreviewView,+ TreeToggle,+ WorkspaceFileMenuLabels,+} from "@prismshadow/penguin-ui";import type { SessionInfo, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";@@ -84,15 +89,16 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { isDesktopShellWindow } from "../../lib/account-menu";import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";+import { isShortcut } from "../../lib/shortcuts/match";+import { currentPlatform } from "../../lib/shortcuts/platform";+import { keymap } from "../../lib/shortcuts/store";import { joinWorkspacePath } from "../../lib/file-path";import { writeClipboard } from "../../lib/clipboard";import { dropRegionAction, isFileDrag } from "../../lib/file-drop";import type { DragSignal } from "../../lib/file-drop";import { MB_BYTES, splitBySize } from "../../lib/upload-limits";import {- CRUMB_ELLIPSIS,TEXT_PREVIEW_LIMIT,- TREE_DIVIDER_PX,TREE_MIN_WIDTH,WORKSPACE_UPLOAD_LIMIT_MB,ancestorDirs,@@ -102,7 +108,6 @@ import {defaultTreeWidth,dropTargetDir,expandTo,- extOf,searchRows,flattenTree,isDirty,@@ -117,10 +122,8 @@ import {readTreeVisible,readTreeWidth,selectionBlock,- splitFileName,upsertEntry,utf8Complete,- visibleCrumbSegments,withExpanded,writeWrapLines,writeTreeVisible,@@ -132,14 +135,8 @@ 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 { 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";/*** Above this, a Markdown file opens in the source view rather than rendered. Highlighting moved to@@ -410,27 +407,6 @@ function pickDroppedFiles(data: DataTransfer): { files: File[]; dirs: string[] }return files.length + dirs.length > 0 ? { files, dirs } : { files: [...data.files], dirs };}-/** ArrowLeft / ArrowRight on the focused divider, in px: coarse enough to get somewhere, fine enough to land. */-const TREE_WIDTH_STEP = 16;--/**- * A breadcrumb item's rendered width, approximated: the toolbar has no text metrics to- * measure against, so one character at the toolbar's text size costs CRUMB_CHAR_PX (a- * wide character — CJK, full-width punctuation — two of those) and the item itself costs- * its padding plus the separator drawn before it. Erring wide is the safe direction: it- * collapses one segment early rather than letting the row outgrow its space.- */-const CRUMB_CHAR_PX = 7;-const CRUMB_ITEM_PX = 16;-const WIDE_CHAR_RE =- /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe6f\uff00-\uff60\uffe0-\uffe6]/;--function crumbItemWidth(text: string): number {- let cells = 0;- for (const ch of text) cells += WIDE_CHAR_RE.test(ch) ? 2 : 1;- return CRUMB_ITEM_PX + cells * CRUMB_CHAR_PX;-}-/*** 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@@ -570,16 +546,8 @@ export function WorkspaceBrowser({});// ----------------------------------------------------------------------------- chromeconst [treeVisible, setTreeVisible] = useState(() => readTreeVisible());- /**- * True for the length of the show/hide transition and only then. The pane's width is also- * the panel's own size talking — dragging the divider, or the dock's edge, moves it too —- * and a transition left permanently on would make those drags lag a fifth of a second- * behind the pointer. The toggle arms it; the timer below disarms it.- */- const [treeSliding, setTreeSliding] = useState(false);/** The dragged tree width, or null while the user has never dragged it (the computed default stands). */const [treeWidthPref, setTreeWidthPref] = useState<number | null>(() => readTreeWidth());- const [resizingTree, setResizingTree] = useState(false);/** Soft wrap, shared by the source view and the editor so Edit reflows nothing (see parseWrapLines). */const [wrapLines, setWrapLines] = useState(() => readWrapLines());/**@@ -589,11 +557,7 @@ export function WorkspaceBrowser({*/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@@ -683,33 +647,9 @@ export function WorkspaceBrowser({}, []);const narrow = isNarrowLayout(width);- // The breadcrumb strip is measured separately: how much room it has is what the- // toolbar's actions leave over, which the panel's own width does not say.- useLayoutEffect(() => {- const el = crumbsRef.current;- if (!el) return;- const measure = () => setCrumbsWidth(Math.round(el.getBoundingClientRect().width));- measure();- const observer = new ResizeObserver(measure);- observer.observe(el);- return () => observer.disconnect();- }, []);-// The tree pane's width: dragged if it ever was, otherwise the computed default, and// either way within the bounds this panel width allows.const treeWidth = clampTreeWidth(treeWidthPref ?? defaultTreeWidth(width), width);- const treeWidthRef = useRef(treeWidth);- treeWidthRef.current = treeWidth;-- // The show/hide transition's window: the toggle arms it, this disarms it once the slide- // has played (toggling again mid-slide restarts the timer). DOCK_TRANSITION_MS is the- // dock's own expand/collapse duration — the pane moves with the same motion — and the- // duration-200 class on the sliding container has to match it.- useEffect(() => {- if (!treeSliding) return;- const timer = window.setTimeout(() => setTreeSliding(false), DOCK_TRANSITION_MS);- return () => window.clearTimeout(timer);- }, [treeSliding, treeVisible]);// --------------------------------------------------------------------------- loading@@ -1238,7 +1178,6 @@ export function WorkspaceBrowser({const setTree = (visible: boolean): void => {setTreeVisible(visible);- setTreeSliding(true);writeTreeVisible(visible);};@@ -1247,39 +1186,6 @@ export function WorkspaceBrowser({writeWrapLines(wrap);};- // ------------------------------------------------------------------------- tree width- // The divider between the two panes. The width follows the pointer against the tree- // pane's own left edge rather than an accumulated delta, so a drag that outruns the- // clamp comes back in step instead of offset by however far it overshot.- const treeResizeProps = usePointerDrag<object>({- threshold: 0,- begin: (event) => {- event.preventDefault(); // no text selection while the divider is dragged- setResizingTree(true);- return {};- },- onMove: (event) => {- const rect = treePaneRef.current?.getBoundingClientRect();- if (!rect) return;- setTreeWidthPref(clampTreeWidth(event.clientX - rect.left, width));- },- onEnd: () => {- setResizingTree(false);- writeTreeWidth(treeWidthRef.current); // once per drag, not per frame- },- onCancel: () => setResizingTree(false),- });-- const onDividerKey = (e: ReactKeyboardEvent<HTMLDivElement>): void => {- const delta =- e.key === "ArrowLeft" ? -TREE_WIDTH_STEP : e.key === "ArrowRight" ? TREE_WIDTH_STEP : 0;- if (delta === 0) return;- e.preventDefault();- const next = clampTreeWidth(treeWidthRef.current + delta, width);- setTreeWidthPref(next);- writeTreeWidth(next);- };-// ----------------------------------------------------------------------------- editingconst startEdit = async (): Promise<void> => {@@ -1632,7 +1538,7 @@ export function WorkspaceBrowser({path: p.path,text: selectionBlock({path: p.path,- language: languageForExtension(extOf(p.name)),+ language: languageForFileName(p.name),selection: selection.text,fromLine: selection.fromLine,toLine: selection.toLine,@@ -1706,25 +1612,15 @@ export function WorkspaceBrowser({/*** 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.+ * two rows spent a whole line of a panel that can be very narrow saying it twice. The strip+ * 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 =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.- const crumbFit = visibleCrumbSegments(- crumbSegments,- crumbsWidth > 0 ? crumbsWidth : Number.POSITIVE_INFINITY,- crumbItemWidth,- );const showTree = narrow ? selectedPath === null : treeVisible;- const showPreview = narrow ? selectedPath !== null : true;const canEdit = preview !== null && editor === null && canEditPreview(preview);/** The source view is on screen: a text file, or Markdown/HTML with the toggle on Source. */const sourceShown =@@ -1742,164 +1638,135 @@ export function WorkspaceBrowser({? S.files.openInNewTab: `${S.files.openInNewTab}: ${S.files.previewNotIsolatedHint}`;const dirLabel = (dir: string): string => (dir === "" ? S.files.root : dir);+ const fileMenuLabels: WorkspaceFileMenuLabels = {+ copyPath: S.files.copyPath,+ addToChat: S.files.addToChat,+ addSelectionToChat: S.files.addSelectionToChat,+ uploadHere: S.files.uploadHere,+ download: S.files.download,+ rename: S.files.renameTitle,+ delete: S.common.delete,+ };+ // The tree pane: its body says, in order, that the root listing failed, that it is on its way,+ // that a search failed, and that a search's answer has not arrived yet — an empty list there+ // would read as "nothing matches", the one answer that must not be guessed.const tree = (- <div- ref={treePaneRef}+ <TreePane{...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 }}- >- {/* 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">- <SearchInput- variant="panel"- className="min-w-0 flex-1"- value={query}- onChange={setQuery}- placeholder={S.files.searchPlaceholder}- aria-label={S.files.searchPlaceholder}- clearLabel={S.files.searchClear}- />- <Tooltip label={S.files.refresh} placement="bottom" className="shrink-0">- <button- type="button"- aria-label={S.files.refresh}- onClick={refreshAll}- className={iconActionClass}- >- <GlyphIcon d={ICONS.refresh} 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 ? (- <Spinner size="sm" label={uploadLabel} />- ) : (- <GlyphIcon d={ICONS.upload} 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>- ) : (+ search={{+ value: query,+ onChange: setQuery,+ placeholder: S.files.searchPlaceholder,+ clearLabel: S.files.searchClear,+ }}+ actions={<>- <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>- )}+ <Tooltip label={S.files.refresh} placement="bottom" className="shrink-0">+ <button+ type="button"+ aria-label={S.files.refresh}+ onClick={refreshAll}+ className={iconActionClass}+ >+ <GlyphIcon d={ICONS.refresh} 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 ? (+ <Spinner size="sm" label={uploadLabel} />+ ) : (+ <GlyphIcon d={ICONS.upload} size={ICON_SIZE.iconButton} />+ )}+ </label>+ </Tooltip></>- )}- {/* 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>- );-- // The divider: a real layout sibling, so the two panes always add up to the panel.- const treeDivider = (- <div- role="separator"- aria-orientation="vertical"- aria-label={S.files.treeWidth}- aria-valuenow={treeWidth}- aria-valuemin={TREE_MIN_WIDTH}- // Before the first measurement there is no ceiling yet (clampTreeWidth applies none),- // so the current width is the honest maximum for that frame.- aria-valuemax={Math.max(maxTreeWidth(width), treeWidth)}- data-tooltip={S.files.treeWidth}- tabIndex={0}- {...treeResizeProps}- onKeyDown={onDividerKey}- className={`w-1.5 shrink-0 cursor-col-resize outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/60 ${- resizingTree- ? "bg-gray-300 dark:bg-gray-600"- : "bg-transparent hover:bg-gray-200 dark:hover:bg-gray-700"- }`}- />+ }+ error={rootError ?? (rootListing === undefined ? null : searchError)}+ loading={rootError === null && rootListing === undefined}+ pending={filter !== "" && searchResult === null ? S.files.searching : null}+ note={+ searchResult?.truncated === true ? S.files.searchTruncated(searchResult.hits.length) : null+ }+ // The row menu. The anchor is the point the gesture landed on rather than any element of+ // the pane, and the panel is portaled (the same shape the sidebar's session row uses).+ menu={+ 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}+ labels={fileMenuLabels}+ downloadHref={(path) => api.workspaceFileUrl(sessionId, path, true)}+ downloadName={baseName}+ onCopyPath={(t) => {+ closeTreeMenu();+ copyPath(t);+ }}+ onAddToChat={(t) => {+ closeTreeMenu();+ addToChat(t);+ }}+ onUploadInto={(dir) => {+ closeTreeMenu();+ uploadInto(dir);+ }}+ onRename={(t) => {+ closeTreeMenu();+ beginFileAction(t.path, "rename");+ }}+ onDelete={(t) => {+ closeTreeMenu();+ beginFileAction(t.path, "delete");+ }}+ onClose={closeTreeMenu}+ />+ </Dropdown>+ )+ }+ >+ <WorkspaceTreeView+ rows={rows}+ selectedPath={selectedPath}+ currentDir={currentDir}+ loadingDirs={loadingDirs}+ dropTargetDir={drag.active ? drag.targetDir : null}+ scrollTo={scrollTo}+ rootEmpty={rootListing !== undefined && rootListing.length === 0}+ filtering={filter !== ""}+ toggled={filter === "" ? toggled : null}+ onToggleDir={filter === "" ? toggleDir : openDirFromSearch}+ onOpenFile={openFile}+ />+ </TreePane>);/**@@ -1922,7 +1789,7 @@ export function WorkspaceBrowser({);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">+ <div className="flex shrink-0 rounded-md bg-gray-100 p-px dark:bg-gray-800">{([["rendered", S.files.htmlRendered],@@ -1947,18 +1814,14 @@ export function WorkspaceBrowser({);/**- * 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.+ * Copy and Edit, floated over the top-right of the file rather than parked in the title row+ * (PreviewPane draws the pill). 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.*/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 itstextarea over that same surface — so it rides here in both modes, which is alsothe only place the editor can reach it from. */}@@ -2014,281 +1877,157 @@ export function WorkspaceBrowser({</a></Tooltip>)}- </div>+ </>);- const previewBody = (p: Preview) => {- if (editor !== null && editor.path === p.path) {- return (- <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}+ /** A part of the view still on its way, or the fetch that failed to bring it. */+ const pendingSource = (): PreviewView =>+ sourceError !== null ? { kind: "error", message: sourceError } : { kind: "loading" };++ /** What the preview pane draws for the file on screen. */+ const previewViewOf = (p: Preview): PreviewView => {+ const truncatedNote = p.truncated === true ? S.files.previewTruncated : undefined;+ if (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.+ return {+ kind: "image",+ src: api.workspaceFileUrl(sessionId, p.path),+ alt: p.name,+ reloadKey: p.nonce,+ };+ }+ if (p.kind === "pdf") {+ return {+ kind: "pdf",+ src: api.workspaceFileUrl(sessionId, p.path),+ title: p.name,+ reloadKey: p.nonce,+ };+ }+ if (p.kind === "html" && richView === "rendered") {+ if (previewIsolated) {+ return {+ kind: "embed",+ node: (+ // 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"/>- </div>- {previewFloatingActions}- </div>- );+ ),+ };+ }+ // Only reachable without content when previewIsolated flipped to false after an+ // isolated preview mounted without it: the lazy source effect is already fetching it,+ // and the srcDoc fallback renders once it lands.+ if (p.content === undefined) return pendingSource();+ return {+ kind: "embed",+ node: (+ // 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"+ />+ ),+ };}- const selection = menuSelection;- return (- <>- {/* 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: the reading box and pipeline message bodies use- // (static HTML with no script execution surface, so no iframe sandbox is needed),- // with the image and link adapters swapped for ones that know the Workspace.- <>- <Prose- text={p.content ?? ""}- className="text-base leading-relaxed text-gray-800 dark:text-gray-100"- 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.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>- )}- </>- )- ) : (- <p className="text-sm text-gray-500 dark:text-gray-400">- {S.files.previewUnsupported}- </p>- )}- </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);- }+ if (p.kind === "md" && richView === "rendered") {+ // Markdown's default rendered view: the reading box and pipeline message bodies use+ // (static HTML with no script execution surface, so no iframe sandbox is needed), with+ // the image and link adapters swapped for ones that know the Workspace.+ return {+ kind: "markdown",+ text: p.content ?? "",+ truncatedNote,+ 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>;}- onRename={(t) => {- previewMenu.close();- beginFileAction(t.path, "rename");- }}- onDelete={(t) => {- previewMenu.close();- beginFileAction(t.path, "delete");- }}- onClose={previewMenu.close}- />- </Dropdown>- </>- );+ 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>+ );+ },+ },+ };+ }+ if (p.kind === "text" || p.kind === "html" || p.kind === "md") {+ // Isolated HTML reaches the Source view before its lazy fetch lands: a skeleton (or the+ // fetch's own error) — toggling back to Rendered is unaffected, and re-entering Source+ // retries the fetch.+ if (p.content === undefined) return pendingSource();+ // 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.+ return {+ kind: "source",+ code: p.content,+ language: languageForFileName(p.name),+ wrap: wrapLines,+ truncatedNote,+ };+ }+ return { kind: "unsupported", message: S.files.previewUnsupported };};/**@@ -2380,25 +2119,124 @@ export function WorkspaceBrowser({</>));- const previewPane = (- <div className="flex min-h-0 min-w-0 flex-1 flex-col">- {selectedPath === null ? (- <EmptyState- title={S.files.selectFile}- action={+ /** The preview on screen: the loaded file, once it is the one the tree has selected. */+ const shown = preview !== null && preview.path === selectedPath ? preview : null;+ const editing = shown !== null && editor !== null && editor.path === shown.path ? editor : null;+ const previewView: PreviewView =+ selectedPath === null+ ? {+ kind: "empty",+ title: S.files.selectFile,+ action:!treeVisible && !narrow ? (<Button size="sm" onClick={() => setTree(true)}>{S.files.showTree}</Button>- ) : undefined- }- />- ) : preview === null || preview.path !== selectedPath ? (- <SkeletonList rows={6} />- ) : (- previewBody(preview)- )}- </div>+ ) : undefined,+ }+ : shown === null+ ? { kind: "opening" }+ : previewViewOf(shown);+ const selection = menuSelection;++ const previewPane = (+ <PreviewPane+ view={previewView}+ actions={previewFloatingActions}+ editor={+ editing !== null && (+ <WorkspaceFileEditor+ path={editing.path}+ value={editing.draft}+ label={S.files.editorLabel(baseName(editing.path))}+ wrap={wrapLines}+ // 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.+ highlight={editing.draft.length <= TEXT_PREVIEW_LIMIT}+ onChange={updateDraft}+ onSave={requestSave}+ // The editor.save binding (⌘S / Ctrl+S by default), read from the keymap at the+ // keystroke so a rebinding in the settings takes effect without a remount.+ isSaveKey={(event) => isShortcut(event, keymap(), "editor.save", currentPlatform())}+ />+ )+ }+ bodyRef={(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);+ }}+ bodyProps={{+ 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,+ }}+ // 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.+ menu={+ shown !== null && (+ <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: shown.path, kind: "file" }}+ labels={fileMenuLabels}+ 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(shown, selection);+ }+ }+ onRename={(t) => {+ previewMenu.close();+ beginFileAction(t.path, "rename");+ }}+ onDelete={(t) => {+ previewMenu.close();+ beginFileAction(t.path, "delete");+ }}+ onClose={previewMenu.close}+ />+ </Dropdown>+ )+ }+ />);return (@@ -2449,81 +2287,52 @@ export function WorkspaceBrowser({)}{/* The path, read out and not navigable: the tree beside it is what navigates, and asecond way in would only be a second thing to keep in step with the editor's- unsaved-changes guard. */}- <div- ref={crumbsRef}- data-tooltip={crumbPath}- className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden px-1 text-sm"- >- {crumbFit.collapsed && (- <span className="shrink-0 text-gray-400 dark:text-gray-500">{CRUMB_ELLIPSIS}</span>- )}- {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>+ unsaved-changes guard. `flex-1` over a zero basis, so the strip measures the room+ the actions leave it and never its own content. */}+ <Breadcrumbs+ className="flex-1"+ items={crumbSegments.map((label) => ({ label }))}+ title={crumbPath}+ />{fileRowActions}</div><div className="relative flex min-h-0 flex-1">- {/* Narrow: one column, tree or preview. */}- {narrow && showTree && tree}- {/* Wide: the tree and its divider stay mounted and slide in and out of the panel's- left edge, on the same 200ms width transition the dock itself expands and- collapses with. Both keep their own width inside the clipping window, so the tree- does not reflow as it moves; the preview beside it takes the room it leaves.- inert while away — a pane at zero width is not somewhere to tab into. */}- {!narrow && (- <div- aria-hidden={!treeVisible}- inert={!treeVisible}- style={{ width: treeVisible ? treeWidth + TREE_DIVIDER_PX : 0 }}- className={`flex min-h-0 shrink-0 overflow-hidden ${- treeSliding ? "transition-[width] duration-200" : ""- }`}- >- {tree}- {treeDivider}- </div>+ {narrow ? (+ // Narrow: one column, tree or preview.+ showTree ? (+ tree+ ) : (+ previewPane+ )+ ) : (+ // Wide: the tree and the handle beside it stay mounted and slide in and out of the+ // panel's left edge, and the preview takes the room they leave.+ <SplitPane+ className="min-w-0 flex-1"+ size={treeWidth}+ min={TREE_MIN_WIDTH}+ // Before the first measurement there is no ceiling yet (clampTreeWidth applies+ // none), so the current width is the honest maximum for that frame.+ max={Math.max(maxTreeWidth(width), treeWidth)}+ label={S.files.treeWidth}+ collapsed={!treeVisible}+ onResize={(px) => setTreeWidthPref(clampTreeWidth(px, width))}+ // Once per drag or key press, not per frame.+ onResizeEnd={(px) => writeTreeWidth(clampTreeWidth(px, width))}+ first={tree}+ second={previewPane}+ />)}- {showPreview && previewPane}{/* Drop feedback: a dashed frame over the panel and a label naming the directory the- files will land in. Pure feedback — pointer-events-none keeps the hit test on the- rows underneath, which is how a folder row can be the target. */}+ files will land in. Pure feedback — it keeps the hit test on the rows underneath,+ which is how a folder row can be the target. */}{drag.active && (- <div- aria-hidden- className="anim-fade pointer-events-none absolute inset-0 z-20 flex items-end justify-center p-3"- >- <div className="absolute inset-1 rounded-lg border-2 border-dashed border-gray-400 bg-white/40 dark:border-gray-500 dark:bg-gray-950/40" />- <div className="relative flex items-center gap-2 rounded-md border border-gray-300 bg-white/95 px-3 py-1.5 text-xs font-medium text-gray-800 shadow-sm dark:border-gray-700 dark:bg-gray-900/95 dark:text-gray-100">- <GlyphIcon d={PAPERCLIP_ICON} size={ICON_SIZE.rowLead} className="text-gray-400" />- <span className="truncate">{S.files.dropToUpload(dirLabel(drag.targetDir))}</span>- </div>- </div>+ <DropOverlay+ variant="frame"+ glyph={PAPERCLIP_ICON}+ title={S.files.dropToUpload(dirLabel(drag.targetDir))}+ />)}</div>diff --git a/packages/web/src/features/chat/workspace-tree-view.tsx b/packages/web/src/features/chat/workspace-tree-view.tsxindex 484ca88a..0dc22a99 100644--- a/packages/web/src/features/chat/workspace-tree-view.tsx+++ b/packages/web/src/features/chat/workspace-tree-view.tsx@@ -1,15 +1,15 @@/**- * The Files panel's directory tree: the shared `FileTree` over the rows lib/workspace-tree.ts- * flattens out of the lazily fetched listings. What this file adds is what only the Workspace- * has — the size and modified time in a row's tooltip and after its name, the directory- * uploads land in standing in for a selection while no file is open, and the three things an- * empty row list can mean.+ * The Files panel's directory tree: the UI package's `FileTree` over the rows+ * lib/workspace-tree.ts flattens out of the lazily fetched listings. What this file adds is what+ * only the Workspace has — the size and modified time in a row's tooltip and after its name, the+ * directory uploads land in standing in for a selection while no file is open, and the three+ * things an empty row list can mean.*/+import { FileTree } from "@prismshadow/penguin-ui";+import type { TreeToggle } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { formatBytes, formatDateTime } from "../../lib/format";import type { TreeRow } from "../../lib/workspace-tree";-import { FileTree } from "../../components/ui/file-tree";-import type { TreeToggle } from "../../components/ui/file-tree";export function WorkspaceTreeView({rows,@@ -61,7 +61,7 @@ export function WorkspaceTreeView({}rowTrailing={(row) =>row.kind === "file" && (- <span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">+ <span className="shrink-0 font-mono text-xs text-fg-subtle">{formatBytes(row.sizeBytes)}</span>)@@ -72,9 +72,9 @@ export function WorkspaceTreeView({onOpenFile={onOpenFile}>{filtering ? (- <p className="px-3 py-2 text-sm text-gray-400">{S.files.searchNoMatch}</p>+ <p className="px-3 py-2 text-sm text-fg-subtle">{S.files.searchNoMatch}</p>) : rootEmpty ? (- <p className="px-3 py-2 text-sm text-gray-400">{S.files.empty}</p>+ <p className="px-3 py-2 text-sm text-fg-subtle">{S.files.empty}</p>) : null}</FileTree>);diff --git a/packages/web/src/features/company/channel-sidebar.tsx b/packages/web/src/features/company/channel-sidebar.tsxindex ea593d58..af45a8a2 100644--- a/packages/web/src/features/company/channel-sidebar.tsx+++ b/packages/web/src/features/company/channel-sidebar.tsx@@ -22,9 +22,11 @@ import {GlyphIcon,ICON_GAP,ICON_SIZE,+ NAV_FILL,PlusIcon,SkeletonList,Text,+ railItemClass,toastError,toastSuccess,} from "@prismshadow/penguin-ui";@@ -126,7 +128,9 @@ function ChannelRow({const note = badgeNote(channel);const unread = channel.unread > 0;return (- <li className="group relative flex items-center rounded-md transition-colors duration-150 hover:bg-gray-200/50 dark:hover:bg-gray-800/70">+ <li+ className={`group relative flex items-center rounded-md transition-colors duration-150 ${NAV_FILL.hover}`}+ ><NavLinkto={orgChannelPath(projectId, orgId, channel.channelId)}onClick={() => onNavigate?.()}@@ -135,7 +139,7 @@ function ChannelRow({className={({ isActive }) =>`flex min-w-0 flex-1 items-center ${ICON_GAP.row} rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${isActive- ? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ ? `${NAV_FILL.selected} font-medium text-gray-900 dark:text-gray-100`: unread? "font-medium text-gray-900 dark:text-gray-100": "text-gray-600 dark:text-gray-400"@@ -326,13 +330,7 @@ export function ChannelRailRows({ projectId, orgId }: { projectId: string; orgIddata-tooltip={name}data-tooltip-placement="right"aria-label={name}- className={({ isActive }) =>- `relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 ${- isActive- ? "bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-500 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- }`- }+ className={({ isActive }) => railItemClass({ active: isActive })}><GlyphIcon d={channelGlyph(channel.channelId)} size={18} />{channel.unread > 0 && (diff --git a/packages/web/src/features/company/handbook-explorer.tsx b/packages/web/src/features/company/handbook-explorer.tsxindex 72f8b514..d194b970 100644--- a/packages/web/src/features/company/handbook-explorer.tsx+++ b/packages/web/src/features/company/handbook-explorer.tsx@@ -17,11 +17,11 @@* the page expands the ones above the selected document.*/import type { OrgHandbookFile } from "@prismshadow/penguin-server/api";+import { FileTree } from "@prismshadow/penguin-ui";+import type { TreeToggle } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { formatBytes, formatDateTime, formatRelativeShort } from "../../lib/format";import type { Locale } from "../../state/locale";-import { FileTree } from "../../components/ui/file-tree";-import type { TreeToggle } from "../../components/ui/file-tree";import type { HandbookRow } from "./handbook-tree";/** Collapse-all mark (lucide chevrons-down-up): two chevrons closing on each other. */diff --git a/packages/web/src/features/company/handbook-page.tsx b/packages/web/src/features/company/handbook-page.tsxindex 1d4470b1..fb5f39b2 100644--- a/packages/web/src/features/company/handbook-page.tsx+++ b/packages/web/src/features/company/handbook-page.tsx@@ -37,6 +37,7 @@ import {toastError,toastSuccess,} from "@prismshadow/penguin-ui";+import type { TreeToggle } from "@prismshadow/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";@@ -47,7 +48,6 @@ import { keymap } from "../../lib/shortcuts/store";import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";import { useDocumentTitle } from "../../lib/use-document-title";import { useLocale } from "../../state/locale";-import type { TreeToggle } from "../../components/ui/file-tree";import { OrgEmptyLine, OrgPage, useOrg } from "./org-layout";import { ErrorLine } from "./shared";import { COLLAPSE_ALL_ICON, HandbookExplorer } from "./handbook-explorer";diff --git a/packages/web/src/features/company/handbook-tree.ts b/packages/web/src/features/company/handbook-tree.tsindex ae371f3d..46c3a766 100644--- a/packages/web/src/features/company/handbook-tree.ts+++ b/packages/web/src/features/company/handbook-tree.ts@@ -8,7 +8,7 @@* relative link inside one document resolves to another document of the handbook.*/import type { OrgHandbookFile } from "@prismshadow/penguin-server/api";-import type { FileTreeRow } from "../../lib/file-tree";+import type { FileTreeRow } from "@prismshadow/penguin-ui";/** The index, `handbook/README.md`: pinned first in the list, and the one file that cannot be deleted. */export const HANDBOOK_INDEX = "README.md";diff --git a/packages/web/src/features/company/org-chart-page.tsx b/packages/web/src/features/company/org-chart-page.tsxindex 29b7379d..0962292b 100644--- a/packages/web/src/features/company/org-chart-page.tsx+++ b/packages/web/src/features/company/org-chart-page.tsx@@ -41,6 +41,7 @@ import {Notice,toastError,toastSuccess,+ usePointerDrag,} from "@prismshadow/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";@@ -50,7 +51,6 @@ import { toneInk } from "../../lib/tone";import { useCompany } from "../../state/company";import { useLiveSessionStatuses } from "../../state/sessions";import { useTheme } from "../../state/theme";-import { usePointerDrag } from "../dock/use-pointer-drag";import { OrgPage, OrgPageSkeleton, useOrg } from "./org-layout";import { orgKey } from "./company-nav";import { liveEmployeeStates } from "./org-sessions";diff --git a/packages/web/src/features/company/org-session-groups.tsx b/packages/web/src/features/company/org-session-groups.tsxindex 69acdaa9..95dfd77a 100644--- a/packages/web/src/features/company/org-session-groups.tsx+++ b/packages/web/src/features/company/org-session-groups.tsx@@ -39,7 +39,10 @@ import {ICONS,ICON_GAP,ICON_SIZE,+ NAV_FILL,+ RailDivider,SkeletonList,+ railItemClass,toastError,toastSuccess,useRowContextMenu,@@ -81,7 +84,7 @@ import type { TempSessionRow } from "./temp-session";*/const rowSurface = (active: boolean) =>`group flex select-none items-center rounded-md pr-1 transition-colors duration-150 ${- active ? "bg-gray-200/70 dark:bg-gray-800" : "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"+ active ? NAV_FILL.selected : NAV_FILL.hover}`;/** The row's own button, at the channel rows' density so the whole sidebar reads as one list. */@@ -381,7 +384,7 @@ export function TempSessionRailRows({ projectId, orgId }: { projectId: string; oif (rows.length === 0) return null;return (<>- <span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" />+ <RailDivider />{rows.map((row) => {const entry = S.company.sessionList.temporaryEntry(row.title);const name = row.activity !== null ? `${entry} · ${S.company.sessionList.running}` : entry;@@ -392,7 +395,7 @@ export function TempSessionRailRows({ projectId, orgId }: { projectId: string; odata-tooltip={name}aria-label={name}onClick={() => openSession(row.sessionId, row.agentId)}- className="relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"+ className={railItemClass()}><AgentAvatar id={row.agentId} name={row.name} size={18} className="rounded" />{row.activity !== null && (@@ -543,7 +546,7 @@ export function DeskRailRows({ projectId, orgId }: { projectId: string; orgId: saria-label={name}disabled={opening === d.agentId}onClick={() => void openDesk(d.agentId, d.sessionId)}- className="relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 hover:bg-gray-200/70 disabled:opacity-60 dark:hover:bg-gray-800"+ className={`${railItemClass()} disabled:opacity-60`}><AgentAvatar id={d.agentId} name={d.name} size={18} className="rounded" />{running && (diff --git a/packages/web/src/features/dock/dock-drag.tsx b/packages/web/src/features/dock/dock-drag.tsxindex 11a23acc..3ef4ec80 100644--- a/packages/web/src/features/dock/dock-drag.tsx+++ b/packages/web/src/features/dock/dock-drag.tsx@@ -86,7 +86,7 @@ function DropTarget(props: {<divdata-dock-pos={props.position}data-testid="dock-layout-target"- className={`${props.shape} rounded-[3px] border transition-colors duration-100 ${+ className={`${props.shape} rounded-[3px] border transition-colors duration-150 ${active? "border-sky-400 bg-sky-500/60": "border-gray-400/70 bg-gray-500/10 dark:border-white/30 dark:bg-white/10"@@ -121,7 +121,7 @@ export function DockDragOverlay({ candidate }: { candidate: DockPosition | null{/* Drop-target widget, kept a comfortable margin off the host's corner. */}<divdata-testid="dock-layout-widget"- className="fixed z-[70] flex items-center gap-1.5 rounded-lg border border-gray-300 bg-white/95 p-2.5 shadow-lg dark:border-white/20 dark:bg-gray-900/90"+ className="fixed z-[70] flex items-center gap-1.5 rounded-lg border border-gray-300 bg-white/95 p-2 shadow-lg dark:border-white/20 dark:bg-gray-900/90"style={{ left: host.right - 108, top: host.bottom - 96 }}><DropTarget position="bottom" candidate={candidate} shape="h-4 w-9" />diff --git a/packages/web/src/features/dock/dock-launcher.tsx b/packages/web/src/features/dock/dock-launcher.tsxindex 977914de..317faccd 100644--- a/packages/web/src/features/dock/dock-launcher.tsx+++ b/packages/web/src/features/dock/dock-launcher.tsx@@ -20,7 +20,9 @@* to its own container is what keeps it off both, and its right edge is the chat column's* (the dock row's, while the dock is hidden). The position is written to the node directly* — a transform driven by two spring drivers — rather than through React state, because a- * drag moves it every frame. The decisions live in dock-launcher-state.ts.+ * drag moves it every frame. The decisions live in dock-launcher-state.ts; the ball and the+ * fan are drawn by the UI package (`LauncherBall`, `LauncherFan`), and this container holds+ * their motion, their gestures and what each entry opens.*/import {useCallback,@@ -31,7 +33,6 @@ import {useSyncExternalStore,} from "react";import type {- CSSProperties,FocusEvent as ReactFocusEvent,KeyboardEvent as ReactKeyboardEvent,ReactNode,@@ -40,17 +41,20 @@ import {GlyphIcon,ICONS,ICON_SIZE,+ LauncherBall,+ LauncherFan,SPRING_DEFAULT,SPRING_MOMENTUM,createSpringDriver,scrollMovesAnchor,toastInfo,+ usePointerDrag,usePrefersReducedMotion,} from "@prismshadow/penguin-ui";import type { SpringDriver } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { NAV_ICONS } from "../../lib/nav-icons";-import { toneDot, toneInk } from "../../lib/tone";+import { toneInk } from "../../lib/tone";import { subscribeTerminals, terminalApiSupported } from "../terminal/terminal-list";import { isBrowserOffered, subscribeBrowser } from "../builtin-browser/browser-store";import { openTerminalInDock } from "./dock-terminal";@@ -63,7 +67,6 @@ import {openPanel,subscribeDock,} from "./dock-state";-import { usePointerDrag } from "./use-pointer-drag";import {FAN_ENTRY_SIZE,LAUNCHER_CAPTION_HEIGHT,@@ -94,13 +97,6 @@ const EDGE_INSET = 32;const DRAG_THRESHOLD = 4;/** The fan's exit animation, after which its entries unmount (`.launcher-fan-out` in styles.css). */const FAN_EXIT_MS = 140;-/**- * Delay between one entry's entrance and the next, the topmost entry first (ms). Short- * enough that the ring arrives as one shape rather than as a trickle of circles.- */-const FAN_STAGGER_MS = 16;-/** Gap between the ball and its caption (px); the pill takes the rest of LAUNCHER_CAPTION_HEIGHT. */-const CAPTION_GAP = 4;export interface DockLauncherProps {/** A pending approval inside a subagent: the amber dot rides the ball and the agents entry. */@@ -122,7 +118,7 @@ export function DockLauncher({ agentsPending }: DockLauncherProps) {});if (!visible) return null;return (- <LauncherBall+ <FloatingLauncheragentsPending={agentsPending}terminalSupported={terminalSupported}browserOffered={browserOffered}@@ -149,23 +145,7 @@ interface FanEntry {choose: () => void;}-// Every entry's box sits on the ball's centre; --fan-x / --fan-y carry it out to its place-// on the arc, as both the resting transform and the entrance animation's end state.-const ENTRY_CLASS =- "absolute flex items-center justify-center rounded-full border border-gray-200/80 bg-white/90 text-gray-600 shadow-[0_2px_8px_rgba(0,0,0,0.10)] backdrop-blur-md transition-colors duration-150 hover:bg-white hover:text-gray-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:border-white/10 dark:bg-gray-900/90 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";--/**- * The one always-visible name, under the ball: a small pill on the same glass, with no- * colour of its own, so it follows the ball's resting-to-hover ink. It reads out whichever- * entry is hovered or focused, and the launcher's own caption the rest of the time.- */-const CAPTION_CLASS =- "pointer-events-none absolute whitespace-nowrap rounded-md border border-gray-200/80 bg-white/85 px-2 py-0.5 text-[13px] font-medium leading-5 shadow-[0_1px_4px_rgba(0,0,0,0.08)] backdrop-blur-md transition-colors duration-150 dark:border-white/10 dark:bg-gray-900/85";--const BALL_CLASS =- "anim-pop relative flex touch-none select-none items-center justify-center rounded-full border border-gray-200/80 text-gray-500 shadow-[0_2px_10px_rgba(0,0,0,0.10)] backdrop-blur-md transition-[background-color,color,opacity,box-shadow] duration-150 hover:bg-white/95 hover:text-gray-800 hover:opacity-100 hover:shadow-[0_4px_16px_rgba(0,0,0,0.14)] focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent dark:border-white/10 dark:text-gray-400 dark:hover:bg-gray-800/95 dark:hover:text-gray-100";--function LauncherBall({+function FloatingLauncher({agentsPending,terminalSupported,browserOffered,@@ -508,65 +488,37 @@ function LauncherBall({style={{ right: EDGE_INSET, width: LAUNCHER_SIZE, height: LAUNCHER_SIZE }}>{fan !== null && (- // A zero-size anchor on the ball's centre: the entries are placed by their own- // transforms, so nothing here may size or clip the arc.- <div- ref={fanRef}- role="group"- aria-label={S.dock.launcherPanels}- data-testid="dock-launcher-fan"- className="absolute left-1/2 top-1/2 h-0 w-0"- >- {entries.map((entry, index) => {- // One slot per entry by construction; the guard is only the index type's.+ <LauncherFan+ fanRef={fanRef}+ label={S.dock.launcherPanels}+ phase={fan.phase}+ entrySize={FAN_ENTRY_SIZE}+ // One slot per entry by construction; the guard is only the index type's.+ entries={entries.flatMap((entry, index) => {const slot = slots[index];- if (slot === undefined) return null;- return (- <button- key={entry.key}- type="button"- data-testid={entry.testId}- // The glyph carries no text, so the name lives in the accessible name and in- // the caption under the ball, which reads out whatever is pointed at. No- // tooltip: it would only repeat the caption a few pixels away.- aria-label={entry.label}- onClick={entry.choose}- onMouseEnter={() => setHoveredKey(entry.key)}- onMouseLeave={() => setHoveredKey((key) => (key === entry.key ? null : key))}- onFocus={() => setHoveredKey(entry.key)}- onBlur={() => setHoveredKey((key) => (key === entry.key ? null : key))}- className={`${ENTRY_CLASS} ${- fan.phase === "closing" ? "launcher-fan-out" : "launcher-fan-in"- }`}- style={+ return slot === undefined+ ? []+ : [{- width: FAN_ENTRY_SIZE,- height: FAN_ENTRY_SIZE,- left: -FAN_ENTRY_SIZE / 2,- top: -FAN_ENTRY_SIZE / 2,- transform: "translate(var(--fan-x), var(--fan-y))",- // Entrance runs down the arc from the top; the exit runs all at once.- animationDelay: fan.phase === "closing" ? "0ms" : `${index * FAN_STAGGER_MS}ms`,- "--fan-x": `${slot.x.toFixed(1)}px`,- "--fan-y": `${slot.y.toFixed(1)}px`,- } as CSSProperties- }- >- {entry.glyphAt(ICON_SIZE.launcherEntry)}- {entry.badge && (- <span- aria-hidden- className={`absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full ring-2 ring-white dark:ring-gray-950 ${toneDot.attention}`}- />- )}- </button>- );+ key: entry.key,+ // The glyph carries no text, so the name lives in the accessible name and+ // in the caption under the ball, which reads out whatever is pointed at.+ label: entry.label,+ glyph: entry.glyphAt(ICON_SIZE.launcherEntry),+ badge: entry.badge,+ testId: entry.testId,+ x: slot.x,+ y: slot.y,+ onChoose: entry.choose,+ },+ ];})}- </div>+ onPoint={setHoveredKey}+ onLeave={(left) => setHoveredKey((key) => (key === left ? null : key))}+ />)}- <button- ref={ballRef}- type="button"+ <LauncherBall+ buttonRef={ballRef}{...dragProps}onClick={onBallClick}onMouseEnter={() => setBallActive(true)}@@ -575,40 +527,20 @@ function LauncherBall({onBlur={() => setBallActive(false)}// No tooltip: the caption under the ball already says what it opens, and the drag is// discovered by dragging.- aria-label={label}+ label={label}aria-expanded={fanOpen}- data-testid="dock-launcher-ball"- style={{ width: LAUNCHER_SIZE, height: LAUNCHER_SIZE }}- className={`${BALL_CLASS} ${- fanOpen || dragging- ? "bg-white/95 text-gray-800 opacity-100 dark:bg-gray-800/95 dark:text-gray-100"- : "bg-white/75 opacity-80 dark:bg-gray-900/75"- } ${dragging ? "cursor-grabbing" : "cursor-pointer"}`}- >- {ballGlyph}- {/* The caption hangs below the ball's circle: the launcher's own word at rest, "open"- while the ball itself is pointed at, and the pointed-at entry's name while the fan- is open — the ball drawing that entry's mark meanwhile. It is the visible readout —- every button carries its own accessible name — so it is hidden from assistive- technology and never folded into the ball's. Its height is spelled from the- constant the vertical clamp reserves, so the two cannot drift apart. */}- <span- aria-hidden- className={`${CAPTION_CLASS} left-1/2 -translate-x-1/2`}- style={{- top: LAUNCHER_SIZE + CAPTION_GAP,- height: LAUNCHER_CAPTION_HEIGHT - CAPTION_GAP,- }}- >- {captionText}- </span>- {agentsPending && (- <span- aria-hidden- className={`absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full ring-2 ring-white dark:ring-gray-950 ${toneDot.attention}`}- />- )}- </button>+ size={LAUNCHER_SIZE}+ // Spelled from the constant the vertical clamp reserves, so the two cannot drift apart.+ captionHeight={LAUNCHER_CAPTION_HEIGHT}+ glyph={ballGlyph}+ // The launcher's own word at rest, "open" while the ball itself is pointed at, and the+ // pointed-at entry's name while the fan is open — the ball drawing that entry's mark+ // meanwhile.+ caption={captionText}+ lit={fanOpen || dragging}+ dragging={dragging}+ badge={agentsPending}+ /></div>);}diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsxindex 6aa17d9e..e02ec573 100644--- a/packages/web/src/features/dock/dock-panel.tsx+++ b/packages/web/src/features/dock/dock-panel.tsx@@ -4,6 +4,9 @@* choosing what to open here. The chat page renders one per open dock — right and/or* bottom — or a single merged bottom surface below the desktop breakpoint.*+ * The drawing is the UI package's (`DockFrame`, `DockTabs`, `DockPicker`); this container+ * binds it to the dock store, the terminal list and the page's panel bodies.+ ** Panel tabs' bodies come from the page through `renderPanel` (they need the page's* session/stream state); terminal tabs' bodies are the pooled xterm views* (terminal-view-pool.tsx), adopted by DOM handoff so tab churn never reconnects a shell.@@ -35,6 +38,10 @@ import type { ReactNode } from "react";import {CloseIcon,ConfirmModal,+ DockFrame,+ DockHeaderButton,+ DockPicker,+ DockTabs,Dropdown,GlyphIcon,ICONS,@@ -42,13 +49,15 @@ import {Menu,MenuItem,MenuSeparator,+ ResizeHandle,+ usePointerDrag,} from "@prismshadow/penguin-ui";+import type { DockPickerChoice, DockTabItem } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { NAV_ICONS } from "../../lib/nav-icons";-import { ChordKbd } from "../../components/ui/chord-kbd";+import { chordKeys } from "../../components/ui/chord-kbd";import { useDisplayedBinding, useShortcutLabel } from "../../lib/shortcuts/use-keymap";import { useCoarsePointer } from "../../lib/use-coarse-pointer";-import { toneDot } from "../../lib/tone";import { useTerminalChrome } from "../terminal/terminal-appearance";import {displayTitle,@@ -99,105 +108,18 @@ import {setPanelWidth,usePanelWidthValue,} from "../chat/use-panel-width";-import { usePointerDrag } from "./use-pointer-drag";--/** Four corners pushed outward / pulled inward: the touch height toggle (see maximize). */-const MAXIMIZE_ICON = "M9 4H4v5M15 4h5v5M9 20H4v-5M15 20h5v-5";-const RESTORE_ICON = "M4 9h5V4M20 9h-5V4M4 15h5v5M20 15h-5v5";-/** Box with an arrow escaping to the top right: detach to its own window. */-const DETACH_ICON = "M14 4h6v6M20 4l-8 8M10 6H5a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5";--/** Small icon-sized header button shared by the dock's controls. */-function DockButton(props: {- label: string;- testId: string;- onClick: () => void;- children: ReactNode;-}) {- // A 24px box is a comfortable mouse target and a poor finger one; the glyph inside keeps- // its size either way, so only the box a finger has to land in grows.- const coarsePointer = useCoarsePointer();- return (- <button- type="button"- data-tooltip={props.label}- aria-label={props.label}- data-testid={props.testId}- onClick={props.onClick}- className={`flex ${coarsePointer ? "h-8 w-8" : "h-6 w-6"} shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200`}- >- {props.children}- </button>- );-}/**- * One tab in the strip: glyph + name + an always-visible ×. Two sibling buttons, not- * nested — a button inside a button is invalid and unclickable. The × has a reserved- * slot of its own after the label, never overlapping it: crowded tabs shrink by- * truncating the label (ellipsis) while the glyph and the × keep their width, so the- * close target stays where the pointer expects it.+ * The picker's order after the agents, the terminal and the built-in browser (each shown only+ * where it can run): the rest of the panels.*/-function DockTabButton(props: {- tabId: string;- label: string;- title: string;- glyph: ReactNode;- active: boolean;- /** Attention dot (e.g. a pending approval inside a subagent) shown beside the name. */- badge: boolean;- closeLabel: string;- /** The keyboard shortcut that runs the same close, named after the label in the ×'s tooltip. */- closeShortcut?: string;- onSelect: () => void;- onClose: () => void;- /** Terminal tabs keep their id on the node for tests and the strip's drag targeting. */- terminalId?: string;-}) {- const coarsePointer = useCoarsePointer();- return (- <div- data-testid="dock-tab"- data-tab-id={props.tabId}- {...(props.terminalId !== undefined ? { "data-terminal-id": props.terminalId } : {})}- data-active={props.active}- className={`flex ${coarsePointer ? "h-8" : "h-6"} max-w-44 items-center rounded-md pr-0.5 transition-colors duration-150 ${- props.active- ? "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"- : "text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-300"- }`}- >- <button- type="button"- data-tooltip={props.title}- onClick={props.onSelect}- className="flex h-full min-w-0 flex-1 items-center gap-1.5 pl-2 pr-1 text-left text-xs"- >- <span aria-hidden className="shrink-0">- {props.glyph}- </span>- <span className="min-w-0 truncate">{props.label}</span>- {props.badge && (- <span aria-hidden className={`h-1.5 w-1.5 shrink-0 rounded-full ${toneDot.attention}`} />- )}- </button>- <button- type="button"- data-tooltip={- props.closeShortcut !== undefined- ? `${props.closeLabel} (${props.closeShortcut})`- : props.closeLabel- }- aria-label={`${props.closeLabel}: ${props.label}`}- data-testid="dock-tab-close"- onClick={props.onClose}- className={`flex ${coarsePointer ? "h-6 w-6" : "h-4 w-4"} shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-200`}- >- <CloseIcon size={10} />- </button>- </div>- );-}+const PICKER_PANELS: readonly PanelKind[] = [+ "workspace",+ "memory",+ "trace",+ "messaging",+ "schedules",+];/*** A terminal tab's body: adopts the shown terminal's pooled container. Only while shown —@@ -240,81 +162,6 @@ function terminalLabel(info: TerminalInfo | undefined, id: string, ordinal: numbreturn `${info.seq ?? ordinal}: ${displayTitle(info.title) || info.name}`;}-/**- * The body of an open dock with no tabs: a centered choice list (Codex-style) — pick what- * to open here. Every side element is a row; the terminal row adopts the newest shell no- * conversation holds, or starts a fresh one, and names its hotkey.- */-function DockPicker({- choose,- chooseTerminal,- terminalSupported,- browserOffered,- horizontal,-}: {- choose: (kind: PanelKind) => void;- chooseTerminal: () => void;- terminalSupported: boolean;- /** The built-in browser can be shown here (the desktop app's own window, with a shell that hosts it). */- browserOffered: boolean;- /** The bottom (and merged) surface lays its choices out in a row, the right one as a list. */- horizontal: boolean;-}) {- const toggleChord = useDisplayedBinding("terminal.toggle");- const rowClass =- "flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm 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";- const row = (kind: PanelKind) => (- <button- key={kind}- type="button"- data-testid={`dock-pick-${kind}`}- onClick={() => choose(kind)}- className={rowClass}- >- <span className="shrink-0 text-gray-500 dark:text-gray-400">{panelGlyph(kind)}</span>- <span className="min-w-0 truncate">{panelLabel(kind)}</span>- </button>- );- return (- <div- data-testid="dock-picker"- className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto p-4"- >- <div- className={- horizontal- ? "flex max-w-full flex-wrap items-center justify-center gap-1"- : "flex w-60 flex-col gap-0.5"- }- >- {row("agents")}- {terminalSupported && (- <button- type="button"- data-testid="dock-pick-terminal"- onClick={chooseTerminal}- className={rowClass}- >- <span className="shrink-0 text-gray-500 dark:text-gray-400">- <GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.iconButton} />- </span>- <span className="min-w-0 flex-1 truncate">{S.terminal.title}</span>- {toggleChord !== null && (- <ChordKbd chord={toggleChord} className="text-gray-400 dark:text-gray-500" />- )}- </button>- )}- {browserOffered && row("builtin-browser")}- {row("workspace")}- {row("memory")}- {row("trace")}- {row("messaging")}- {row("schedules")}- </div>- </div>- );-}-export interface DockPanelProps {view: DockView;/** The page's panel bodies (they need its session/stream state); null hides that kind from the add menu too. */@@ -340,6 +187,7 @@ export function DockPanel({useSyncExternalStore(subscribeDock, dockVersion);const terminals = useSyncExternalStore(subscribeTerminals, liveTerminals);const closeShortcut = useShortcutLabel("terminal.close");+ const toggleChord = useDisplayedBinding("terminal.toggle");const browserOffered = useSyncExternalStore(subscribeBrowser, isBrowserOffered);const terminalById = new Map(terminals.map((t) => [t.id, t]));const { position, merged, tabs, activeKey } = view;@@ -387,31 +235,9 @@ export function DockPanel({detachTerminal(activeTab.terminalId, home);}, [activeTab, merged, position]);- // The shown tab keeps itself in view: with many tabs the strip scrolls, and a- // half-clipped active tab reads as a stray × button at the strip's edge.+ // The strip's node: the drag below hit-tests its tabs (the strip itself keeps the shown+ // tab in view and scrolls sideways under the wheel).const stripRef = useRef<HTMLDivElement | null>(null);- useEffect(() => {- if (activeKey === null) return;- stripRef.current- ?.querySelector(`[data-tab-id="${CSS.escape(activeKey)}"]`)- ?.scrollIntoView({ block: "nearest", inline: "nearest" });- }, [activeKey, tabs]);-- // Wheel over the strip scrolls it sideways (there is no vertical axis to scroll, and a- // trackpad's deltaX works too). Native non-passive listener: React's synthetic onWheel- // is passive, so preventDefault there cannot stop the page handling the event.- useEffect(() => {- const strip = stripRef.current;- if (!strip) return;- const onWheel = (event: WheelEvent): void => {- const delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;- if (delta === 0 || strip.scrollWidth <= strip.clientWidth) return;- event.preventDefault();- strip.scrollLeft += delta;- };- strip.addEventListener("wheel", onWheel, { passive: false });- return () => strip.removeEventListener("wheel", onWheel);- }, []);// ------------------------------------------------------------------ header drag: move dockconst [headerDrag, setHeaderDrag] = useState<{@@ -508,32 +334,25 @@ export function DockPanel({// dock — the ref is how both handles reach the box they resize.const rootRef = useRef<HTMLDivElement | null>(null);- const resizerDragProps = usePointerDrag<object>({- threshold: 0,- begin: (event) => {- event.preventDefault(); // no text selection while dragging the boundary- setResizing(true);- return {};- },- onMove: (event) => {- const pane = rootRef.current?.getBoundingClientRect();- if (!pane) return;- if (horizontal) {- // The ratio's basis is the chat page column ([data-dock-host]), the same box the- // rendered height is computed from below.- const host = document.querySelector("[data-dock-host]")?.getBoundingClientRect();- if (!host || host.height === 0) return;- setBottomRatio((pane.bottom - event.clientY) / host.height);- } else {- setPanelWidth(pane.right - event.clientX);- }- },- onEnd: () => {- setResizing(false);- if (!horizontal) persistPanelWidth(); // once per drag, not per frame- },- onCancel: () => setResizing(false),- });+ /** One move of a boundary drag: the pointer's position, as the dock's new size. */+ const resizeTo = (event: PointerEvent): void => {+ const pane = rootRef.current?.getBoundingClientRect();+ if (!pane) return;+ if (horizontal) {+ // The ratio's basis is the chat page column ([data-dock-host]), the same box the+ // rendered height is computed from below.+ const host = document.querySelector("[data-dock-host]")?.getBoundingClientRect();+ if (!host || host.height === 0) return;+ setBottomRatio((pane.bottom - event.clientY) / host.height);+ } else {+ setPanelWidth(pane.right - event.clientX);+ }+ };+ const resizeEnd = (committed: boolean): void => {+ setResizing(false);+ // Once per drag, not per frame; an abandoned drag stores nothing.+ if (committed && !horizontal) persistPanelWidth();+ };// The bottom dock's height in PIXELS: ratio × the measured chat column, with the same// clamps the drag applies. Pixels rather than a CSS percentage so the expand/collapse@@ -542,7 +361,7 @@ export function DockPanel({// refit its grid on every intermediate height).// Lazy initial measurement: on every mount but the app's very first commit the host is// already in the DOM, so the first paint uses the real height — a 0 start would make- // the height jump 0→target one commit later, which the transition class turns into an+ // the height jump 0→target one commit later, which the transition turns into an// unasked-for slide (and an instant mount is exactly the case that must not slide).// On the first commit the host is not attached yet; that mount is the animated initial// restore, whose entrance starts at 0 by design.@@ -611,9 +430,14 @@ export function DockPanel({portal={{ direction: "down", align: "right" }}menuClass="w-56"button={- <DockButton label={S.dock.addTab} testId="dock-add" onClick={() => setAddOpen(!addOpen)}>+ <DockHeaderButton+ label={S.dock.addTab}+ coarse={coarsePointer}+ data-testid="dock-add"+ onClick={() => setAddOpen(!addOpen)}+ ><GlyphIcon d={ICONS.plus} size={ICON_SIZE.iconButton} />- </DockButton>+ </DockHeaderButton>}><Menu>@@ -682,8 +506,8 @@ export function DockPanel({// A flip the store marks instant (a scope switch, a cross-dock move) must apply without// sliding. Leaving the tree is no longer what makes that instant — the node outlives a- // collapse now — so the transition class is left off for the commit that carries the flip- // and restored two frames later, once the new size has been painted.+ // collapse now — so the animation is left off for the commit that carries the flip and+ // restored two frames later, once the new size has been painted.const [snap, setSnap] = useState(false);const lastOpen = useRef(open);if (lastOpen.current !== open) {@@ -724,112 +548,67 @@ export function DockPanel({};useEffect(() => subscribeTerminalCloseRequests((id) => closeRequest.current(id)), []);- const header = (- <header- data-testid="dock-header"- {...headerDragProps}- className={`flex shrink-0 items-center gap-2 border-b border-gray-200 px-2 py-1.5 text-xs dark:border-gray-800 ${- merged ? "" : "cursor-grab select-none"- }`}- >- {/* Tab strip: this dock's tabs, current one highlighted; drag sideways to reorder,- drag out to move onto the other edge. Scrolls when the tabs outgrow the header. */}- <div- ref={stripRef}- data-testid="dock-tab-strip"- {...stripDragProps}- className="no-scrollbar flex min-w-0 items-center gap-1 overflow-x-auto"- >- {tabs.map((tab) => {- const key = tabKey(tab);- if (tab.kind === "panel") {- return (- <DockTabButton- key={key}- tabId={key}- label={panelLabel(tab.panel)}- title={panelLabel(tab.panel)}- glyph={panelGlyph(tab.panel, ICON_SIZE.inlineGlyph)}- active={key === activeKey}- badge={panelBadges?.[tab.panel] === true}- closeLabel={S.dock.closeTab}- onSelect={() => activateTab(key)}- onClose={() => closeTab(tab, panelLabel(tab.panel))}- />- );- }- const info = terminalById.get(tab.terminalId);- const label = terminalLabel(- info,- tab.terminalId,- terminalOrdinals.get(tab.terminalId) ?? 1,- );- return (- <DockTabButton- key={key}- tabId={key}- terminalId={tab.terminalId}- label={label}- title={info ? `${info.name} — ${info.cwd}` : label}- glyph={<GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.inlineGlyph} />}- active={key === activeKey}- badge={false}- closeLabel={S.terminal.killShell}- closeShortcut={closeShortcut ?? undefined}- onSelect={() => activateTab(key)}- onClose={() => closeTab(tab, label)}- />- );- })}- </div>- <span className="min-w-0 flex-1" />-- {/* Right-hand action cluster with uniform spacing, ending in close. */}- <div className="flex shrink-0 items-center gap-1.5">- {activeTab?.kind === "terminal" && (- <DockButton label={S.terminal.detach} testId="dock-detach" onClick={detach}>- <GlyphIcon d={DETACH_ICON} size={ICON_SIZE.rowLead} />- </DockButton>- )}- {addMenu}- {!merged && tabs.length > 0 && (- <DockButton- label={position === "right" ? S.dock.moveToBottom : S.dock.moveToRight}- testId="dock-move"- onClick={() => moveDock(position, other)}- >- <GlyphIcon- d={position === "right" ? ICONS.panelBottom : ICONS.panelRight}- size={ICON_SIZE.rowLead}- />- </DockButton>- )}- {horizontal && coarsePointer && tabs.length > 0 && (- <DockButton- label={maximized ? S.dock.restore : S.dock.maximize}- testId="dock-maximize"- onClick={toggleMaximized}- >- <GlyphIcon d={maximized ? RESTORE_ICON : MAXIMIZE_ICON} size={ICON_SIZE.rowLead} />- </DockButton>- )}- <DockButton label={S.dock.hideDock} testId="dock-close" onClick={hide}>- <CloseIcon size={12} />- </DockButton>- </div>- </header>- );+ // The strip's items: panel tabs by their panel's name and mark, terminal tabs by their+ // shell's seq and title, closed by killing the shell.+ const stripTabs: DockTabItem[] = tabs.map((tab) => {+ const key = tabKey(tab);+ if (tab.kind === "panel") {+ return {+ key,+ label: panelLabel(tab.panel),+ glyph: panelGlyph(tab.panel, ICON_SIZE.inlineGlyph),+ badge: panelBadges?.[tab.panel] === true,+ closeLabel: S.dock.closeTab,+ };+ }+ const info = terminalById.get(tab.terminalId);+ const label = terminalLabel(info, tab.terminalId, terminalOrdinals.get(tab.terminalId) ?? 1);+ return {+ key,+ label,+ title: info ? `${info.name} — ${info.cwd}` : label,+ glyph: <GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.inlineGlyph} />,+ closeLabel: S.terminal.killShell,+ closeShortcut: closeShortcut ?? undefined,+ terminalId: tab.terminalId,+ };+ });+ const closeByKey = (key: string): void => {+ const tab = tabs.find((t) => tabKey(t) === key);+ const item = stripTabs.find((t) => t.key === key);+ if (tab && item) closeTab(tab, item.label);+ };++ // An open dock with nothing in it yet: the picker chooses what this dock opens. The+ // terminal row adopts the newest shell no conversation holds, or starts a fresh one, and+ // names its hotkey while one is bound; the built-in browser is offered only where it can+ // be shown (the desktop app's own window, with a shell that hosts it).+ const pickPanel = (kind: PanelKind): DockPickerChoice => ({+ key: kind,+ label: panelLabel(kind),+ glyph: panelGlyph(kind),+ onChoose: () => openPanel(kind, merged ? undefined : position),+ });+ const pickerChoices: DockPickerChoice[] = [+ pickPanel("agents"),+ ...(terminalSupported+ ? [+ {+ key: "terminal",+ label: S.terminal.title,+ glyph: <GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.iconButton} />,+ ...(toggleChord !== null ? { keys: chordKeys(toggleChord) } : {}),+ onChoose: () => void openTerminalInDock(merged ? undefined : position),+ },+ ]+ : []),+ ...(browserOffered ? [pickPanel("builtin-browser")] : []),+ ...PICKER_PANELS.map(pickPanel),+ ];const bodies =tabs.length === 0 ? (- // An open dock with nothing in it yet: the picker chooses what this dock opens.- <DockPicker- choose={(kind) => openPanel(kind, merged ? undefined : position)}- chooseTerminal={() => void openTerminalInDock(merged ? undefined : position)}- terminalSupported={terminalSupported}- browserOffered={browserOffered}- horizontal={horizontal}- />+ <DockPicker choices={pickerChoices} horizontal={horizontal} />) : (<div className="relative min-h-0 flex-1">{tabs.map((tab) => {@@ -868,95 +647,105 @@ export function DockPanel({</ConfirmModal>);- if (horizontal) {- return (- <div- ref={rootRef}- data-testid="dock"- data-position="bottom"- // A closed dock stays in the tree at zero size, so what is on screen is data-open,- // not the node's presence (dock-drag.tsx and the e2e specs select on it).- data-open={open}- // Collapsed to 0 while closing/entering; the border belongs to the open state- // only — with border-box sizing a collapsed dock would still paint its 1px,- // leaving a hairline where nothing is.- style={{ height: open && entered ? bottomHeight : 0 }}- inert={!open}- className={`relative flex w-full shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${- open ? "border-t border-gray-200 dark:border-gray-800" : ""- } ${resizing || snap ? "" : "transition-[height] duration-200"}`}- >- {/* The handle straddles the boundary as an overlay, costing no height. Only while- open — a collapsing dock must not keep a grabbable edge behind. */}- {open && (- <div- data-testid="dock-resizer"- role="separator"- aria-orientation="horizontal"- aria-label={S.dock.resize}- data-tooltip={S.dock.resize}- {...resizerDragProps}- onDoubleClick={onResizerDoubleClick}- className={`absolute -top-[3px] left-0 right-0 z-20 h-1.5 cursor-ns-resize transition-colors duration-150 ${- resizing ? "bg-sky-500/60" : "bg-transparent hover:bg-sky-500/40"- }`}- />- )}- {/* Content fixed at the settled height inside the clipping window: while the- outer box animates through intermediate heights, nothing reflows — xterm- keeps its grid, panels keep their layout — the surface just slides. */}- <div style={{ height: bottomHeight }} className="flex min-h-0 shrink-0 flex-col">- {header}- {bodies}- </div>- {overlayActive && <DockDragOverlay candidate={overlayCandidate} />}- {killConfirm}- </div>- );- }+ // The boundary handle: on the bottom dock an overlay straddling the top edge (it costs no+ // height), on the right dock a layout sibling (it must cost real width). The store clamps+ // the size a drag asks for.+ const handle = (+ <ResizeHandle+ data-testid="dock-resizer"+ axis={horizontal ? "y" : "x"}+ edge={horizontal ? "start" : undefined}+ label={S.dock.resize}+ onResizeStart={() => setResizing(true)}+ onResize={resizeTo}+ onResizeEnd={resizeEnd}+ onReset={onResizerDoubleClick}+ />+ );++ const settledSize = horizontal ? bottomHeight : sideWidth;return (- <>- {/* A layout-sibling handle, not an overlay: it must cost real width so the chat- column measures the same under every surface. Only while open — a collapsing- dock must not leave a bare strip behind. */}- {open && (- <div- data-testid="dock-resizer"- role="separator"- aria-orientation="vertical"- aria-label={S.dock.resize}- data-tooltip={S.dock.resize}- {...resizerDragProps}- onDoubleClick={onResizerDoubleClick}- className={`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 ${- resizing ? "bg-sky-500/60" : "bg-transparent hover:bg-sky-500/40"- }`}+ <DockFrame+ position={horizontal ? "bottom" : "right"}+ open={open}+ // Collapsed to 0 while closing or entering.+ size={open && entered ? settledSize : 0}+ contentSize={settledSize}+ animate={!resizing && !snap}+ rootRef={rootRef}+ headerProps={headerDragProps}+ movable={!merged}+ tabs={+ // Drag sideways to reorder, drag out to move onto the other edge.+ <DockTabs+ tabs={stripTabs}+ active={activeKey}+ onSelect={activateTab}+ onClose={closeByKey}+ coarse={coarsePointer}+ stripRef={stripRef}+ {...stripDragProps}/>- )}- <div- ref={rootRef}- data-testid="dock"- data-position="right"- // What is on screen is data-open, not the node's presence (see the bottom branch).- data-open={open}- // The border belongs to the open state only (see the bottom branch's note).- style={{ width: open && entered ? sideWidth : 0 }}- inert={!open}- className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${- open ? "border-l border-gray-200 dark:border-gray-800" : ""- } ${resizing || snap ? "" : "transition-[width] duration-200"}`}- >- {/* Fixed-width content inside the clipping window: while the outer element- animates through intermediate widths, the content must not reflow frame by- frame — text would squeeze, and xterm would refit its grid on every one. */}- <div style={{ width: sideWidth }} className="flex min-h-0 flex-1 flex-col">- {header}- {bodies}- </div>- {overlayActive && <DockDragOverlay candidate={overlayCandidate} />}- {killConfirm}- </div>- </>+ }+ actions={+ <>+ {activeTab?.kind === "terminal" && (+ <DockHeaderButton+ label={S.terminal.detach}+ coarse={coarsePointer}+ data-testid="dock-detach"+ onClick={detach}+ >+ <GlyphIcon d={ICONS.boxArrowOut} size={ICON_SIZE.rowLead} />+ </DockHeaderButton>+ )}+ {addMenu}+ {!merged && tabs.length > 0 && (+ <DockHeaderButton+ label={position === "right" ? S.dock.moveToBottom : S.dock.moveToRight}+ coarse={coarsePointer}+ data-testid="dock-move"+ onClick={() => moveDock(position, other)}+ >+ <GlyphIcon+ d={position === "right" ? ICONS.panelBottom : ICONS.panelRight}+ size={ICON_SIZE.rowLead}+ />+ </DockHeaderButton>+ )}+ {horizontal && coarsePointer && tabs.length > 0 && (+ <DockHeaderButton+ label={maximized ? S.dock.restore : S.dock.maximize}+ coarse+ data-testid="dock-maximize"+ onClick={toggleMaximized}+ >+ <GlyphIcon+ d={maximized ? ICONS.cornersIn : ICONS.cornersOut}+ size={ICON_SIZE.rowLead}+ />+ </DockHeaderButton>+ )}+ <DockHeaderButton+ label={S.dock.hideDock}+ coarse={coarsePointer}+ data-testid="dock-close"+ onClick={hide}+ >+ <CloseIcon size={12} />+ </DockHeaderButton>+ </>+ }+ handle={handle}+ overlays={+ <>+ {overlayActive && <DockDragOverlay candidate={overlayCandidate} />}+ {killConfirm}+ </>+ }+ >+ {bodies}+ </DockFrame>);}diff --git a/packages/web/src/features/plugins/plugin-detail.tsx b/packages/web/src/features/plugins/plugin-detail.tsxindex 3a56e0d1..504ec753 100644--- a/packages/web/src/features/plugins/plugin-detail.tsx+++ b/packages/web/src/features/plugins/plugin-detail.tsx@@ -9,11 +9,8 @@* on hand at once and nothing here is fetched per directory.*/import { useEffect, useState } from "react";-import { Badge, ICONS, Modal } from "@prismshadow/penguin-ui";-import { FileBrowser } from "../../components/ui/file-browser";-import type { FileBrowserPreview } from "../../components/ui/file-browser";-import type { TreeToggle } from "../../components/ui/file-tree";-import type { FileTreeRow } from "../../lib/file-tree";+import { Badge, FileBrowser, ICONS, Modal } from "@prismshadow/penguin-ui";+import type { FileBrowserPreview, FileTreeRow, TreeToggle } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { baseName } from "../../lib/workspace-tree";@@ -244,6 +241,10 @@ export function PluginDetailModal({headerFallback={plugin.name}preview={preview}emptyPreview={error ?? S.common.none}+ emptyDirLabel={S.files.empty}+ truncatedLabel={S.files.previewTruncated}+ unsupportedLabel={S.files.previewUnsupported}+ downloadLabel={S.files.download}stripFrontmatteronToggleDir={toggleDir}onOpenFile={setSelected}diff --git a/packages/web/src/lib/workspace-tree.ts b/packages/web/src/lib/workspace-tree.tsindex 15c7c2f0..4745ed31 100644--- a/packages/web/src/lib/workspace-tree.ts+++ b/packages/web/src/lib/workspace-tree.ts@@ -3,23 +3,23 @@* - the directory tree's shape — listings fetched lazily per directory and keyed by its* Workspace-relative path ("" is the root), the set of open directories, and the flat* row list the tree renders from the two (the row's own shape and the keyboard step over- * it are shared with the app's other file trees, in lib/file-tree.ts);+ * it are the UI package's `FileTree`'s, shared with the app's other file trees);* - the search box's filter over the rows that are loaded;* - which directory a dropped batch lands in;* - when the panel is too narrow for a tree beside a preview, and how wide the tree pane* may be dragged when it is not;- * - how many breadcrumb segments fit on the toolbar's single row;* - which files count as text — by extension, or by looking at their first bytes when- * the extension says nothing — and so can be previewed as text and edited in place;+ * the extension says nothing — and so can be previewed as text and edited in place, and+ * how the read-only file browser previews a file by its name;* - 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 { FileBrowserPreviewKind, FileTreeRow } from "@prismshadow/penguin-ui";import type { WorkspaceFileEntry, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";import { joinWorkspacePath } from "./file-path";-import type { FileTreeRow } from "./file-tree";// ------------------------------------------------------------------------------- layout@@ -38,13 +38,6 @@ export function isNarrowLayout(panelWidth: number): boolean {/** Narrowest the tree pane may be dragged: below this a nested name is all ellipsis. */export const TREE_MIN_WIDTH = 160;-/**- * The divider between the tree and the preview, in px — `w-1.5` in the panel. It rides with- * the tree pane in the sliding container that shows and hides them together, which is why- * that container's width has to know it.- */-export const TREE_DIVIDER_PX = 6;-/** Room the preview keeps whatever the tree is dragged to. */export const PREVIEW_MIN_WIDTH = 240;@@ -215,45 +208,6 @@ export function searchRows(hits: readonly WorkspaceSearchHit[]): TreeRow[] {}));}-// -------------------------------------------------------------------------- breadcrumbs--/** The single item a run of dropped leading segments collapses into. */-export const CRUMB_ELLIPSIS = "…";--/** What of a path the toolbar can show: the trailing segments that fit, and whether anything was dropped ahead of them. */-export interface CrumbLayout {- visible: string[];- collapsed: boolean;-}--/**- * Which breadcrumb segments fit across `availablePx`, tail first. The current directory —- * the last segment — is always kept, however long it is; leading segments are taken while- * they fit and the rest collapse into one ellipsis item, so the toolbar's actions never get- * pushed onto a second row. `measure` gives a rendered item's width in px, ellipsis item- * included, which is what lets a test state a fixed per-character width.- */-export function visibleCrumbSegments(- segments: readonly string[],- availablePx: number,- measure: (text: string) => number,-): CrumbLayout {- if (segments.length === 0) return { visible: [], collapsed: false };- const last = segments.length - 1;- const visible = [segments[last]!];- let used = measure(segments[last]!);- for (let i = last - 1; i >= 0; i -= 1) {- // Taking this segment still leaves an ellipsis ahead of it unless it is the first one,- // so the ellipsis is priced into every step but the last.- const ellipsis = i > 0 ? measure(CRUMB_ELLIPSIS) : 0;- const width = measure(segments[i]!);- if (used + width + ellipsis > availablePx) break;- visible.unshift(segments[i]!);- used += width;- }- return { visible, collapsed: visible.length < segments.length };-}-// --------------------------------------------------------------------------------- drop/**@@ -332,6 +286,19 @@ export function previewKindFor(name: string): PreviewKind {return "unknown";}+/**+ * How a file previews in the read-only file browser (the UI package's `FileBrowser`), from its+ * name: the Workspace panel's own classification, minus the two answers a read-only browser+ * cannot give. HTML reads as its source, since rendering it would need the panel's sandboxed+ * frame; a name that says nothing reads as unsupported, since nobody there is reading the first+ * bytes to find out.+ */+export function previewKindOf(name: string): FileBrowserPreviewKind {+ const kind = previewKindFor(name);+ if (kind === "html") return "text";+ return kind === "unknown" ? "unsupported" : kind;+}+/*** `bytes` without a multi-byte UTF-8 sequence cut off at its end: a read chunk can end* anywhere, and judging validity on the partial character would call a text file binary.@@ -559,19 +526,6 @@ export interface ExcerptReference {text: string;}-/**- * 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.diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex 0772ac08..d5d0a1d6 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -254,43 +254,6 @@animation: msg-in 180ms ease-out both;}-/* Files panel: a directory's rows grow out of, and shrink back into, its row. Grid tracks- rather than height so the closed state needs no measurement; the inner box clips. Under- reduced motion the keyframes are off and each class rests at its own end state — open- at 1fr, closing at 0fr — and the view drops a closed group on a timer. Matches the- chevron's 200ms rotation. */-.tree-group {- display: grid;- grid-template-rows: 1fr;-}-.tree-group > div {- min-height: 0;- overflow: hidden;-}-.tree-group-open {- animation: tree-group-open 200ms ease-out;-}-.tree-group-close {- grid-template-rows: 0fr;- animation: tree-group-close 200ms ease-in;-}-@keyframes tree-group-open {- from {- grid-template-rows: 0fr;- }- to {- grid-template-rows: 1fr;- }-}-@keyframes tree-group-close {- from {- grid-template-rows: 1fr;- }- to {- grid-template-rows: 0fr;- }-}-/* Outline jump feedback: a soft brand wash fading out over the landed-on message. Applied byconversation-outline.tsx to the [data-outline-anchor] wrapper via classList — deliberatelyoutside React's managed props, so stream re-renders don't strip it mid-flash. */diff --git a/packages/web/test/context-menu.test.ts b/packages/web/test/context-menu.test.tsindex d8a10627..7ce8e37d 100644--- a/packages/web/test/context-menu.test.ts+++ b/packages/web/test/context-menu.test.ts@@ -8,9 +8,9 @@* everywhere else, and nothing in a node-only suite (`environment: "node"`, no jsdom) would notice* a `preventDefault` that had crept onto a document-level listener — so the scan asserts there is* no global contextmenu listener in either root. And the feature must not be mouse-only: the- * sidebar's Session rows spread all three openers (right-click, Shift+F10, press-and-hold) and- * name the anchor's owner, which the scroll rule needs to leave a menu open while an unrelated- * container scrolls.+ * sidebar's Session rows (the UI package's `SessionRow`) spread all three openers (right-click,+ * Shift+F10, press-and-hold) and name the anchor's owner, which the scroll rule needs to leave a+ * menu open while an unrelated container scrolls.*/import { describe, expect, it } from "vitest";import { expectEveryRootScanned, expectSingleHome, scanSources } from "./helpers/roots";@@ -34,6 +34,8 @@ const DROPDOWN = "packages/ui/src/components/overlays/dropdown/dropdown.tsx";const CONTEXT_MENU = "packages/ui/src/components/overlays/portal-panel/use-row-context-menu.ts";const RULES = "packages/ui/src/components/overlays/portal-panel/context-menu.ts";const SIDEBAR = "packages/web/src/components/layout/sidebar.tsx";+/** The sidebar's conversation row, which owns the row's menu wiring. */+const SESSION_ROW = "packages/ui/src/components/shell/session-row/session-row.tsx";describe("sourceFiles", () => {it("scans every source root, and finds the menu modules in one place each", () => {@@ -51,6 +53,7 @@ describe("sourceFiles", () => {expect(paths.filter((p) => p.includes("\\"))).toEqual([]);expect(paths).toContain(CONTEXT_MENU);expect(paths).toContain(SIDEBAR);+ expect(paths).toContain(SESSION_ROW);});});@@ -68,18 +71,21 @@ describe("native-menu suppression scope", () => {});it("gives the sidebar row all three openers, so the menu is not mouse-only", () => {- const sidebar = sourceFiles().find(([path]) => path === SIDEBAR);- expect(sidebar).toBeDefined();+ const row = sourceFiles().find(([path]) => path === SESSION_ROW);+ expect(row).toBeDefined();// The row spreads the hook's handlers (contextmenu + Shift+F10 + press-and-hold) and// guards its own click against the one a hold replays.- expect(sidebar![1]).toContain("{...ctx.rowProps}");- expect(sidebar![1]).toContain("ctx.consumeLongPressClick()");+ expect(row![1]).toContain("{...ctx.rowProps}");+ expect(row![1]).toContain("ctx.consumeLongPressClick()");+ // And the sidebar draws its conversations with that row.+ const sidebar = sourceFiles().find(([path]) => path === SIDEBAR);+ expect(sidebar![1]).toContain("<SessionRow");});it("names the anchor's owner alongside the anchor, so the scroll rule has one to test", () => {// Without the wiring, scrollMovesAnchor is asked about a null owner on every scroll and// answers "dismiss" — the package's rule tests would still pass while the bug was back.- const sidebar = sourceFiles().find(([path]) => path === SIDEBAR);- expect(sidebar![1]).toContain("anchorOwner={ctx.anchorOwner}");+ const row = sourceFiles().find(([path]) => path === SESSION_ROW);+ expect(row![1]).toContain("anchorOwner={ctx.anchorOwner}");});});diff --git a/packages/web/test/deslop.test.ts b/packages/web/test/deslop.test.tsindex 2d0ea0a7..8e613079 100644--- a/packages/web/test/deslop.test.ts+++ b/packages/web/test/deslop.test.ts@@ -36,10 +36,11 @@ const WEB = SCAN.files.filter((file) => file.root === "web");/*** The homes §3 names, as the web app spells them today. It has no Spinner of its own (the* package's is the one), the chevron's rotation left with the chevron, the sheet's and the- * drawer's motion with them (W3), and the streaming caret's pulse with the reply body (W6).+ * drawer's motion with them (W6), the streaming caret's pulse with the reply body (W6), and the+ * launcher fan's with the launcher (W7).*/const POLICY: DeslopPolicy = {- transformMotion: ["dock-launcher.tsx"],+ transformMotion: [],entranceMotion: [],pulseHomes: ["dot.tsx"],spinnerHomes: [],@@ -57,23 +58,9 @@ const POLICY: DeslopPolicy = {* `W10` is the follow-up sweep of the code that landed on main while the waves were in flight.*/const ALLOWLIST: DeslopAllowlist = {- "components/layout/app-layout.tsx": { 1: [1, "W7"] },- "components/layout/sidebar.tsx": { 1: [3, "W7"], 12: [5, "W7"], 13: [2, "W7"], 14: [2, "W7"] },"features/builtin-browser/browser-tab-strip.tsx": { 12: [2, "W10"] },- "features/chat/drop-zone.tsx": { 18: [1, "W7"] },"features/chat/model-picker-modal.tsx": { 12: [1, "W10"] },- "features/chat/shortcuts-folder.tsx": { 12: [1, "W7"] },- "features/chat/workspace-browser.tsx": {- 1: [1, "W7"],- 12: [3, "W7"],- 13: [1, "W7"],- 18: [1, "W7"],- },"features/chat/workspace-finder.tsx": { 12: [6, "W10"] },- "features/chat/workspace-tree-view.tsx": { 13: [1, "W7"] },- "features/dock/dock-drag.tsx": { 3: [1, "W7"], 12: [1, "W7"] },- "features/dock/dock-launcher.tsx": { 13: [1, "W7"], 18: [3, "W7"], 19: [4, "W7"] },- "features/dock/dock-panel.tsx": { 1: [2, "W7"], 12: [2, "W7"] },"features/settings/shortcut-recorder.tsx": { 12: [1, "W10"], 13: [1, "W10"] },"features/settings/shortcuts-section.tsx": { 13: [1, "W10"] },"features/terminal/terminal-appearance.ts": { 9: [1, "W10"] },diff --git a/packages/web/test/icon-registry.test.ts b/packages/web/test/icon-registry.test.tsindex d4cefc5b..243f4836 100644--- a/packages/web/test/icon-registry.test.ts+++ b/packages/web/test/icon-registry.test.ts@@ -25,8 +25,7 @@ const WEB = SCAN.files.filter((file) => file.root === "web");/** Glyph paths outside the registry, by path under `packages/web/src`: `[count, wave]`. */const ALLOWLIST: Readonly<Record<string, readonly [number, string]>> = {- "components/layout/app-layout.tsx": [3, "W7"],- "components/layout/sidebar.tsx": [4, "W7"],+ "components/layout/sidebar.tsx": [2, "W7"],"features/chat/attached-files-banner.tsx": [1, "W6"],"features/chat/conversation-outline.tsx": [1, "W6"],"features/chat/goal-use.ts": [1, "W6"],@@ -42,7 +41,6 @@ const ALLOWLIST: Readonly<Record<string, readonly [number, string]>> = {"features/company/finance-page.tsx": [1, "W4"],"features/company/handbook-explorer.tsx": [1, "W4"],"features/company/shared.tsx": [2, "W4"],- "features/dock/dock-panel.tsx": [3, "W7+W10"],"features/models/models-page.tsx": [4, "W4"],"features/plugins/plugins-page.tsx": [2, "W4"],"features/schedules/schedule-panel.tsx": [3, "W4"],diff --git a/packages/web/test/markdown-math.test.ts b/packages/web/test/markdown-math.test.tsindex b5db6cda..4d006263 100644--- a/packages/web/test/markdown-math.test.ts+++ b/packages/web/test/markdown-math.test.ts@@ -36,10 +36,10 @@ describe("the pipeline every renderer shares", () => {expectEveryRootScanned(SCAN);});- it("are the known renderers: Md, the shared file browser, a Trace event and a plugin's page", () => {+ it("are the known renderers: Md, a Trace event and a plugin's page", () => {+ // The shared file browser draws its Markdown through `Md`, so it is not one of them.expect(renderers.map((file) => file.id).sort()).toEqual(["packages/ui/src/components/content/prose/prose.tsx",- "packages/web/src/components/ui/file-browser.tsx","packages/web/src/features/plugins/plugin-detail-page.tsx","packages/web/src/features/traces/trace-event-row.tsx",]);@@ -57,7 +57,7 @@ describe("the pipeline every renderer shares", () => {}expect(file.text, file.id).toContain(HOME[file.root]);}- expect(total).toBe(5); // Md, the shared file browser, a plugin's page, two in trace-event-row+ expect(total).toBe(4); // Md, a plugin's page, two in trace-event-row});it("no renderer assembles its own pipeline out of the underlying plugins", () => {diff --git a/packages/web/test/menu-style.test.ts b/packages/web/test/menu-style.test.tsindex 3028f5c3..1e7c2b0a 100644--- a/packages/web/test/menu-style.test.ts+++ b/packages/web/test/menu-style.test.ts@@ -38,10 +38,8 @@ describe("menus and pickers", () => {});it("draw their rows with the Menu family, never a hand-built menu row", () => {- // The Session row's menu keeps its own rows until the sidebar's rows move into the package.- const pending = ["packages/web/src/components/ui/session-row-menu.tsx"];const handBuilt = SCAN.files- .filter((file) => file.root === "web" && !pending.includes(file.id))+ .filter((file) => file.root === "web").filter((file) => /\bmenuRow(?:Class|Tone)\b/.test(file.text)).map((file) => file.id);expect(handBuilt).toEqual([]);diff --git a/packages/web/test/session-activity.test.ts b/packages/web/test/session-activity.test.tsindex f31dee79..2bf9f8dd 100644--- a/packages/web/test/session-activity.test.ts+++ b/packages/web/test/session-activity.test.ts@@ -12,6 +12,8 @@ import { S } from "../src/lib/strings";import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } from "./helpers/roots";const SCAN = scanSources();+/** The sidebar's conversation row: the package draws the marks, the sidebar hands it their words. */+const SESSION_ROW = "packages/ui/src/components/shell/session-row/session-row.tsx";describe("the activity marks' sources", () => {it("scan every source root, and find the icon module in one place", () => {@@ -87,14 +89,16 @@ describe("the app's words for the activity marks", () => {});it("hands every mark its label wherever the app draws one", () => {+ // The sidebar row is the package's SessionRow: the sidebar names each mark, the row draws+ // the mark with the name it was handed.const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;- expect(sidebar).toMatch(- /<ActivityIcon activity=\{activity\} label=\{sessionActivityLabel\(activity\)\}/,- );- expect(sidebar).toMatch(/<ScheduleMark label=\{S\.chat\.sessionScheduled\}/);- expect(sidebar).toMatch(- /<BackgroundTasksMark\s+label=\{S\.chat\.backgroundTasks\(background\)\}/,- );+ expect(sidebar).toMatch(/\{ state: activity, label: sessionActivityLabel\(activity\) \}/);+ expect(sidebar).toMatch(/scheduledLabel: S\.chat\.sessionScheduled/);+ expect(sidebar).toMatch(/label: S\.chat\.backgroundTasks\(background\)/);+ const row = sourceFile(SCAN, SESSION_ROW).text;+ expect(row).toMatch(/<ActivityIcon activity=\{activity\.state\} label=\{activity\.label\}/);+ expect(row).toMatch(/<ScheduleMark label=\{scheduledLabel\}/);+ expect(row).toMatch(/<BackgroundTasksMark label=\{background\.label\}/);const desks = sourceFile(SCAN, "packages/web/src/features/company/org-session-groups.tsx").text;expect(desks).toMatch(/<ActivityIcon activity=\{activity\} label=\{sessionActivityLabel\(activity\)\}/,@@ -102,9 +106,9 @@ describe("the app's words for the activity marks", () => {});it("reserves the glyph's box on a row with no glyph, so a row never shifts", () => {- // Every glyph renders into the same row-mark box, and the sidebar reserves that box when- // there is no glyph at all — otherwise the title would re-flow as a run starts, finishes and- // is read. The placeholder is read from the sidebar itself so the two cannot drift apart.+ // Every glyph renders into the same row-mark box, and the sidebar's row reserves that box+ // when there is no glyph at all — otherwise the title would re-flow as a run starts, finishes+ // and is read. The placeholder is read from the row itself so the two cannot drift apart.expect(ICON_SIZE.rowMark).toBe(12);for (const activity of ACTIVITIES) {const markup = renderToStaticMarkup(@@ -112,7 +116,7 @@ describe("the app's words for the activity marks", () => {);expect(markup).toContain("width:12px;height:12px");}- const sidebar = sourceFile(SCAN, "packages/web/src/components/layout/sidebar.tsx").text;- expect(sidebar).toMatch(/activity === null.*\n?.*className="block h-3 w-3 shrink-0"/);+ const row = sourceFile(SCAN, SESSION_ROW).text;+ expect(row).toMatch(/activity === null.*\n?.*className="block h-3 w-3 shrink-0"/);});});diff --git a/packages/web/test/session-row-menu.test.ts b/packages/web/test/session-row-menu.test.tsindex dd764860..a057fc4e 100644--- a/packages/web/test/session-row-menu.test.ts+++ b/packages/web/test/session-row-menu.test.ts@@ -29,6 +29,8 @@ import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } froconst SCAN = scanSources();const ROW_MENU = "packages/web/src/components/ui/session-row-menu.tsx";+/** The package's row, which draws the hover buttons both the sidebar and the desk rows use. */+const SESSION_ROW = "packages/ui/src/components/shell/session-row/session-row.tsx";/** Every test that switches locale puts the default (zh) back. */afterEach(() => setActiveStrings(zh));@@ -100,8 +102,9 @@ describe("contextMenuActions", () => {describe("the hover buttons' CSS contract", () => {// Node-only suite, so this is asserted against the source text (title-reveal.test.ts// convention). It is worth pinning: an invisible button still takes taps, and these are- // invisible for the whole of every touch session, delete included.- const source = sourceFile(SCAN, ROW_MENU).text;+ // invisible for the whole of every touch session, delete included. The buttons are the UI+ // package's (`RowHoverActions`); this module hands them their actions.+ const source = sourceFile(SCAN, SESSION_ROW).text;it("gates pointer events on the same conditions as visibility, leaving no phantom tap target", () => {expect(source).toContain("pointer-events-none");diff --git a/packages/web/test/workspace-tree.test.ts b/packages/web/test/workspace-tree.test.tsindex 0972742c..0db93bd1 100644--- a/packages/web/test/workspace-tree.test.ts+++ b/packages/web/test/workspace-tree.test.ts@@ -1,10 +1,10 @@/*** Files panel logic (lib/workspace-tree.ts): the tree's rows from lazily loaded listings,- * 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, when leaving the editor has to ask, and what- * the panel's "add to conversation" puts in the composer.+ * the rows a whole-Workspace search draws, where a drop lands, the narrow-layout decision and+ * the tree pane's width bounds, which files count as text (by name, or by their bytes when the+ * name says nothing) and how the read-only file browser previews one, 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, WorkspaceSearchHit } from "@prismshadow/penguin-server/api";@@ -33,16 +33,15 @@ import {parseTreeWidth,pathReference,previewKindFor,+ previewKindOf,readWrapLines,readTreeVisible,readTreeWidth,selectionBlock,- splitFileName,lineSuffix,sortEntries,upsertEntry,utf8Complete,- visibleCrumbSegments,withExpanded,writeWrapLines,writeTreeVisible,@@ -213,41 +212,6 @@ describe("searchRows", () => {});});-describe("visibleCrumbSegments", () => {- /** A fixed advance per character, so the fit is arithmetic rather than a font. */- const measure = (text: string): number => text.length * 10;-- it("shows the whole path when it fits", () => {- expect(visibleCrumbSegments(["root", "aa", "bb"], 1000, measure)).toEqual({- visible: ["root", "aa", "bb"],- collapsed: false,- });- expect(visibleCrumbSegments([], 1000, measure)).toEqual({ visible: [], collapsed: false });- });-- it("drops leading segments until the rest fit, pricing in the ellipsis they become", () => {- // "cc" 20 + "bb" 20 + the ellipsis still ahead of them 10 = 50, within 60; "aa" would- // make it 70.- expect(visibleCrumbSegments(["root", "aa", "bb", "cc"], 60, measure)).toEqual({- visible: ["bb", "cc"],- collapsed: true,- });- // At 100 the first segment fits too, and with nothing left ahead of it there is no- // ellipsis to pay for.- expect(visibleCrumbSegments(["root", "aa", "bb", "cc"], 100, measure)).toEqual({- visible: ["root", "aa", "bb", "cc"],- collapsed: false,- });- });-- it("always keeps the current directory, however little room there is", () => {- expect(visibleCrumbSegments(["root", "aa", "bb"], 0, measure)).toEqual({- visible: ["bb"],- collapsed: true,- });- });-});-describe("file kinds", () => {it("decides the preview kind from the name, leaving an unknown name to be sniffed", () => {expect(previewKindFor("README.md")).toBe("md");@@ -259,6 +223,12 @@ describe("file kinds", () => {expect(previewKindFor("archive.tar.gz")).toBe("unknown");});+ it("reads HTML as source and an unknown name as unsupported in the read-only browser", () => {+ expect(previewKindOf("index.html")).toBe("text");+ expect(previewKindOf("Makefile")).toBe("unsupported");+ expect(previewKindOf("README.md")).toBe("md");+ });+it("takes UTF-8 text for text, including a chunk cut inside a multi-byte character", () => {const encode = (s: string) => new TextEncoder().encode(s);expect(looksLikeText(encode("all: build\n\tgo build ./...\n"))).toBe(true);@@ -388,24 +358,6 @@ describe("tree visibility preference", () => {});});-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");diff --git a/scripts/ui-migrate.json b/scripts/ui-migrate.jsonindex 3ffe2d7a..c9277260 100644--- a/scripts/ui-migrate.json+++ b/scripts/ui-migrate.json@@ -737,6 +737,92 @@}]},+ "W7": {+ "packages/web/src/features/dock/use-pointer-drag": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/layout/resize-handle/use-pointer-drag.ts",+ "names": ["usePointerDrag"]+ }+ ],+ "packages/web/src/lib/file-tree": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/files/file-tree/tree-rows.ts",+ "names": ["FileTreeRow", "TreeKeyAction", "subtreeEnd", "treeKeyStep"]+ }+ ],+ "packages/web/src/components/ui/file-tree": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/files/file-tree/file-tree.tsx",+ "names": ["FileTree", "TreeToggle"]+ }+ ],+ "packages/web/src/components/ui/file-browser": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/files/file-browser/file-browser.tsx",+ "names": ["FileBrowser", "FileBrowserPreview", "FileBrowserPreviewKind"]+ },+ {+ "owner": "W7-A",+ "target": "packages/web/src/lib/workspace-tree",+ "dest": "packages/web/src/lib/workspace-tree.ts",+ "names": ["previewKindOf"]+ }+ ],+ "packages/web/src/features/chat/workspace-file-menu": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/files/workspace-file-menu/workspace-file-menu.tsx",+ "names": ["WorkspaceFileMenuRows", "FileMenuTarget"]+ }+ ],+ "packages/web/src/features/chat/workspace-editor": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/content/workspace-file-editor/workspace-file-editor.tsx",+ "names": ["WorkspaceFileEditor"]+ }+ ],+ "packages/web/src/lib/workspace-tree": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/navigation/breadcrumbs/crumb-fit.ts",+ "names": ["CRUMB_ELLIPSIS", "CrumbLayout", "visibleCrumbSegments", "splitFileName"]+ },+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/layout/resize-handle/resize-handle.tsx",+ "names": ["TREE_DIVIDER_PX→RESIZE_HANDLE_PX"]+ }+ ],+ "packages/web/src/lib/frontmatter": [+ {+ "owner": "W7-A",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/content/prose/frontmatter.ts",+ "names": ["bodyWithoutFrontmatter"]+ }+ ],+ "packages/web/src/features/chat/panels-toolbar": [+ {+ "owner": "W7-C",+ "target": "packages/web/src/features/chat/dock-toggles",+ "dest": "packages/web/src/features/chat/dock-toggles.tsx",+ "names": ["PanelsToolbar→DockToggles", "PanelsToolbarProps→DockTogglesProps"]+ }+ ]+ },"W6": {"packages/web/src/features/chat/work-group": [{