A local-first multi-agent app development platform, built on PenguinHarness
feat(web): restore the hover archive/delete pair and move the row menu to right-click (#341)
Yaowei Zheng304e2cd57a7c
diff --git a/changelog/unreleased/2026-08-19-session-row-actions.md b/changelog/unreleased/2026-08-19-session-row-actions.mdnew file mode 100644index 00000000..5752a061--- /dev/null+++ b/changelog/unreleased/2026-08-19-session-row-actions.md@@ -0,0 +1,28 @@+# Web App: session row actions split between a hover pair and a right-click menu++- **Date:** 2026-08-19+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#341](https://github.com/Prism-Shadow/penguin-harness/pull/341)++[中文版](2026-08-19-session-row-actions.zh.md)++Hovering a conversation row in the chat sidebar had come to reveal a single ellipsis button, and every action on the row — including archive and delete — sat one click further in, inside its dropdown. The hover affordance went back to what shipped through v0.2.2: archive and delete as direct icon buttons in the row's trailing slot. The rest of the set did not go away; the whole menu, pin and rename included, now opens on right-click.++## The hover pair++- Hovering a row swaps the trailing last-active time for archive/unarchive and delete, one click each; delete keeps its red treatment. Tabbing onto either button reveals that button, so the pair stays reachable without a pointer.+- The slot reserves the pair's width, so rows with no last-active time no longer let the icons overhang the title, and the icons still line up in one column down the list.+- The buttons take pointer events only while they are actually revealed, so the row's right end holds no invisible tap target on a touch screen — where a hover-gated button never becomes visible at all.++## The context menu++- Right-clicking a row opens pin/unpin, rename, archive/unarchive and delete at the pointer. Pin appears only on active-list rows, where it can actually reorder something — the archived, subagent and scheduled folders offer the other three.+- Touch opens the same menu with a press-and-hold (500ms, abandoned if the finger travels more than 10px, and the click the screen replays afterwards no longer opens the conversation), and the keyboard opens it with Shift+F10 against the focused row, anchored to the row's own box rather than to the viewport corner. Neither hover nor a secondary click exists on a touch screen, so the gesture is not the only way in.+- The panel reuses the shared `Dropdown` through a new virtual-anchor mode, so it inherits that primitive's dismissal (Escape through the shared esc-layer stack, outside click, and scroll), its focus handling (opening focuses the first item; Escape hands focus back to the row), and its viewport clamping and flip near an edge. A pointer-anchored panel dismisses on scroll rather than following the trigger it no longer has.+- The browser's own context menu is suppressed inside the row's handler alone: nothing is bound at the document or window level, so right-clicking anywhere else in the app is unchanged.++## List option icons++- The list-options menu's four rows took leading glyphs: a folder for Workspace grouping and the Agent glyph for Agent grouping — the same two the section header's grouping toggle shows, now read from one shared map — plus a clock for most-recent order and up/down arrows for the drag-reordered manual order.+- The glyphs are decorative beside labels that stay, so each row's accessible name is unchanged.diff --git a/changelog/unreleased/2026-08-19-session-row-actions.zh.md b/changelog/unreleased/2026-08-19-session-row-actions.zh.mdnew file mode 100644index 00000000..924a4bc2--- /dev/null+++ b/changelog/unreleased/2026-08-19-session-row-actions.zh.md@@ -0,0 +1,28 @@+# Web App:会话行操作拆成悬停两键与右键菜单++- **Date:** 2026-08-19+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#341](https://github.com/Prism-Shadow/penguin-harness/pull/341)++[English](2026-08-19-session-row-actions.md)++聊天侧边栏里悬停一条会话行时,浮现出来的一度只是一枚省略号按钮,行上的每一项操作——归档与删除也在内——都还要再点一下才够得到。悬停处的操作现在改回 v0.2.2 及更早版本一直提供的样子:归档与删除作为两枚图标按钮直接落在行尾。其余操作并没有消失,包含置顶与重命名在内的完整菜单改由右键打开。++## 悬停两键++- 悬停一行时,行尾的最近活跃时间让位给归档/取消归档与删除,各自一次点击即可,删除仍保留红色处理。用 Tab 移到其中任意一枚按钮,该按钮即显形,因此不用指针也够得到这两项。+- 该槽位预留了这两枚按钮自身的宽度,因此没有最近活跃时间的行不会再让图标压到标题上,整列图标也依旧对齐成一条竖线。+- 这两枚按钮只在真正显形时才接收指针事件,因此触屏上行尾不会留下一个看不见的点击目标——在那里,悬停显形的按钮根本不会显形。++## 右键菜单++- 右键点击一行,会在指针处打开置顶/取消置顶、重命名、归档/取消归档与删除。置顶只出现在活跃列表的行上——那里它才真的能改变顺序;已归档、子智能体与定时任务的折叠夹提供另外三项。+- 触屏用长按打开同一个菜单(500ms,手指移动超过 10px 即作废,之后被屏幕补发的那次点击也不再打开会话),键盘则用 Shift+F10 对焦点所在行打开,并锚定到该行自身的盒子而不是视口角落。触屏既没有悬停也没有右键,因此这个手势并不是唯一入口。+- 菜单面板复用共享的 `Dropdown`,走的是新增的虚拟锚点模式,于是直接继承了该基础组件的关闭方式(经共享 esc 层栈的 Esc、点击外部、滚动)、焦点处理(打开时聚焦首项,Esc 把焦点交回该行),以及靠近视口边缘时的夹取与翻转。锚在指针上的面板遇到滚动时选择关闭,而不是去追一个它本就没有的触发元素。+- 浏览器自带的右键菜单只在该行的处理函数内部被接管:没有任何东西注册到 document 或 window 上,所以在应用的其他位置右键,行为一如既往。++## 列表选项图标++- 列表选项菜单的四行都加上了前导图标:按 Workspace 分组用文件夹、按 Agent 分组用 Agent 图形——与分区标题栏里那个分组切换按钮所用的正是同两枚,现在统一从一张共享映射表里读取——最近更新用时钟,拖拽得来的手动排序用上下箭头。+- 这些图形只是标签旁的装饰,标签本身没有被替换掉,因此每一行的可访问名称都未发生变化。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 147e5e66..404ca1e5 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -37,6 +37,17 @@ A new conversation starts as a draft: pick the Agent, the Workspace (via a serveThere are four approval modes: `allow-all`, `deny-all`, `read-only` (only read-only tools pass), and `always-ask`. See [Tools and Approvals](/tools).+### The Conversation List++The sidebar's conversation list groups by Workspace or by Agent. Grouping and sort order are switched in the **List options** menu (the sliders icon in the section header), where each option carries its own icon: a folder for Workspace grouping, the Agent glyph for Agent grouping, a clock for most-recent order, and up/down arrows for the drag-reordered manual order.++A row's actions come at two levels:++- **Hovering** a row replaces the trailing last-active time with two icon buttons — archive and delete. They are reachable from the keyboard too: tabbing onto either one reveals it;+- **Right-clicking** a row opens the full menu at the pointer: pin, rename, archive, delete. A **long press** on touch and **Shift+F10** on the keyboard open the same menu, since neither hover nor a secondary click exists there. Escape, a click elsewhere, or scrolling the list dismisses it; the browser's own context menu is taken over on conversation rows only, and stays as usual everywhere else on the page.++Pinning is offered only in the active list — the archived, subagent and scheduled folders leave it out — and a pinned conversation sorts to the top of its group. The choice is remembered per Project in the browser.+### Streaming Rendering- Model text renders token by token; thinking blocks are collapsible;diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex d89751ce..1ebc241f 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -37,6 +37,17 @@ penguin web审批模式共四种:`allow-all`(全部放行)、`deny-all`(全部拒绝)、`read-only`(仅放行只读工具)、`always-ask`(每次询问),详见[工具与审批](/tools)。+### 会话列表++侧边栏的会话列表按 Workspace 或 Agent 分组,分组方式与排序方式在标题栏的**列表选项**菜单(滑块图标)里切换,每个选项前带一枚对应图标:文件夹表示按 Workspace 分组、机器人表示按 Agent 分组、时钟表示按最近更新排序、上下箭头表示手动拖拽排序。++会话行的操作分两层:++- **悬停**一行时,行尾的最近活跃时间让位给两个图标按钮——归档与删除;键盘同样够得到:Tab 到其中任意一个,该按钮即显形;+- **右键点击**一行,在指针处打开完整菜单:置顶、重命名、归档、删除。触屏**长按**、键盘 **Shift+F10** 打开同一个菜单(触屏没有悬停,也没有右键)。按 Esc、点击别处或滚动列表都会关闭它;系统右键菜单只在会话行上被接管,页面其他位置照常。++置顶只在活跃列表里出现(已归档、子智能体与定时任务的折叠夹中没有这一项),置顶的会话排在所属分组的最前面,该状态按 Project 记在浏览器本地。+### 流式渲染- 模型文本逐 Token 渲染,思考块可折叠;diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 4c31049f..beb8e754 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -10,10 +10,12 @@* draft in that Workspace) or by Agent (group header = Agent name + new chat + Agent settings;* shows all Agents, including empty groups). Groups can be pinned via the header's hover pin* toggle: pinned groups sort before unpinned within their mode, keeping each partition's own- * order. Conversations can be pinned too (row ellipsis menu; persisted per Project in+ * order. Conversations can be pinned too (row context menu; persisted per Project in* localStorage): pinned rows bubble to the top of their group's active list. Each row's- * trailing slot shows the compact last-active time at rest and swaps to the ellipsis menu- * on hover/focus -> bottom user config (theme / language / logout).+ * trailing slot shows the compact last-active time at rest and swaps to archive + delete+ * icon buttons on hover/focus; the full set (pin, rename, archive, delete) opens as a+ * context menu on right-click, Shift+F10, or a press-and-hold on touch+ * -> bottom user config (theme / language / logout).* Desktop keeps it pinned as the left column; mobile puts the whole thing in a drawer.* New chats always enter draft state (/chat/new, route state specifies the Agent and optionally* the Workspace): Model / Workspace / approval mode are all chosen on the draft input card, so@@ -89,11 +91,27 @@ import {import type { SessionSortMode } from "../../lib/session-order";import { Switch } from "../ui/switch";import { Dropdown } from "../ui/dropdown";+import { useRowContextMenu } from "../ui/context-menu";+import {+ HOVER_ROW_ACTIONS,+ PENCIL_ICON,+ PIN_ICON,+ SessionRowHoverActions,+ SessionRowMenuRows,+ TRASH_ICON,+ contextMenuActions,+ overflowMenuDangerClass,+ overflowMenuGlyph,+ overflowMenuRowClass,+} from "../ui/session-row-menu";+import type { SessionRowAction } from "../ui/session-row-menu";import { AgentAvatar } from "../ui/agent-avatar";import { CheckIcon, ChevronDown, GEAR_ICON, NAV_ICONS } from "../ui/icons";import {FOLDER_ICON,FOLDER_OPEN_ICON,+ GROUP_MODE_ICONS,+ SORT_MODE_ICONS,FolderSection,GroupHeader,Icon,@@ -132,20 +150,7 @@ import { forceUpdateCheck, updateCheckOutcome, useVersionInfo } from "../../lib//** New-chat pencil (the pinned "New chat" button and the collapsed rail share it). */export const NEW_CHAT_ICON = "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";-/** Pushpin (lucide pin: head + body + stem), the group-header pin toggle / pinned indicator. */-const PIN_ICON =- "M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1z";--/** Row-menu item glyphs (thin-line, leading each item per the reference design): pencil / archive / unarchive / trash. */-const PENCIL_ICON = "M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3";-const ARCHIVE_ICON =- "M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M9.5 13.5 12 16l2.5-2.5";-const UNARCHIVE_ICON =- "M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M12 17v-5m-2.5 2L12 11l2.5 3";-const TRASH_ICON =- "M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6";--/** The session row's overflow-menu trigger: three FILLED dots (the stroke version read too faint against the last-active times). */+/** The workspace group's overflow-menu trigger: three FILLED dots (the stroke version read too faint at this size). */function EllipsisGlyph({ size = 16 }: { size?: number }) {return (<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden>@@ -218,21 +223,6 @@ const headerControlClass = (active: boolean) =>const menuSectionClass ="px-2.5 pb-0.5 pt-1.5 text-[11px] font-medium text-gray-400 dark:text-gray-500";-/** Compact overflow-menu row (session row menu + workspace group menu; reference density): small text, leading thin-line glyph. */-const overflowMenuRowClass =- "flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800";--/** The overflow menus' destructive row (delete keeps the red treatment; its glyph inherits the red). */-const overflowMenuDangerClass =- "flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-red-600 transition-colors duration-150 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40";--/** The overflow menus' muted leading glyph (the danger row inlines its own so the red inherits). */-const overflowMenuGlyph = (d: string) => (- <span className="shrink-0 text-gray-400 dark:text-gray-500">- <Icon d={d} size={13} />- </span>-);-/*** Collapsed-group and pinned-group persistence (survives a refresh), one storage key* per Project and concern — group keys are Agent ids / Workspace paths, which are@@ -1412,6 +1402,7 @@ export function Sidebar({><p className={menuSectionClass}>{S.chat.groupModeSection}</p><MenuRadioRow+ icon={GROUP_MODE_ICONS.workspace}label={S.chat.groupByWorkspace}checked={groupMode === "workspace"}onSelect={() => {@@ -1420,6 +1411,7 @@ export function Sidebar({}}/><MenuRadioRow+ icon={GROUP_MODE_ICONS.agent}label={S.chat.groupByAgent}checked={groupMode === "agent"}onSelect={() => {@@ -1432,6 +1424,7 @@ export function Sidebar({{/* Manual order is offered only where a drag can actually happen (see canDrag). */}{canDrag && (<MenuRadioRow+ icon={SORT_MODE_ICONS.manual}label={S.chat.sortManual}checked={sortMode === "manual"}onSelect={() => {@@ -1441,6 +1434,7 @@ export function Sidebar({/>)}<MenuRadioRow+ icon={SORT_MODE_ICONS.recent}label={S.chat.sortRecent}checked={sortMode === "recent"}onSelect={() => {@@ -2122,12 +2116,21 @@ function GroupPinButton({ pinned, onToggle }: { pinned: boolean; onToggle: () =>/*** Single Session row: title + pinned indicator + status dot/approval badge, and one* trailing slot that swaps its content — at rest it shows the compact last-active time,- * on row hover / keyboard focus / while open it shows the ellipsis overflow menu- * instead (the menu trigger overlays the exact same slot; the old rename / archive /- * delete hover icons live inside the menu now, joined by pin — one glyph instead of a- * row of three). The menu panel goes through the Dropdown body portal so the sidebar- * scroller can't clip it. A truncated title scrolls its tail into view while the row- * is hovered or keyboard-focused (#309; Truncated's scrollReveal + data-title-reveal).+ * on row hover — or on either of them taking focus — it shows archive and delete as+ * direct icon buttons.+ * That pair is the affordance every release up to v0.2.2 shipped (as icon buttons in+ * exactly this slot), restored here: the 0.3 line had replaced it with an ellipsis+ * dropdown carrying pin / rename / archive / delete, which cost two clicks for the two+ * actions people actually reach for.+ *+ * The rest of the set did not disappear — **right-clicking the row** opens all four as a+ * context menu at the pointer (useRowContextMenu; also Shift+F10 from the keyboard and+ * press-and-hold on touch, since neither hover nor a secondary click exists there). Both+ * panels go through the Dropdown body portal so the sidebar scroller can't clip them, and+ * both read their action set from session-row-menu.tsx.+ *+ * A truncated title scrolls its tail into view while the row is hovered or+ * keyboard-focused (#309; Truncated's scrollReveal + data-title-reveal).*/function SessionRow({s,@@ -2177,12 +2180,29 @@ function SessionRow({onDelete: (s: SessionInfo) => void;onToggleArchive: (s: SessionInfo) => void;}) {- const [menuOpen, setMenuOpen] = useState(false);- /** Close the menu, then run the action (every item shares this). */- const item = (fn: (x: SessionInfo) => void) => () => {- setMenuOpen(false);- fn(s);+ const ctx = useRowContextMenu();+ /** Run one action on this Session, closing the context menu first if it was open. */+ const run = (action: SessionRowAction) => {+ ctx.close();+ const handler: Record<SessionRowAction, (x: SessionInfo) => void> = {+ pin: onTogglePin,+ rename: onRename,+ archive: onToggleArchive,+ delete: onDelete,+ };+ handler[action](s);+ };+ /**+ * Menu items hand focus back to the row before acting: the panel unmounts under the+ * user, and the context menu is the only keyboard route to pin and rename, so a+ * Shift+F10 → Enter user would otherwise be dropped onto <body> and lose their place in+ * the list. Actions that open a dialog (rename, delete) take focus from there as usual.+ */+ const runFromMenu = (action: SessionRowAction) => {+ ctx.returnFocus()?.focus();+ run(action);};+ const rowState = { archived: s.archived, pinned };return (<liclassName="relative"@@ -2203,7 +2223,13 @@ function SessionRow({// data-title-reveal: hovering the row / keyboard-focusing its button scrolls a// truncated title's tail into view (the Truncated below; styles.css #309 rules).data-title-reveal- className={`group flex items-center rounded-md pr-1 transition-colors duration-150 ${+ ref={ctx.rowRef}+ // Right-click / Shift+F10 / press-and-hold open the row's context menu. The+ // native menu is suppressed inside this handler only — the rest of the app keeps+ // the browser's own. select-none keeps a held press from raising the text+ // selection callout on touch instead of the menu.+ {...ctx.rowProps}+ className={`group flex select-none items-center rounded-md pr-1 transition-colors duration-150 ${draggable ? "cursor-grab " : ""}${active@@ -2213,7 +2239,12 @@ function SessionRow({><buttontype="button"- onClick={() => onOpen(s)}+ // A press-and-hold that opened the context menu must not also open the Session:+ // touch screens replay the held press as a click once the finger lifts.+ onClick={() => {+ if (ctx.consumeLongPressClick()) return;+ onOpen(s);+ }}className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left">{agentHint !== undefined && (@@ -2257,77 +2288,50 @@ function SessionRow({</span>)}</button>- {/* Trailing swap slot: resting last-active time / hover-focus-open ellipsis menu.- The trigger is a CONSTANT 28px square anchored at the slot's right edge — NOT a- whole-slot overlay: the slot's width rides the time string (2 分钟前 vs 31 分钟前),- and a slot-centered glyph landed at a different x per row, so the ellipses never- formed a vertical column (the user saw it shift with the time's character count).- Right-anchored, every row's dots share one x and line up with the group-header- ellipsis above (a right-flush 28px square at the same 4px inset). The swap stays- a pure opacity handoff: time hides on row hover (group-hover), when the trigger- holds keyboard focus (peer-focus-visible; the button precedes the time span so- the peer combinator can reach it), and while the menu is open — regardless of the- time being wider than the square. */}+ {/* Trailing swap slot: resting last-active time / hover-focus archive + delete.+ The buttons form a CONSTANT-width group anchored at the slot's right edge —+ NOT a whole-slot overlay: the slot's width rides the time string (2 分钟前 vs+ 31 分钟前), and slot-centered glyphs landed at a different x per row, so the+ icons never formed a vertical column (the user saw them shift with the time's+ character count). Right-anchored, every row's icons share one x. min-w-12+ reserves the pair's own width, so on a row with no time they still don't+ overhang the title. The swap stays a pure opacity handoff: the time hides on+ row hover (group-hover) and while a button holds focus (peer-focus-within; the+ group precedes the time span so the peer combinator can reach it). */}+ <div className="relative flex h-6 min-w-12 shrink-0 items-center justify-end">+ {/* No hover pill on these (a fill as wide as the date read ugly); feedback is+ the glyph color deepening — red for delete. */}+ <div className="peer absolute right-0 top-1/2 flex -translate-y-1/2 items-center">+ <SessionRowHoverActions actions={HOVER_ROW_ACTIONS} state={rowState} onRun={run} />+ </div>+ {lastActive !== "" && (+ <span+ aria-hidden+ className="pointer-events-none px-1 text-[11px] text-gray-400 transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0 dark:text-gray-500"+ >+ {lastActive}+ </span>+ )}+ </div>+ {/* The full set, one right-click away (also Shift+F10 / press-and-hold — see+ useRowContextMenu). `contents` keeps this wrapper out of the row's flex+ layout: it renders no box of its own, the panel is portaled, and the anchor+ is the viewport point the gesture landed on rather than this element. */}<Dropdown- open={menuOpen}- setOpen={setMenuOpen}- portal={{ direction: "down", align: "right" }}- className="flex h-6 min-w-7 shrink-0 items-center justify-end"- menuClass="w-32"- button={- <>- {/* No hover pill on this trigger (a fill as wide as the date read ugly);- feedback is the icon color deepening only, and the filled dots carry- enough weight to read as interactive on their own. */}- <button- type="button"- title={S.chat.sessionMenu}- aria-label={S.chat.sessionMenu}- aria-haspopup="menu"- aria-expanded={menuOpen}- onClick={() => setMenuOpen(!menuOpen)}- className={`peer absolute right-0 top-1/2 flex h-7 w-7 -translate-y-1/2 items-center justify-center text-gray-500 transition-all duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100 ${- menuOpen- ? "opacity-100"- : "opacity-0 focus-visible:opacity-100 group-hover:opacity-100"- }`}- >- <EllipsisGlyph />- </button>- {lastActive !== "" && (- <span- aria-hidden- className={`pointer-events-none px-1 text-[11px] text-gray-400 transition-opacity duration-150 group-hover:opacity-0 peer-focus-visible:opacity-0 dark:text-gray-500 ${- menuOpen ? "opacity-0" : ""- }`}- >- {lastActive}- </span>- )}- </>- }+ open={ctx.open}+ setOpen={ctx.setOpen}+ portal={{ direction: "down", align: "left" }}+ anchorRect={ctx.anchor}+ returnFocus={ctx.returnFocus}+ className="contents"+ menuClass="w-36"+ button={null}>- {canPin && (- <button type="button" className={overflowMenuRowClass} onClick={item(onTogglePin)}>- {overflowMenuGlyph(PIN_ICON)}- {pinned ? S.chat.unpinSession : S.chat.pinSession}- </button>- )}- <button type="button" className={overflowMenuRowClass} onClick={item(onRename)}>- {overflowMenuGlyph(PENCIL_ICON)}- {S.chat.renameSession}- </button>- <button type="button" className={overflowMenuRowClass} onClick={item(onToggleArchive)}>- {overflowMenuGlyph(s.archived ? UNARCHIVE_ICON : ARCHIVE_ICON)}- {s.archived ? S.chat.unarchiveSession : S.chat.archiveSession}- </button>- <button type="button" className={overflowMenuDangerClass} onClick={item(onDelete)}>- {/* The glyph inherits the row's red. */}- <span className="shrink-0">- <Icon d={TRASH_ICON} size={13} />- </span>- {S.chat.deleteSession}- </button>+ <SessionRowMenuRows+ actions={contextMenuActions(canPin)}+ state={rowState}+ onRun={runFromMenu}+ /></Dropdown></div></li>@@ -2388,12 +2392,23 @@ function GroupOverflowMenu({ onRename, onDelete }: { onRename: () => void; onDel);}-/** List-settings menu option: label left, checkmark marks the active choice (reference-style radio row; aria-pressed carries the state). Same type scale as the session/workspace overflow menus (用户口径: 字体和 Session 更多一样). */+/**+ * List-settings menu option: leading glyph + label, with a checkmark marking the active+ * choice (reference-style radio row; aria-pressed carries the state). Same type scale and+ * leading-glyph column as the session/workspace overflow menus (用户口径: 字体和 Session+ * 更多一样), so the two menus read as one family.+ *+ * The glyph is decorative — it names the option's subject (a folder for Workspace+ * grouping, a clock for recency) beside a label that is never dropped, so the row's+ * accessible name stays the label alone.+ */function MenuRadioRow({+ icon,label,checked,onSelect,}: {+ icon: string;label: string;checked: boolean;onSelect: () => void;@@ -2405,7 +2420,10 @@ function MenuRadioRow({onClick={onSelect}className={`${overflowMenuRowClass} justify-between`}>- <span className="truncate">{label}</span>+ <span className="flex min-w-0 items-center gap-2">+ {overflowMenuGlyph(icon)}+ <span className="truncate">{label}</span>+ </span>{checked && <CheckIcon className="shrink-0 text-gray-500 dark:text-gray-400" />}</button>);diff --git a/packages/web/src/components/ui/context-menu.tsx b/packages/web/src/components/ui/context-menu.tsxnew file mode 100644index 00000000..2b2b6a27--- /dev/null+++ b/packages/web/src/components/ui/context-menu.tsx@@ -0,0 +1,193 @@+/**+ * Row context menu (controlled by the caller's `Dropdown`): a hook that turns a+ * secondary click, the keyboard's context-menu chord, and touch press-and-hold into one+ * anchored open, plus the handlers to spread on the row that owns it.+ *+ * It deliberately renders nothing. The panel is a `Dropdown` in `anchorRect` mode, so a+ * context menu inherits — rather than re-implements — that primitive's dismiss stack+ * (Escape through the shared esc-layer, outside click, scroll), its focus handling+ * (opening focuses the first item, Escape hands focus back), and its viewport clamping+ * and flip. The only thing the Dropdown cannot know is where the pointer was, which is+ * what the anchor this hook produces supplies.+ *+ * Native-menu suppression is scoped by construction: `preventDefault` is called inside+ * the row's own `onContextMenu`, so it only ever runs for events that originated in that+ * row. Nothing is bound to `document` or `window` — right-clicking anywhere else in the+ * app still gets the browser's own menu.+ *+ * This half owns only the DOM: element rects, the hold timer, and dispatching events.+ * Every decision — which gesture counts, which anchor, whether a dismiss is believed —+ * is pure and lives in `lib/context-menu.ts`, where the sequences can be tested without+ * a DOM.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import type {+ KeyboardEvent as ReactKeyboardEvent,+ MouseEvent as ReactMouseEvent,+ PointerEvent as ReactPointerEvent,+} from "react";+import {+ IDLE_HOLD,+ LONG_PRESS_MS,+ contextMenuAnchor,+ isContextMenuKey,+ isLongPressPointer,+ longPressMoved,+ pointerAnchor,+ reduceHold,+} from "../../lib/context-menu";+import type { AnchorRect, HoldEvent, HoldState } from "../../lib/context-menu";++/** Handlers the owning row spreads onto its container element. */+export interface ContextMenuRowProps {+ onContextMenu: (e: ReactMouseEvent) => void;+ onKeyDown: (e: ReactKeyboardEvent) => void;+ onPointerDown: (e: ReactPointerEvent) => void;+ onPointerMove: (e: ReactPointerEvent) => void;+ onPointerUp: (e: ReactPointerEvent) => void;+ onPointerCancel: (e: ReactPointerEvent) => void;+}++export interface RowContextMenu {+ /** Attach to the row container: it is both the gesture target and the keyboard anchor. */+ rowRef: (el: HTMLElement | null) => void;+ rowProps: ContextMenuRowProps;+ open: boolean;+ /** Dismiss requests from the Dropdown (Escape / outside click / scroll). */+ setOpen: (v: boolean) => void;+ /** Viewport box to place the panel against; null while closed. */+ anchor: AnchorRect | null;+ /** Focus target when Escape closes the panel — the row's own button. */+ returnFocus: () => HTMLElement | null;+ /**+ * True exactly once, for the click a touch screen replays after a press-and-hold: the+ * row's click handler calls it first so opening the menu does not also open the row.+ */+ consumeLongPressClick: () => boolean;+ /** Close from inside the panel (an item ran). */+ close: () => void;+}++export function useRowContextMenu(): RowContextMenu {+ const row = useRef<HTMLElement | null>(null);+ const [anchor, setAnchor] = useState<AnchorRect | null>(null);+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const pressFrom = useRef<{ x: number; y: number } | null>(null);+ const hold = useRef<HoldState>(IDLE_HOLD);++ const cancelTimer = useCallback(() => {+ if (timer.current !== null) {+ clearTimeout(timer.current);+ timer.current = null;+ }+ pressFrom.current = null;+ }, []);++ // A row can unmount mid-press — the list re-renders on every session patch, and the+ // sidebar itself unmounts on navigation — so a pending hold has to die with it rather+ // than fire into a component that is gone.+ useEffect(() => cancelTimer, [cancelTimer]);++ /** The row's own box, in viewport coordinates (the keyboard path's anchor). */+ const rowRect = useCallback((): AnchorRect => {+ const r = row.current?.getBoundingClientRect();+ return r+ ? { top: r.top, bottom: r.bottom, left: r.left, right: r.right }+ : { top: 0, bottom: 0, left: 0, right: 0 };+ }, []);++ /** Run one gesture event through the pure lifecycle and apply what it asks for. */+ const dispatch = useCallback((event: HoldEvent, eventAnchor?: AnchorRect) => {+ const out = reduceHold(hold.current, event);+ hold.current = out.state;+ if (out.open === "held") {+ const at = pressFrom.current;+ if (at) setAnchor(pointerAnchor(at.x, at.y));+ } else if (out.open === "event" && eventAnchor) {+ setAnchor(eventAnchor);+ }+ if (out.close) setAnchor(null);+ return out;+ }, []);++ /**+ * Did this event actually come from the row, rather than from the menu panel?+ * React propagates events through its own tree, and the Dropdown's portal is a React+ * child of this row — so without this check, right-clicking a menu item would bubble+ * back here and jump the open menu to sit under the cursor. The panel is mounted on+ * `document.body`, so it fails a DOM containment test while any real row child passes.+ */+ const fromRow = (e: { currentTarget: unknown; target: unknown }): boolean => {+ const host = e.currentTarget as Node | null;+ return host instanceof Node && host.contains(e.target as Node);+ };++ const rowProps: ContextMenuRowProps = {+ onContextMenu: (e) => {+ if (!fromRow(e)) return;+ // The whole of this feature's native-menu suppression: scoped to events raised+ // inside this row, never registered globally.+ e.preventDefault();+ dispatch({ kind: "nativemenu", at: Date.now() }, contextMenuAnchor(e, rowRect()));+ // The browser may have timed the hold itself; our own timer must not fire on top.+ if (hold.current.held) cancelTimer();+ },+ onKeyDown: (e) => {+ if (!fromRow(e)) return;+ if (!isContextMenuKey(e)) return;+ // Also stops the browser synthesizing its own contextmenu from this chord where it+ // does that, so the menu opens exactly once.+ e.preventDefault();+ setAnchor(rowRect());+ },+ onPointerDown: (e) => {+ if (!fromRow(e)) return;+ dispatch({ kind: "pointerdown", pointerType: e.pointerType });+ if (!isLongPressPointer(e.pointerType)) return;+ const x = e.clientX;+ const y = e.clientY;+ pressFrom.current = { x, y };+ timer.current = setTimeout(() => {+ timer.current = null;+ dispatch({ kind: "hold", at: Date.now() });+ }, LONG_PRESS_MS);+ },+ onPointerMove: (e) => {+ const from = pressFrom.current;+ if (from === null) return;+ if (longPressMoved(from, { x: e.clientX, y: e.clientY })) cancelTimer();+ },+ onPointerUp: () => {+ cancelTimer();+ dispatch({ kind: "pointerup", at: Date.now() });+ },+ onPointerCancel: () => {+ cancelTimer();+ dispatch({ kind: "pointerup", at: Date.now() });+ },+ };++ const close = useCallback(() => {+ hold.current = { ...hold.current, held: false };+ setAnchor(null);+ }, []);++ return {+ rowRef: useCallback((el: HTMLElement | null) => {+ row.current = el;+ }, []),+ rowProps,+ open: anchor !== null,+ setOpen: (v) => {+ if (v) return;+ // The dismiss is only believed outside the post-lift grace window: a touch screen+ // replays the held press as a mousedown on the row, which the Dropdown reads as an+ // outside click on the menu that same gesture just opened.+ dispatch({ kind: "dismiss", at: Date.now() });+ },+ anchor,+ returnFocus: () => row.current?.querySelector<HTMLElement>("button") ?? null,+ consumeLongPressClick: () => dispatch({ kind: "click" }).swallow,+ close,+ };+}diff --git a/packages/web/src/components/ui/dropdown.tsx b/packages/web/src/components/ui/dropdown.tsxindex 1b6c5581..7a610e2d 100644--- a/packages/web/src/components/ui/dropdown.tsx+++ b/packages/web/src/components/ui/dropdown.tsx@@ -22,6 +22,14 @@* items (wrapping), and closing via Escape returns focus to the trigger — without this a* keyboard user could open a menu and never reach its contents, which is exactly what* happened when the sidebar's row actions moved from bare buttons into these panels.+ *+ * `anchorRect` turns the same panel into a context menu: placement measures the given+ * viewport box instead of the container's own, so the menu can hang off the point a+ * secondary click landed on while everything else — the dismiss stack, focus handling,+ * edge clamping and flip — stays shared with every other menu. A virtual anchor is a+ * position rather than an element, so scrolling **dismisses** such a panel instead of+ * re-placing it: the point it was anchored to has moved out from under it, and there is+ * no trigger left to follow.*/import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import { createPortal } from "react-dom";@@ -47,6 +55,8 @@ export function Dropdown({menuStyle,className,portal,+ anchorRect,+ returnFocus,onEscape,}: {button: ReactNode;@@ -61,6 +71,18 @@ export function Dropdown({className?: string;/** Render the panel through a body portal at fixed viewport coordinates, escaping any clipping ancestor. */portal?: DropdownPortal;+ /**+ * Place the panel against this viewport box instead of the container's own — a context+ * menu opened at the pointer, where the "trigger" is a whole row rather than a button.+ * Requires `portal`. While set, scrolling dismisses the panel rather than re-placing it.+ */+ anchorRect?: { top: number; bottom: number; left: number; right: number } | null;+ /**+ * Element to focus when Escape closes the panel. Defaults to the first button inside+ * the container, which is the trigger for an ordinary dropdown; a context menu has no+ * trigger of its own and points this at the row it was opened from.+ */+ returnFocus?: () => HTMLElement | null;/*** When provided, the window-level Escape calls this instead of setOpen(false) — for panels* whose close-request semantics differ from a plain dismiss (e.g. an editor where outside@@ -80,8 +102,8 @@ export function Dropdown({/** The caller-rendered trigger's button element (focus target when Escape closes the menu). */const triggerButton = useCallback(- () => ref.current?.querySelector<HTMLElement>("button") ?? null,- [],+ () => returnFocus?.() ?? ref.current?.querySelector<HTMLElement>("button") ?? null,+ [returnFocus],);/** The panel's focusable items, in DOM order (menu rows, and any input/link a panel carries). */@@ -172,7 +194,9 @@ export function Dropdown({setPos(null);return;}- const rect = ref.current.getBoundingClientRect();+ // A virtual anchor (context menu) is already in viewport coordinates; otherwise the+ // container's own box is the trigger.+ const rect = anchorRect ?? ref.current.getBoundingClientRect();// offsetWidth/offsetHeight, not the bounding rect: the panel plays a pop-in scale// animation, and a mid-animation rect reports a smaller box — which would under-clamp the// left edge and let the settled panel overrun the viewport. The offset box is untransformed.@@ -200,7 +224,16 @@ export function Dropdown({: { top: rect.bottom + PANEL_GAP }),});// eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, portal?.direction, portal?.align, children]);+ }, [+ open,+ portal?.direction,+ portal?.align,+ children,+ anchorRect?.top,+ anchorRect?.left,+ anchorRect?.bottom,+ anchorRect?.right,+ ]);useLayoutEffect(place, [place]);@@ -213,15 +246,24 @@ export function Dropdown({if (!open || !portal) return;const onScroll = (e: Event) => {if (panelRef.current?.contains(e.target as Node)) return;- place();+ // A pointer-anchored panel has nothing left to follow once the content under the+ // pointer moves, so it dismisses instead (the usual context-menu behavior).+ if (anchorRect) setOpenRef.current(false);+ else place();+ };+ // A resize moves the same anchor point out from under the panel, so it dismisses for+ // the same reason a scroll does.+ const onResize = () => {+ if (anchorRect) setOpenRef.current(false);+ else place();};window.addEventListener("scroll", onScroll, true);- window.addEventListener("resize", place);+ window.addEventListener("resize", onResize);return () => {window.removeEventListener("scroll", onScroll, true);- window.removeEventListener("resize", place);+ window.removeEventListener("resize", onResize);};- }, [open, portal, place]);+ }, [open, portal, place, anchorRect]);// Portaled panels sit at z-[60], above a Modal's z-50 overlay (a body portal appended// after the overlay would otherwise paint UNDER it and be unclickable); in-flow panelsdiff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsxindex 8adc4a39..e2b665be 100644--- a/packages/web/src/components/ui/group-list.tsx+++ b/packages/web/src/components/ui/group-list.tsx@@ -8,6 +8,7 @@*/import type { ReactNode } from "react";import { S } from "../../lib/strings";+import type { SessionSortMode } from "../../lib/session-order";import { Chevron } from "./chevron";/** Minimal stroke-icon wrapper shared by the grouped lists (moved from sidebar.tsx). */@@ -41,9 +42,36 @@ export const FOLDER_OPEN_ICON =export const AGENT_GROUP_ICON ="M12 3v3m-6 4a6 6 0 0 1 12 0v5a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-5zm3 3h.01M15 13h.01";+/** Clock (lucide clock, drawn as one path), the "most recent" sort option. */+export const CLOCK_ICON = "M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0M12 6v6l4 2";++/** Opposed up/down arrows (lucide arrow-up-down), the drag-reordered "manual order" sort option. */+export const REORDER_ICON = "m21 16-4 4-4-4M17 20V4M3 8l4-4 4 4M7 4v16";+/** Grouping mode of a Session list (persisted; Workspace is the default). */export type GroupMode = "workspace" | "agent";+/**+ * Leading glyph per grouping mode — the one place these are chosen, read by both the+ * two-icon toggle below and the sidebar's list-options menu, so a row and its toggle can+ * never end up wearing different icons for the same mode. Each glyph names the thing the+ * list is grouped *into*: a folder for Workspaces, the Agent glyph for Agents.+ */+export const GROUP_MODE_ICONS: Record<GroupMode, string> = {+ workspace: FOLDER_ICON,+ agent: AGENT_GROUP_ICON,+};++/**+ * Leading glyph per sort mode, distinguishing what actually decides the order rather than+ * decorating the rows: a clock for recency, and the reorder arrows of the drag that+ * produces a manual order.+ */+export const SORT_MODE_ICONS: Record<SessionSortMode, string> = {+ recent: CLOCK_ICON,+ manual: REORDER_ICON,+};+/*** One storage key for every grouped-list surface (sidebar + Trace page): the grouping* choice is a single user preference, not a per-page one — switching it anywhere@@ -82,8 +110,8 @@ export function GroupModeToggle({<div className="flex items-center gap-0.5">{([- { value: "workspace", icon: FOLDER_ICON, label: S.chat.groupByWorkspace },- { value: "agent", icon: AGENT_GROUP_ICON, label: S.chat.groupByAgent },+ { value: "workspace", icon: GROUP_MODE_ICONS.workspace, label: S.chat.groupByWorkspace },+ { value: "agent", icon: GROUP_MODE_ICONS.agent, label: S.chat.groupByAgent },] as const).map((opt) => (<buttondiff --git a/packages/web/src/components/ui/session-row-menu.tsx b/packages/web/src/components/ui/session-row-menu.tsxnew file mode 100644index 00000000..b37a32b7--- /dev/null+++ b/packages/web/src/components/ui/session-row-menu.tsx@@ -0,0 +1,186 @@+/**+ * Actions on a sidebar Session row, and the two surfaces that offer them.+ *+ * The row carries a **pared-back hover affordance** and a **full context menu**, and this+ * module owns which actions belong to each so the two cannot drift:+ *+ * - Hovering a row reveals archive and delete as direct icon buttons — the shape the row+ * had in every released version up to v0.2.2, restored here after the 0.3 line had+ * folded them into an ellipsis dropdown.+ * - Right-clicking a row (or holding it on touch, or Shift+F10 on the keyboard) opens the+ * whole set — pin, rename, archive, delete — as a labelled menu.+ *+ * Rename therefore keeps a home: `design/specs/06-PROTOTYPE.md` requires that every+ * Session支持重命名、归档与删除, and paring the hover affordance down would otherwise have+ * dropped rename off the row entirely.+ */+import { S } from "../../lib/strings";+import { Icon } from "./group-list";++/** Pushpin (lucide pin: head + body + stem), the group-header pin toggle / pinned indicator. */+export const PIN_ICON =+ "M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1z";++/** Row-action glyphs (thin-line, matching the shared Icon set): pencil / archive / unarchive / trash. */+export const PENCIL_ICON = "M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3";+export const ARCHIVE_ICON =+ "M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M9.5 13.5 12 16l2.5-2.5";+export const UNARCHIVE_ICON =+ "M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M12 17v-5m-2.5 2L12 11l2.5 3";+export const TRASH_ICON =+ "M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6";++/** Compact overflow-menu row (session row menu + workspace group menu): small text, leading thin-line glyph. */+export const overflowMenuRowClass =+ "flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800";++/** The overflow menus' destructive row (delete keeps the red treatment; its glyph inherits the red). */+export const overflowMenuDangerClass =+ "flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-red-600 transition-colors duration-150 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40";++/** The overflow menus' muted leading glyph (a danger row inlines its own so the red inherits). */+export const overflowMenuGlyph = (d: string) => (+ <span className="shrink-0 text-gray-400 dark:text-gray-500">+ <Icon d={d} size={13} />+ </span>+);++/** One thing a Session row can do to its Session. */+export type SessionRowAction = "pin" | "rename" | "archive" | "delete";++/** Row state the labels and glyphs read (both of the toggles flip on it). */+export interface SessionRowState {+ archived: boolean;+ pinned: boolean;+}++/**+ * The hover affordance's actions, restored to the released shape: archive and delete,+ * nothing else. Everything else on the row is one right-click away.+ */+export const HOVER_ROW_ACTIONS: readonly SessionRowAction[] = ["archive", "delete"];++/**+ * The context menu's actions. Pin only reorders rows in the active list, so folder rows+ * (archived / subagent / scheduled) offer the rest without it — the same gate the+ * ellipsis menu applied before this moved.+ */+export function contextMenuActions(canPin: boolean): readonly SessionRowAction[] {+ return canPin ? ["pin", "rename", "archive", "delete"] : ["rename", "archive", "delete"];+}++export interface SessionRowMenuItem {+ /** Label in the action's current state, and the icon-only buttons' accessible name. */+ label: string;+ icon: string;+ /** Destructive: red row in the menu, red hover on the icon button. */+ danger: boolean;+}++/** Label + glyph for one action, given the state of the row it sits on. */+export function sessionRowMenuItem(+ action: SessionRowAction,+ state: SessionRowState,+): SessionRowMenuItem {+ switch (action) {+ case "pin":+ return {+ label: state.pinned ? S.chat.unpinSession : S.chat.pinSession,+ icon: PIN_ICON,+ danger: false,+ };+ case "rename":+ return { label: S.chat.renameSession, icon: PENCIL_ICON, danger: false };+ case "archive":+ return {+ label: state.archived ? S.chat.unarchiveSession : S.chat.archiveSession,+ icon: state.archived ? UNARCHIVE_ICON : ARCHIVE_ICON,+ danger: false,+ };+ case "delete":+ return { label: S.chat.deleteSession, icon: TRASH_ICON, danger: true };+ }+}++/** The context menu's body: one labelled row per action, in the given order. */+export function SessionRowMenuRows({+ actions,+ state,+ onRun,+}: {+ actions: readonly SessionRowAction[];+ state: SessionRowState;+ onRun: (action: SessionRowAction) => void;+}) {+ return (+ <>+ {actions.map((action) => {+ const item = sessionRowMenuItem(action, state);+ return (+ <button+ key={action}+ type="button"+ className={item.danger ? overflowMenuDangerClass : overflowMenuRowClass}+ onClick={() => onRun(action)}+ >+ {item.danger ? (+ /* The glyph inherits the row's red. */+ <span className="shrink-0">+ <Icon d={item.icon} size={13} />+ </span>+ ) : (+ overflowMenuGlyph(item.icon)+ )}+ {item.label}+ </button>+ );+ })}+ </>+ );+}++/**+ * Hover affordance: icon-only buttons that fade in over the row, the pre-0.3 treatment.+ * Deliberately hover/focus-gated and therefore desktop-only — Tailwind scopes `hover:`+ * behind `@media (hover: hover)`, so these never appear on a touch screen, where the same+ * actions are reached by holding the row instead.+ *+ * Which is why they are **pointer-events-gated on exactly the same conditions as their+ * opacity**, not just faded out: an invisible button still takes taps, so a bare+ * `opacity-0` would leave a phantom delete target sitting over the right end of every row+ * for the one class of user who can never see it. Keyboard focus is unaffected by+ * `pointer-events`, so Tab still reaches them and revealing them re-arms the click.+ */+export function SessionRowHoverActions({+ actions,+ state,+ onRun,+}: {+ actions: readonly SessionRowAction[];+ state: SessionRowState;+ onRun: (action: SessionRowAction) => void;+}) {+ return (+ <>+ {actions.map((action) => {+ const item = sessionRowMenuItem(action, state);+ return (+ <button+ key={action}+ type="button"+ title={item.label}+ aria-label={item.label}+ onClick={() => onRun(action)}+ className={`pointer-events-none flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 ${+ item.danger+ ? "hover:text-red-600 dark:hover:text-red-400"+ : "hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"+ }`}+ >+ <Icon d={item.icon} size={14} />+ </button>+ );+ })}+ </>+ );+}diff --git a/packages/web/src/lib/context-menu.ts b/packages/web/src/lib/context-menu.tsnew file mode 100644index 00000000..f8ab47ee--- /dev/null+++ b/packages/web/src/lib/context-menu.ts@@ -0,0 +1,194 @@+/**+ * Pure geometry and gesture rules behind a row context menu (the sidebar's Session rows+ * are the first user). The component half is `components/ui/context-menu.tsx`; the parts+ * that decide *where* a menu lands and *whether* a gesture counts as a request for one+ * live here so they can be tested in this package's node-only vitest environment.+ *+ * A context menu must not be a mouse-only affordance: `design/specs/06-PROTOTYPE.md`+ * states that hover-reveal is desktop-only because touch screens have no hover, and a+ * secondary click is desktop-only for the same reason. So three gestures open the same+ * menu — a right-click at the pointer, the platform's keyboard chord against the focused+ * row, and press-and-hold on touch — and the rules for telling them apart are here.+ */++/** Viewport-space box a portaled panel is placed against (the Dropdown's `anchorRect`). */+export interface AnchorRect {+ top: number;+ bottom: number;+ left: number;+ right: number;+}++/** The subset of a `contextmenu` event the anchoring rules read. */+export interface ContextMenuEventLike {+ button: number;+ clientX: number;+ clientY: number;+}++/** A point, for the press-and-hold slop test. */+export interface Point {+ x: number;+ y: number;+}++/** Zero-size box at the pointer: a context menu hangs off the click point itself. */+export function pointerAnchor(x: number, y: number): AnchorRect {+ return { top: y, bottom: y, left: x, right: x };+}++/**+ * Was this `contextmenu` event produced by a pointer rather than by the keyboard?+ * Browsers synthesize one for the Menu key and Shift+F10 with `button: 0` — no button was+ * pressed — and several report its coordinates as (0, 0); a real secondary click always+ * carries `button: 2`. Treating (0, 0) as keyboard-invoked costs nothing, because a list+ * row inside the sidebar can never be right-clicked at the viewport origin.+ */+export function isPointerContextMenu(e: ContextMenuEventLike): boolean {+ return e.button === 2 && !(e.clientX === 0 && e.clientY === 0);+}++/**+ * Where the menu opens: at the pointer for a real secondary click, and against the row's+ * own box when the keyboard asked for it — a keyboard user has no pointer, so a+ * pointer-anchored panel would land in the corner of the screen, detached from the row it+ * acts on.+ */+export function contextMenuAnchor(e: ContextMenuEventLike, row: AnchorRect): AnchorRect {+ return isPointerContextMenu(e) ? pointerAnchor(e.clientX, e.clientY) : row;+}++/**+ * Shift+F10 — the platform chord for "open the context menu for the focused element".+ * Handled explicitly rather than left to the browser: Windows and Linux browsers+ * synthesize a `contextmenu` event from it, but macOS keyboards have no Menu key and+ * Safari synthesizes nothing, which would stand a keyboard-only Mac user in front of a+ * menu they cannot open.+ */+export function isContextMenuKey(e: { key: string; shiftKey: boolean }): boolean {+ return e.shiftKey && e.key === "F10";+}++/** Press-and-hold before a touch counts as a context-menu request (ms). */+export const LONG_PRESS_MS = 500;++/** Slop allowed during the hold: past this the finger is scrolling or dragging, not pressing. */+export const LONG_PRESS_SLOP_PX = 10;++/**+ * Grace period after a press-and-hold opened the menu, during which a dismiss request is+ * ignored (ms). Touch screens replay a held press as compatibility mouse events once the+ * finger lifts, and that synthetic `mousedown` lands on the row — outside the panel — so+ * the menu the gesture just opened would dismiss itself before it could be read.+ */+export const LONG_PRESS_SETTLE_MS = 350;++/** Only touch and pen press-and-hold; a mouse has a secondary button and uses it. */+export function isLongPressPointer(pointerType: string): boolean {+ return pointerType === "touch" || pointerType === "pen";+}++/** Did the finger travel far enough during the hold to make this a scroll instead? */+export function longPressMoved(from: Point, to: Point): boolean {+ return (+ Math.abs(to.x - from.x) > LONG_PRESS_SLOP_PX || Math.abs(to.y - from.y) > LONG_PRESS_SLOP_PX+ );+}++/** Is a dismiss arriving inside the grace window that started at `fromMs` (see LONG_PRESS_SETTLE_MS)? */+export function withinSettleWindow(fromMs: number, nowMs: number): boolean {+ return nowMs - fromMs < LONG_PRESS_SETTLE_MS;+}++/**+ * The gesture's lifecycle, as a pure reducer.+ *+ * A press-and-hold is not one event but a sequence, and the sequence is where this gets+ * subtle: the browser may raise its own `contextmenu` mid-hold and beat our timer to it,+ * and when the finger finally lifts the screen replays the whole press as compatibility+ * mouse events — a `mousedown` that lands on the row (which the menu reads as an outside+ * click) and a `click` on the row's button (which would open the conversation). Both+ * arrive at **lift**, not at open, so the grace period is measured from the lift.+ *+ * Keeping this out of the hook is what makes it testable at all: the component half needs+ * a DOM, this needs only an ordered list of events.+ */+export interface HoldState {+ /** Pointer type of the gesture in flight ("" between gestures). */+ pointer: string;+ /** A press-and-hold owns the open menu, so its replayed click and mousedown are still expected. */+ held: boolean;+ /** Start of the grace period in which a dismiss is ignored. */+ settleFrom: number;+}++export const IDLE_HOLD: HoldState = { pointer: "", held: false, settleFrom: 0 };++export type HoldEvent =+ | { kind: "pointerdown"; pointerType: string }+ /** The press-and-hold timer elapsed. */+ | { kind: "hold"; at: number }+ /** The browser raised its own contextmenu (a right-click, or a hold it timed itself). */+ | { kind: "nativemenu"; at: number }+ | { kind: "pointerup"; at: number }+ /** The menu asked to close (Escape, outside click, scroll). */+ | { kind: "dismiss"; at: number }+ /** The row's button was activated. */+ | { kind: "click" };++export interface HoldOutcome {+ state: HoldState;+ /** `"held"` anchors at the pressed point, `"event"` by the event's own rule, null opens nothing. */+ open: "held" | "event" | null;+ close: boolean;+ /** Swallow the row's activation — this click is the one the hold replayed. */+ swallow: boolean;+}++const OUTCOME = { open: null, close: false, swallow: false } as const;++export function reduceHold(state: HoldState, event: HoldEvent): HoldOutcome {+ switch (event.kind) {+ case "pointerdown":+ // Cleared for every gesture, mouse included: a flag left set by a hold whose replayed+ // click never arrived must not swallow the next real tap.+ return { ...OUTCOME, state: { ...state, pointer: event.pointerType, held: false } };+ case "hold":+ return {+ ...OUTCOME,+ state: { ...state, held: true, settleFrom: event.at },+ open: "held",+ };+ case "nativemenu":+ // Our timer already opened it; don't re-anchor the menu out from under the finger.+ if (state.held) return { ...OUTCOME, state };+ // The browser timed the hold before we did — it is still a hold, and its replayed+ // events still have to be absorbed.+ if (isLongPressPointer(state.pointer))+ return {+ ...OUTCOME,+ state: { ...state, held: true, settleFrom: event.at },+ open: "event",+ };+ return { ...OUTCOME, state, open: "event" };+ case "pointerup":+ // The lift is when the replayed events start arriving, so the grace period starts here+ // rather than when the menu opened — a user who reads the menu before lifting would+ // otherwise have it dismissed by their own finger.+ return {+ ...OUTCOME,+ state: {+ ...state,+ pointer: "",+ settleFrom: state.held ? event.at : state.settleFrom,+ },+ };+ case "dismiss":+ if (state.held && withinSettleWindow(state.settleFrom, event.at))+ return { ...OUTCOME, state };+ return { ...OUTCOME, state: { ...state, held: false }, close: true };+ case "click":+ if (!state.held) return { ...OUTCOME, state };+ return { ...OUTCOME, state: { ...state, held: false }, swallow: true };+ }+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 4fb2aaa5..66f292f3 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1320,7 +1320,6 @@ Scenarios:archiveSession: "Archive",unarchiveSession: "Unarchive",/** Per-row ellipsis overflow menu (pin / rename / archive / delete live inside it) and the row-level pin. */- sessionMenu: "Chat options",pinSession: "Pin",unpinSession: "Unpin",pinnedSession: "Pinned",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 66eb30a7..b10b94cb 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1276,7 +1276,6 @@ Benchmark:archiveSession: "归档",unarchiveSession: "取消归档",/** Per-row ellipsis overflow menu (pin / rename / archive / delete live inside it) and the row-level pin. */- sessionMenu: "对话选项",pinSession: "置顶",unpinSession: "取消置顶",pinnedSession: "已置顶",diff --git a/packages/web/test/context-menu.test.ts b/packages/web/test/context-menu.test.tsnew file mode 100644index 00000000..f1c60e71--- /dev/null+++ b/packages/web/test/context-menu.test.ts@@ -0,0 +1,312 @@+/**+ * context-menu.ts unit tests: the rules deciding which gesture asks for a row's context+ * menu and where the panel lands.+ *+ * Two things matter beyond the arithmetic. **Anchoring** has to distinguish a real+ * secondary click from the keyboard chord browsers synthesize a `contextmenu` event for,+ * because a keyboard user has no pointer and a pointer-anchored panel would open in the+ * corner of the screen. And the feature must not be mouse-only: touch screens have+ * neither hover nor a secondary button, which is exactly why+ * `design/specs/06-PROTOTYPE.md` requires touch to keep a path of its own.+ *+ * The second half pins **suppression scope** against the source text. Preventing the+ * browser's own menu is correct on the row and wrong everywhere else, and nothing in a+ * node-only suite (`environment: "node"`, no jsdom) would notice a `preventDefault` that+ * had crept onto a document-level listener — so the scan asserts there is no global+ * contextmenu listener in the package, and that the one handler doing the suppressing+ * lives in the hook the row spreads onto itself (title-reveal.test.ts convention).+ */+import { readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve, sep } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import {+ IDLE_HOLD,+ LONG_PRESS_MS,+ LONG_PRESS_SETTLE_MS,+ LONG_PRESS_SLOP_PX,+ contextMenuAnchor,+ isContextMenuKey,+ isLongPressPointer,+ isPointerContextMenu,+ longPressMoved,+ pointerAnchor,+ reduceHold,+ withinSettleWindow,+} from "../src/lib/context-menu";+import type { HoldEvent } from "../src/lib/context-menu";++const ROW = { top: 100, bottom: 132, left: 8, right: 260 };++describe("pointerAnchor", () => {+ it("is a zero-size box at the point, so the panel hangs off the click itself", () => {+ expect(pointerAnchor(420, 300)).toEqual({ top: 300, bottom: 300, left: 420, right: 420 });+ });+});++describe("isPointerContextMenu", () => {+ it("recognizes a secondary click", () => {+ expect(isPointerContextMenu({ button: 2, clientX: 420, clientY: 300 })).toBe(true);+ });++ it("rejects the keyboard-synthesized event, which reports no button", () => {+ expect(isPointerContextMenu({ button: 0, clientX: 130, clientY: 110 })).toBe(false);+ });++ it("rejects the (0, 0) coordinates some browsers report for the Menu key", () => {+ expect(isPointerContextMenu({ button: 2, clientX: 0, clientY: 0 })).toBe(false);+ });+});++describe("contextMenuAnchor", () => {+ it("opens at the pointer for a right-click", () => {+ expect(contextMenuAnchor({ button: 2, clientX: 420, clientY: 300 }, ROW)).toEqual(+ pointerAnchor(420, 300),+ );+ });++ it("falls back to the row's own box when the keyboard asked, not to the viewport corner", () => {+ expect(contextMenuAnchor({ button: 0, clientX: 0, clientY: 0 }, ROW)).toEqual(ROW);+ });+});++describe("isContextMenuKey", () => {+ it("is Shift+F10, the platform chord for the focused element's context menu", () => {+ expect(isContextMenuKey({ key: "F10", shiftKey: true })).toBe(true);+ });++ it("ignores a bare F10 and other shifted keys, so the row eats no ordinary typing", () => {+ expect(isContextMenuKey({ key: "F10", shiftKey: false })).toBe(false);+ expect(isContextMenuKey({ key: "F11", shiftKey: true })).toBe(false);+ expect(isContextMenuKey({ key: "Enter", shiftKey: true })).toBe(false);+ });+});++describe("press-and-hold (the touch path)", () => {+ it("holds for touch and pen only — a mouse has a secondary button and uses it", () => {+ expect(isLongPressPointer("touch")).toBe(true);+ expect(isLongPressPointer("pen")).toBe(true);+ expect(isLongPressPointer("mouse")).toBe(false);+ expect(isLongPressPointer("")).toBe(false);+ });++ it("tolerates a finger's jitter but treats real travel as a scroll", () => {+ const from = { x: 100, y: 200 };+ expect(longPressMoved(from, { x: 100, y: 200 })).toBe(false);+ expect(longPressMoved(from, { x: 100 + LONG_PRESS_SLOP_PX, y: 200 })).toBe(false);+ expect(longPressMoved(from, { x: 100, y: 200 + LONG_PRESS_SLOP_PX + 1 })).toBe(true);+ expect(longPressMoved(from, { x: 100 - LONG_PRESS_SLOP_PX - 1, y: 200 })).toBe(true);+ });++ it("waits long enough not to fire on an ordinary tap", () => {+ expect(LONG_PRESS_MS).toBeGreaterThanOrEqual(400);+ expect(LONG_PRESS_SETTLE_MS).toBeGreaterThan(0);+ });++ it("ignores a dismiss inside the grace window that started at the given moment", () => {+ const opened = 10_000;+ expect(withinSettleWindow(opened, opened)).toBe(true);+ expect(withinSettleWindow(opened, opened + LONG_PRESS_SETTLE_MS - 1)).toBe(true);+ expect(withinSettleWindow(opened, opened + LONG_PRESS_SETTLE_MS)).toBe(false);+ expect(withinSettleWindow(opened, opened + 5_000)).toBe(false);+ });+});++/**+ * The gesture lifecycle, driven as ordered sequences. This is where the interesting bugs+ * live — every one of the cases below is a real touch sequence, not a synthetic one — and+ * it is only reachable from a node-only suite because the decisions were kept pure.+ */+describe("reduceHold", () => {+ /** Feed a sequence, returning each step's outcome. */+ const play = (events: HoldEvent[]) => {+ let state = IDLE_HOLD;+ return events.map((e) => {+ const out = reduceHold(state, e);+ state = out.state;+ return out;+ });+ };++ it("opens on the hold and swallows the click the lift replays", () => {+ const [, held, , click] = play([+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "hold", at: 1_000 },+ { kind: "pointerup", at: 1_200 },+ { kind: "click" },+ ]);+ expect(held!.open).toBe("held");+ expect(click!.swallow).toBe(true);+ });++ it("measures the grace window from the LIFT, so reading the menu before lifting is safe", () => {+ // The whole point: the menu opens at 1s and the user studies it for two seconds before+ // lifting. The compatibility mousedown arrives at the lift, not at the open — anchoring+ // the window to the open time would dismiss the menu the gesture just produced.+ const [, , , dismiss] = play([+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "hold", at: 1_000 },+ { kind: "pointerup", at: 3_000 },+ { kind: "dismiss", at: 3_010 },+ ]);+ expect(dismiss!.close).toBe(false);+ });++ it("believes a dismiss once the replayed events can no longer be in flight", () => {+ const [, , , dismiss] = play([+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "hold", at: 1_000 },+ { kind: "pointerup", at: 3_000 },+ { kind: "dismiss", at: 3_000 + LONG_PRESS_SETTLE_MS },+ ]);+ expect(dismiss!.close).toBe(true);+ });++ it("treats a native contextmenu raised during a touch hold as the hold itself", () => {+ // Android raises its own contextmenu mid-hold and can beat our timer to it. If that is+ // not recognized as a hold, the lift's replayed click falls through and opens the+ // conversation on top of the menu.+ const [, native, , click] = play([+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "nativemenu", at: 1_000 },+ { kind: "pointerup", at: 1_100 },+ { kind: "click" },+ ]);+ expect(native!.open).toBe("event");+ expect(native!.state.held).toBe(true);+ expect(click!.swallow).toBe(true);+ });++ it("does not re-anchor an already-held menu when the browser raises its own afterwards", () => {+ const [, , native] = play([+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "hold", at: 1_000 },+ { kind: "nativemenu", at: 1_050 },+ ]);+ expect(native!.open).toBeNull();+ });++ it("leaves a mouse right-click free of hold semantics", () => {+ const [, native, dismiss, click] = play([+ { kind: "pointerdown", pointerType: "mouse" },+ { kind: "nativemenu", at: 1_000 },+ { kind: "dismiss", at: 1_010 },+ { kind: "click" },+ ]);+ expect(native!.open).toBe("event");+ expect(native!.state.held).toBe(false);+ // No grace window for a mouse: the very next outside click closes the menu.+ expect(dismiss!.close).toBe(true);+ expect(click!.swallow).toBe(false);+ });++ it("clears a hold flag left over from a gesture whose replayed click never came", () => {+ const [, , down, click] = play([+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "hold", at: 1_000 },+ // No click followed; the next gesture starts clean rather than eating its tap.+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "click" },+ ]);+ expect(down!.state.held).toBe(false);+ expect(click!.swallow).toBe(false);+ });++ it("swallows only one click per hold", () => {+ const [, , , first, second] = play([+ { kind: "pointerdown", pointerType: "touch" },+ { kind: "hold", at: 1_000 },+ { kind: "pointerup", at: 1_100 },+ { kind: "click" },+ { kind: "click" },+ ]);+ expect(first!.swallow).toBe(true);+ expect(second!.swallow).toBe(false);+ });+});++/**+ * Every .ts/.tsx under packages/web/src, as [relative path, source] pairs.+ *+ * Paths are normalized to forward slashes here, once, rather than at each comparison:+ * `join` yields `\` on Windows, so every `path === "components/ui/…"` in this file would+ * silently match nothing there and collapse its assertions into "expected undefined to be+ * defined" — green on Linux, red on the Windows CI job. Callers can rely on POSIX+ * separators on every platform.+ */+function sourceFiles(): Array<[string, string]> {+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "../src");+ const out: Array<[string, string]> = [];+ const walk = (dir: string) => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (/\.tsx?$/.test(entry.name))+ out.push([+ full+ .slice(root.length + 1)+ .split(sep)+ .join("/"),+ readFileSync(full, "utf8"),+ ]);+ }+ };+ walk(root);+ return out;+}++describe("sourceFiles", () => {+ it("reports POSIX-separated paths whatever the platform's separator is", () => {+ // Pins the contract the assertions below depend on. A no-op assertion on Linux, and+ // the one that fails first on Windows if the normalization is ever dropped.+ const paths = sourceFiles().map(([path]) => path);+ expect(paths.length).toBeGreaterThan(0);+ expect(paths.filter((p) => p.includes("\\"))).toEqual([]);+ expect(paths).toContain("components/ui/context-menu.tsx");+ expect(paths).toContain("components/layout/sidebar.tsx");+ });+});++describe("native-menu suppression scope", () => {+ it("registers no global contextmenu listener, so the browser's own menu survives off the row", () => {+ const global = sourceFiles().filter(([, src]) =>+ /addEventListener\(\s*["']contextmenu["']/.test(src),+ );+ expect(global.map(([path]) => path)).toEqual([]);+ });++ it("calls preventDefault inside the contextmenu handler itself, not somewhere adjacent", () => {+ // Tied to the handler rather than to the file: preventDefault also appears in+ // onKeyDown, so file-level presence would prove nothing about the native menu.+ const hook = sourceFiles().find(([path]) => path === "components/ui/context-menu.tsx");+ expect(hook).toBeDefined();+ const handler = /onContextMenu:\s*\(e\)\s*=>\s*\{([\s\S]*?)\n {4}\},/.exec(hook![1]);+ expect(handler).not.toBeNull();+ expect(handler![1]).toContain("e.preventDefault()");+ });++ it("ignores events that bubbled out of the portaled panel rather than the row", () => {+ // React propagates through its own tree, so the Dropdown's body portal — a React child+ // of the row — would otherwise re-anchor the open menu when one of its items is+ // right-clicked. A DOM containment check separates the two trees.+ const hook = sourceFiles().find(([path]) => path === "components/ui/context-menu.tsx");+ const src = hook![1];+ expect(src).toContain("host.contains(e.target as Node)");+ for (const handler of ["onContextMenu", "onKeyDown", "onPointerDown"]) {+ const body = new RegExp(`${handler}:\\s*\\(e\\)\\s*=>\\s*\\{([\\s\\S]*?)\\n {4}\\},`).exec(+ src,+ );+ expect(body, `${handler} should exist`).not.toBeNull();+ expect(body![1], `${handler} should guard on fromRow`).toContain("if (!fromRow(e)) return;");+ }+ });++ it("gives the sidebar row all three openers, so the menu is not mouse-only", () => {+ const sidebar = sourceFiles().find(([path]) => path === "components/layout/sidebar.tsx");+ expect(sidebar).toBeDefined();+ // The row spreads the hook's handlers (contextmenu + Shift+F10 + press-and-hold) and+ // guards its own click against the one a hold replays.+ expect(sidebar![1]).toContain("{...ctx.rowProps}");+ expect(sidebar![1]).toContain("ctx.consumeLongPressClick()");+ });+});diff --git a/packages/web/test/group-list.test.ts b/packages/web/test/group-list.test.tsindex 27c287a3..7ea2879b 100644--- a/packages/web/test/group-list.test.ts+++ b/packages/web/test/group-list.test.ts@@ -5,9 +5,30 @@* via route state); workspace grouping creates a Workspace (a new-chat draft — there* is no standalone Workspace entity, one comes into being with the conversation* created in it).+ *+ * Plus the list-options menu's glyphs. The icons are decorative — every row keeps its+ * own text label — but they are only worth drawing if they tell the options apart, so+ * the mapping is pinned per option rather than merely asserted non-empty. Grouping reads+ * its glyphs from the same map the two-icon header toggle uses, so a mode cannot end up+ * wearing one icon in the toggle and another in the menu.*/+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";-import { newEntityForGroupMode } from "../src/components/ui/group-list";+import {+ AGENT_GROUP_ICON,+ CLOCK_ICON,+ FOLDER_ICON,+ GROUP_MODE_ICONS,+ REORDER_ICON,+ SORT_MODE_ICONS,+ newEntityForGroupMode,+} from "../src/components/ui/group-list";+import type { GroupMode } from "../src/components/ui/group-list";+import type { SessionSortMode } from "../src/lib/session-order";+import { zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";describe("newEntityForGroupMode", () => {it("agent grouping creates an Agent; workspace grouping (the default) creates a Workspace", () => {@@ -15,3 +36,44 @@ describe("newEntityForGroupMode", () => {expect(newEntityForGroupMode("workspace")).toBe("workspace");});});++describe("list-options glyphs", () => {+ it("names each grouping mode by what the list is grouped into", () => {+ // The same glyphs the header's grouping toggle shows, so the two surfaces agree.+ expect(GROUP_MODE_ICONS).toEqual({ workspace: FOLDER_ICON, agent: AGENT_GROUP_ICON });+ });++ it("names each sort mode by what decides the order: a clock, and the reorder arrows", () => {+ expect(SORT_MODE_ICONS).toEqual({ recent: CLOCK_ICON, manual: REORDER_ICON });+ });++ it("is what the menu rows and the header toggle both actually render", () => {+ // The claim worth pinning is not the map's contents but that nothing re-picks an icon+ // beside it: a hardcoded glyph at either call site is how the toggle and the menu would+ // drift apart. Node-only suite, so this reads the sources (title-reveal.test.ts).+ const read = (p: string) =>+ readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), p), "utf8");+ const sidebar = read("../src/components/layout/sidebar.tsx");+ for (const mode of ["workspace", "agent"] satisfies GroupMode[])+ expect(sidebar).toContain(`icon={GROUP_MODE_ICONS.${mode}}`);+ for (const mode of ["recent", "manual"] satisfies SessionSortMode[])+ expect(sidebar).toContain(`icon={SORT_MODE_ICONS.${mode}}`);+ // The header toggle reads the same map rather than the raw constants.+ expect(read("../src/components/ui/group-list.tsx")).toContain("GROUP_MODE_ICONS.workspace");+ });++ it("gives all four rows glyphs that differ, so an icon distinguishes rather than decorates", () => {+ const icons = [...Object.values(GROUP_MODE_ICONS), ...Object.values(SORT_MODE_ICONS)];+ expect(icons.every((d) => d.length > 0)).toBe(true);+ expect(new Set(icons).size).toBe(icons.length);+ });++ it("leaves every row a real label in both locales — the glyph never carries the name", () => {+ for (const dict of [zh, en]) {+ expect(dict.chat.groupByWorkspace).toBeTruthy();+ expect(dict.chat.groupByAgent).toBeTruthy();+ expect(dict.chat.sortRecent).toBeTruthy();+ expect(dict.chat.sortManual).toBeTruthy();+ }+ });+});diff --git a/packages/web/test/session-row-menu.test.ts b/packages/web/test/session-row-menu.test.tsnew file mode 100644index 00000000..512b6ed6--- /dev/null+++ b/packages/web/test/session-row-menu.test.ts@@ -0,0 +1,151 @@+/**+ * session-row-menu.tsx unit tests: which actions each of a Session row's two surfaces+ * offers, and how each one labels itself.+ *+ * The split is the point of the change and the thing most likely to be undone by+ * accident, so it is pinned by value rather than by shape: **hover gives archive and+ * delete and nothing else** — the affordance every release up to v0.2.2 shipped — while+ * the right-click menu carries the full set. Rename in particular must stay in the+ * context menu: `design/specs/06-PROTOTYPE.md` requires every Session to support+ * 重命名、归档与删除, and the pared-back hover pair alone would not satisfy that.+ *+ * vitest runs node-only here (`environment: "node"`, no jsdom), so these assert against+ * the exported manifests and label helpers rather than a rendered DOM+ * (title-reveal.test.ts convention).+ */+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";+import {+ ARCHIVE_ICON,+ HOVER_ROW_ACTIONS,+ PENCIL_ICON,+ PIN_ICON,+ TRASH_ICON,+ UNARCHIVE_ICON,+ contextMenuActions,+ sessionRowMenuItem,+} from "../src/components/ui/session-row-menu";+import type { SessionRowAction } from "../src/components/ui/session-row-menu";+import { setActiveStrings, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++/** Every test that switches locale puts the default (zh) back. */+afterEach(() => setActiveStrings(zh));++const RESTING = { archived: false, pinned: false };++describe("HOVER_ROW_ACTIONS", () => {+ it("is the released archive + delete pair, in that order, and nothing more", () => {+ expect([...HOVER_ROW_ACTIONS]).toEqual(["archive", "delete"]);+ });++ it("does not carry rename or pin — those moved to the context menu", () => {+ expect(HOVER_ROW_ACTIONS as readonly string[]).not.toContain("rename");+ expect(HOVER_ROW_ACTIONS as readonly string[]).not.toContain("pin");+ });+});++describe("contextMenuActions", () => {+ it("carries the whole set when the row can be pinned", () => {+ expect([...contextMenuActions(true)]).toEqual(["pin", "rename", "archive", "delete"]);+ });++ it("drops only pin on rows where pinning cannot reorder anything (folder rows)", () => {+ expect([...contextMenuActions(false)]).toEqual(["rename", "archive", "delete"]);+ });++ it("is a superset of the hover pair, so nothing is reachable by hover alone", () => {+ for (const canPin of [true, false]) {+ for (const action of HOVER_ROW_ACTIONS) {+ expect(contextMenuActions(canPin)).toContain(action);+ }+ }+ });++ it("keeps rename reachable in every state (design/specs/06-PROTOTYPE.md: 重命名、归档与删除)", () => {+ expect(contextMenuActions(true)).toContain("rename");+ expect(contextMenuActions(false)).toContain("rename");+ });+});++describe("the hover buttons' CSS contract", () => {+ // Node-only suite, so this is asserted against the source text (title-reveal.test.ts+ // convention). It is worth pinning: an invisible button still takes taps, and these are+ // invisible for the whole of every touch session, delete included.+ const source = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), "../src/components/ui/session-row-menu.tsx"),+ "utf8",+ );++ it("gates pointer events on the same conditions as visibility, leaving no phantom tap target", () => {+ expect(source).toContain("pointer-events-none");+ // Both reveal paths must re-arm the click, or the buttons would be visible and dead —+ // and each reveal must pair with its own pointer-events grant, since either half alone+ // yields a button that is visible-but-dead or invisible-but-tappable.+ for (const on of ["group-hover", "focus"]) {+ expect(source).toContain(`${on}:pointer-events-auto`);+ expect(source).toContain(`${on}:opacity-100`);+ }+ // `focus`, not `focus-visible`: the time span it swaps with hides on plain+ // focus-within, and the two conditions have to agree or the slot goes blank.+ expect(source).not.toContain("focus-visible:opacity-100");+ });+});++describe("sessionRowMenuItem", () => {+ it("gives every action a label, a glyph, and only delete the destructive treatment", () => {+ const all: SessionRowAction[] = ["pin", "rename", "archive", "delete"];+ for (const action of all) {+ const item = sessionRowMenuItem(action, RESTING);+ expect(item.label).toBeTruthy();+ expect(item.icon).toBeTruthy();+ expect(item.danger).toBe(action === "delete");+ }+ });++ it("gives the actions distinct glyphs, so a row is not read by its label alone", () => {+ const icons = (["pin", "rename", "archive", "delete"] as SessionRowAction[]).map(+ (a) => sessionRowMenuItem(a, RESTING).icon,+ );+ expect(new Set(icons).size).toBe(icons.length);+ expect(icons).toEqual([PIN_ICON, PENCIL_ICON, ARCHIVE_ICON, TRASH_ICON]);+ });++ it("flips archive's label and glyph on an archived row", () => {+ expect(sessionRowMenuItem("archive", { archived: false, pinned: false })).toMatchObject({+ label: zh.chat.archiveSession,+ icon: ARCHIVE_ICON,+ });+ expect(sessionRowMenuItem("archive", { archived: true, pinned: false })).toMatchObject({+ label: zh.chat.unarchiveSession,+ icon: UNARCHIVE_ICON,+ });+ });++ it("flips pin's label on a pinned row, keeping the one pin glyph", () => {+ expect(sessionRowMenuItem("pin", { archived: false, pinned: false }).label).toBe(+ zh.chat.pinSession,+ );+ expect(sessionRowMenuItem("pin", { archived: false, pinned: true }).label).toBe(+ zh.chat.unpinSession,+ );+ expect(sessionRowMenuItem("pin", { archived: false, pinned: true }).icon).toBe(PIN_ICON);+ });++ it("reads the active dictionary, so both locales name every action", () => {+ setActiveStrings(en);+ expect(sessionRowMenuItem("archive", RESTING).label).toBe(en.chat.archiveSession);+ expect(sessionRowMenuItem("delete", RESTING).label).toBe(en.chat.deleteSession);+ expect(sessionRowMenuItem("rename", RESTING).label).toBe(en.chat.renameSession);+ // The hover buttons are icon-only, so their label IS their accessible name: an English+ // row must not fall back to the zh catalog and leave a Chinese name on the button.+ for (const action of HOVER_ROW_ACTIONS) {+ const label = sessionRowMenuItem(action, RESTING).label;+ expect(label).toBeTruthy();+ expect(label).not.toBe(sessionRowMenuItem(action, RESTING).icon);+ expect(Object.values(zh.chat)).not.toContain(label);+ }+ });+});