Skip to content

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

feat(web): sidebar nav entries share one order and one set of names, and each is pinned or collapsible (#909)

Yaowei Zheng57a81a55e289
diff --git a/changelog/unreleased/2026-09-30-nav-pinning.md b/changelog/unreleased/2026-09-30-nav-pinning.md
new file mode 100644
index 00000000..e62db395
--- /dev/null
+++ b/changelog/unreleased/2026-09-30-nav-pinning.md
@@ -0,0 +1,43 @@
+# Sidebar entries share one set of names and one order, and each is pinned or collapsible
+
+- **Date:** 2026-09-30
+- **Type:** feature
+- **Scope:** `web`, `ui`, `docs`
+- **PR:** [#909](https://github.com/Prism-Shadow/penguin-harness/pull/909)
+
+[中文版](2026-09-30-nav-pinning.zh.md)
+
+The sidebar's nav entries got one set of names and one order in both languages. Every page entry
+became either pinned or collapsible, and the chevron under the nav folds only the collapsible ones.
+New chat is the exception: it is always pinned.
+
+## Names and order
+
+- The entries read 新建对话 · 智能体 · 模型库 · 插件市场 · 机器管理 · 成本中心 · 评估中心 in Chinese
+ and New chat · Agents · Models · Plugins · Machines · Cost Center · Evaluation Center in English.
+ Models moved ahead of Plugins in the page manifest. The Chinese Machines entry changed from 机器
+ to 机器管理, and so did the Machines page heading and the one message that names the page. The
+ chat page's empty-state button changed from 新对话 to 新建对话, the name of the nav entry it
+ repeats.
+- The collapsed rail builds its page icons from the same manifest. It follows the new order and
+ shows Machines to admins, which it had left out.
+
+## Pinned and collapsible entries
+
+- New chat, Agents, Models and Plugins are pinned by default. Machines, Cost Center and Evaluation
+ Center are collapsible, and the collapsible area starts expanded. Each area keeps manifest
+ order, and with nothing collapsible the chevron is hidden.
+- A pin button appears at the end of a row on hover or keyboard focus, and always on touch
+ screens. It is filled while the entry is pinned, and its tooltip reads **Pin** or **Unpin**.
+ Dragging a row into or out of the collapsible area does the same.
+- New chat keeps its fixed slot above the scroll area; it has no pin button and cannot be dragged.
+- The choices are saved per browser in `penguin.sidebarNavPinned`, as the entries whose state
+ differs from the default. A key the manifest does not know is ignored, so a page with no stored
+ choice takes its default. A folded state already stored in `penguin.sidebarNavGroupCollapsed`
+ keeps folding, now only the collapsible area.
+- Company mode's six entries still fold as one group, with no pins.
+- The pieces are the UI package's: `SidebarNavGroup` takes the pinned entries above its fold, a
+ drop target for the fold and a way to leave the fold out, `SidebarNavArea` is a run of pinned
+ entries that takes a drop, and `SidebarNavEntry` is a `NavRow` with the pin toggle and the drag
+ handle. `NavRow` gains `groupHover` and `draggable={false}` for a row inside such an entry.
+- The docs' Web App page describes the entries, the pins and the Machines row (admins only).
diff --git a/changelog/unreleased/2026-09-30-nav-pinning.zh.md b/changelog/unreleased/2026-09-30-nav-pinning.zh.md
new file mode 100644
index 00000000..4afac512
--- /dev/null
+++ b/changelog/unreleased/2026-09-30-nav-pinning.zh.md
@@ -0,0 +1,25 @@
+# 侧栏导航统一文案与顺序,入口分常驻与可收起
+
+- **Date:** 2026-09-30
+- **Type:** feature
+- **Scope:** `web`, `ui`, `docs`
+- **PR:** [#909](https://github.com/Prism-Shadow/penguin-harness/pull/909)
+
+[English](2026-09-30-nav-pinning.md)
+
+侧栏导航入口统一为中英各一套名称、同一个顺序。每个页面入口都分为常驻或可收起,导航下方的箭头只折叠可收起的入口。新建对话是例外,始终常驻。
+
+## 名称与顺序
+
+- 入口中文依次为新建对话、智能体、模型库、插件市场、机器管理、成本中心、评估中心,英文依次为 New chat、Agents、Models、Plugins、Machines、Cost Center、Evaluation Center。页面清单里模型库移到插件市场之前。机器入口的中文名由「机器」改为「机器管理」,机器管理页的标题和唯一一条提到该页面的提示随之修改。对话页空状态的按钮由「新对话」改为「新建对话」,与它对应的导航入口同名。
+- 收起的侧栏也从同一份清单生成页面图标,因此顺序随之更新,并向管理员显示此前漏掉的机器管理。
+
+## 常驻与可收起的入口
+
+- 默认新建对话、智能体、模型库、插件市场常驻,机器管理、成本中心、评估中心可收起,收起区默认展开。两个区域都按清单顺序排列,没有可收起的入口时不显示箭头。
+- 鼠标悬停或键盘聚焦时,行尾出现图钉按钮,触屏上始终显示。入口常驻时图钉为实心,提示为「取消常驻」,否则提示「常驻」。把入口拖进或拖出收起区效果相同。
+- 新建对话仍在滚动区上方的固定位置,没有图钉按钮,也不能拖动。
+- 选择按浏览器保存在 `penguin.sidebarNavPinned`,只记录与默认不同的入口。清单里没有的键会被忽略,没有记录的页面取默认值。已保存在 `penguin.sidebarNavGroupCollapsed` 的折叠状态继续生效,只折叠收起区。
+- 公司模式的六个入口仍整组折叠,没有图钉。
+- 这些部件属于 UI 包:`SidebarNavGroup` 可在折叠区上方放置常驻入口,可将折叠区设为放置目标,也可省去折叠区;`SidebarNavArea` 是一段可接受放置的常驻入口;`SidebarNavEntry` 是带图钉按钮与拖动手柄的 `NavRow`。`NavRow` 新增 `groupHover` 与 `draggable={false}`,供这类入口中的行使用。
+- 文档的 Web App 页面补充了这些入口、图钉和机器管理一行(仅管理员)。
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index b92b891f..e8a45ba9 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -644,7 +644,7 @@ penguin server status [--root <dir>]
只有当记录的 pid 还活着、端口也能建立连接时,`running` 才是 true,所以复用的 pid 不会冒充存活的服务器。没有服务器在运行时,`port` 和 `pid` 为 `null`。`machineId` 在本机至少启动过一次服务器之前为 `null`:id 在首次启动时生成,此后永不改变。数据根目录照常取自 `--root` 或 `PENGUIN_HOME`。
-**机器**页面通过 ssh 运行这条命令,询问一台机器正在做什么,这也是输出采用 JSON 而不是文字说明的原因。
+**机器管理**页面通过 ssh 运行这条命令,询问一台机器正在做什么,这也是输出采用 JSON 而不是文字说明的原因。
### penguin server reset-admin-password
@@ -669,7 +669,7 @@ penguin server stop [--root <dir>]
服务器停不下来时,命令打印 `{"ok":false,"pid":…,"detail":"…"}` 并以退出码 1 退出。出现这种情况的情形有:信号无法送达;`SIGTERM` 发出 15 秒后服务器仍占用着数据根目录;以及在 Windows 上——那里无法通过信号实现优雅停止,只能从服务器自己的控制台停止。
-**机器**页面重启一台机器时,会通过 ssh 运行这条命令。之所以用命令而不是直接向服务器发请求,是因为需要停止的机器通常正是平台版本过期的那台,而平台路由要等机器跑上带这条路由的构建版本才会存在。
+**机器管理**页面重启一台机器时,会通过 ssh 运行这条命令。之所以用命令而不是直接向服务器发请求,是因为需要停止的机器通常正是平台版本过期的那台,而平台路由要等机器跑上带这条路由的构建版本才会存在。
## penguin version
diff --git a/packages/docs/content/security.zh.md b/packages/docs/content/security.zh.md
index 06a84500..d45a9aa2 100644
--- a/packages/docs/content/security.zh.md
+++ b/packages/docs/content/security.zh.md
@@ -23,7 +23,7 @@ PenguinHarness 用真实凭据在真实机器上运行 Agent,所以值得弄
| 用密码登录;密码以 scrypt 哈希存储,登录尝试有频率限制 | Web 登录页、`penguin auth login` |
| 桌面应用静默登录自己的窗口 | 窗口打开时的一次性令牌 |
| 凭本地所有权铸造会话,全程不需要密码 | `penguin auth token` |
-| 通过 ssh 管理机器,网络上不传密码 | **机器**页面 |
+| 通过 ssh 管理机器,网络上不传密码 | **机器管理**页面 |
| 会话是服务端的一行记录:可逐个收回、重启后依然存在、使用期间自动续期(30 天) | 所有场景 |
| 每个会话都记录自己的建立方式 | 会话的 `via` 值(见下文) |
| 收回单个会话,或收回某个用户的全部会话 | **登出**、管理员重置用户密码 |
@@ -126,7 +126,7 @@ penguin auth token # no password, no prompt: inserts a session row
## 通过 ssh 管理远程机器
-**机器**页面通过 ssh 管理其他机器,一切操作都以 ssh 账户的身份运行。
+**机器管理**页面通过 ssh 管理其他机器,一切操作都以 ssh 账户的身份运行。
要对一台机器的 API 执行操作,控制器通过 ssh 在那台机器上运行 `penguin auth token`。机器自己的 CLI 往机器自己的数据库里写入一行会话记录。经过网络的只有会话令牌,有效期一小时。
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 218db0ab..1bfd9826 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -86,14 +86,15 @@ From top to bottom, the sidebar holds:
- The **Development** / **Company** switch, only when company mode is available: an admin has enabled it for the server, and you have not turned it off for yourself. Company mode swaps the page entries below for an organization's pages, and the conversation list for its channels. See [Company mode](/company-mode).
- The Project switcher, with the **Collapse sidebar** button beside it. See [Projects and members](#projects-and-members).
-- **New chat**, which opens a new conversation draft. See [Chat](/chat).
-- The page entries. The chevron under the last one folds them away:
+- The nav entries:
| Entry | What it is for | Guide |
| --- | --- | --- |
+| **New chat** | Open a new conversation draft | [Chat](/chat) |
| **Agents** | Create agents and edit their prompt, memory, runtime, tools, Skills, hooks, Vault and scheduled tasks | [Agents](/agents) |
-| **Plugins** | Browse plugins, install their Skills and hook packages onto agents, and add server plugins to the Project | [Skills](/skills) |
| **Models** | Configure the Project's models, providers and credentials | [Models](/models) |
+| **Plugins** | Browse plugins, install their Skills and hook packages onto agents, and add server plugins to the Project | [Skills](/skills) |
+| **Machines** | Install this PenguinHarness build on other hosts over ssh and manage the connections to them (admins only) | [Security Model](/security#manage-remote-machines-over-ssh) |
| **Cost Center** | Token usage, cost and server errors by agent, model and time range | [Cost Center](/usage) |
| **Evaluation Center** | Benchmarks: evaluate agents and optimize them against a Benchmark | [Evaluation Center](/evaluation-center) |
@@ -103,6 +104,17 @@ From top to bottom, the sidebar holds:
- The update row, which names where an update stands and opens the update dialog. See [Updates](/updates).
- **Sign out**.
+### Pinned and collapsible entries
+
+**New chat** is always pinned. **Agents**, **Models** and **Plugins** are pinned by default: they always show. The other entries sit in a collapsible area under them, and the chevron bar at the bottom of that area folds it away or opens it again. The area starts open, and the browser remembers whether you folded it.
+
+To change which entries are pinned:
+
+- Point at an entry and select the pin at the end of its row. A filled pin means the entry is pinned; selecting it moves the entry into the collapsible area, and selecting an empty pin pins the entry. On a touch screen the pin is always shown.
+- Or drag an entry into the collapsible area to make it collapsible, or out of it to pin it.
+
+Each area keeps the order of the table above, however its entries got there, and with nothing collapsible the chevron bar is gone. The choices are saved per browser. The collapsed rail shows every entry either way.
+
### Notification dots
A dot on a page entry means something is waiting there:
@@ -110,8 +122,8 @@ A dot on a page entry means something is waiting there:
| Entry | What the dot means |
| --- | --- |
| **Agents** | Agents on an outdated kernel |
-| **Plugins** | Plugin updates |
| **Models** | Preset models to sync (shown to owners) |
+| **Plugins** | Plugin updates |
| **Cost Center** | Unexpected errors |
A dot on your avatar means a software update. Pointing at an entry names what is waiting.
@@ -122,13 +134,9 @@ A dot on your avatar means a software update. Pointing at an entry names what is
On a narrow window, the sidebar hides behind a menu button in a top bar and opens as a drawer.
-### Trajectories and Machines
-
-Two parts of the app have no sidebar entry.
-
-**Trajectories** is a side panel of the chat page, not a page of its own. It shows the open conversation's Trace files, with a summary, per-turn statistics, an execution timeline, and the individual events. **Export** downloads a file. See [Chat](/chat).
+### Trajectories
-**Machines** installs this PenguinHarness build on other hosts over ssh, choosing from the server account's `~/.ssh/config`. It is not offered in the sidebar in this release. An admin can reach it at `/machines`.
+**Trajectories** has no sidebar entry: it is a side panel of the chat page, not a page of its own. It shows the open conversation's Trace files, with a summary, per-turn statistics, an execution timeline, and the individual events. **Export** downloads a file. See [Chat](/chat).
### Language and theme
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index a82e4f4b..a4560d5d 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -86,14 +86,15 @@ penguin web
- **开发** / **公司**切换,只在公司模式可用时出现:管理员已为服务器启用公司模式,而你没有为自己关闭它。切换到公司模式后,下面的页面入口换成组织的页面,对话列表换成频道。见[公司模式](/company-mode)。
- Project 切换器,旁边是**收起侧栏**按钮。见 [Project 与成员](#project-与成员)。
-- **新建对话**,打开一份新的对话草稿。见[对话](/chat)。
-- 页面入口。最后一项下方的箭头可以把这组入口折叠起来:
+- 导航入口:
| 入口 | 用途 | 指南 |
| --- | --- | --- |
+| **新建对话** | 打开一份新的对话草稿 | [对话](/chat) |
| **智能体** | 创建 Agent,编辑它们的提示词、记忆、运行参数、工具、Skill、钩子、密钥保险柜和定时任务 | [Agent](/agents) |
-| **插件市场** | 浏览插件,把插件中的 Skill 和钩子包安装到 Agent 上,为 Project 添加服务端插件 | [Skill](/skills) |
| **模型库** | 配置 Project 的模型、供应商和凭证 | [模型](/models) |
+| **插件市场** | 浏览插件,把插件中的 Skill 和钩子包安装到 Agent 上,为 Project 添加服务端插件 | [Skill](/skills) |
+| **机器管理** | 通过 ssh 把当前版本的 PenguinHarness 安装到其他主机上,并管理与它们的连接(仅管理员) | [安全模型](/security#通过-ssh-管理远程机器) |
| **成本中心** | 按 Agent、模型和时间范围查看 Token 用量、成本和服务器异常 | [成本中心](/usage) |
| **评估中心** | Benchmark:评估 Agent,并以 Benchmark 为标准优化 Agent | [评估中心](/evaluation-center) |
@@ -103,6 +104,17 @@ penguin web
- 更新行,显示更新进行到哪一步,点击打开更新对话框,见[更新 PenguinHarness](/updates)。
- **登出**。
+### 常驻与可收起的入口
+
+**新建对话**始终常驻;**智能体**、**模型库**和**插件市场**默认常驻,始终显示。其余入口位于它们下方的收起区,区底带箭头的横条可以把整个收起区折叠或展开。收起区一开始是展开的,折叠与否记在浏览器里。
+
+调整哪些入口常驻:
+
+- 把鼠标指向入口,点击行尾的图钉。实心图钉表示该入口常驻,点击后它移入收起区;点击空心图钉则让入口常驻。触屏上图钉始终显示。
+- 也可以把入口拖进收起区,让它可以收起;或者拖出收起区,让它常驻。
+
+两个区域都按上表的顺序排列,与入口怎样移过去无关;没有可收起的入口时,箭头横条也不再显示。常驻设置按浏览器保存。收起的侧栏始终显示全部入口。
+
### 提醒圆点
页面入口上出现圆点,说明那里有事情等你处理:
@@ -110,8 +122,8 @@ penguin web
| 入口 | 圆点的含义 |
| --- | --- |
| **智能体** | 有 Agent 的内核版本过旧 |
-| **插件市场** | 有插件可以更新 |
| **模型库** | 有预置模型可以同步(仅 owner 可见) |
+| **插件市场** | 有插件可以更新 |
| **成本中心** | 有未预期的错误 |
头像上的圆点表示有软件更新。鼠标指向入口,可以看到具体在等什么。
@@ -122,13 +134,9 @@ penguin web
窗口较窄时,侧边栏收进顶栏的菜单按钮里,点击后以抽屉形式展开。
-### 轨迹观测与机器
-
-应用里有两个部分没有侧边栏入口。
-
-**轨迹观测**是对话页的一个侧边面板,而不是独立页面。它展示当前对话的 Trace 文件,包括汇总、每轮统计、执行时间线和逐条事件,点击**导出**可以下载文件。见[对话](/chat)。
+### 轨迹观测
-**机器**页通过 ssh 把当前版本的 PenguinHarness 安装到其他主机上,主机从服务器账户的 `~/.ssh/config` 中选择。这个版本的侧边栏还没有它的入口,管理员可以直接访问 `/machines`。
+**轨迹观测**没有侧边栏入口:它是对话页的一个侧边面板,而不是独立页面。它展示当前对话的 Trace 文件,包括汇总、每轮统计、执行时间线和逐条事件,点击**导出**可以下载文件。见[对话](/chat)。
### 语言与主题
diff --git a/packages/ui/src/components/navigation/nav-list/nav-list.tsx b/packages/ui/src/components/navigation/nav-list/nav-list.tsx
index ef780a3c..176a6d36 100644
--- a/packages/ui/src/components/navigation/nav-list/nav-list.tsx
+++ b/packages/ui/src/components/navigation/nav-list/nav-list.tsx
@@ -19,6 +19,11 @@
* 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.
+ *
+ * A row may share its box with a control laid over its end (the sidebar's pin toggle): then its
+ * hover answers to the enclosing `group` (`groupHover`), so the fill holds while the pointer is on
+ * the control, and a row whose whole box is a drag handle keeps its link from starting a drag of
+ * its own address (`draggable={false}`).
*/
import { createContext, useContext } from "react";
import type { ReactNode } from "react";
@@ -40,10 +45,12 @@ 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.
+ * hover and one selection hold across the column. `groupHover` is the same hover wash for a row
+ * whose hover answers to its enclosing `group`.
*/
export const NAV_FILL = {
hover: "hover:bg-fg/5",
+ groupHover: "group-hover:bg-fg/5",
selected: "bg-fg/7",
} as const;
@@ -88,15 +95,20 @@ 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 }> = {
+/**
+ * The selected and resting looks, per surface. `groupRest` is the resting look of a row whose
+ * hover answers to its enclosing `group`; a selected row keeps its own fill under the pointer.
+ */
+const STATE: Record<NavSurface, { active: string; rest: string; groupRest: string }> = {
default: {
active: "bg-line-muted font-medium text-fg",
rest: "text-fg-muted hover:bg-surface-muted hover:text-fg",
+ groupRest: "text-fg-muted group-hover:bg-surface-muted group-hover:text-fg",
},
muted: {
active: `${NAV_FILL.selected} font-medium text-fg`,
rest: `text-fg-muted ${NAV_FILL.hover} hover:text-fg`,
+ groupRest: `text-fg-muted ${NAV_FILL.groupHover} group-hover:text-fg`,
},
};
@@ -111,19 +123,24 @@ export function navRowClass({
density = "md",
orientation = "vertical",
surface = "default",
+ groupHover = false,
}: {
active?: boolean;
disabled?: boolean;
density?: NavRowDensity;
orientation?: NavListOrientation;
surface?: NavSurface;
+ /** The hover answers to the enclosing `group` rather than to the row alone. */
+ groupHover?: boolean;
} = {}): string {
const width = orientation === "responsive" ? "shrink-0 sm:w-full" : "w-full";
const state = disabled
? "cursor-not-allowed text-fg-subtle"
: active
? STATE[surface].active
- : STATE[surface].rest;
+ : groupHover
+ ? STATE[surface].groupRest
+ : STATE[surface].rest;
return `flex ${width} items-center whitespace-nowrap rounded-md text-left transition-colors duration-150 ${DENSITY[density]} ${state}`;
}
@@ -137,6 +154,8 @@ export interface NavRowLinkProps {
"aria-current"?: "page";
"aria-label"?: string;
"data-tooltip"?: string;
+ /** `false`: the link starts no drag of its own address (the row around it is the handle). */
+ draggable?: false;
onClick?: () => void;
children: ReactNode;
}
@@ -154,6 +173,16 @@ export interface NavRowProps {
density?: NavRowDensity;
/** The surface the row sits on: `muted` on the app's navigation column. */
surface?: NavSurface;
+ /**
+ * The hover answers to the enclosing `group`: for a row sharing its box with a control laid over
+ * its end, whose hover must not drop the row's fill.
+ */
+ groupHover?: boolean;
+ /**
+ * `false`: a link starts no drag of its own address, for a row inside an element that is itself
+ * the drag handle — the whole row moves instead.
+ */
+ draggable?: false;
/** 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>`. */
@@ -174,6 +203,8 @@ export function NavRow({
disabled = false,
density = "md",
surface = "default",
+ groupHover = false,
+ draggable,
href,
renderLink,
onClick,
@@ -182,12 +213,13 @@ export function NavRow({
className = "",
}: NavRowProps) {
const orientation = useContext(NavOrientationContext);
- const classes = `${navRowClass({ active, disabled, density, orientation, surface })} ${className}`;
+ const classes = `${navRowClass({ active, disabled, density, orientation, surface, groupHover })} ${className}`;
const current = active && !disabled ? ("page" as const) : undefined;
const named = {
...(ariaLabel !== undefined ? { "aria-label": ariaLabel } : {}),
...(tooltip !== undefined ? { "data-tooltip": tooltip } : {}),
};
+ const dragless = draggable === false ? { draggable: false as const } : {};
const content = (
<>
{glyph !== undefined && (
@@ -216,6 +248,7 @@ export function NavRow({
className: classes,
...(current !== undefined ? { "aria-current": current } : {}),
...named,
+ ...dragless,
...(onClick !== undefined ? { onClick } : {}),
children: content,
})}
@@ -223,7 +256,14 @@ export function NavRow({
);
}
return (
- <a href={href} aria-current={current} onClick={onClick} {...named} className={classes}>
+ <a
+ href={href}
+ aria-current={current}
+ onClick={onClick}
+ {...named}
+ {...dragless}
+ className={classes}
+ >
{content}
</a>
);
diff --git a/packages/ui/src/components/shell/session-row/session-row.tsx b/packages/ui/src/components/shell/session-row/session-row.tsx
index e88a0f17..b8e27d2b 100644
--- a/packages/ui/src/components/shell/session-row/session-row.tsx
+++ b/packages/ui/src/components/shell/session-row/session-row.tsx
@@ -55,7 +55,7 @@ export interface RowActionItem {
}
/** A hover button's glyph: a notch under the icon-button rung, sized to the row's 24px buttons. */
-const ACTION_GLYPH = 14;
+export const ROW_ACTION_GLYPH = 14;
/**
* The hover buttons: the reveal is gated on pointer events exactly as on opacity, because an
@@ -63,9 +63,9 @@ const ACTION_GLYPH = 14;
* 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.
+ * blank. The sidebar's nav entries draw their pin toggle with the same look (sidebar-frame.tsx).
*/
-const HOVER_BUTTON =
+export const ROW_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";
/**
@@ -99,11 +99,11 @@ export function RowHoverActions({
data-tooltip={action.label}
aria-label={action.label}
onClick={action.onSelect}
- className={`${HOVER_BUTTON} ${
+ className={`${ROW_HOVER_BUTTON} ${
action.danger === true ? "hover:text-tone-danger-fg" : "hover:text-fg"
}`}
>
- <GlyphIcon d={action.glyph} size={ACTION_GLYPH} />
+ <GlyphIcon d={action.glyph} size={ROW_ACTION_GLYPH} />
</button>
))}
<button
@@ -112,11 +112,11 @@ export function RowHoverActions({
aria-label={moreLabel}
aria-haspopup="menu"
onClick={openMore}
- className={`${HOVER_BUTTON} hover:text-fg`}
+ className={`${ROW_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 />
+ <GlyphIcon d={ICONS.ellipsis} size={ROW_ACTION_GLYPH} filled />
</button>
</>
);
diff --git a/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx b/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx
index 34defd60..a9888a0e 100644
--- a/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx
+++ b/packages/ui/src/components/shell/sidebar-frame/sidebar-frame.tsx
@@ -2,8 +2,10 @@
* 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 — pinned entries that always show, then the ones that fold away under a slim
+ * toggle — its entries with their pin toggles and the areas a dragged entry can land in, 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
@@ -16,14 +18,21 @@
* 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 type {
+ DragEvent as ReactDragEvent,
+ MouseEvent as ReactMouseEvent,
+ 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";
+import { NAV_FILL, NavRow } from "../../navigation/nav-list/nav-list";
+import type { NavRowProps } from "../../navigation/nav-list/nav-list";
+import { ROW_ACTION_GLYPH, ROW_HOVER_BUTTON } from "../session-row/session-row";
/**
* A list-header control's glyph: one step under the icon-button rung, since the control's square
@@ -105,19 +114,58 @@ export function SidebarFrame({
}
/**
- * 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.
+ * A nav area a dragged entry can be dropped into: the caller's drag handlers, and whether a drag
+ * the area would take is over it now, which lays the accent ring over the area.
+ */
+export interface SidebarDropTarget {
+ /** A drag this area would take is over it. */
+ over: boolean;
+ onDragOver: (e: ReactDragEvent) => void;
+ onDragLeave: (e: ReactDragEvent) => void;
+ onDrop: (e: ReactDragEvent) => void;
+}
+
+const dropHandlers = (drop: SidebarDropTarget | undefined) =>
+ drop === undefined
+ ? {}
+ : { onDragOver: drop.onDragOver, onDragLeave: drop.onDragLeave, onDrop: drop.onDrop };
+
+/**
+ * The ring over the area a drop would land in. It is laid over the area's `relative` box rather
+ * than drawn by the box itself, because the rows paint over their container and a selected row's
+ * fill would hide an outline of the box's own.
+ */
+function DropRing() {
+ return (
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-0 z-10 rounded-md ring-1 ring-inset ring-accent"
+ />
+ );
+}
+
+/**
+ * The page nav: the pinned entries, which always show, then the rest 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.
+ *
+ * With nothing to fold (`foldable={false}`) neither the group nor its toggle is drawn. With
+ * `drop`, the group and its toggle band are one drop target, ringed while a drag it would take is
+ * over them.
*/
export function SidebarNavGroup({
collapsed,
onToggle,
expandLabel,
collapseLabel,
+ pinned,
+ foldable = true,
+ drop,
+ toggleRef,
children,
}: {
collapsed: boolean;
@@ -126,39 +174,160 @@ export function SidebarNavGroup({
expandLabel: string;
/** The toggle's name while they show. */
collapseLabel: string;
+ /** The entries that show whatever the fold, above it (a `SidebarNavArea`). */
+ pinned?: ReactNode;
+ /** Whether there is a group to fold: false draws neither the group nor its toggle. */
+ foldable?: boolean;
+ /** The group and its toggle band as a drop target. */
+ drop?: SidebarDropTarget;
+ /** The toggle's node: where the caller sends focus that cannot land in the folded group. */
+ toggleRef?: Ref<HTMLButtonElement>;
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}>
+ {pinned}
+ {foldable && (
+ <div {...dropHandlers(drop)} className="relative flex flex-col gap-px">
<div
- className={`space-y-px transition-opacity duration-200 ${
- collapsed ? "opacity-0" : "opacity-100"
- }`}
+ data-layout-motion
+ className={`grid ${collapsed ? "grid-rows-[0fr]" : "grid-rows-[1fr]"}`}
>
- {children}
+ <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
+ ref={toggleRef}
+ 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>
+ {drop?.over === true && <DropRing />}
</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>
);
}
+/**
+ * A run of nav entries outside the fold — the pinned ones — as the place a dragged entry can
+ * land: the caller's `drop` wiring, and the ring while a drag it would take is over it. `reserve`
+ * keeps a row's height while the run is empty, so a drag still has somewhere to land.
+ */
+export function SidebarNavArea({
+ drop,
+ reserve = false,
+ children,
+}: {
+ drop?: SidebarDropTarget;
+ /** Hold a row's height with no rows in it. */
+ reserve?: boolean;
+ children?: ReactNode;
+}) {
+ return (
+ <div
+ {...dropHandlers(drop)}
+ className={`relative flex flex-col gap-px${reserve ? " min-h-8" : ""}`}
+ >
+ {children}
+ {drop?.over === true && <DropRing />}
+ </div>
+ );
+}
+
+/** A nav entry's pin toggle, as its caller describes it. */
+export interface SidebarNavPin {
+ /** The entry is pinned: the tack is filled. */
+ pinned: boolean;
+ /** The toggle's accessible name, the same either way: `aria-pressed` carries the state. */
+ label: string;
+ /** The hint: the move a click makes ("Pin" while unpinned, "Unpin" while pinned). */
+ tooltip: string;
+ onToggle: (e: ReactMouseEvent<HTMLButtonElement>) => void;
+ /** The toggle's node: a caller moving focus onto it once the entry has changed area reads it. */
+ buttonRef?: Ref<HTMLButtonElement>;
+}
+
+export interface SidebarNavEntryProps extends Omit<
+ NavRowProps,
+ "badge" | "surface" | "groupHover" | "draggable"
+> {
+ pin: SidebarNavPin;
+ /** A mark at the row's end (an update dot) that gives way to the toggle wherever it shows. */
+ badge?: ReactNode;
+ /** The whole row is a drag handle; the caller wires the handlers below. */
+ draggable?: boolean;
+ onDragStart?: (e: ReactDragEvent) => void;
+ onDragEnd?: () => void;
+}
+
+/**
+ * A page entry on the navigation column that the reader can pin: the column's `NavRow`, with a
+ * pin toggle over the row's end (a button cannot sit inside the row's link, so the toggle is laid
+ * over the link's last pixels and the link keeps the whole row as its hit area). The toggle is the
+ * conversation rows' hover button — flat, shown on the row's hover or its own focus, taking taps
+ * only while shown — with one addition: where there is no hover at all it always shows, because
+ * the toggle is then the only way to move an entry. The tack is filled while pinned.
+ *
+ * The row's hover answers to the entry as a whole, so its fill holds while the pointer is on the
+ * toggle. A badge sits at the row's end, where the toggle appears, so it gives way to the toggle —
+ * the conversation rows' time-and-actions handoff — and where the toggle always shows it moves
+ * just left of it. Draggable, the whole entry is the handle and its link starts no drag of its own.
+ */
+export function SidebarNavEntry({
+ pin,
+ badge,
+ draggable = false,
+ onDragStart,
+ onDragEnd,
+ ...row
+}: SidebarNavEntryProps) {
+ return (
+ <div
+ className="group relative flex items-center"
+ {...(draggable ? { draggable: true, onDragStart, onDragEnd } : {})}
+ >
+ <NavRow
+ {...row}
+ surface="muted"
+ groupHover
+ {...(draggable ? { draggable: false as const } : {})}
+ />
+ <span className="peer absolute right-1 top-1/2 flex -translate-y-1/2">
+ <button
+ ref={pin.buttonRef}
+ type="button"
+ data-tooltip={pin.tooltip}
+ aria-label={pin.label}
+ aria-pressed={pin.pinned}
+ onClick={pin.onToggle}
+ className={`${ROW_HOVER_BUTTON} hover:text-fg [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100`}
+ >
+ <GlyphIcon d={ICONS.pin} size={ROW_ACTION_GLYPH} filled={pin.pinned} />
+ </button>
+ </span>
+ {badge !== undefined && (
+ <span className="pointer-events-none absolute inset-y-0 right-0 transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0 [@media(hover:none)]:right-6.5">
+ {badge}
+ </span>
+ )}
+ </div>
+ );
+}
+
/**
* 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'
diff --git a/packages/ui/test/sidebar-frame.test.ts b/packages/ui/test/sidebar-frame.test.ts
index bb33fd21..7045b0ae 100644
--- a/packages/ui/test/sidebar-frame.test.ts
+++ b/packages/ui/test/sidebar-frame.test.ts
@@ -1,7 +1,8 @@
/**
* 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
+ * only block that shrinks, a page nav whose pinned entries stay above the part that folds under
+ * its toggle, entries that carry a pin toggle and drag as a whole, a list header whose label is
* the eyebrow rung, and the column's washes in place of surface steps.
*/
import { createElement } from "react";
@@ -9,16 +10,35 @@ 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 { ROW_HOVER_BUTTON } from "../src/components/shell/session-row/session-row";
import {
SidebarAccountButton,
SidebarControl,
SidebarFrame,
SidebarListHeader,
+ SidebarNavArea,
+ SidebarNavEntry,
SidebarNavGroup,
sidebarControlClass,
} from "../src/components/shell/sidebar-frame/sidebar-frame";
+import type {
+ SidebarDropTarget,
+ SidebarNavEntryProps,
+} from "../src/components/shell/sidebar-frame/sidebar-frame";
import { classTokens, renderStatic } from "../src/testing";
+/** A drop target's wiring, with a drag it would take over it or not. */
+const dropTarget = (over: boolean): SidebarDropTarget => ({
+ over,
+ onDragOver: () => {},
+ onDragLeave: () => {},
+ onDrop: () => {},
+});
+
+/** The ring a drop target draws while a drag it would take is over it. */
+const DROP_RING =
+ '<span aria-hidden="true" class="pointer-events-none absolute inset-0 z-10 rounded-md ring-1 ring-inset ring-accent"></span>';
+
const frame = (props: Partial<Parameters<typeof SidebarFrame>[0]> = {}) =>
renderStatic(
createElement(SidebarFrame, {
@@ -94,6 +114,134 @@ describe("SidebarNavGroup", () => {
});
});
+describe("SidebarNavGroup's pinned entries and drop targets", () => {
+ const nav = (props: Partial<Parameters<typeof SidebarNavGroup>[0]> = {}) =>
+ renderStatic(
+ createElement(SidebarNavGroup, {
+ collapsed: false,
+ onToggle: () => {},
+ expandLabel: "展开",
+ collapseLabel: "折叠",
+ children: createElement("a", { href: "/usage" }, "Cost Center"),
+ ...props,
+ }),
+ );
+ const agents = createElement("a", { href: "/agents" }, "Agents");
+
+ it("draws the pinned entries above the fold, in the same navigation", () => {
+ expect(nav({ pinned: agents })).toMatch(
+ /^<nav class="space-y-px"><a href="\/agents">Agents<\/a><div class="relative flex flex-col gap-px"><div data-layout-motion="true"/,
+ );
+ });
+
+ it("keeps the pinned entries shown and reachable while the rest is folded", () => {
+ const html = nav({ collapsed: true, pinned: agents });
+ expect(html.indexOf('href="/agents"')).toBeLessThan(html.indexOf('inert=""'));
+ });
+
+ it("draws neither the fold nor its toggle with nothing to fold", () => {
+ const html = nav({ foldable: false, pinned: agents });
+ expect(html).toBe('<nav class="space-y-px"><a href="/agents">Agents</a></nav>');
+ });
+
+ it("rings the fold and its toggle band while a drag it would take is over them, and only then", () => {
+ expect(nav({ drop: dropTarget(true) })).toContain(`</button>${DROP_RING}</div></nav>`);
+ expect(nav({ drop: dropTarget(false) })).not.toContain("ring-accent");
+ expect(nav()).not.toContain("ring-accent");
+ });
+});
+
+describe("SidebarNavArea", () => {
+ it("rings its run while a drag it would take is over it", () => {
+ const html = renderStatic(
+ createElement(SidebarNavArea, { drop: dropTarget(true) }, createElement("a", null, "New")),
+ );
+ expect(html).toBe(`<div class="relative flex flex-col gap-px"><a>New</a>${DROP_RING}</div>`);
+ expect(
+ renderStatic(createElement(SidebarNavArea, { drop: dropTarget(false) }, "rows")),
+ ).not.toContain("ring-accent");
+ });
+
+ it("holds a row's height with no rows in it only when asked to", () => {
+ expect(classTokens(renderStatic(createElement(SidebarNavArea, { reserve: true })))).toContain(
+ "min-h-8",
+ );
+ expect(classTokens(renderStatic(createElement(SidebarNavArea, {})))).not.toContain("min-h-8");
+ });
+});
+
+describe("SidebarNavEntry", () => {
+ const pin = (pinned: boolean) => ({
+ pinned,
+ label: "Pin",
+ tooltip: pinned ? "Unpin" : "Pin",
+ onToggle: () => {},
+ });
+ const entry = (props: Partial<SidebarNavEntryProps> = {}) =>
+ renderStatic(
+ createElement(SidebarNavEntry, {
+ label: "Models",
+ glyph: ICONS.chip,
+ href: "/models",
+ pin: pin(true),
+ ...props,
+ }),
+ );
+
+ it("names its pin the same either way and carries the state in aria-pressed, the hint naming the move", () => {
+ expect(entry()).toContain('data-tooltip="Unpin" aria-label="Pin" aria-pressed="true"');
+ expect(entry({ pin: pin(false) })).toContain(
+ 'data-tooltip="Pin" aria-label="Pin" aria-pressed="false"',
+ );
+ });
+
+ it("fills the tack only while pinned", () => {
+ expect(entry().match(/fill="currentColor"/g)).toHaveLength(1);
+ expect(entry({ pin: pin(false) })).not.toContain('fill="currentColor"');
+ });
+
+ it("reveals the pin as the conversation rows reveal their hover buttons, and always shows it where nothing hovers", () => {
+ const tokens = classTokens(entry());
+ expect(tokens).toEqual(expect.arrayContaining(ROW_HOVER_BUTTON.split(" ")));
+ expect(tokens).toEqual(
+ expect.arrayContaining([
+ "[@media(hover:none)]:opacity-100",
+ "[@media(hover:none)]:pointer-events-auto",
+ ]),
+ );
+ });
+
+ it("keeps the row's fill while the pointer is on the pin: the hover answers to the whole entry", () => {
+ const tokens = classTokens(entry());
+ expect(tokens).toEqual(expect.arrayContaining(["group", NAV_FILL.groupHover]));
+ expect(tokens).not.toContain(NAV_FILL.hover);
+ // A selected entry keeps its own fill under the pointer.
+ const active = classTokens(entry({ active: true }));
+ expect(active).toContain(NAV_FILL.selected);
+ expect(active).not.toContain(NAV_FILL.groupHover);
+ });
+
+ it("drags as a whole: the entry is the handle, and its link starts no drag of its own", () => {
+ expect(entry({ draggable: true, onDragStart: () => {}, onDragEnd: () => {} })).toMatch(
+ /^<div class="group relative flex items-center" draggable="true"><a href="\/models" draggable="false" class="/,
+ );
+ expect(entry()).not.toContain("draggable");
+ });
+
+ it("puts a badge after the pin, giving way to it and moving clear of it where it always shows", () => {
+ const html = entry({ badge: createElement("i", { "data-dot": "" }) });
+ expect(html.indexOf('aria-pressed="true"')).toBeLessThan(html.indexOf("data-dot"));
+ expect(classTokens(html)).toEqual(
+ expect.arrayContaining([
+ "peer",
+ "group-hover:opacity-0",
+ "peer-focus-within:opacity-0",
+ "[@media(hover:none)]:right-6.5",
+ ]),
+ );
+ });
+});
+
describe("SidebarListHeader", () => {
const header = (searching: boolean) =>
renderStatic(
@@ -166,6 +314,35 @@ describe("NavRow on the navigation column", () => {
expect(navRowClass({ active: true })).toContain("bg-line-muted");
});
+ it("answers to the enclosing group's hover when asked, leaving a selected row's fill alone", () => {
+ const rest = navRowClass({ surface: "muted", groupHover: true }).split(" ");
+ expect(rest).toEqual(expect.arrayContaining([NAV_FILL.groupHover, "group-hover:text-fg"]));
+ expect(rest).not.toContain(NAV_FILL.hover);
+ const active = navRowClass({ active: true, surface: "muted", groupHover: true }).split(" ");
+ expect(active).toContain(NAV_FILL.selected);
+ expect(active.filter((token) => token.startsWith("group-hover:"))).toEqual([]);
+ });
+
+ it("hands a router a link that starts no drag of its own when the row is inside a handle", () => {
+ const seen: NavRowLinkProps[] = [];
+ renderStatic(
+ createElement(NavRow, {
+ label: "Agents",
+ href: "/agents",
+ surface: "muted",
+ draggable: false,
+ renderLink: (link: NavRowLinkProps) => {
+ seen.push(link);
+ return null;
+ },
+ }),
+ );
+ expect(seen[0]).toMatchObject({ href: "/agents", draggable: false });
+ expect(renderStatic(createElement(NavRow, { label: "Agents", href: "/agents" }))).not.toContain(
+ "draggable",
+ );
+ });
+
it("hands a router its link: the address, the row's classes and the current page", () => {
const seen: NavRowLinkProps[] = [];
const html = renderStatic(
diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjs
index da7cee9f..9dacb78a 100644
--- a/packages/web/e2e/layout.spec.mjs
+++ b/packages/web/e2e/layout.spec.mjs
@@ -27,10 +27,11 @@
* chrome used to stop fitting below ~412px;
* - the sidebar's "New chat" button has no background fill (same gray-scale style as nav items);
* - the collapsed rail shows, in product-specified order, last conversation / new chat /
- * Agents / Plugins / Models / Cost Center / Evaluation Center, each labeled by a
- * localized (en + zh) styled tooltip on hover and by no native `title` (two tooltips would
- * stack); "last conversation" targets the most recently active non-archived session and is
- * disabled while none exists; expanding from the rail restores the pinned sidebar;
+ * Agents / Models / Plugins / Cost Center / Evaluation Center (the user is a member, so no
+ * Machines), each labeled by a localized (en + zh) styled tooltip on hover and by no native
+ * `title` (two tooltips would stack); "last conversation" targets the most recently active
+ * non-archived session and is disabled while none exists; expanding from the rail restores
+ * the pinned sidebar;
* - login page: a single brand penguin logo above the form (part of the form area; the
* background still only has the trace animation), the trace animation grows in after a
* delayed blank first paint, no two trace segments cross or touch (except where a fork shares
@@ -419,20 +420,24 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation",
"Last conversation",
"New chat",
"Agents",
- "Plugins",
"Models",
+ "Plugins",
"Cost Center",
"Evaluation Center",
];
const attrs = (name) =>
entries.evaluateAll((els, n) => els.map((el) => el.getAttribute(n)), name);
- expect(await attrs("aria-label"), "rail order (en)").toEqual(EN);
+ // An entry on a badge trail appends what is waiting (" · …") to its name, and Models does
+ // here: replacing the Project's model table above leaves presets to sync. The order is
+ // about the names.
+ const names = async () => (await attrs("aria-label")).map((label) => label.split(" · ")[0]);
+ expect(await names(), "rail order (en)").toEqual(EN);
// No native title anywhere on the rail: it would open a second, slower tooltip under the
// styled one, which is the whole reason the styled one exists.
expect(await attrs("title"), "rail carries no native tooltips (en)").toEqual(EN.map(() => null));
const tooltip = page.getByTestId("tooltip");
await rail.getByRole("link", { name: "Models" }).hover();
- await expect(tooltip, "rail tooltip (en)").toHaveText("Models");
+ await expect(tooltip, "rail tooltip (en)").toHaveText(/^Models/);
await rail.getByRole("button", { name: "Last conversation" }).hover();
await expect(tooltip, "rail tooltip follows the pointer (en)").toHaveText("Last conversation");
@@ -491,15 +496,16 @@ test("layout: collapsed rail — order, bilingual tooltips, last conversation",
await page.addInitScript(() => localStorage.setItem("penguin.lang", "zh"));
await page.reload();
await expect(entries).toHaveCount(7);
- const ZH = ["最近一次对话", "新建对话", "智能体", "插件市场", "模型库", "成本中心", "评估中心"];
- expect(await attrs("aria-label"), "rail order (zh)").toEqual(ZH);
+ const ZH = ["最近一次对话", "新建对话", "智能体", "模型库", "插件市场", "成本中心", "评估中心"];
+ expect(await names(), "rail order (zh)").toEqual(ZH);
expect(await attrs("title"), "rail carries no native tooltips (zh)").toEqual(ZH.map(() => null));
await rail.getByRole("link", { name: "模型库" }).hover();
- await expect(page.getByTestId("tooltip"), "rail tooltip (zh)").toHaveText("模型库");
+ await expect(page.getByTestId("tooltip"), "rail tooltip (zh)").toHaveText(/^模型库/);
// --- Expand: the rail's top button (localized) restores the pinned sidebar ---
await page.getByRole("button", { name: "展开侧栏" }).click();
- await expect(page.locator("aside")).toHaveClass(/w-64/);
+ // The app's sidebar is the first <aside>; the Plugins page open here has one of its own.
+ await expect(page.locator("aside").first()).toHaveClass(/w-64/);
await expect(page.getByRole("button", { name: "收起侧栏" })).toBeVisible();
});
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index 3def87c7..43633fa2 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -30,6 +30,7 @@ import { S } from "../../lib/strings";
import { onCommand } from "../../lib/shortcuts/dispatcher";
import { useShortcutTitle } from "../../lib/shortcuts/use-keymap";
import { latestConversation, withoutOrgSessions } from "../../lib/session-grouping";
+import { navKeysFor } from "../../lib/nav-group-collapse";
import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";
import { useAuth } from "../../state/auth";
import { useProject } from "../../state/project";
@@ -72,8 +73,9 @@ function pinnedSidebarOnScreen(): boolean {
/**
* 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.
+ * last conversation / new chat / Agents / Models / Plugins / Machines (admins) / Cost Center /
+ * Evaluation Center; 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 name and the same
* words in a styled tooltip (the package's `RailItem`). The entries' names come from the same
@@ -126,9 +128,10 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
/** Mirrors the pinned sidebar's "New chat" (use-new-chat.ts): parks any typed-but-unsent draft text first, then opens a draft that names nothing, so it starts on the Project's new-chat defaults. */
const newChat = useNewChat();
- /** Page entries (rail positions 3-8): same routes, same labels as the pinned nav.
- Traces is not among them: reading a Trace happens in the chat toolbar's panel
- switcher, which is the only place it happens. */
+ /** Page entries (after last conversation and new chat): the pinned nav's manifest, routes
+ and labels, in its order, and all of them whether pinned or collapsible there — the
+ rail has no fold. Traces is not among them: reading a Trace happens in the chat
+ toolbar's panel switcher, which is the only place it happens. */
const pages: ReadonlyArray<{
key: string;
/** Where the entry leads — null while company mode has no organization, which renders it disabled. */
@@ -146,13 +149,13 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
icon: COMPANY_NAV_ICONS[key],
note: null,
}))
- : [
- { to: "/agents", label: S.nav.agents, icon: NAV_ICONS.agents },
- { to: "/plugins", label: S.nav.plugins, icon: NAV_ICONS.plugins },
- { to: "/models", label: S.nav.models, icon: NAV_ICONS.models },
- { to: "/usage", label: S.nav.usage, icon: NAV_ICONS.usage },
- { to: "/benchmark", label: S.nav.benchmark, icon: NAV_ICONS.benchmark },
- ].map((item) => ({ ...item, key: item.to, note: navNoteFor(badges, item.to) }));
+ : navKeysFor(user?.isAdmin === true).map((key) => ({
+ key,
+ to: `/${key}`,
+ label: S.nav[key],
+ icon: NAV_ICONS[key],
+ note: navNoteFor(badges, `/${key}`),
+ }));
/**
* The rail's avatar hangs its menu off the rail's OUTER edge rather than over the rail:
@@ -279,10 +282,10 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
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. */}
+ {/* 3 onward. Page entries. Four sit on a badge trail — Agents (an outdated kernel),
+ Plugins, 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 (
diff --git a/packages/web/src/components/layout/router-link.tsx b/packages/web/src/components/layout/router-link.tsx
index f6e55f0f..5343f82b 100644
--- a/packages/web/src/components/layout/router-link.tsx
+++ b/packages/web/src/components/layout/router-link.tsx
@@ -15,6 +15,7 @@ export function renderRouterLink(link: NavRowLinkProps) {
aria-current={link["aria-current"]}
aria-label={link["aria-label"]}
data-tooltip={link["data-tooltip"]}
+ draggable={link.draggable}
onClick={link.onClick}
>
{link.children}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index f7533737..f8ad00df 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -1,10 +1,12 @@
/**
* Single-column sidebar, top to bottom:
- * Project switcher -> new chat (a draft on the Project's new-chat defaults) + page nav
- * (Agents → Evaluation Center, one collapsible group behind a nav-row-wide chevron button
- * under its last entry: arrow
- * up = click to collapse, arrow down while collapsed = the way back; state persists in
- * localStorage, the pinned new-chat block never collapses) -> Session area with three grouping
+ * Project switcher -> nav: New chat (a draft on the Project's new-chat defaults), always pinned
+ * in its fixed slot above the scroll area, then Agents → Evaluation Center. Each page entry is
+ * pinned (always shown) or collapsible (folded away by a nav-row-wide chevron button under the
+ * collapsible area: arrow up = click to collapse, arrow down while collapsed = the way back);
+ * Agents, Models and Plugins are pinned by default, a row's hover pin button or a drag across
+ * the areas moves an entry, and both the fold and the pin choices persist in localStorage
+ * (nav-group-collapse.ts) -> Session area with three grouping
* modes (chosen in the section header's list options; the
* choice and each Project's group collapse and pin state persist in localStorage): by Workspace
* (the default; groups loaded Sessions by their
@@ -75,6 +77,8 @@ import {
SidebarControl,
SidebarFrame,
SidebarListHeader,
+ SidebarNavArea,
+ SidebarNavEntry,
SidebarNavGroup,
SidebarSwitcherButton,
SkeletonList,
@@ -84,6 +88,7 @@ import {
toastInfo,
toastSuccess,
} from "@prismshadow/penguin-ui";
+import type { SidebarDropTarget } from "@prismshadow/penguin-ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { formatRelativeShort } from "../../lib/format";
@@ -130,9 +135,15 @@ import { machineForSession } from "../../lib/session-machines";
import { nameOnMachine } from "../../lib/workspace-machines";
import {
initialNavGroupCollapsed,
- navKeysFor,
+ initialNavPinOverrides,
+ isNavPinned,
+ navEntryKeysFor,
+ splitNavEntries,
storeNavGroupCollapsed,
+ storeNavPinOverrides,
+ withNavPinned,
} from "../../lib/nav-group-collapse";
+import type { NavEntryKey, NavGroupKey } from "../../lib/nav-group-collapse";
import {
loadPinnedSessions,
removePinnedSession,
@@ -246,6 +257,18 @@ const GROUP_DRAG_MIME = "application/x-penguin-group-key";
*/
const isGroupDrag = (e: ReactDragEvent): boolean => e.dataTransfer.types.includes(GROUP_DRAG_MIME);
+/** Private drag payload type of a nav entry moved between the pinned and collapsible areas (never text/plain, as above). */
+const NAV_DRAG_MIME = "application/x-penguin-nav-entry";
+
+/** Is the drag in flight a nav entry of ours? Authorizes a nav drop the way isGroupDrag authorizes a group drop. */
+const isNavDrag = (e: ReactDragEvent): boolean => e.dataTransfer.types.includes(NAV_DRAG_MIME);
+
+/** The two nav areas a dragged entry can be dropped into. */
+type NavArea = "pinned" | "collapsible";
+
+/** A page entry of the development nav: every entry but New chat, which keeps its fixed slot. */
+const isNavPage = (key: NavEntryKey): key is NavGroupKey => key !== "newChat";
+
/** Manual drag-reordering needs a pointer that can drag (HTML5 DnD never fires from touch) — the outline rail's query. */
const DRAG_POINTER_QUERY = "(hover: hover) and (pointer: fine)";
@@ -462,8 +485,21 @@ export function Sidebar({
const pinStoreKey = currentProjectId === null ? null : pinnedGroupsKey(currentProjectId);
const folderOnlyStoreKey =
currentProjectId === null ? null : expandedFolderOnlyGroupsKey(currentProjectId);
- /** Collapsed page-nav group (the 智能体 → 评估中心 entries; expanded by default, the choice persists across sessions). */
+ /** Folded collapsible nav area (company mode: the whole nav group); expanded by default, the choice persists across sessions. */
const [navCollapsed, setNavCollapsed] = useState(initialNavGroupCollapsed);
+ /** The user's changes to which nav entries are pinned (the defaults live in nav-group-collapse.ts); persisted like the fold. */
+ const [navPins, setNavPins] = useState(initialNavPinOverrides);
+ /** Nav entry being dragged across the areas, and the area a drop would move it into. */
+ const [navDrag, setNavDrag] = useState<NavEntryKey | null>(null);
+ const [navDropArea, setNavDropArea] = useState<NavArea | null>(null);
+ /**
+ * The entry whose pin button takes focus once its row re-mounts in the other area. Moving
+ * an entry moves its row to another container, and the button that had focus goes with the
+ * old one — a keyboard user would be dropped onto <body>.
+ */
+ const pinFocusRef = useRef<NavEntryKey | null>(null);
+ /** The chevron toggle: where focus goes when the moved row lands in a folded (inert) area. */
+ const navToggleRef = useRef<HTMLButtonElement | null>(null);
/** Grouping mode of the Session list (Workspace by default; the choice persists across sessions). */
const [groupMode, setGroupModeState] = useState<GroupMode>(initialGroupMode);
/** Collapsed groups (expanded by default), keyed by Agent id or Workspace group key depending on the mode; persisted per Project. */
@@ -619,6 +655,65 @@ export function Sidebar({
setNavCollapsed(next);
};
+ /** Pin or unpin one nav entry: the pin button and a drop across the areas both land here. */
+ const setNavPinned = (key: NavEntryKey, pinned: boolean) => {
+ const next = withNavPinned(navPins, key, pinned);
+ if (next === navPins) return;
+ storeNavPinOverrides(next);
+ setNavPins(next);
+ };
+
+ /**
+ * Drag wiring of one development-mode nav entry: the row is its own handle. Offered only
+ * where a pointer that can drag exists (HTML5 drag-and-drop never fires from touch); the
+ * pin button is the way everywhere, and the only one there.
+ */
+ const navEntryDragProps = (key: NavEntryKey) =>
+ canDrag
+ ? {
+ draggable: true,
+ onDragStart: (e: ReactDragEvent) => {
+ e.dataTransfer.setData(NAV_DRAG_MIME, key);
+ e.dataTransfer.effectAllowed = "move";
+ setNavDrag(key);
+ },
+ onDragEnd: () => {
+ setNavDrag(null);
+ setNavDropArea(null);
+ },
+ }
+ : {};
+
+ /**
+ * Drop wiring of one nav area. Only a drag that would move the entry to this side is
+ * accepted, so dropping a row back into its own area is not a drop at all; where inside the
+ * area it lands is not asked, since both areas keep manifest order.
+ */
+ const navAreaDrop = (area: NavArea): SidebarDropTarget => ({
+ over: navDropArea === area,
+ onDragOver: (e) => {
+ if (navDrag === null || !isNavDrag(e)) return;
+ if (isNavPinned(navDrag, navPins) === (area === "pinned")) return;
+ e.preventDefault();
+ // The effect must be one effectAllowed permits, or the drop never fires (groupDragProps).
+ e.dataTransfer.dropEffect = "move";
+ setNavDropArea(area);
+ },
+ // Crossing onto one of the area's own rows fires dragleave too; still inside is no change.
+ onDragLeave: (e) => {
+ const to = e.relatedTarget;
+ if (to instanceof Node && e.currentTarget.contains(to)) return;
+ setNavDropArea((prev) => (prev === area ? null : prev));
+ },
+ onDrop: (e) => {
+ if (navDrag === null || !isNavDrag(e)) return;
+ e.preventDefault();
+ setNavPinned(navDrag, area === "pinned");
+ setNavDrag(null);
+ setNavDropArea(null);
+ },
+ });
+
/** Workspace-mode per-group exact server totals (folded from the per-Agent per-Workspace counts). */
const workspaceGroupCounts = useMemo(
() => aggregateWorkspaceCounts(workspaceCountsByAgent),
@@ -1745,19 +1840,16 @@ export function Sidebar({
);
/**
- * Page entries of the collapsible nav group. Development mode: 智能体 → 评估中心, driven by
- * the NAV_GROUP_KEYS manifest minus the entries this user's role cannot reach. Company
- * mode: the organization's six pages (COMPANY_NAV_KEYS) — channels are not among them,
- * they are the list below. Always mounted — the collapse animates their height to zero and
- * turns them inert.
+ * Company mode's nav rows: the organization's six pages (COMPANY_NAV_KEYS) — channels are not
+ * among them, they are the list below — all in the fold, with no pins and no drag. Always
+ * mounted — the fold animates their height to zero and turns them inert.
*/
- const navItems: Array<{
+ const companyNavItems: Array<{
key: string;
/** Where the row leads — null for a row with nowhere to lead, which renders disabled. */
to: string | null;
label: string;
icon: string;
- note: string | null;
}> = inCompany
? COMPANY_NAV_KEYS.map((key) => ({
key,
@@ -1767,15 +1859,73 @@ export function Sidebar({
to: navOrg === null ? null : orgPagePath(navOrg.projectId, navOrg.orgId, key),
label: S.nav.org[key],
icon: COMPANY_NAV_ICONS[key],
- note: null,
}))
- : navKeysFor(user?.isAdmin === true).map((key) => ({
- key,
- to: `/${key}`,
- label: S.nav[key],
- icon: NAV_ICONS[key],
- note: navNoteFor(badges, `/${key}`),
- }));
+ : [];
+
+ /**
+ * Development mode's entries by area (nav-group-collapse.ts): New chat, then the
+ * NAV_GROUP_KEYS manifest minus the entries this user's role cannot reach, each pinned or
+ * collapsible, both areas in manifest order. New chat is always pinned and renders in its
+ * fixed slot above the scroll area, so the pinned rows here are the pages after it.
+ */
+ const navSplit = splitNavEntries(navEntryKeysFor(user?.isAdmin === true), navPins);
+ const pinnedNavPages = navSplit.pinned.filter(isNavPage);
+ const collapsibleNavPages = navSplit.collapsible.filter(isNavPage);
+
+ /**
+ * One development-mode page entry: the package's pinnable nav row, bound to its route, its
+ * badge trail, its pin choice and its drag. Four entries sit on a badge trail — Agents (an
+ * outdated kernel, fixed on the Agent settings page two clicks down), Plugins, Models and the
+ * Cost Center (each cleared on the page itself). 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. The dot
+ * hangs at the row's right edge, vertically centred on the row.
+ */
+ const renderNavEntry = (key: NavGroupKey) => {
+ const to = `/${key}`;
+ const label = S.nav[key];
+ const note = navNoteFor(badges, to);
+ const pinned = isNavPinned(key, navPins);
+ return (
+ <SidebarNavEntry
+ key={key}
+ label={label}
+ glyph={NAV_ICONS[key]}
+ href={to}
+ active={isCurrentPath(to, location.pathname)}
+ renderLink={renderRouterLink}
+ onClick={() => onNavigate?.()}
+ {...navEntryDragProps(key)}
+ pin={{
+ pinned,
+ label: S.nav.pinEntry,
+ tooltip: pinned ? S.nav.unpinEntry : S.nav.pinEntry,
+ onToggle: (e) => {
+ // A keyboard toggle follows its row into the other area (see pinFocusRef).
+ if (e.currentTarget.matches(":focus-visible")) pinFocusRef.current = key;
+ setNavPinned(key, !pinned);
+ },
+ buttonRef: (el) => {
+ if (el === null || pinFocusRef.current !== key) return;
+ pinFocusRef.current = null;
+ el.focus();
+ // A row that lands in the folded area is inert and cannot take focus: the chevron
+ // that unfolds it is the nearest place to stand. It is read once this commit is
+ // done, since the commit may be mounting the chevron together with the row.
+ if (document.activeElement !== el) {
+ queueMicrotask(() => navToggleRef.current?.focus());
+ }
+ },
+ }}
+ {...(note !== null
+ ? {
+ ariaLabel: `${label} · ${note}`,
+ tooltip: note,
+ badge: <UpdateDot size="inline" position="right-2.5 top-1/2 -translate-y-1/2" />,
+ }
+ : {})}
+ />
+ );
+ };
/**
* The account row at the column's foot: the trigger for the account menu both this sidebar and
@@ -2061,66 +2211,77 @@ export function Sidebar({
</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).
+ // New chat: always pinned, in the one slot between the switcher above and the scroll area
+ // below; it has no pin button and cannot be dragged. 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. Its slot
+ // belongs to the pinned area, so it also takes an entry dragged out of the collapsible
+ // one. 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"
- />
+ <SidebarNavArea drop={navAreaDrop("pinned")}>
+ <NavRow
+ surface="muted"
+ label={S.chat.newSessionMenu}
+ tooltip={newChatTitle}
+ glyph={NEW_CHAT_ICON}
+ active={activeSessionId === DRAFT_SESSION_ID}
+ onClick={() => newChat()}
+ className="font-medium"
+ />
+ </SidebarNavArea>
),
})}
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. */}
+ {/* The page nav: in development mode the pinned pages, then the collapsible ones folded
+ away under the slim toggle (with nothing collapsible there is no toggle); in company
+ mode the organization's six pages, all under the toggle. The fold persists. Folded rows
+ stay mounted — the fold animates their height to zero and turns them inert. The nav
+ and the session list scroll together. Mid-drag, an empty pinned run keeps a row's
+ height and a hidden toggle band comes back, so either side can take the drop. */}
<SidebarNavGroup
collapsed={navCollapsed}
onToggle={toggleNavGroup}
expandLabel={S.nav.expandGroup}
collapseLabel={S.nav.collapseGroup}
+ toggleRef={navToggleRef}
+ {...(inCompany
+ ? {}
+ : {
+ pinned:
+ pinnedNavPages.length > 0 || navDrag !== null ? (
+ <SidebarNavArea
+ drop={navAreaDrop("pinned")}
+ reserve={pinnedNavPages.length === 0}
+ >
+ {pinnedNavPages.map(renderNavEntry)}
+ </SidebarNavArea>
+ ) : undefined,
+ foldable: collapsibleNavPages.length > 0 || navDrag !== null,
+ drop: navAreaDrop("collapsible"),
+ })}
>
- {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" />,
- }
- : {})}
- />
- ))}
+ {inCompany
+ ? companyNavItems.map((item) => (
+ /* 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?.()}
+ />
+ ))
+ : collapsibleNavPages.map(renderNavEntry)}
</SidebarNavGroup>
{inCompany ? (
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index 9082f7b5..0ea39796 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -215,6 +215,12 @@ export const KEY_RULES: readonly KeyRule[] = [
scope: "browser",
why: "Whether the static page-nav group is folded; the nav is built from a compile-time manifest.",
},
+ {
+ kind: "exact",
+ key: "penguin.sidebarNavPinned",
+ scope: "browser",
+ why: "Which nav entries stay out of the fold; keyed by the compile-time manifest, names nothing on the server.",
+ },
{
kind: "exact",
key: "penguin.steerMode",
diff --git a/packages/web/src/lib/nav-group-collapse.ts b/packages/web/src/lib/nav-group-collapse.ts
index 05a066e3..8b2ad2be 100644
--- a/packages/web/src/lib/nav-group-collapse.ts
+++ b/packages/web/src/lib/nav-group-collapse.ts
@@ -1,26 +1,27 @@
/**
- * Collapse state of the sidebar's page-nav group (pure decisions, unit tested): the
- * 智能体 → 评估中心 run of entries collapses as one group behind a nav-row-wide chevron
- * button under the group's last entry (arrow up = collapse; collapsed, the button
- * stays — arrow down — as the way back). The pinned "New chat" block above is NOT
- * part of the group — it stays visible in both states (the manifest below simply never
- * contains it).
+ * The sidebar's nav entries and how they fold (pure decisions, unit tested). In development
+ * mode every entry — New chat, then the page manifest below — is either PINNED, always
+ * shown, or COLLAPSIBLE, inside the area a nav-row-wide chevron button under it folds away
+ * (arrow up = collapse; collapsed, the button stays — arrow down — as the way back). New
+ * chat, Agents, Models and Plugins are pinned by default; the user moves an entry across
+ * with the row's pin button or by dragging it into or out of the collapsible area. Both
+ * areas keep manifest order, and with nothing collapsible there is no chevron. Company
+ * mode's six entries stay outside the split: they fold as one group behind the same button.
*
- * One global storage key, not per Project: the nav is identical everywhere, so like the
- * grouping mode (GROUP_MODE_KEY) this is a single user preference — toggling it anywhere
- * toggles it everywhere. Storage is injectable (model-group-expansion.ts convention:
- * vitest runs in Node, no localStorage); nothing stored, unrecognized values, and
- * throwing storage all fall back to expanded — the default.
+ * Global storage keys, not per Project: the nav is identical everywhere, so like the
+ * grouping mode (GROUP_MODE_KEY) the fold and the pin choices are single user preferences —
+ * changing them anywhere changes them everywhere. Storage is injectable
+ * (model-group-expansion.ts convention: vitest runs in Node, no localStorage); nothing
+ * stored, unrecognized values, and throwing storage all fall back to the defaults.
*/
/**
- * Page entries of the collapsible nav group, in rendered order. Each key names its
- * route (`/<key>`), its S.nav label, and its NAV_ICONS glyph — the sidebar derives
- * its nav rows from this manifest, so the covered range is pinned here (and in the
- * unit tests) rather than duplicated. Some entries are admin-only (see below), so the
- * sidebar renders navKeysFor(user.isAdmin), not the raw manifest. Traces is deliberately
- * absent: reading a Trace happens in the chat toolbar's panel switcher, which is the only
- * place it happens.
+ * Page entries of the nav, in rendered order. Each key names its route (`/<key>`), its
+ * S.nav label, and its NAV_ICONS glyph — the sidebar derives its nav rows from this
+ * manifest, so the covered range is pinned here (and in the unit tests) rather than
+ * duplicated. Some entries are admin-only (see below), so the sidebar renders
+ * navKeysFor(user.isAdmin), not the raw manifest. Traces is deliberately absent: reading a
+ * Trace happens in the chat toolbar's panel switcher, which is the only place it happens.
*/
import { NAV_PAGE_KEYS, PAGES } from "./pages";
@@ -64,14 +65,87 @@ export function navKeysFor(isAdmin: boolean): readonly NavGroupKey[] {
}
/**
- * Page entries that are visible and reachable: collapsing hides the whole group (the
- * chevron-button toggle and the pinned "New chat" block above are outside it and stay).
- * The sidebar keeps the rows mounted while collapsed — the collapse is an animated
- * height tween — but at zero height, faded out, and inert: exactly this empty set of
- * reachable entries.
+ * A development-mode nav entry: New chat or a page. New chat opens a draft rather than a
+ * route, so it is not in the manifest; it is the one entry that is always pinned (see
+ * isNavPinnable), while every page is pinned or collapsible at the user's choice.
*/
-export function visibleNavKeys(collapsed: boolean, isAdmin = true): readonly NavGroupKey[] {
- return collapsed ? [] : navKeysFor(isAdmin);
+export type NavEntryKey = "newChat" | NavGroupKey;
+
+/** Every entry this user sees, in rendered order: New chat first, then their pages. */
+export function navEntryKeysFor(isAdmin: boolean): readonly NavEntryKey[] {
+ return ["newChat", ...navKeysFor(isAdmin)];
+}
+
+/** Entries pinned until the user says otherwise; every other entry, a page added later included, starts collapsible. */
+export const DEFAULT_PINNED_NAV_KEYS: ReadonlySet<NavEntryKey> = new Set<NavEntryKey>([
+ "newChat",
+ "agents",
+ "models",
+ "plugins",
+]);
+
+/**
+ * The user's pin choices that differ from the defaults, by entry: true = pinned, false =
+ * collapsible. An entry absent here takes its default, which is what lets a page added in a
+ * later release arrive where its own default puts it.
+ */
+export type NavPinOverrides = Readonly<Partial<Record<NavEntryKey, boolean>>>;
+
+/** Whether the user may move an entry between the areas: every page may; New chat never folds away. */
+export function isNavPinnable(key: NavEntryKey): boolean {
+ return key !== "newChat";
+}
+
+export function isNavPinned(key: NavEntryKey, overrides: NavPinOverrides): boolean {
+ if (!isNavPinnable(key)) return true;
+ return overrides[key] ?? DEFAULT_PINNED_NAV_KEYS.has(key);
+}
+
+/** The two areas, each keeping the order `keys` has — the manifest's, whatever order the entries were moved in. */
+export function splitNavEntries(
+ keys: readonly NavEntryKey[],
+ overrides: NavPinOverrides,
+): { pinned: NavEntryKey[]; collapsible: NavEntryKey[] } {
+ const pinned: NavEntryKey[] = [];
+ const collapsible: NavEntryKey[] = [];
+ for (const key of keys) {
+ if (isNavPinned(key, overrides)) pinned.push(key);
+ else collapsible.push(key);
+ }
+ return { pinned, collapsible };
+}
+
+/**
+ * `overrides` with one entry pinned or unpinned — the write both the pin button and a drop
+ * make. A choice that matches the default is removed rather than stored, so only deviations
+ * are ever kept; a call that changes nothing returns `overrides` itself, and callers skip the
+ * write on that identity.
+ */
+export function withNavPinned(
+ overrides: NavPinOverrides,
+ key: NavEntryKey,
+ pinned: boolean,
+): NavPinOverrides {
+ if (!isNavPinnable(key) || isNavPinned(key, overrides) === pinned) return overrides;
+ const next: Partial<Record<NavEntryKey, boolean>> = { ...overrides };
+ if (pinned === DEFAULT_PINNED_NAV_KEYS.has(key)) delete next[key];
+ else next[key] = pinned;
+ return next;
+}
+
+/**
+ * Entries that are visible and reachable, in rendered order: the pinned ones always, the
+ * collapsible ones only while their area is expanded (the chevron-button toggle is outside
+ * both and stays). The sidebar keeps folded rows mounted — the fold is an animated height
+ * tween — but at zero height, faded out, and inert: exactly their absence from this list.
+ */
+export function visibleNavKeys(
+ collapsed: boolean,
+ isAdmin = true,
+ overrides: NavPinOverrides = {},
+): readonly NavEntryKey[] {
+ const { pinned, collapsible } = splitNavEntries(navEntryKeysFor(isAdmin), overrides);
+ return collapsed ? pinned : [...pinned, ...collapsible];
}
/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */
@@ -80,7 +154,7 @@ export interface NavCollapseStorage {
setItem(key: string, value: string): void;
}
-/** The single global key (`penguin.…` naming convention); holds "collapsed" / "expanded". */
+/** The fold's single global key (`penguin.…` naming convention); holds "collapsed" / "expanded". */
export const NAV_GROUP_COLLAPSED_KEY = "penguin.sidebarNavGroupCollapsed";
/**
@@ -110,3 +184,43 @@ export function storeNavGroupCollapsed(collapsed: boolean, storage?: NavCollapse
/* best-effort persistence (quota limits / private browsing) */
}
}
+
+/** The pin choices' single global key; holds NavPinOverrides as a JSON object. */
+export const NAV_PINNED_KEY = "penguin.sidebarNavPinned";
+
+/** Keys a stored choice may name: the whole manifest, pages this user is not offered included (New chat is never a choice). */
+const NAV_ENTRY_KEYS: ReadonlySet<string> = new Set<string>(NAV_GROUP_KEYS);
+
+/**
+ * Reads the stored choices. Only a boolean under a key the manifest knows is kept, so a key
+ * this build does not have — a page since removed, a hand edit — is ignored rather than
+ * trusted; absent, unparseable or throwing storage reads as no choices, i.e. the defaults.
+ * `localStorage` is resolved inside the try for the reason initialNavGroupCollapsed gives.
+ */
+export function initialNavPinOverrides(storage?: NavCollapseStorage): NavPinOverrides {
+ try {
+ const parsed: unknown = JSON.parse((storage ?? localStorage).getItem(NAV_PINNED_KEY) ?? "{}");
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
+ const overrides: Partial<Record<NavEntryKey, boolean>> = {};
+ for (const [key, value] of Object.entries(parsed)) {
+ if (NAV_ENTRY_KEYS.has(key) && typeof value === "boolean") {
+ overrides[key as NavEntryKey] = value;
+ }
+ }
+ return overrides;
+ } catch {
+ return {};
+ }
+}
+
+/** Writes the choices on every change (best-effort, like the fold). */
+export function storeNavPinOverrides(
+ overrides: NavPinOverrides,
+ storage?: NavCollapseStorage,
+): void {
+ try {
+ (storage ?? localStorage).setItem(NAV_PINNED_KEY, JSON.stringify(overrides));
+ } catch {
+ /* best-effort persistence (quota limits / private browsing) */
+ }
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 14b12f3b..c65b1599 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -31,6 +31,9 @@ export const en: Strings = {
expandGroup: "Expand",
pinGroup: "Pin group",
unpinGroup: "Unpin group",
+ /** A nav entry's pin toggle: a pinned entry stays visible when the collapsible area folds. */
+ pinEntry: "Pin",
+ unpinEntry: "Unpin",
/** Company mode's page entries (S.nav.org.<key>, the COMPANY_NAV_KEYS manifest), and the mode switch's option names. */
org: {
overview: "Overview",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 9b32daa3..8a823f57 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -18,10 +18,10 @@ export const zh = {
nav: {
chat: "对话",
- newChat: "新对话",
+ newChat: "新建对话",
agents: "智能体",
models: "模型库",
- machines: "机器",
+ machines: "机器管理",
plugins: "插件市场",
usage: "成本中心",
traces: "轨迹观测",
@@ -36,6 +36,9 @@ export const zh = {
expandGroup: "展开",
pinGroup: "置顶分组",
unpinGroup: "取消置顶",
+ /** A nav entry's pin toggle: a pinned entry stays visible when the collapsible area folds. */
+ pinEntry: "常驻",
+ unpinEntry: "取消常驻",
/** Company mode's page entries (S.nav.org.<key>, the COMPANY_NAV_KEYS manifest), and the mode switch's option names. */
org: {
overview: "概览",
@@ -49,7 +52,7 @@ export const zh = {
/** Machines page: the server's own ssh hosts, and installing this build on one. */
machines: {
- pageTitle: "机器",
+ pageTitle: "机器管理",
/** Tooltip on the version in the header: what this server would install. */
imageVersion: (version: string) => `本服务端版本:${version}`,
noImage:
@@ -156,7 +159,7 @@ export const zh = {
serverUpOn: (port: number) => `运行中,端口 ${port}`,
/** The progress log's own heading, so the block is not an unlabelled wall of text. */
output: "输出",
- agentsUnreachable: "那台机器尚未连接——请在「机器」页面使用它",
+ agentsUnreachable: "那台机器尚未连接——请在「机器管理」页面使用它",
adminOnly: "只有管理员可以管理机器。",
},
diff --git a/packages/web/src/module.json b/packages/web/src/module.json
index 0159d2a1..2e2420d4 100644
--- a/packages/web/src/module.json
+++ b/packages/web/src/module.json
@@ -38,6 +38,17 @@
"builtin": "AgentSettingsPage"
}
},
+ {
+ "id": "web.models",
+ "key": "models",
+ "path": "/models",
+ "nav": "main",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "ModelsPage"
+ }
+ },
{
"id": "web.plugins",
"key": "plugins",
@@ -60,17 +71,6 @@
"builtin": "PluginDetailPage"
}
},
- {
- "id": "web.models",
- "key": "models",
- "path": "/models",
- "nav": "main",
- "admin": false,
- "released": true,
- "renderer": {
- "builtin": "ModelsPage"
- }
- },
{
"id": "web.machines",
"key": "machines",
diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.ts
index 58a06787..8d767c1f 100644
--- a/packages/web/test/install-scope.test.ts
+++ b/packages/web/test/install-scope.test.ts
@@ -84,6 +84,7 @@ function populated(): ReturnType<typeof memStorage> {
"penguin.sidebarGroupMode": "agent",
"penguin.sidebarSortMode": "manual",
"penguin.sidebarNavGroupCollapsed": "collapsed",
+ "penguin.sidebarNavPinned": '{"models":false}',
"penguin.steerMode": "followup",
"penguin.dock.launcherY": "0.25",
"penguin.dock.launcherHidden": "1",
@@ -116,6 +117,7 @@ const PREFERENCE_KEYS = [
"penguin.sidebarGroupMode",
"penguin.sidebarSortMode",
"penguin.sidebarNavGroupCollapsed",
+ "penguin.sidebarNavPinned",
"penguin.steerMode",
"penguin.dock.launcherY",
"penguin.dock.launcherHidden",
diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.ts
index 89c0f0cf..6e461a66 100644
--- a/packages/web/test/nav-group-collapse.test.ts
+++ b/packages/web/test/nav-group-collapse.test.ts
@@ -1,25 +1,33 @@
/**
- * nav-group-collapse.ts unit tests: the sidebar's collapsible page-nav group, toggled
- * by a nav-row-wide chevron button under the group's last entry (no label — tooltip
- * and aria carry the collapse/expand names; arrow up = collapse, and the button
- * itself stays while collapsed as the way back). The group covers exactly
- * the 智能体 → 评估中心 run of entries in rendered order (the sidebar derives its nav
- * rows from the NAV_GROUP_KEYS manifest, so the range is pinned here); the pinned
- * "New chat" block is never part of the manifest, so collapsing cannot hide it. The
- * choice persists globally in one localStorage key (injectable storage): a remount
- * reads it back, nothing stored / unrecognized values / throwing storage all fall
- * back to expanded — the default.
+ * nav-group-collapse.ts unit tests: the sidebar's nav entries and how they fold. In
+ * development mode every entry — New chat, then the page manifest — is pinned (always shown)
+ * or collapsible (inside the area a nav-row-wide chevron button folds away; no label —
+ * tooltip and aria carry the collapse/expand names; arrow up = collapse, and the button
+ * itself stays while collapsed as the way back). New chat, Agents, Models and Plugins are
+ * pinned by default; a pin toggle or a drop moves an entry across, only the changes from the
+ * defaults are stored, and both areas keep manifest order. The fold and the pin choices each
+ * persist in one global localStorage key (injectable storage): a remount reads them back, and
+ * nothing stored / unrecognized values / throwing storage all fall back to the defaults.
*/
import { describe, expect, it } from "vitest";
import {
+ DEFAULT_PINNED_NAV_KEYS,
NAV_GROUP_COLLAPSED_KEY,
NAV_GROUP_KEYS,
+ NAV_PINNED_KEY,
initialNavGroupCollapsed,
+ initialNavPinOverrides,
+ isNavPinnable,
+ isNavPinned,
+ navEntryKeysFor,
navKeysFor,
+ splitNavEntries,
storeNavGroupCollapsed,
+ storeNavPinOverrides,
visibleNavKeys,
+ withNavPinned,
} from "../src/lib/nav-group-collapse";
-import type { NavCollapseStorage } from "../src/lib/nav-group-collapse";
+import type { NavCollapseStorage, NavPinOverrides } from "../src/lib/nav-group-collapse";
import { NAV_ICONS } from "../src/lib/nav-icons";
import { zh } from "../src/lib/strings";
import { en } from "../src/lib/strings-en";
@@ -34,14 +42,32 @@ function memStorage(): NavCollapseStorage & { map: Map<string, string> } {
};
}
+/** Storage whose every call throws (quota exceeded / private mode). */
+const brokenStorage: NavCollapseStorage = {
+ getItem: () => {
+ throw new Error("denied");
+ },
+ setItem: () => {
+ throw new Error("denied");
+ },
+};
+
+/** Storage whose GETTER throws (blocked site data): touching the method itself raises. */
+const hostileStorage = {
+ get getItem(): never {
+ throw new Error("SecurityError");
+ },
+ setItem: () => undefined,
+} as unknown as NavCollapseStorage;
+
describe("NAV_GROUP_KEYS", () => {
- it("covers exactly the 智能体 → 评估中心 range, in rendered order", () => {
+ it("covers exactly the Agents → Evaluation Center range, in rendered order", () => {
// Traces is deliberately absent: the Trace panel moved into the chat toolbar's panel
// switcher (features/dock), and /traces stays reachable through its deep links only.
expect([...NAV_GROUP_KEYS]).toEqual([
"agents",
- "plugins",
"models",
+ "plugins",
"machines",
"usage",
"benchmark",
@@ -59,12 +85,48 @@ describe("NAV_GROUP_KEYS", () => {
}
});
- it("the pinned New chat entry is not in the group, so collapsing cannot hide it", () => {
- // The "New chat" block (S.chat.newSessionMenu, 「新建对话」) renders above the nav,
- // outside the group container — the manifest never governs it.
+ it("New chat is not a page of the manifest: it opens a draft, not a route", () => {
expect(NAV_GROUP_KEYS as readonly string[]).not.toContain("newChat");
expect(NAV_GROUP_KEYS as readonly string[]).not.toContain("chat");
- expect(zh.chat.newSessionMenu).toBeTruthy();
+ });
+});
+
+describe("navEntryKeysFor", () => {
+ it("puts New chat first, then this user's pages", () => {
+ expect([...navEntryKeysFor(true)]).toEqual(["newChat", ...navKeysFor(true)]);
+ expect([...navEntryKeysFor(false)]).toEqual(["newChat", ...navKeysFor(false)]);
+ });
+
+ it("reads one set of names in one order, in both languages", () => {
+ const keys = navEntryKeysFor(true);
+ expect(keys.map((key) => zh.nav[key])).toEqual([
+ "新建对话",
+ "智能体",
+ "模型库",
+ "插件市场",
+ "机器管理",
+ "成本中心",
+ "评估中心",
+ ]);
+ expect(keys.map((key) => en.nav[key])).toEqual([
+ "New chat",
+ "Agents",
+ "Models",
+ "Plugins",
+ "Machines",
+ "Cost Center",
+ "Evaluation Center",
+ ]);
+ });
+
+ it("New chat's nav label is the one its tooltip and the collapsed rail use", () => {
+ expect(zh.nav.newChat).toBe(zh.chat.newSessionMenu);
+ expect(en.nav.newChat).toBe(en.chat.newSessionMenu);
+ });
+
+ it("the Machines page heading is its nav label", () => {
+ expect(zh.machines.pageTitle).toBe(zh.nav.machines);
+ expect(en.machines.pageTitle).toBe(en.nav.machines);
});
});
@@ -72,7 +134,7 @@ describe("navKeysFor", () => {
it("hides the admin-only entries from a member, and nothing else", () => {
// /api/machines is admin-gated server-side (it spawns ssh with the server account's
// keys), so offering a member the row would only ever produce a 403.
- expect([...navKeysFor(false)]).toEqual(["agents", "plugins", "models", "usage", "benchmark"]);
+ expect([...navKeysFor(false)]).toEqual(["agents", "models", "plugins", "usage", "benchmark"]);
// An admin sees the whole manifest, machines included — the row it hides from a member.
// The Plugins page carries the built-in library and the deployment's registry both,
// under one key.
@@ -81,15 +143,124 @@ describe("navKeysFor", () => {
});
});
+describe("pinned vs. collapsible", () => {
+ it("defaults: New chat, Agents, Models and Plugins pinned; the rest collapsible", () => {
+ expect([...DEFAULT_PINNED_NAV_KEYS]).toEqual(["newChat", "agents", "models", "plugins"]);
+ expect(splitNavEntries(navEntryKeysFor(true), {})).toEqual({
+ pinned: ["newChat", "agents", "models", "plugins"],
+ collapsible: ["machines", "usage", "benchmark"],
+ });
+ });
+
+ it("a member's areas are cut from their own entries: an admin-only page is in neither", () => {
+ expect(splitNavEntries(navEntryKeysFor(false), {})).toEqual({
+ pinned: ["newChat", "agents", "models", "plugins"],
+ collapsible: ["usage", "benchmark"],
+ });
+ // A choice stored for it (an admin signed in on this browser before) offers nothing.
+ const { pinned, collapsible } = splitNavEntries(navEntryKeysFor(false), { machines: true });
+ expect([...pinned, ...collapsible]).not.toContain("machines");
+ });
+
+ it("unpinning stores the deviation, and the entry joins the collapsible area in manifest order", () => {
+ const unpinned = withNavPinned({}, "models", false);
+ expect(unpinned).toEqual({ models: false });
+ expect(isNavPinned("models", unpinned)).toBe(false);
+ // Models lands ahead of Machines (its manifest place), not at the end it was moved to.
+ expect(splitNavEntries(navEntryKeysFor(true), unpinned)).toEqual({
+ pinned: ["newChat", "agents", "plugins"],
+ collapsible: ["models", "machines", "usage", "benchmark"],
+ });
+ });
+
+ it("pinning a collapsible entry keeps manifest order however the moves were ordered", () => {
+ const first = withNavPinned(withNavPinned({}, "benchmark", true), "usage", true);
+ const second = withNavPinned(withNavPinned({}, "usage", true), "benchmark", true);
+ expect(first).toEqual(second);
+ expect(splitNavEntries(navEntryKeysFor(true), first)).toEqual({
+ pinned: ["newChat", "agents", "models", "plugins", "usage", "benchmark"],
+ collapsible: ["machines"],
+ });
+ });
+
+ it("moving an entry back to its default removes the stored choice", () => {
+ const back = withNavPinned(withNavPinned({}, "models", false), "models", true);
+ expect(back).toEqual({});
+ expect("models" in back).toBe(false);
+ const machines = withNavPinned(withNavPinned({}, "machines", true), "machines", false);
+ expect(machines).toEqual({});
+ });
+
+ it("a move that changes nothing returns the same object, so the caller skips the write", () => {
+ const overrides: NavPinOverrides = { models: false };
+ expect(withNavPinned(overrides, "agents", true)).toBe(overrides);
+ expect(withNavPinned(overrides, "models", false)).toBe(overrides);
+ expect(withNavPinned(overrides, "usage", false)).toBe(overrides);
+ });
+
+ it("New chat is always pinned: no choice moves it, and a stored one is ignored", () => {
+ expect(isNavPinnable("newChat")).toBe(false);
+ expect(isNavPinnable("usage")).toBe(true);
+ const overrides: NavPinOverrides = {};
+ expect(withNavPinned(overrides, "newChat", false)).toBe(overrides);
+ expect(isNavPinned("newChat", { newChat: false })).toBe(true);
+ expect(splitNavEntries(navEntryKeysFor(true), { newChat: false }).pinned[0]).toBe("newChat");
+ const storage = memStorage();
+ storage.setItem(NAV_PINNED_KEY, JSON.stringify({ newChat: false, usage: true }));
+ expect(initialNavPinOverrides(storage)).toEqual({ usage: true });
+ });
+
+ it("everything pinned leaves the collapsible area empty, so folding hides nothing", () => {
+ let overrides: NavPinOverrides = {};
+ for (const key of navEntryKeysFor(true)) overrides = withNavPinned(overrides, key, true);
+ expect(overrides).toEqual({ machines: true, usage: true, benchmark: true });
+ const { collapsible } = splitNavEntries(navEntryKeysFor(true), overrides);
+ expect(collapsible).toEqual([]);
+ expect(visibleNavKeys(true, true, overrides)).toEqual(navEntryKeysFor(true));
+ });
+
+ it("everything collapsible still leaves New chat pinned, and folding shows only it", () => {
+ let overrides: NavPinOverrides = {};
+ for (const key of navEntryKeysFor(true)) overrides = withNavPinned(overrides, key, false);
+ expect(splitNavEntries(navEntryKeysFor(true), overrides).pinned).toEqual(["newChat"]);
+ expect(visibleNavKeys(true, true, overrides)).toEqual(["newChat"]);
+ });
+
+ it("the pin toggle's accessible names exist in both languages, pin and unpin distinct", () => {
+ for (const [locale, dict] of [
+ ["zh", zh],
+ ["en", en],
+ ] as const) {
+ expect(dict.nav.pinEntry, locale).toBeTruthy();
+ expect(dict.nav.unpinEntry, locale).toBeTruthy();
+ expect(dict.nav.pinEntry, locale).not.toBe(dict.nav.unpinEntry);
+ }
+ });
+});
+
describe("visibleNavKeys", () => {
- it("expanded shows the whole group; collapsed leaves no entry visible or reachable (the sidebar renders the mounted rows inert at zero height)", () => {
- expect(visibleNavKeys(false)).toEqual(navKeysFor(true));
- expect(visibleNavKeys(true)).toEqual([]);
+ it("expanded shows every entry; collapsed leaves only the pinned ones visible and reachable (the sidebar renders the folded rows inert at zero height)", () => {
+ expect(visibleNavKeys(false)).toEqual(navEntryKeysFor(true));
+ expect(visibleNavKeys(true)).toEqual(["newChat", "agents", "models", "plugins"]);
});
- it("a member's expanded group is their own manifest, not the admin's", () => {
- expect(visibleNavKeys(false, false)).toEqual(navKeysFor(false));
- expect(visibleNavKeys(true, false)).toEqual([]);
+ it("a member's nav is their own manifest, not the admin's", () => {
+ expect(visibleNavKeys(false, false)).toEqual(navEntryKeysFor(false));
+ expect(visibleNavKeys(true, false)).toEqual(["newChat", "agents", "models", "plugins"]);
+ });
+
+ it("renders the pinned area first, then the collapsible one", () => {
+ const overrides = withNavPinned({}, "models", false);
+ expect(visibleNavKeys(false, true, overrides)).toEqual([
+ "newChat",
+ "agents",
+ "plugins",
+ "models",
+ "machines",
+ "usage",
+ "benchmark",
+ ]);
+ expect(visibleNavKeys(true, true, overrides)).toEqual(["newChat", "agents", "plugins"]);
});
it("the chevron-button toggle's accessible names exist in both languages (icon-only button: aria + tooltip carry them)", () => {
@@ -114,17 +285,30 @@ describe("persisted collapse state (one global localStorage key)", () => {
it("toggle → store → a fresh mount-time read restores the collapsed state", () => {
const s = memStorage();
- // Collapse: what the sidebar renders shrinks to nothing but the header toggle …
+ // Collapse: what the sidebar renders shrinks to the pinned entries and the toggle …
storeNavGroupCollapsed(true, s);
expect(s.map.get(NAV_GROUP_COLLAPSED_KEY)).toBe("collapsed");
// … and a re-mount (initialNavGroupCollapsed is the useState initializer) restores it.
expect(initialNavGroupCollapsed(s)).toBe(true);
- expect(visibleNavKeys(initialNavGroupCollapsed(s))).toEqual([]);
+ expect(visibleNavKeys(initialNavGroupCollapsed(s))).toEqual([
+ "newChat",
+ "agents",
+ "models",
+ "plugins",
+ ]);
// Expand again: the choice round-trips both ways.
storeNavGroupCollapsed(false, s);
expect(s.map.get(NAV_GROUP_COLLAPSED_KEY)).toBe("expanded");
expect(initialNavGroupCollapsed(s)).toBe(false);
- expect(visibleNavKeys(initialNavGroupCollapsed(s))).toEqual(navKeysFor(true));
+ expect(visibleNavKeys(initialNavGroupCollapsed(s))).toEqual(navEntryKeysFor(true));
+ });
+
+ it("a stored collapsed state folds the collapsible area only; the pinned entries stay", () => {
+ const s = memStorage();
+ s.map.set(NAV_GROUP_COLLAPSED_KEY, "collapsed");
+ expect(initialNavGroupCollapsed(s)).toBe(true);
+ const shown = visibleNavKeys(initialNavGroupCollapsed(s), true, initialNavPinOverrides(s));
+ expect(shown).toEqual(["newChat", "agents", "models", "plugins"]);
});
it("unrecognized stored values fall back to expanded", () => {
@@ -136,26 +320,74 @@ describe("persisted collapse state (one global localStorage key)", () => {
});
it("storage throwing (quota/private mode): store does not throw, read yields the default", () => {
- const broken: NavCollapseStorage = {
- getItem: () => {
- throw new Error("denied");
- },
- setItem: () => {
- throw new Error("denied");
- },
- };
- expect(() => storeNavGroupCollapsed(true, broken)).not.toThrow();
- expect(initialNavGroupCollapsed(broken)).toBe(false);
+ expect(() => storeNavGroupCollapsed(true, brokenStorage)).not.toThrow();
+ expect(initialNavGroupCollapsed(brokenStorage)).toBe(false);
});
it("storage whose GETTER throws (blocked site data) degrades instead of escaping the useState initializer", () => {
- const hostile = {
- get getItem(): never {
- throw new Error("SecurityError");
- },
- setItem: () => undefined,
- } as unknown as NavCollapseStorage;
- expect(() => initialNavGroupCollapsed(hostile)).not.toThrow();
- expect(initialNavGroupCollapsed(hostile)).toBe(false);
+ expect(() => initialNavGroupCollapsed(hostileStorage)).not.toThrow();
+ expect(initialNavGroupCollapsed(hostileStorage)).toBe(false);
+ });
+});
+
+describe("persisted pin choices (one global localStorage key)", () => {
+ it("nothing stored reads as no choices — the defaults — and reading never writes", () => {
+ const s = memStorage();
+ expect(initialNavPinOverrides(s)).toEqual({});
+ expect(s.map.size).toBe(0);
+ });
+
+ it("a move → store → a fresh mount-time read restores the areas", () => {
+ const s = memStorage();
+ const moved = withNavPinned(withNavPinned({}, "models", false), "usage", true);
+ storeNavPinOverrides(moved, s);
+ expect(JSON.parse(s.map.get(NAV_PINNED_KEY)!)).toEqual({ models: false, usage: true });
+ const restored = initialNavPinOverrides(s);
+ expect(restored).toEqual(moved);
+ expect(splitNavEntries(navEntryKeysFor(true), restored)).toEqual({
+ pinned: ["newChat", "agents", "plugins", "usage"],
+ collapsible: ["models", "machines", "benchmark"],
+ });
+ });
+
+ it("only the deviations are stored: moving back empties the record", () => {
+ const s = memStorage();
+ storeNavPinOverrides(withNavPinned(withNavPinned({}, "models", false), "models", true), s);
+ expect(s.map.get(NAV_PINNED_KEY)).toBe("{}");
+ });
+
+ it("keys this build does not know are ignored, so a page without a stored choice takes its default", () => {
+ const s = memStorage();
+ s.map.set(
+ NAV_PINNED_KEY,
+ JSON.stringify({ traces: true, apps: false, models: false, machines: true }),
+ );
+ // machines is admin-only but still a manifest key: an admin's choice survives a member's
+ // visit in the same browser.
+ expect(initialNavPinOverrides(s)).toEqual({ models: false, machines: true });
+ });
+
+ it("a value that is not a boolean is ignored, and the entry keeps its default", () => {
+ const s = memStorage();
+ s.map.set(NAV_PINNED_KEY, JSON.stringify({ models: "false", usage: 1, agents: null }));
+ expect(initialNavPinOverrides(s)).toEqual({});
+ });
+
+ it("unparseable or non-object values read as no choices", () => {
+ const s = memStorage();
+ for (const raw of ["", "{", "null", "[]", '["models"]', "true", "7", '"models"']) {
+ s.map.set(NAV_PINNED_KEY, raw);
+ expect(initialNavPinOverrides(s), raw).toEqual({});
+ }
+ });
+
+ it("storage throwing (quota/private mode): store does not throw, read yields the defaults", () => {
+ expect(() => storeNavPinOverrides({ models: false }, brokenStorage)).not.toThrow();
+ expect(initialNavPinOverrides(brokenStorage)).toEqual({});
+ });
+
+ it("storage whose GETTER throws degrades instead of escaping the useState initializer", () => {
+ expect(() => initialNavPinOverrides(hostileStorage)).not.toThrow();
+ expect(initialNavPinOverrides(hostileStorage)).toEqual({});
});
});