A local-first multi-agent app development platform, built on PenguinHarness
feat(web): collapsible agents→evaluation nav group with remembered state (#277)
Yaowei Zhengc31cd3beb580
diff --git a/packages/web/e2e/chat.spec.mjs b/packages/web/e2e/chat.spec.mjsindex 098c2222..976212dd 100644--- a/packages/web/e2e/chat.spec.mjs+++ b/packages/web/e2e/chat.spec.mjs@@ -351,9 +351,12 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })await page.keyboard.press("Escape");// --- session rename (manual title wins over the auto-generated one) ---+ // Row actions live in the per-row ellipsis menu ("对话选项"); its panel is body-portaled,+ // so the items are page-level, not inside the row locator.const renameTarget = sidebar.locator("li", { hasText: "Configure Tailwind theme" }).first();await renameTarget.hover();- await renameTarget.getByRole("button", { name: "重命名对话" }).click();+ await renameTarget.getByRole("button", { name: "对话选项" }).click();+ await page.getByRole("button", { name: "重命名对话" }).click();await page.getByLabel("标题").fill("My renamed title");await page.getByRole("button", { name: "保存" }).click();await expect(sidebar.getByText("My renamed title")).toBeVisible();@@ -367,9 +370,10 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })await page.reload();const throwaway = sidebar.locator("li", { hasText: "新对话" }).first();await expect(throwaway).toBeVisible();- // Archive: moves it under the collapsed "已归档" group.+ // Archive via the row menu: moves it under the collapsed "已归档" group.await throwaway.hover();- await throwaway.getByRole("button", { name: "归档", exact: true }).click();+ await throwaway.getByRole("button", { name: "对话选项" }).click();+ await page.getByRole("button", { name: "归档", exact: true }).click();await expect(sidebar.getByText(/已归档(\d+)/).first()).toBeVisible();await sidebar.getByText(/已归档(\d+)/)@@ -377,9 +381,10 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page }).click();const archived = sidebar.locator("li", { hasText: "新对话" }).first();await expect(archived).toBeVisible();- // Delete from the archived group (delete + archive share one action group).+ // Delete from the archived group (delete + archive share the same row menu).await archived.hover();- await archived.getByRole("button", { name: "删除对话" }).click();+ await archived.getByRole("button", { name: "对话选项" }).click();+ await page.getByRole("button", { name: "删除对话" }).click();await page.getByRole("button", { name: "删除", exact: true }).click();await expect(sidebar.getByText("新对话")).toHaveCount(0);diff --git a/packages/web/e2e/draft.spec.mjs b/packages/web/e2e/draft.spec.mjsindex 8cd190bd..9f07c28a 100644--- a/packages/web/e2e/draft.spec.mjs+++ b/packages/web/e2e/draft.spec.mjs@@ -284,7 +284,9 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses).toBe("0");- // —— Switch the sidebar to agent mode via the section-header toggle (persists in localStorage) ——+ // —— Switch the sidebar to agent mode via the header's list-settings menu (persists in+ // localStorage; the grouping radios moved from the inline toggle into this menu) ——+ await page.getByRole("button", { name: "列表选项" }).click();await page.getByRole("button", { name: "按 Agent 分组" }).click();await expect.poll(() => page.evaluate(() => localStorage.getItem("penguin.sidebarGroupMode")))diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex cf1000b6..87535627 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -1,14 +1,19 @@/*** Single-column sidebar, top to bottom:- * Project switcher -> new chat (default_agent draft) + fixed nav (Agents / models / cost center /- * Trace) -> Session area with two grouping modes (a small toggle in the section header; the+ * Project switcher -> new chat (default_agent draft) + 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 two grouping modes (a small toggle in the section header; the* choice and each Project's group collapse and pin state persist in localStorage): by Workspace* (the default; groups loaded Sessions by their* Workspace path, temporary workspaces merged into one trailing group, header "+" starts a* 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 -> bottom user config (theme / language / logout).+ * order. Conversations can be pinned too (row ellipsis 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).* 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@@ -16,7 +21,7 @@* Color scheme is white/gray-based: active state uses a solid gray fill, running status uses a small color dot, no large blocks of color.*/import { useEffect, useMemo, useRef, useState } from "react";-import type { ReactNode } from "react";+import type { DragEvent as ReactDragEvent, ReactNode } from "react";import { NavLink, useMatch, useNavigate } from "react-router";import type {SessionCategory,@@ -25,7 +30,7 @@ import type {} from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";-import { formatMonthDay } from "../../lib/format";+import { formatMonthDay, formatRelativeShort } from "../../lib/format";import { apiErrorText } from "../../lib/api-error";import { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";@@ -40,25 +45,58 @@ import {SIDEBAR_PAGE_SIZE,aggregateWorkspaceCounts,groupSessionsByWorkspace,+ matchesSessionQuery,partitionSessions,pinnedFirst,sessionCategory,workspaceGroupKey,+ workspaceLabel,} from "../../lib/session-grouping";import type { FolderCategory, SessionPartition } from "../../lib/session-grouping";+import {+ NAV_GROUP_KEYS,+ initialNavGroupCollapsed,+ storeNavGroupCollapsed,+} from "../../lib/nav-group-collapse";+import {+ loadPinnedSessions,+ removePinnedSession,+ savePinnedSessions,+ togglePinnedSession,+} from "../../lib/pinned-sessions";+import {+ loadWorkspaceRegistry,+ mergeRegisteredWorkspaces,+ registerWorkspace,+ saveWorkspaceRegistry,+ setWorkspaceAlias,+ unregisterWorkspace,+} from "../../lib/workspace-registry";+import type { WorkspaceEntry } from "../../lib/workspace-registry";+import {+ applyManualReorder,+ initialSessionSortMode,+ loadSessionOrder,+ moveInSequence,+ orderSessionRows,+ removeFromSessionOrder,+ saveSessionOrder,+ storeSessionSortMode,+} from "../../lib/session-order";+import type { SessionSortMode } from "../../lib/session-order";import { Switch } from "../ui/switch";import { Dropdown } from "../ui/dropdown";import { AgentAvatar } from "../ui/agent-avatar";-import { ChevronDown, GEAR_ICON, NAV_ICONS } from "../ui/icons";+import { CheckIcon, ChevronDown, GEAR_ICON, NAV_ICONS } from "../ui/icons";import {FOLDER_ICON,FOLDER_OPEN_ICON,FolderSection,GroupHeader,- GroupModeToggle,Icon,MoreRow,initialGroupMode,+ newEntityForGroupMode,storeGroupMode,} from "../ui/group-list";import type { GroupMode } from "../ui/group-list";@@ -68,10 +106,11 @@ import { Badge } from "../ui/badge";import { Modal } from "../ui/modal";import { ConfirmModal } from "../ui/confirm-modal";import { Button } from "../ui/button";-import { Input } from "../ui/input";+import { Input, noAutofill } from "../ui/input";import { Segmented } from "../ui/segmented";import { SkeletonList } from "../ui/skeleton";import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";+import { WorkspaceSelect } from "../../features/chat/workspace-select";import { clearDraft, sessionDraftKey } from "../../features/chat/draft-cache";import {draftSessionTitle,@@ -93,9 +132,103 @@ export const NEW_CHAT_ICON = "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Lconst 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). */+function EllipsisGlyph({ size = 16 }: { size?: number }) {+ return (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden>+ <circle cx="5" cy="12" r="2" />+ <circle cx="12" cy="12" r="2" />+ <circle cx="19" cy="12" r="2" />+ </svg>+ );+}++/** Magnifier (lucide search), the section header's search toggle. */+const SEARCH_ICON = "M21 21l-4.35-4.35M17 11a6 6 0 1 1-12 0 6 6 0 0 1 12 0z";++/** Horizontal sliders (lucide sliders-horizontal), the section header's list-settings menu. */+const SLIDERS_ICON = "M21 5h-7M10 5H3M21 12h-9M8 12H3M21 19h-5M12 19H3M14 2v6M8 9v6M16 16v6";++/** Close cross (the expanded search field's clear button). */+const CLOSE_ICON = "M18 6L6 18M6 6l12 12";++/**+ * Private drag payload type of a manual session reorder. Deliberately NOT `text/plain`:+ * the composer is a controlled textarea with no drop guard, and a native text drop+ * mutates its value and fires `input` — a mis-aimed reorder would paste a session id+ * into the user's message. Nothing outside these rows reads this type.+ */+const SESSION_DRAG_MIME = "application/x-penguin-session-id";++/** 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)";++/**+ * Mode-dependent create glyph: the entity's own icon (folder / robot) shrunk toward+ * the top-left, with a plus badge in the freed bottom-right corner — no knockout disc+ * needed (a background-colored punch would mismatch the hover pill), so it stays+ * legible at icon size in both themes. Stroke style matches the shared Icon set.+ */+function AddBadgeIcon({ base, size = 15 }: { base: string; size?: number }) {+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.7"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ >+ <g transform="translate(-1 -1) scale(0.82)">+ <path d={base} />+ </g>+ <path d="M18.5 15.5v6M15.5 18.5h6" strokeWidth="2" />+ </svg>+ );+}+const menuItemClass ="block w-full px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800";+/** Section-header icon control (search / list settings / create): the grouping-toggle button look — active renders as a pressed fill. */+const headerControlClass = (active: boolean) =>+ `flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors duration-150 ${+ active+ ? "bg-gray-200/70 text-gray-700 dark:bg-gray-800 dark:text-gray-200"+ : "text-gray-400 hover:bg-gray-200/50 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800/70 dark:hover:text-gray-300"+ }`;++/** Muted section label inside the list-settings menu (分组方式 / 排序方式), at the overflow menus' density. */+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@@ -250,6 +383,8 @@ export function Sidebar({const currentProjectId = currentProject?.projectId ?? null;const collapseStoreKey = currentProjectId === null ? null : collapsedGroupsKey(currentProjectId);const pinStoreKey = currentProjectId === null ? null : pinnedGroupsKey(currentProjectId);+ /** Collapsed page-nav group (the 智能体 → 评估中心 entries; expanded by default, the choice persists across sessions). */+ const [navCollapsed, setNavCollapsed] = useState(initialNavGroupCollapsed);/** 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. */@@ -260,12 +395,60 @@ export function Sidebar({const [pinnedGroups, setPinnedGroups] = useState<ReadonlySet<string>>(() =>loadGroupSet(pinStoreKey),);+ /** Pinned conversations (bubbled to the top of their group's active list), Session ids; persisted per Project frontend-side (lib/pinned-sessions.ts). */+ const [pinnedSessions, setPinnedSessions] = useState<ReadonlySet<string>>(() =>+ loadPinnedSessions(currentProjectId),+ );+ /** Row sort mode ("recent" default / "manual" drag order; the choice persists across sessions like the grouping mode). */+ const [sortMode, setSortModeState] = useState<SessionSortMode>(initialSessionSortMode);+ /** Manual row order (Session ids; only relative order within a co-rendered partition matters); persisted per Project AND grouping mode — the modes cut different partitions. */+ const [sessionOrder, setSessionOrder] = useState<readonly string[]>(() =>+ loadSessionOrder(currentProjectId, initialGroupMode()),+ );+ /** Manually-added Workspaces (header 新建工作区; render as empty groups until Sessions exist, with optional display aliases); persisted per Project. */+ const [registeredWorkspaces, setRegisteredWorkspaces] = useState<readonly WorkspaceEntry[]>(() =>+ loadWorkspaceRegistry(currentProjectId),+ );+ /** Registered Workspace being renamed (alias edit; null = none) and the alias being typed. */+ const [renamingWorkspace, setRenamingWorkspace] = useState<{ path: string } | null>(null);+ const [workspaceAliasText, setWorkspaceAliasText] = useState("");+ /** Registered Workspace pending removal confirmation (null = none); label = the group's displayed name for the confirm copy. */+ const [deletingWorkspace, setDeletingWorkspace] = useState<{+ path: string;+ label: string;+ } | null>(null);+ /** Live title search: the input's visibility and its query (transient — never persisted). */+ const [searchOpen, setSearchOpen] = useState(false);+ const [searchQuery, setSearchQuery] = useState("");+ /** Header list-settings dropdown (grouping + sort radios). */+ const [listSettingsOpen, setListSettingsOpen] = useState(false);+ /**+ * Whether a pointer that can drag is present (the outline rail's HOVER_QUERY idiom).+ * HTML5 drag-and-drop never fires from touch, and the sort mode is one GLOBAL+ * preference: offering 手动排序 in the mobile drawer would freeze that list in an+ * order the phone has no gesture to change — and flip the desktop too. The option is+ * hidden there; an already-stored "manual" degrades to recency on such a device.+ */+ const [canDrag, setCanDrag] = useState(() => window.matchMedia(DRAG_POINTER_QUERY).matches);+ useEffect(() => {+ const mq = window.matchMedia(DRAG_POINTER_QUERY);+ const onChange = (e: MediaQueryListEvent) => setCanDrag(e.matches);+ mq.addEventListener("change", onChange);+ return () => mq.removeEventListener("change", onChange);+ }, []);+ /** Row being dragged (manual sort only) and the current drop hint (target row + which edge). */+ const [dragSession, setDragSession] = useState<{ scope: string; id: string } | null>(null);+ const [dropHint, setDropHint] = useState<{ id: string; after: boolean } | null>(null);// Project resolved on first load / switched: swap in that Project's persisted collapse/pin sets.useEffect(() => {setCollapsedGroups(loadGroupSet(collapseStoreKey));setPinnedGroups(loadGroupSet(pinStoreKey));+ setPinnedSessions(loadPinnedSessions(currentProjectId));+ setSessionOrder(loadSessionOrder(currentProjectId, groupMode));+ setRegisteredWorkspaces(loadWorkspaceRegistry(currentProjectId));setGroupCap(SIDEBAR_GROUP_PAGE_SIZE);- }, [collapseStoreKey, pinStoreKey]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [collapseStoreKey, pinStoreKey, currentProjectId]);/** Expanded folders (subagent / scheduled / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set());/** "More" rows with a fetch in flight, keyed `${category}\0${groupKey}` — the row disables and reads "loading" so a page that lands entirely in other groups still visibly did something. */@@ -290,12 +473,25 @@ export function Sidebar({const setGroupMode = (mode: GroupMode) => {storeGroupMode(mode);setGroupModeState(mode);- // The two modes have unrelated group lists: restart the reveal window.+ // The two modes have unrelated group lists: restart the reveal window, and swap in+ // this mode's own manual order (the stored sequence is read within partitions, whose+ // boundaries are exactly what the mode decides — one shared array would scramble).+ setSessionOrder(loadSessionOrder(currentProjectId, mode));setGroupCap(SIDEBAR_GROUP_PAGE_SIZE);};- /** Workspace groups (workspace mode): computed from the flat list, temp directories merged last. */- const workspaceGroups = useMemo(() => groupSessionsByWorkspace(sessions), [sessions]);+ /** Collapse/expand the page-nav group (same store-then-set convention as setGroupMode). */+ const toggleNavGroup = () => {+ const next = !navCollapsed;+ storeNavGroupCollapsed(next);+ setNavCollapsed(next);+ };++ /** Workspace groups (workspace mode): computed from the flat list, temp directories merged last, plus the manually-added Workspaces as empty groups on top (newest registration first). */+ const workspaceGroups = useMemo(+ () => mergeRegisteredWorkspaces(groupSessionsByWorkspace(sessions), registeredWorkspaces),+ [sessions, registeredWorkspaces],+ );/** Workspace-mode per-group exact server totals (folded from the per-Agent per-Workspace counts). */const workspaceGroupCounts = useMemo(@@ -319,6 +515,10 @@ export function Sidebar({groupMode === "agent" ? s.agentId : workspaceGroupKey(s.workspace);const toggleGroup = (key: string) => {+ // Inert while searching: groups render force-opened then, so a click would change+ // nothing on screen while silently rewriting the persisted collapse state — the user+ // would find groups flipped once the query clears.+ if (searching) return;// Computed outside the state updater (theme.tsx convention): the persistence write is a// side effect, and updaters must stay pure (double-invoked in StrictMode).const next = new Set(collapsedGroups);@@ -337,6 +537,65 @@ export function Sidebar({saveGroupSet(pinStoreKey, next);};+ /** Pin / unpin one conversation (row menu; same toggle-and-persist convention). */+ const toggleSessionPin = (sessionId: string) => {+ const next = togglePinnedSession(pinnedSessions, sessionId);+ setPinnedSessions(next);+ savePinnedSessions(currentProjectId, next);+ };++ /** Switch the row sort mode (store-then-set convention). Leaving manual KEEPS the stored order — toggling back restores it. */+ const setSortMode = (mode: SessionSortMode) => {+ storeSessionSortMode(mode);+ setSortModeState(mode);+ };++ /** Search active = a non-blank query is live-filtering the list. */+ const searching = searchQuery.trim() !== "";++ /** The sort actually applied: a stored "manual" needs a drag-capable pointer to mean anything (see canDrag). */+ const effectiveSortMode: SessionSortMode = sortMode === "manual" && canDrag ? "manual" : "recent";++ /** Title filter of one group's loaded rows (search only sees loaded pages — there is no server-side search). */+ const filterRows = (rows: SessionInfo[]) =>+ searching ? rows.filter((s) => matchesSessionQuery(s, searchQuery)) : rows;++ /** Close the search row and drop the filter (the toggle button, the clear ×, and Escape all land here). */+ const closeSearch = () => {+ setSearchOpen(false);+ setSearchQuery("");+ };++ /**+ * Drop of a manual drag: commit the reordered partition sequence into the stored+ * order (the sequence moves to the array's front; only relative order within a+ * co-rendered partition is ever read, so other groups' ids are unaffected).+ */+ const commitManualDrop = (partitionIds: readonly string[], targetId: string, after: boolean) => {+ if (!dragSession) return;+ const seq = moveInSequence(partitionIds, dragSession.id, targetId, after);+ // Identity guard: a drop that changes nothing (self-drop, or landing where the row+ // already sat) must not rewrite and persist a fresh array.+ if (seq === partitionIds) return;+ const next = applyManualReorder(sessionOrder, seq);+ setSessionOrder(next);+ saveSessionOrder(currentProjectId, groupMode, next);+ };++ /** Parked drafts through the live search (matched on their first-line title). */+ const shownDrafts = searching+ ? draftEntries.filter((e) =>+ draftSessionTitle(e).toLowerCase().includes(searchQuery.trim().toLowerCase()),+ )+ : draftEntries;++ /** Whether the active search hits anything anywhere (drafts included) — drives the quiet no-match line. */+ const hasSearchMatches =+ shownDrafts.length > 0 ||+ (groupMode === "agent"+ ? orderedAgents.some((a) => filterRows(byAgent.get(a.agentId) ?? []).length > 0)+ : orderedWorkspaceGroups.some((g) => filterRows(g.sessions).length > 0));+/** In-flight key of one group's category "More" (folderKey shares the same composite for folder categories). */const loadKey = (groupKey: string, category: SessionCategory) => `${category}\0${groupKey}`;@@ -360,6 +619,9 @@ export function Sidebar({* folder's own "More" row does the paging from there).*/const toggleFolder = (groupKey: string, category: FolderCategory, agentIds: string[]) => {+ // Inert while searching (same reason as toggleGroup): folders render force-opened,+ // so a click would only fire a pointless category fetch and desync the open state.+ if (searching) return;const key = folderKey(groupKey, category);const opening = !openFolders.has(key);setOpenFolders((prev) => {@@ -440,6 +702,18 @@ export function Sidebar({remove(target.sessionId);// The session is gone, so clear its input draft too (no orphaned keys left in localStorage; keys are scoped per user, #68).if (user) clearDraft(sessionDraftKey(user.userId, target.sessionId));+ // Prune its pin and manual-order entry as well (both helpers return the same+ // reference when the id wasn't present — the write is skipped then).+ const prunedPins = removePinnedSession(pinnedSessions, target.sessionId);+ if (prunedPins !== pinnedSessions) {+ setPinnedSessions(prunedPins);+ savePinnedSessions(currentProjectId, prunedPins);+ }+ const prunedOrder = removeFromSessionOrder(sessionOrder, target.sessionId);+ if (prunedOrder !== sessionOrder) {+ setSessionOrder(prunedOrder);+ saveSessionOrder(currentProjectId, groupMode, prunedOrder);+ }setDeletingSession(null);// The deleted session was the one open: jump to this Agent's next conversation, otherwise// fall back to the chat home page. Auto-opened conversations are never archived (hidden by@@ -506,6 +780,63 @@ export function Sidebar({/** A Session always needs an Agent, so the workspace-mode "+" uses the current Agent, falling back to default_agent. */const workspaceNewChatAgentId = currentAgent?.agentId ?? defaultAgentId;+ /** Header create-button tooltip (the created object follows the grouping mode). */+ const newEntityLabel =+ newEntityForGroupMode(groupMode) === "agent" ? S.agent.create : S.chat.newWorkspaceEntity;++ /** Persist-if-changed for every registry mutation (register / alias / unregister share the same-reference fast exit). */+ const applyRegistryChange = (next: readonly WorkspaceEntry[]) => {+ if (next === registeredWorkspaces) return;+ setRegisteredWorkspaces(next);+ saveWorkspaceRegistry(currentProjectId, next);+ };++ /**+ * 新建工作区: register the browsed pick so it surfaces as a group immediately, Sessions+ * or not. Empty registered groups sort after the session-backed ones, so widen the+ * group display cap to cover the whole list — otherwise, past ten groups, the freshly+ * added Workspace would land behind 更多分组 and the click would look like a no-op.+ */+ const addWorkspace = (path: string) => {+ const next = registerWorkspace(registeredWorkspaces, path);+ if (next === registeredWorkspaces) return;+ applyRegistryChange(next);+ setGroupCap((c) => Math.max(c, workspaceGroups.length + 1));+ };++ /** Paths with a registry entry — only their groups offer the rename/remove overflow. */+ const registeredPaths = useMemo(+ () => new Set(registeredWorkspaces.map((e) => e.path)),+ [registeredWorkspaces],+ );++ /** Open the alias editor pre-filled with the current alias ("" = following the basename). */+ const openRenameWorkspace = (path: string) => {+ setWorkspaceAliasText(registeredWorkspaces.find((e) => e.path === path)?.alias ?? "");+ setRenamingWorkspace({ path });+ };++ /** Commit the alias (blank reverts the label to the directory basename). Direct save — no server, nothing destructive. */+ const confirmRenameWorkspace = () => {+ if (!renamingWorkspace) return;+ applyRegistryChange(+ setWorkspaceAlias(registeredWorkspaces, renamingWorkspace.path, workspaceAliasText),+ );+ setRenamingWorkspace(null);+ };++ /**+ * 删除工作区 (confirmed via the shared ConfirmModal, like every destructive-looking+ * action): drops the sidebar registry entry only — disk and Sessions are never+ * touched, the confirm copy says exactly that, and re-adding restores it. A group+ * that still has Sessions simply persists as session-derived.+ */+ const confirmDeleteWorkspace = () => {+ if (!deletingWorkspace) return;+ applyRegistryChange(unregisterWorkspace(registeredWorkspaces, deletingWorkspace.path));+ setDeletingWorkspace(null);+ };+const openSession = (s: SessionInfo) => {// Cross-group click: the current Agent follows this Session's own Agent.setCurrentAgentId(s.agentId);@@ -519,24 +850,111 @@ export function Sidebar({);/** Session rows shared by both modes; withAgentHint adds a small Agent avatar per row (workspace mode, where the group no longer names the Agent). */- const renderRows = (rows: SessionInfo[], withAgentHint: boolean) => (+ const renderRows = (+ rows: SessionInfo[],+ withAgentHint: boolean,+ /** Manual sort only: the drag scope (group key) plus the group's FULL ordered active list — the drop must commit every loaded row of the partition, not the display-capped slice the user happens to see. */+ dragCtx?: { scope: string; fullRows: SessionInfo[] },+ /** Whether these rows are the group's ACTIVE list (the only rows pinning can reorder). */+ activeList = false,+ ) => (<ul className="space-y-0.5">- {rows.map((s) => (- <SessionRow- key={s.sessionId}- s={s}- active={s.sessionId === activeSessionId}- {...(withAgentHint ? { agentHint: agentNameById.get(s.agentId) ?? s.agentId } : {})}- onOpen={openSession}- onRename={(x) => {- setRenameError(null);- setRenameText(x.title ?? "");- setRenamingSession(x);- }}- onDelete={(x) => setDeletingSession(x)}- onToggleArchive={(x) => void toggleArchive(x)}- />- ))}+ {rows.map((s) => {+ // Manual-sort drag wiring (active lists only; never while searching — a filtered+ // view is not the real order). A drop stays within its own scope AND its own+ // pin partition: dragging can reorder but never pin or unpin.+ const dragging =+ dragCtx !== undefined && dragSession?.scope === dragCtx.scope ? dragSession : null;+ const samePartition =+ dragging !== null &&+ dragging.id !== s.sessionId &&+ pinnedSessions.has(dragging.id) === pinnedSessions.has(s.sessionId);+ const drag =+ dragCtx === undefined+ ? {}+ : {+ draggable: true,+ onDragStart: (e: ReactDragEvent) => {+ // Firefox refuses to start a drag without payload data — but the id must+ // NOT ride on text/plain: the composer is a controlled textarea with no+ // drop guard, so a mis-aimed reorder would paste a session id straight+ // into the user's message. A private type is invisible to text drops.+ e.dataTransfer.setData(SESSION_DRAG_MIME, s.sessionId);+ e.dataTransfer.effectAllowed = "move" as const;+ setDragSession({ scope: dragCtx.scope, id: s.sessionId });+ },+ onDragEnd: () => {+ setDragSession(null);+ setDropHint(null);+ },+ onDragOver: (e: ReactDragEvent) => {+ if (!dragging || !samePartition) return;+ e.preventDefault();+ const rect = e.currentTarget.getBoundingClientRect();+ const after = e.clientY - rect.top > rect.height / 2;+ setDropHint((prev) =>+ prev?.id === s.sessionId && prev.after === after+ ? prev+ : { id: s.sessionId, after },+ );+ },+ onDragLeave: () => setDropHint((prev) => (prev?.id === s.sessionId ? null : prev)),+ onDrop: (e: ReactDragEvent) => {+ if (!dragging || !samePartition) return;+ e.preventDefault();+ const rect = e.currentTarget.getBoundingClientRect();+ const after = e.clientY - rect.top > rect.height / 2;+ // The FULL partition (every loaded row of this group on the dragged+ // row's side of the pin boundary), not the visible slice: committing+ // only the capped rows would drop the hidden ones out of the stored+ // sequence, and they would come back as "newcomers" at the top.+ const partitionIds = dragCtx.fullRows+ .filter(+ (r) => pinnedSessions.has(r.sessionId) === pinnedSessions.has(dragging.id),+ )+ .map((r) => r.sessionId);+ commitManualDrop(partitionIds, s.sessionId, after);+ setDragSession(null);+ setDropHint(null);+ },+ dropEdge:+ samePartition && dropHint?.id === s.sessionId+ ? dropHint.after+ ? ("below" as const)+ : ("above" as const)+ : null,+ };+ return (+ <SessionRow+ key={s.sessionId}+ s={s}+ active={s.sessionId === activeSessionId}+ pinned={pinnedSessions.has(s.sessionId)}+ // Pinning is an ACTIVE-list priority: folder rows (subagent / scheduled /+ // archived) are ordered chronologically inside their folder and never pass+ // through orderSessionRows, so a pin there would write an id, light the+ // glyph, move nothing — and then shift the active list's drag partition.+ canPin={activeList}+ // Last ACTIVITY, not creation: the server stamps lastActiveAt when a run+ // starts and again when it ends, so a running row shows its run-start time+ // (it recedes while the run continues — the pulsing status dot beside it is+ // what says "active right now"). CLI-adopted and subagent rows are not+ // driven by this server, so theirs stays at createdAt.+ lastActive={formatRelativeShort(s.lastActiveAt, locale)}+ {...(withAgentHint ? { agentHint: agentNameById.get(s.agentId) ?? s.agentId } : {})}+ {...drag}+ onOpen={openSession}+ onTogglePin={(x) => toggleSessionPin(x.sessionId)}+ onRename={(x) => {+ setRenameError(null);+ setRenameText(x.title ?? "");+ setRenamingSession(x);+ }}+ onDelete={(x) => setDeletingSession(x)}+ onToggleArchive={(x) => void toggleArchive(x)}+ />+ );+ })}</ul>);@@ -563,17 +981,24 @@ export function Sidebar({totals: SessionCategoryCounts | undefined,) => {const rows = parts[category];+ // While searching the folder speaks for its loaded MATCHES only: a match hidden+ // behind a collapsed folder would look like a missing result (the models page's+ // search-forces-open rationale), so the folder is forced open, labelled by the+ // match count, hidden when nothing matches, and never offers "More" (the server+ // cannot search unloaded rows).+ if (searching && rows.length === 0) return null;// Loaded rows win a disagreement with the totals (counts refresh only on reload).- const total = Math.max(totals?.[category] ?? 0, rows.length);+ const total = searching ? rows.length : Math.max(totals?.[category] ?? 0, rows.length);if (total === 0) return null;// More while the group's share isn't fully loaded AND somewhere is left to fetch from// (counts drifting above reality would otherwise leave a dead button until reload).- const more = rows.length < total && agentIds.some((id) => hasMoreFor(id, category));+ const more =+ !searching && rows.length < total && agentIds.some((id) => hasMoreFor(id, category));return (<FolderSectionkey={category}label={S.chat.folderGroups[category](total)}- open={openFolders.has(folderKey(groupKey, category))}+ open={searching || openFolders.has(folderKey(groupKey, category))}onToggle={() => toggleFolder(groupKey, category, agentIds)}more={more}pending={pendingLoads.has(loadKey(groupKey, category))}@@ -609,14 +1034,35 @@ export function Sidebar({agentsFor: (category: SessionCategory) => string[],) => {const cap = groupCaps.get(groupKey) ?? SIDEBAR_PAGE_SIZE;- const shownActive = parts.active.slice(0, cap);+ // Row order: the pinned cluster first, then — under manual sort — the stored order+ // within each pin partition (lib/session-order.ts). Both reorder only rows already+ // FETCHED: a pinned conversation that lives past the loaded pages does not surface+ // until "More" pulls its page in (the list has no server-side pin), so the pinned+ // cluster leads what is loaded, not the Agent's whole history. Folder rows keep+ // their chronological order: pinning and manual order are active-list concerns.+ // While searching, the display cap is bypassed — every loaded match shows, and+ // "More" hides (it pages the unfiltered list and would read as "more matches",+ // which the server cannot promise).+ const orderedActive = orderSessionRows(parts.active, (s) => s.sessionId, {+ pinned: pinnedSessions,+ sortMode: effectiveSortMode,+ order: sessionOrder,+ recencyOf: (s) => s.lastActiveAt,+ });+ const shownActive = searching ? orderedActive : orderedActive.slice(0, cap);+ /** Manual sort only (never on a search-filtered view): drag scope + the group's full ordered list, so a drop commits the whole partition. */+ const dragCtx =+ effectiveSortMode === "manual" && !searching+ ? { scope: groupKey, fullRows: orderedActive }+ : undefined;// Only the outer active rows drive the group's "More" — the folders never feed it:// hidden loaded rows exist, or the group's own active share isn't fully loaded yet.const activeAgents = agentsFor("active");const activeTotal = Math.max(totals?.active ?? 0, parts.active.length);const hasMore =- parts.active.length > cap ||- (parts.active.length < activeTotal && activeAgents.some((id) => hasMoreFor(id, "active")));+ !searching &&+ (parts.active.length > cap ||+ (parts.active.length < activeTotal && activeAgents.some((id) => hasMoreFor(id, "active"))));const folders = FOLDER_CATEGORIES.map((category) =>renderFolder(groupKey, category, parts, withAgentHint, agentsFor(category), totals),);@@ -629,7 +1075,9 @@ export function Sidebar({{S.chat.noSessions}</p>) : (- renderRows(shownActive, withAgentHint)+ // Drag-reorder is offered on the active list under manual sort (folders keep+ // chronological order), and never on a search-filtered view.+ renderRows(shownActive, withAgentHint, dragCtx, true))}{/* Load/reveal more (kept adjacent to the active list it extends, above the folders) */}@@ -659,14 +1107,10 @@ export function Sidebar({/>);- const navItems: Array<{ to: string; label: string; icon: string }> = [- { to: "/agents", label: S.nav.agents, icon: NAV_ICONS.agents },- { to: "/skills", label: S.nav.skills, icon: NAV_ICONS.skills },- { to: "/models", label: S.nav.models, icon: NAV_ICONS.models },- { to: "/usage", label: S.nav.usage, icon: NAV_ICONS.usage },- { to: "/traces", label: S.nav.traces, icon: NAV_ICONS.traces },- { to: "/benchmark", label: S.nav.benchmark, icon: NAV_ICONS.benchmark },- ];+ /** Page entries of the collapsible nav group (智能体 → 评估中心, driven by the NAV_GROUP_KEYS manifest). Always mounted — the collapse animates their height to zero and turns them inert. */+ const navItems: Array<{ to: string; label: string; icon: string }> = NAV_GROUP_KEYS.map(+ (key) => ({ to: `/${key}`, label: S.nav[key], icon: NAV_ICONS[key] }),+ );const themeOptions: ReadonlyArray<{ value: ThemeMode; label: string }> = [{ value: "light", label: S.settings.themeLight },@@ -804,45 +1248,251 @@ export function Sidebar({folder made the whole page scroll (composer pushed up, blank space below). */}<div className="relative min-h-0 flex-1 overflow-y-auto px-2 pb-2"><nav className="space-y-0.5">- {navItems.map((item) => (- <NavLink- key={item.to}- to={item.to}- onClick={() => onNavigate?.()}- className={({ isActive }) =>- `flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${- isActive- ? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"- }`- }- >- <span className="text-gray-500 dark:text-gray-400">- <Icon d={item.icon} />- </span>- {item.label}- </NavLink>- ))}+ {/* Expand/collapse SLIDE: grid-template-rows tweens between 0fr and 1fr with the+ inner overflow-hidden clipping the rows (the skills/models-page convention) —+ the moving clip edge reveals/hides the entries while the toggle button and the+ Session list below glide up/down with it; a subtle opacity fade rides along,+ both 200ms, moving as one with the chevron flip below. The rows stay mounted+ for the tween but go inert while collapsed (zero-height rows must not stay+ Tab-focusable or clickable). Transitions fire only on state CHANGES, so a mount+ restoring a persisted collapsed state renders collapsed instantly — only user+ toggles animate; reduced motion is covered by the global+ prefers-reduced-motion override in styles.css. */}+ <div+ className={`grid transition-[grid-template-rows] duration-200 ease-out ${+ navCollapsed ? "grid-rows-[0fr]" : "grid-rows-[1fr]"+ }`}+ >+ <div className="overflow-hidden" inert={navCollapsed}>+ <div+ className={`space-y-0.5 transition-opacity duration-200 ${+ navCollapsed ? "opacity-0" : "opacity-100"+ }`}+ >+ {navItems.map((item) => (+ <NavLink+ key={item.to}+ to={item.to}+ onClick={() => onNavigate?.()}+ className={({ isActive }) =>+ `flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${+ isActive+ ? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"+ }`+ }+ >+ <span className="text-gray-500 dark:text-gray-400">+ <Icon d={item.icon} />+ </span>+ {item.label}+ </NavLink>+ ))}+ </div>+ </div>+ </div>+ {/* Collapse toggle of the page-nav group (智能体 → 评估中心): a slim (h-4)+ nav-row-wide button directly under the group's last entry — a centered chevron+ pointing UP while expanded (click to collapse) and DOWN while collapsed (the+ button stays as the only way back, right under the new-chat boundary once the+ entries are hidden). The soft resting band is deliberate — the sidebar's one+ exception to flat-at-rest: it makes the strip read as the seam between the+ page nav above and the Session list below (the ruled separator it replaces+ was rejected as a line under the button); hover deepens it a step further so+ it stays clearly interactive. Icon-only, so tooltip + aria carry the name+ (GroupHeader's collapse/expand wording). */}+ <button+ type="button"+ onClick={toggleNavGroup}+ aria-expanded={!navCollapsed}+ aria-label={navCollapsed ? S.nav.expandGroup : S.nav.collapseGroup}+ title={navCollapsed ? S.nav.expandGroup : S.nav.collapseGroup}+ className="flex h-4 w-full items-center justify-center rounded-md bg-gray-200/70 text-gray-400 transition-colors duration-150 hover:bg-gray-300/60 hover:text-gray-700 dark:bg-gray-800/70 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-300"+ >+ <ChevronDown+ size={12}+ className={`transition-transform duration-200 ${navCollapsed ? "" : "rotate-180"}`}+ />+ </button></nav>- {/* Section header: list label + grouping-mode toggle (the choice persists in localStorage).- The separator above it spans the sidebar's full width (-mx-2 undoes the scroller's- padding, px-3 puts the row's own inset back), as it did when it sat on the scroller's- top edge — it now travels with the list instead of framing a pinned nav. */}- <div className="-mx-2 mt-3 flex items-center justify-between border-t border-gray-200 px-3 pt-2 dark:border-gray-800">- <span className="px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">+ {/* Section header: list label + right-aligned controls (icon + tooltip family):+ search, list settings (grouping + sort radios — the old inline grouping+ toggle relocated into this menu), and the mode-dependent create button (the+ created object follows the grouping mode). The search is a mac-style+ IN-PLACE expansion — no extra row: the two grid columns tween (the 0fr/1fr+ trick, horizontal), the label's column collapsing while the controls column+ takes the full width and the field inside grows leftward over the label's+ place; the magnifier morphs from toggle button into the field's leading+ glyph. No ruled separator at this boundary — see the nav toggle above. */}+ <div+ className={`mt-3 grid items-center px-1 pt-2 transition-[grid-template-columns] duration-200 ease-out ${+ searchOpen ? "grid-cols-[0fr_1fr]" : "grid-cols-[1fr_1fr]"+ }`}+ >+ <span+ className={`min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${+ searchOpen ? "opacity-0" : "opacity-100"+ }`}+ >{S.chat.sessionList}</span>- <GroupModeToggle value={groupMode} onChange={setGroupMode} />+ <div className="flex min-w-0 items-center justify-end gap-0.5">+ {searchOpen ? (+ /* Expanded field: leading magnifier glyph + input + clear ×, one bordered+ box filling the row (its width rides the column tween). Esc and × both+ collapse it and drop the filter. */+ <div className="flex h-6 min-w-0 flex-1 items-center gap-1 rounded-md border border-gray-300 bg-white px-1.5 transition-colors duration-150 focus-within:border-gray-400 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-500">+ <span aria-hidden className="shrink-0 text-gray-400 dark:text-gray-500">+ <Icon d={SEARCH_ICON} size={12} />+ </span>+ <input+ autoFocus+ value={searchQuery}+ placeholder={S.chat.searchSessionsPlaceholder}+ aria-label={S.chat.searchSessions}+ {...noAutofill}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ closeSearch();+ }+ }}+ className="min-w-0 flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"+ />+ <button+ type="button"+ title={S.chat.searchClear}+ aria-label={S.chat.searchClear}+ onClick={closeSearch}+ className="flex h-4 w-4 shrink-0 items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-300"+ >+ <Icon d={CLOSE_ICON} size={11} />+ </button>+ </div>+ ) : (+ <button+ type="button"+ title={S.chat.searchSessions}+ aria-label={S.chat.searchSessions}+ onClick={() => setSearchOpen(true)}+ className={headerControlClass(false)}+ >+ <Icon d={SEARCH_ICON} size={14} />+ </button>+ )}+ <Dropdown+ open={listSettingsOpen}+ setOpen={setListSettingsOpen}+ portal={{ direction: "down", align: "right" }}+ menuClass="w-40"+ button={+ <button+ type="button"+ title={S.chat.listSettings}+ aria-label={S.chat.listSettings}+ aria-haspopup="menu"+ aria-expanded={listSettingsOpen}+ onClick={() => setListSettingsOpen(!listSettingsOpen)}+ className={headerControlClass(listSettingsOpen)}+ >+ <Icon d={SLIDERS_ICON} size={14} />+ </button>+ }+ >+ <p className={menuSectionClass}>{S.chat.groupModeSection}</p>+ <MenuRadioRow+ label={S.chat.groupByWorkspace}+ checked={groupMode === "workspace"}+ onSelect={() => {+ setGroupMode("workspace");+ setListSettingsOpen(false);+ }}+ />+ <MenuRadioRow+ label={S.chat.groupByAgent}+ checked={groupMode === "agent"}+ onSelect={() => {+ setGroupMode("agent");+ setListSettingsOpen(false);+ }}+ />+ <div className="my-1 border-t border-gray-100 dark:border-gray-800" />+ <p className={menuSectionClass}>{S.chat.sortModeSection}</p>+ {/* Manual order is offered only where a drag can actually happen (see canDrag). */}+ {canDrag && (+ <MenuRadioRow+ label={S.chat.sortManual}+ checked={sortMode === "manual"}+ onSelect={() => {+ setSortMode("manual");+ setListSettingsOpen(false);+ }}+ />+ )}+ <MenuRadioRow+ label={S.chat.sortRecent}+ checked={sortMode === "recent"}+ onSelect={() => {+ setSortMode("recent");+ setListSettingsOpen(false);+ }}+ />+ </Dropdown>+ {/* Mode-dependent create — 具体新建的对象按分组方式决定, the icon following+ suit (folder+ / robot+, a bottom-right plus badge on the entity's glyph):+ agent grouping opens the Agents page's existing create dialog (route+ state); workspace grouping opens the SAME directory-browse menu the+ draft's workspace picker uses — the picked directory registers as a+ workspace group immediately, Sessions or not. */}+ {newEntityForGroupMode(groupMode) === "agent" ? (+ <button+ type="button"+ title={newEntityLabel}+ aria-label={newEntityLabel}+ onClick={() => {+ navigate("/agents", { state: { create: true } });+ onNavigate?.();+ }}+ className={headerControlClass(false)}+ >+ <AddBadgeIcon base={NAV_ICONS.agents} />+ </button>+ ) : (+ <WorkspaceSelect+ // Remount per Project: the picker browses lazily and caches the listing+ // for its lifetime, so a long-lived instance would show the PREVIOUS+ // Project's directories after a switch — and register that path into the+ // new Project's registry.+ key={currentProjectId ?? "no-project"}+ projectId={currentProjectId ?? ""}+ workspace=""+ onChange={addWorkspace}+ trigger={(open, toggle) => (+ <button+ type="button"+ title={newEntityLabel}+ aria-label={newEntityLabel}+ aria-expanded={open}+ onClick={toggle}+ className={headerControlClass(open)}+ >+ <AddBadgeIcon base={FOLDER_ICON} />+ </button>+ )}+ />+ )}+ </div></div>{/* Parked draft conversations (unsent new chats, newest first): pinned above bothgrouping modes — they belong to no Agent or Workspace until sent. Hidden- entirely while there are none. */}- {draftEntries.length > 0 && (+ entirely while there are none; the search filter applies to their titles too. */}+ {shownDrafts.length > 0 && (<div className="pt-2.5"><GroupHeader- open={!collapsedGroups.has(DRAFTS_GROUP_KEY)}+ open={searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)}onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}icon={<span className="shrink-0 text-gray-400 dark:text-gray-500">@@ -851,11 +1501,11 @@ export function Sidebar({}label={S.chat.draftGroup}uppercase- count={draftEntries.length}+ count={shownDrafts.length}/>- {!collapsedGroups.has(DRAFTS_GROUP_KEY) && (+ {(searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)) && (<ul className="space-y-0.5">- {draftEntries.map((entry) => (+ {shownDrafts.map((entry) => (<DraftRowkey={entry.id}entry={entry}@@ -873,9 +1523,14 @@ export function Sidebar({loading && agents.length === 0 ? (<SkeletonList rows={5} />) : (- orderedAgents.slice(0, groupCap).map((agent) => {- const parts = partitionSessions(byAgent.get(agent.agentId) ?? []);- const collapsed = collapsedGroups.has(agent.agentId);+ // While searching: every group renders (cap bypassed), zero-match groups+ // hide, and the rest are forced open — a hit inside a collapsed group would+ // look like a missing result.+ orderedAgents.slice(0, searching ? orderedAgents.length : groupCap).map((agent) => {+ const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);+ if (searching && groupRows.length === 0) return null;+ const parts = partitionSessions(groupRows);+ const collapsed = !searching && collapsedGroups.has(agent.agentId);const pinned = pinnedGroups.has(agent.agentId);return (<div key={agent.agentId} className="pt-2.5">@@ -932,75 +1587,102 @@ export function Sidebar({}))) : null}- {groupMode === "agent" && orderedAgents.length > groupCap+ {groupMode === "agent" && !searching && orderedAgents.length > groupCap? moreGroupsRow(orderedAgents.length): null}{groupMode === "agent" ? null : loading && sessions.length === 0 ? (<SkeletonList rows={5} />- ) : orderedWorkspaceGroups.length === 0 ? (+ ) : orderedWorkspaceGroups.length === 0 && !searching ? (<p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">{S.chat.noSessions}</p>) : (- orderedWorkspaceGroups.slice(0, groupCap).map((group) => {- const parts = partitionSessions(group.sessions);- const collapsed = collapsedGroups.has(group.key);- const pinned = pinnedGroups.has(group.key);- /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */- const counts = workspaceGroupCounts.get(group.key);- const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];- const agentsFor = (category: SessionCategory) => [- ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),- ];- return (- <div key={group.key} className="pt-2.5">- {/* Group header: collapse toggle (folder icon + directory basename + count, full+ // Same search treatment as agent mode: cap bypassed, zero-match groups hidden, the rest forced open.+ orderedWorkspaceGroups+ .slice(0, searching ? orderedWorkspaceGroups.length : groupCap)+ .map((group) => {+ const groupRows = filterRows(group.sessions);+ if (searching && groupRows.length === 0) return null;+ const parts = partitionSessions(groupRows);+ const collapsed = !searching && collapsedGroups.has(group.key);+ const pinned = pinnedGroups.has(group.key);+ /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */+ const counts = workspaceGroupCounts.get(group.key);+ const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];+ const agentsFor = (category: SessionCategory) => [+ ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),+ ];+ return (+ <div key={group.key} className="pt-2.5">+ {/* Group header: collapse toggle (folder icon + directory basename + count, fullpath in the tooltip; the count = the group's active conversations only, exactserver share, loaded rows win a disagreement — the folders never feed it) +pin + new chat in this Workspace. */}- <GroupHeader- open={!collapsed}- onToggle={() => toggleGroup(group.key)}- icon={- /* Folder opens and closes with the group */- <span className="shrink-0 text-gray-400 dark:text-gray-500">- <Icon d={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON} size={15} />- </span>- }- label={group.temp ? S.chat.tempWorkspaces : group.label}- count={Math.max(counts?.totals.active ?? 0, parts.active.length)}- {...(group.fullPath !== null ? { title: group.fullPath } : {})}- actions={- <>- <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />- {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the current one, falling back to default_agent */}- <button- type="button"- title={S.chat.newSessionInWorkspace}- aria-label={S.chat.newSessionInWorkspace}- onClick={() => newChat(workspaceNewChatAgentId, group.fullPath ?? "")}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <Icon d="M12 5v14M5 12h14" size={18} />- </button>- </>- }- />+ <GroupHeader+ open={!collapsed}+ onToggle={() => toggleGroup(group.key)}+ icon={+ /* Folder opens and closes with the group */+ <span className="shrink-0 text-gray-400 dark:text-gray-500">+ <Icon d={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON} size={15} />+ </span>+ }+ label={group.temp ? S.chat.tempWorkspaces : group.label}+ count={+ searching+ ? parts.active.length+ : Math.max(counts?.totals.active ?? 0, parts.active.length)+ }+ {...(group.fullPath !== null ? { title: group.fullPath } : {})}+ actions={+ <>+ <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />+ {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the current one, falling back to default_agent */}+ <button+ type="button"+ title={S.chat.newSessionInWorkspace}+ aria-label={S.chat.newSessionInWorkspace}+ onClick={() => newChat(workspaceNewChatAgentId, group.fullPath ?? "")}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"+ >+ <Icon d="M12 5v14M5 12h14" size={18} />+ </button>+ {/* Manually-added (registry-backed) Workspaces only: rename-alias /+ remove-from-sidebar overflow, to the right of the "+" (session-+ derived groups have no registry entry for these to act on). */}+ {registeredPaths.has(group.key) && (+ <GroupOverflowMenu+ onRename={() => openRenameWorkspace(group.key)}+ onDelete={() =>+ setDeletingWorkspace({ path: group.key, label: group.label })+ }+ />+ )}+ </>+ }+ />- {/* A workspace group can span Agents: the group body fans folder loads and "More"+ {/* A workspace group can span Agents: the group body fans folder loads and "More"out per category to the Agents whose share of THIS group is non-zero (plus theAgents already contributing loaded rows) — the active list and each folderpage independently. */}- {collapsed- ? null- : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}- </div>- );- })+ {collapsed+ ? null+ : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}+ </div>+ );+ }))}- {groupMode === "workspace" && orderedWorkspaceGroups.length > groupCap+ {groupMode === "workspace" && !searching && orderedWorkspaceGroups.length > groupCap? moreGroupsRow(orderedWorkspaceGroups.length): null}++ {/* Quiet no-match line: the search is live and nothing — drafts included — hit. */}+ {searching && !hasSearchMatches && (+ <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">+ {S.chat.searchNoMatches}+ </p>+ )}</div>{/* Bottom user config */}@@ -1258,6 +1940,38 @@ export function Sidebar({/></Modal>+ {/* Rename workspace (alias edit, same Modal + Input idiom as rename chat): the alias+ replaces the directory basename as the group label; leaving it blank reverts to+ the basename — so an empty save is valid here, unlike the chat rename. */}+ <Modal+ open={renamingWorkspace !== null}+ title={S.chat.renameWorkspace}+ onClose={() => setRenamingWorkspace(null)}+ footer={+ <>+ <Button onClick={() => setRenamingWorkspace(null)}>{S.common.cancel}</Button>+ <Button variant="primary" onClick={confirmRenameWorkspace}>+ {S.common.save}+ </Button>+ </>+ }+ >+ <Input+ label={S.chat.renameWorkspaceLabel}+ hint={S.chat.renameWorkspaceHint}+ value={workspaceAliasText}+ placeholder={renamingWorkspace ? workspaceLabel(renamingWorkspace.path) : ""}+ autoFocus+ maxLength={80}+ onChange={(e) => setWorkspaceAliasText(e.target.value)}+ onKeyDown={(e) => {+ // isComposing guard (the repo's IME convention, cf. workspace-select.tsx):+ // accepting a Chinese candidate fires Enter, which would save the raw pinyin.+ if (e.key === "Enter" && !e.nativeEvent.isComposing) confirmRenameWorkspace();+ }}+ />+ </Modal>+{/* Delete chat confirmation (shared ConfirmModal) */}<ConfirmModalopen={deletingSession !== null}@@ -1274,6 +1988,21 @@ export function Sidebar({</p></ConfirmModal>+ {/* Remove-workspace confirmation (shared ConfirmModal, same stop as the other+ destructive-looking actions): the copy is honest about the scope — sidebar+ registry entry only, disk and Sessions untouched, re-addable anytime. */}+ <ConfirmModal+ open={deletingWorkspace !== null}+ title={S.chat.deleteWorkspace}+ confirmLabel={S.common.delete}+ onClose={() => setDeletingWorkspace(null)}+ onConfirm={confirmDeleteWorkspace}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {deletingWorkspace ? S.chat.deleteWorkspaceConfirm(deletingWorkspace.label) : ""}+ </p>+ </ConfirmModal>+{/* Delete parked-draft confirmation: purely local (localStorage entry), but the typedcontent is gone for good, which deserves the same explicit stop as a session. */}<ConfirmModal@@ -1378,31 +2107,86 @@ function GroupPinButton({ pinned, onToggle }: { pinned: boolean; onToggle: () =>);}-/** Single Session row: title + status dot/approval badge + hover action group (rename, archive/unarchive, delete). */+/**+ * 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.+ */function SessionRow({s,active,+ pinned,+ canPin = false,+ lastActive,agentHint,+ draggable = false,+ dropEdge = null,+ onDragStart,+ onDragEnd,+ onDragOver,+ onDragLeave,+ onDrop,onOpen,+ onTogglePin,onRename,onDelete,onToggleArchive,}: {s: SessionInfo;active: boolean;+ /** Row is pinned (bubbled to its group's top; small pin glyph on the title). */+ pinned: boolean;+ /** Whether pinning can actually reorder this row — active-list rows only; folder rows hide the action (see renderRows). */+ canPin?: boolean;+ /** Preformatted compact last-active time ("" hides the slot's resting text). */+ lastActive: string;/** Agent display name; when set (workspace mode) a small avatar keeps the Agent context visible on the row. */agentHint?: string;+ /** Manual sort: the row can be drag-reordered (the sidebar wires the handlers below). */+ draggable?: boolean;+ /** Drop indicator edge while another row hovers over this one (a thin accent line above/below). */+ dropEdge?: "above" | "below" | null;+ onDragStart?: (e: ReactDragEvent) => void;+ onDragEnd?: () => void;+ onDragOver?: (e: ReactDragEvent) => void;+ onDragLeave?: () => void;+ onDrop?: (e: ReactDragEvent) => void;onOpen: (s: SessionInfo) => void;+ onTogglePin: (s: SessionInfo) => void;onRename: (s: SessionInfo) => void;onDelete: (s: SessionInfo) => void;onToggleArchive: (s: SessionInfo) => void;}) {- const actionBtn =- "flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 focus-visible:opacity-100 group-hover:opacity-100";+ 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);+ };return (- <li>+ <li+ className="relative"+ {...(draggable+ ? { draggable: true, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }+ : {})}+ >+ {/* Manual-drag drop indicator: a thin accent line on the edge the drop would land on (both themes read it against the row gap). */}+ {dropEdge !== null && (+ <div+ aria-hidden+ className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${+ dropEdge === "above" ? "-top-px" : "-bottom-px"+ }`}+ />+ )}<divclassName={`group flex items-center rounded-md pr-1 transition-colors duration-150 ${+ draggable ? "cursor-grab " : ""+ }${active? "bg-gray-200/70 dark:bg-gray-800": "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"@@ -1431,6 +2215,16 @@ function SessionRow({: "text-gray-700 dark:text-gray-300"}`}/>+ {/* Pinned indicator: a dim pin after the title (tooltip + sr text; unpin lives in the row menu). */}+ {pinned && canPin && (+ <span+ title={S.chat.pinnedSession}+ className="shrink-0 text-gray-400 dark:text-gray-500"+ >+ <Icon d={PIN_ICON} size={12} />+ <span className="sr-only">{S.chat.pinnedSession}</span>+ </span>+ )}{/* No per-row source tag: subagent / scheduled Sessions live in their own labelled, collapsed folders, so a badge on the title would just repeat the folder. */}<StatusDot session={s} />{s.pendingApprovalCount > 0 && (@@ -1439,52 +2233,160 @@ function SessionRow({</span>)}</button>- {/* Action group: rename + archive/unarchive + delete */}- <div className="flex shrink-0 items-center">- <button- type="button"- title={S.chat.renameSession}- aria-label={S.chat.renameSession}- onClick={() => onRename(s)}- className={`${actionBtn} hover:bg-gray-300/60 hover:text-gray-700 dark:hover:bg-gray-700 dark:hover:text-gray-200`}- >- <Icon d="M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3" size={14} />+ {/* 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. */}+ <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>+ )}+ </>+ }+ >+ {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"- title={s.archived ? S.chat.unarchiveSession : S.chat.archiveSession}- aria-label={s.archived ? S.chat.unarchiveSession : S.chat.archiveSession}- onClick={() => onToggleArchive(s)}- className={`${actionBtn} hover:bg-gray-300/60 hover:text-gray-700 dark:hover:bg-gray-700 dark:hover:text-gray-200`}- >- <Icon- d={- s.archived- ? "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"- : "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"- }- size={14}- />+ <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"- title={S.chat.deleteSession}- aria-label={S.chat.deleteSession}- onClick={() => onDelete(s)}- className={`${actionBtn} hover:bg-gray-300/60 hover:text-red-600 dark:hover:bg-gray-700 dark:hover:text-red-400`}- >- {/* Trash can: lid (4..20), handle, body (5..19, symmetric sides), two vertical ribs */}- <Icon- d="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"- size={14}- />+ <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>- </div>+ </Dropdown></div></li>);}+/**+ * Registry-backed workspace group's overflow (… to the right of the header's "+"):+ * 重命名工作区 / 删除工作区 in the session-row menu's compact style. Sits among the+ * header's action buttons — outside the header's collapse toggle, so opening it never+ * expands/collapses the group. Body-portaled like every menu inside the scroller.+ */+function GroupOverflowMenu({ onRename, onDelete }: { onRename: () => void; onDelete: () => void }) {+ const [open, setOpen] = useState(false);+ /** Close first, then act (the rename modal opens on top; the delete is immediate). */+ const item = (fn: () => void) => () => {+ setOpen(false);+ fn();+ };+ return (+ <Dropdown+ open={open}+ setOpen={setOpen}+ portal={{ direction: "down", align: "right" }}+ menuClass="w-32"+ className="shrink-0"+ button={+ /* No hover pill on this trigger (user: color, not background, should carry the+ hover hint) — feedback is the glyph deepening in light / brightening in dark,+ the session-row ellipsis treatment. Geometry: the same h-7 w-7 square as the+ sibling "+" and the LAST action in the header, flush at GroupHeader's px-1+ inset — which equals the session rows' pr-1, so with the row trigger's 16px+ glyph the dot columns line up with the rows' trailing slot below. */+ <button+ type="button"+ title={S.chat.workspaceMenu}+ aria-label={S.chat.workspaceMenu}+ aria-haspopup="menu"+ aria-expanded={open}+ onClick={() => setOpen(!open)}+ className="flex h-7 w-7 shrink-0 items-center justify-center text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100"+ >+ <EllipsisGlyph size={16} />+ </button>+ }+ >+ <button type="button" className={overflowMenuRowClass} onClick={item(onRename)}>+ {overflowMenuGlyph(PENCIL_ICON)}+ {S.chat.renameWorkspace}+ </button>+ <button type="button" className={overflowMenuDangerClass} onClick={item(onDelete)}>+ <span className="shrink-0">+ <Icon d={TRASH_ICON} size={13} />+ </span>+ {S.chat.deleteWorkspace}+ </button>+ </Dropdown>+ );+}++/** 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 更多一样). */+function MenuRadioRow({+ label,+ checked,+ onSelect,+}: {+ label: string;+ checked: boolean;+ onSelect: () => void;+}) {+ return (+ <button+ type="button"+ aria-pressed={checked}+ onClick={onSelect}+ className={`${overflowMenuRowClass} justify-between`}+ >+ <span className="truncate">{label}</span>+ {checked && <CheckIcon className="shrink-0 text-gray-500 dark:text-gray-400" />}+ </button>+ );+}+function SettingRow({ label, children }: { label: string; children: ReactNode }) {return (<div>diff --git a/packages/web/src/components/ui/dropdown.tsx b/packages/web/src/components/ui/dropdown.tsxindex b39b66bb..1b6c5581 100644--- a/packages/web/src/components/ui/dropdown.tsx+++ b/packages/web/src/components/ui/dropdown.tsx@@ -17,10 +17,15 @@* own handler sees itself not on top and stays; the next Escape closes the dialog. The* event is deliberately NOT stopped, so element-level Escape handlers inside the panel* (e.g. an input reverting its draft) still run on the same press.+ *+ * Keyboard: opening moves focus to the panel's first focusable item, Up/Down walk the+ * 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.*/import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import { createPortal } from "react-dom";-import type { CSSProperties, ReactNode } from "react";+import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";import { isTopEscLayer, popEscLayer, pushEscLayer } from "./modal";/** Gap between the trigger and the portaled panel, and the panel's minimum distance from the viewport edge (px). */@@ -73,6 +78,55 @@ export function Dropdown({maxHeight: number;} | null>(null);+ /** The caller-rendered trigger's button element (focus target when Escape closes the menu). */+ const triggerButton = useCallback(+ () => ref.current?.querySelector<HTMLElement>("button") ?? null,+ [],+ );++ /** The panel's focusable items, in DOM order (menu rows, and any input/link a panel carries). */+ const panelItems = useCallback(+ () =>+ panelRef.current+ ? [+ ...panelRef.current.querySelectorAll<HTMLElement>(+ 'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',+ ),+ ]+ : [],+ [],+ );++ // Opening moves focus into the panel (first item), so the menu is operable from the+ // keyboard at all. Runs after the panel has mounted, portal or in-flow alike.+ useEffect(() => {+ if (!open) return;+ panelItems()[0]?.focus();+ }, [open, panelItems]);++ /**+ * Up/Down walk the panel's items, wrapping at both ends (the standard menu idiom) —+ * but only for plain menus. Two panels own their own keyboard model (model-select and+ * the slash/skill pickers drive a highlighted-index list from an autofocused search+ * box), so this yields whenever an inner handler already consumed the key, and+ * whenever focus sits in a text field where the arrows belong to the caret.+ */+ const onPanelKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;+ if (e.defaultPrevented) return;+ const focused = document.activeElement;+ const tag = focused?.tagName;+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;+ const items = panelItems();+ if (items.length === 0) return;+ e.preventDefault();+ const at = items.indexOf(document.activeElement as HTMLElement);+ const step = e.key === "ArrowDown" ? 1 : -1;+ const next =+ at < 0 ? (step === 1 ? 0 : items.length - 1) : (at + step + items.length) % items.length;+ items[next]?.focus();+ };+// Latest-callback refs: the open effect below must re-run ONLY on open/close — if it also// re-ran on a callback identity change, its esc-layer would pop and re-push, wrongly// jumping above any dialog opened in the meantime.@@ -89,10 +143,13 @@ export function Dropdown({if (panelRef.current?.contains(target)) return;setOpenRef.current(false);};- // Escape closes only when this menu is the topmost esc layer (see the header comment).+ // Escape closes only when this menu is the topmost esc layer (see the header comment)+ // and hands focus back to the trigger — a keyboard user must not be stranded on a+ // panel that just unmounted.const layer = pushEscLayer();const onKey = (e: KeyboardEvent) => {if (e.key !== "Escape" || !isTopEscLayer(layer)) return;+ triggerButton()?.focus();const esc = onEscapeRef.current;if (esc) esc();else setOpenRef.current(false);@@ -181,6 +238,7 @@ export function Dropdown({createPortal(<divref={panelRef}+ onKeyDown={onPanelKeyDown}style={{position: "fixed",// Before the first measurement the panel is rendered invisibly at the@@ -206,6 +264,7 @@ export function Dropdown({) : (<divref={panelRef}+ onKeyDown={onPanelKeyDown}{...(menuStyle !== undefined ? { style: menuStyle } : {})}className={`absolute ${panelClass}`}>diff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsxindex 7d4f1ad5..8adc4a39 100644--- a/packages/web/src/components/ui/group-list.tsx+++ b/packages/web/src/components/ui/group-list.tsx@@ -55,6 +55,17 @@ export function initialGroupMode(): GroupMode {return localStorage.getItem(GROUP_MODE_KEY) === "agent" ? "agent" : "workspace";}+/**+ * Entity the sidebar's "new" header button creates, decided by the grouping mode (the+ * created object follows what the list is grouped by): agent mode → an Agent (the+ * Agents page's existing create dialog), workspace mode → a Workspace (a new-chat+ * draft — there is no Workspace entity on the server; a Workspace comes into being+ * with the conversation created in it, chosen or auto-created on the draft card).+ */+export function newEntityForGroupMode(mode: GroupMode): "agent" | "workspace" {+ return mode === "agent" ? "agent" : "workspace";+}+export function storeGroupMode(mode: GroupMode): void {localStorage.setItem(GROUP_MODE_KEY, mode);}diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsxindex 683d86c8..c4a19474 100644--- a/packages/web/src/features/agents/agents-page.tsx+++ b/packages/web/src/features/agents/agents-page.tsx@@ -14,8 +14,8 @@* gray placeholder with an undeletable tooltip) are square icon buttons (tooltip shows the full* name); "Create Agent" only fills in name + description.*/-import { useState } from "react";-import { useNavigate } from "react-router";+import { useEffect, useState } from "react";+import { useLocation, useNavigate } from "react-router";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";@@ -100,6 +100,19 @@ export function AgentsPage() {setIdError(undefined);setCreateOpen(true);};++ // Cross-page create intent (the sidebar's mode-dependent "new" button navigates here+ // with { create: true } route state — the chat draft's route-state idiom): open the+ // existing create dialog once, then strip the state so a refresh or back-nav doesn't+ // reopen it.+ const location = useLocation();+ const createIntent = (location.state as { create?: boolean } | null)?.create === true;+ useEffect(() => {+ if (!createIntent) return;+ openCreate();+ navigate(location.pathname, { replace: true });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [createIntent]);/** Agent pending delete confirmation (null = none). */const [deleting, setDeleting] = useState<{ agentId: string; name: string } | null>(null);const [deleteError, setDeleteError] = useState<string | null>(null);diff --git a/packages/web/src/features/chat/workspace-select.tsx b/packages/web/src/features/chat/workspace-select.tsxindex 7b800fc4..45fa169e 100644--- a/packages/web/src/features/chat/workspace-select.tsx+++ b/packages/web/src/features/chat/workspace-select.tsx@@ -9,7 +9,7 @@* tier (z-[60]) clears the Modal overlay.*/import { useCallback, useEffect, useRef, useState } from "react";-import type { MouseEvent as ReactMouseEvent } from "react";+import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";import type { DirListResponse } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";@@ -39,12 +39,19 @@ export function WorkspaceSelect({workspace,onChange,variant = "pill",+ trigger,}: {projectId: string;workspace: string;onChange: (path: string) => void;/** Trigger style: the draft page's pill (default), or a dialog form control (see the header comment). */variant?: "pill" | "form";+ /**+ * Caller-rendered trigger (the sidebar's 新建工作区 header button): replaces the pill+ * and switches the panel to the shared body portal — the sidebar's scroller would+ * clip an in-flow panel. The same browse menu, byte for byte.+ */+ trigger?: (open: boolean, toggle: () => void) => ReactNode;}) {const [open, setOpen] = useState(false);/**@@ -263,7 +270,9 @@ export function WorkspaceSelect({strokeLinejoin="round"/></svg>- <span className="min-w-0 flex-1 truncate">{entry.name}</span>+ <span className="min-w-0 flex-1 truncate" title={entry.name}>+ {entry.name}+ </span></button></li>))}@@ -309,6 +318,24 @@ export function WorkspaceSelect({</div>);+ // Custom trigger (sidebar header): portaled panel, right-aligned under the trigger —+ // placement and flipping are the portal's job, so no dock measurement here. w-64+ // (the Dropdown default menu width): the pill/form variants' w-80 overhung the+ // sidebar; long entry names truncate with their full text in the row tooltip.+ if (trigger) {+ return (+ <Dropdown+ open={open}+ setOpen={setFormOpen}+ portal={{ direction: "down", align: "right" }}+ menuClass="w-64"+ button={trigger(open, () => setFormOpen(!open))}+ >+ {menu}+ </Dropdown>+ );+ }+// Form: the shared full-width trigger (its label goes mono once a real path is set).if (variant === "form") {return (diff --git a/packages/web/src/lib/format.ts b/packages/web/src/lib/format.tsindex 06d77e2e..74f5d4fd 100644--- a/packages/web/src/lib/format.ts+++ b/packages/web/src/lib/format.ts@@ -253,6 +253,29 @@ export function formatRelativeDate(iso: string, locale: "zh" | "en"): string {return locale === "en" ? `updated ${days} days ago` : `${days} 天前更新`;}+/**+ * ISO timestamp → compact "how long ago from now" for narrow rows (the sidebar's+ * per-conversation time): under a minute zh 「刚刚」 / en "now", then minute / hour /+ * day steps — zh keeps the dictionary wording (`5 分钟前`), en stays ultra-short+ * (`5m`, `3h`, `2d`) per the CLI-style abbreviation register. A week or older — or a+ * future time (clock skew) — falls back to the absolute month-day (formatMonthDay);+ * an unparsable value yields "" so callers hide the slot rather than show garbage.+ */+export function formatRelativeShort(iso: string, locale: "zh" | "en"): string {+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return "";+ const diffMs = Date.now() - d.getTime();+ if (diffMs < 0) return formatMonthDay(iso, locale);+ const min = Math.floor(diffMs / 60_000);+ if (min < 1) return locale === "en" ? "now" : "刚刚";+ if (min < 60) return locale === "en" ? `${min}m` : `${min} 分钟前`;+ const hours = Math.floor(min / 60);+ if (hours < 24) return locale === "en" ? `${hours}h` : `${hours} 小时前`;+ const days = Math.floor(hours / 24);+ if (days < 7) return locale === "en" ? `${days}d` : `${days} 天前`;+ return formatMonthDay(iso, locale);+}+/** ISO timestamp → local `HH:mm:ss` (inline display in the Trace timeline); returns the input unchanged if parsing fails. */export function formatTime(iso: string): string {const d = new Date(iso);diff --git a/packages/web/src/lib/nav-group-collapse.ts b/packages/web/src/lib/nav-group-collapse.tsnew file mode 100644index 00000000..16040707--- /dev/null+++ b/packages/web/src/lib/nav-group-collapse.ts@@ -0,0 +1,78 @@+/**+ * 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).+ *+ * 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.+ */++/**+ * 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.+ */+export const NAV_GROUP_KEYS = [+ "agents",+ "skills",+ "models",+ "usage",+ "traces",+ "benchmark",+] as const;+export type NavGroupKey = (typeof NAV_GROUP_KEYS)[number];++/**+ * 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.+ */+export function visibleNavKeys(collapsed: boolean): readonly NavGroupKey[] {+ return collapsed ? [] : NAV_GROUP_KEYS;+}++/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */+export interface NavCollapseStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/** The single global key (`penguin.…` naming convention); holds "collapsed" / "expanded". */+export const NAV_GROUP_COLLAPSED_KEY = "penguin.sidebarNavGroupCollapsed";++/**+ * Reads the persisted choice; only an explicit "collapsed" collapses — anything else+ * (absent / unrecognized / throwing storage) is the expanded default. `localStorage` is+ * resolved INSIDE the try, never as a default parameter: merely touching it throws a+ * SecurityError when site data is blocked (or in a partitioned iframe), and this runs+ * from a useState initializer — an escaping throw would take the sidebar's first render+ * down.+ */+export function initialNavGroupCollapsed(storage?: NavCollapseStorage): boolean {+ try {+ return (storage ?? localStorage).getItem(NAV_GROUP_COLLAPSED_KEY) === "collapsed";+ } catch {+ return false;+ }+}++/** Writes the choice on every toggle (best-effort: quota limits / private browsing fail silently). */+export function storeNavGroupCollapsed(collapsed: boolean, storage?: NavCollapseStorage): void {+ try {+ (storage ?? localStorage).setItem(+ NAV_GROUP_COLLAPSED_KEY,+ collapsed ? "collapsed" : "expanded",+ );+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}diff --git a/packages/web/src/lib/pinned-sessions.ts b/packages/web/src/lib/pinned-sessions.tsnew file mode 100644index 00000000..02b82756--- /dev/null+++ b/packages/web/src/lib/pinned-sessions.ts@@ -0,0 +1,87 @@+/**+ * Pinned Sessions of the sidebar's conversation list (pure decisions, unit tested):+ * pinning a conversation bubbles its row to the top of its group's active list — the+ * row-level counterpart of the existing group pin, applied with the same `pinnedFirst`+ * ordering inside every grouping mode.+ *+ * Persistence is frontend-side: `SessionInfo` carries no pinned field and+ * `SessionPatchRequest` accepts none, so a server route would need schema + API+ * changes — deliberately out of scope here. Instead the ids persist per Project in+ * localStorage (`penguin.…` key naming, matching the sidebar's collapsed/pinned group+ * sets), with injectable storage (model-group-expansion.ts convention: vitest runs in+ * Node, no localStorage). Deleting a Session prunes its id via removePinnedSession;+ * ids orphaned by deletions elsewhere (another browser/device) stay inert — a pin is+ * a pure membership test and a row that never renders is never asked about.+ */++/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */+export interface PinnedSessionsStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/** Storage key of one Project's pinned-session id set (sidebar key-naming convention, `penguin.sidebarPinnedGroups.<projectId>` &c.). */+export const pinnedSessionsKey = (projectId: string): string =>+ `penguin.pinnedSessions.${projectId}`;++/**+ * Reads a Project's persisted pinned ids; no Project yet, nothing stored, or corrupted+ * storage degrade to the empty set (nothing pinned — the default). A stored array+ * survives element-level junk: non-strings are dropped, strings kept.+ */+export function loadPinnedSessions(+ projectId: string | null,+ storage?: PinnedSessionsStorage,+): Set<string> {+ if (projectId === null) return new Set();+ try {+ // localStorage is resolved INSIDE the try, never as a default parameter: merely+ // touching it throws a SecurityError when site data is blocked (or in a partitioned+ // iframe), and this runs from a useState initializer — an escaping throw would take+ // the whole sidebar's first render down.+ const store = storage ?? localStorage;+ const parsed: unknown = JSON.parse(store.getItem(pinnedSessionsKey(projectId)) ?? "[]");+ return new Set(+ Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === "string") : [],+ );+ } catch {+ return new Set();+ }+}++/** Writes a Project's pinned ids on every change (best-effort: quota limits / private browsing fail silently). */+export function savePinnedSessions(+ projectId: string | null,+ pinned: ReadonlySet<string>,+ storage?: PinnedSessionsStorage,+): void {+ if (projectId === null) return;+ try {+ (storage ?? localStorage).setItem(pinnedSessionsKey(projectId), JSON.stringify([...pinned]));+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}++/** Immutable pin/unpin of one Session id (state-updater shape; the input set is never mutated). */+export function togglePinnedSession(pinned: ReadonlySet<string>, sessionId: string): Set<string> {+ const next = new Set(pinned);+ if (next.has(sessionId)) next.delete(sessionId);+ else next.add(sessionId);+ return next;+}++/**+ * Prune on Session delete: drops the id, returning the INPUT set unchanged (same+ * reference) when it wasn't pinned — callers skip the state update and storage write+ * on the common unpinned path.+ */+export function removePinnedSession(+ pinned: ReadonlySet<string>,+ sessionId: string,+): ReadonlySet<string> {+ if (!pinned.has(sessionId)) return pinned;+ const next = new Set(pinned);+ next.delete(sessionId);+ return next;+}diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.tsindex cd414d92..ab1aa365 100644--- a/packages/web/src/lib/session-grouping.ts+++ b/packages/web/src/lib/session-grouping.ts@@ -85,6 +85,17 @@ export function sessionCategory(s: SessionInfo): SessionCategory {return s.source === "subagent" || s.source === "schedule" ? s.source : "active";}+/**+ * Whether a Session matches the sidebar's live title search: case-insensitive substring+ * over the stored title (untitled Sessions have none and never match a non-empty+ * query); a blank/whitespace query matches everything (search inactive).+ */+export function matchesSessionQuery(s: SessionInfo, query: string): boolean {+ const q = query.trim().toLowerCase();+ if (q === "") return true;+ return (s.title ?? "").toLowerCase().includes(q);+}+/** The collapsed-folder categories of a group, in render order (below the active user rows). */export const FOLDER_CATEGORIES = ["subagent", "schedule", "archived"] as const;export type FolderCategory = (typeof FOLDER_CATEGORIES)[number];diff --git a/packages/web/src/lib/session-order.ts b/packages/web/src/lib/session-order.tsnew file mode 100644index 00000000..3699e98b--- /dev/null+++ b/packages/web/src/lib/session-order.ts@@ -0,0 +1,209 @@+/**+ * Sort mode and manual order of the sidebar's conversation rows (pure decisions, unit+ * tested). Two settings work together:+ *+ * - Sort mode — "recent" (the default: rows keep the store's newest-first order) or+ * "manual" (drag-reorderable). One global key like the grouping mode: a single user+ * preference, not per Project.+ * - Manual order — one array of Session ids per Project AND grouping mode (the modes cut+ * the same Sessions into different partitions, so one shared array would let a drag in+ * one mode scramble the other). Only the RELATIVE order of ids that render together in+ * one partition ever matters (rows are compared only within a group's own list), so a+ * drop simply rewrites the affected partition's sequence to the front of the array+ * (applyManualReorder) — the caller must commit the partition's FULL loaded sequence,+ * not the display-capped slice, or the hidden rows would fall out and return as+ * "newcomers". Rows not in the array — new Sessions — go to the TOP of their partition+ * keeping their recency order; stored ids that no longer exist stay inert (membership+ * lookups only) and deletion prunes via removeFromSessionOrder.+ *+ * Ordering composes with the row pins (pinned-sessions.ts): the pinned cluster always+ * renders first, and the manual order applies WITHIN the pinned cluster and within the+ * rest independently — dragging never pins or unpins (orderSessionRows).+ *+ * Storage is injectable (model-group-expansion.ts convention: vitest runs in Node, no+ * localStorage); malformed values degrade to the defaults.+ */+import { pinnedFirst } from "./session-grouping";+import type { GroupMode } from "../components/ui/group-list";++export type SessionSortMode = "recent" | "manual";++/** The single global key (`penguin.…` naming, GROUP_MODE_KEY convention); holds "manual" / "recent". */+export const SESSION_SORT_MODE_KEY = "penguin.sidebarSortMode";++/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */+export interface SessionOrderStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/**+ * Reads the persisted sort mode; only an explicit "manual" switches — anything else+ * (absent / unrecognized / throwing storage) is the "recent" default, so a fresh profile+ * looks unchanged. `localStorage` is resolved INSIDE the try, never as a default+ * parameter: merely touching it throws a SecurityError when site data is blocked (or in+ * a partitioned iframe), and this runs from a useState initializer — an escaping throw+ * would take the whole sidebar's first render down.+ */+export function initialSessionSortMode(storage?: SessionOrderStorage): SessionSortMode {+ try {+ const store = storage ?? localStorage;+ return store.getItem(SESSION_SORT_MODE_KEY) === "manual" ? "manual" : "recent";+ } catch {+ return "recent";+ }+}++export function storeSessionSortMode(mode: SessionSortMode, storage?: SessionOrderStorage): void {+ try {+ (storage ?? localStorage).setItem(SESSION_SORT_MODE_KEY, mode);+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}++/**+ * Storage key of one Project's manual order (sidebar key-naming convention,+ * `penguin.pinnedSessions.<projectId>` &c.), scoped BY GROUPING MODE: the stored+ * sequence is only ever read within a partition, and the two modes cut the same+ * Sessions into different partitions — one shared array would let a drag in workspace+ * mode scramble the agent-mode order (and vice versa).+ */+export const sessionOrderKey = (projectId: string, mode: GroupMode): string =>+ `penguin.sessionOrder.${projectId}.${mode}`;++/** Reads a Project+mode's persisted manual order; no Project, nothing stored, or corrupted storage degrade to empty (pure recency). Junk array elements are dropped. (localStorage resolved inside the try — see initialSessionSortMode.) */+export function loadSessionOrder(+ projectId: string | null,+ mode: GroupMode,+ storage?: SessionOrderStorage,+): string[] {+ if (projectId === null) return [];+ try {+ const store = storage ?? localStorage;+ const parsed: unknown = JSON.parse(store.getItem(sessionOrderKey(projectId, mode)) ?? "[]");+ return Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === "string") : [];+ } catch {+ return [];+ }+}++/** Writes a Project+mode's manual order on every drop (best-effort: quota limits / private browsing fail silently). */+export function saveSessionOrder(+ projectId: string | null,+ mode: GroupMode,+ order: readonly string[],+ storage?: SessionOrderStorage,+): void {+ if (projectId === null) return;+ try {+ (storage ?? localStorage).setItem(sessionOrderKey(projectId, mode), JSON.stringify(order));+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}++/**+ * Applies the stored manual order to one partition's rows: rows absent from the order+ * (new Sessions) come FIRST keeping their input (recency) order, then the listed rows+ * by their stored position. Stale stored ids simply match nothing.+ */+export function applyManualOrder<T>(+ rows: readonly T[],+ keyOf: (row: T) => string,+ order: readonly string[],+): T[] {+ if (order.length === 0) return [...rows];+ const pos = new Map(order.map((id, i) => [id, i]));+ const unlisted: T[] = [];+ const listed: T[] = [];+ for (const row of rows) (pos.has(keyOf(row)) ? listed : unlisted).push(row);+ listed.sort((a, b) => (pos.get(keyOf(a)) ?? 0) - (pos.get(keyOf(b)) ?? 0));+ return [...unlisted, ...listed];+}++/**+ * The full row-ordering pipeline of one group's active list:+ *+ * 1. recency — newest `recencyOf` first (the Session's `lastActiveAt`: 「最近更新」 means+ * last ACTIVITY, not creation), ties broken by key descending to match the store's+ * stable tiebreaker. Applied in both modes: it IS the recent mode's order, and in+ * manual mode it is the order rows not yet in the stored sequence arrive in.+ * 2. the pinned cluster first (pinnedFirst), then+ * 3. under manual sort, the stored order within the pinned cluster and within the rest+ * independently, so a drag can never move a row across the pin boundary.+ *+ * Only rows already FETCHED are ordered. The server still pages by `created_at DESC`+ * (listByAgent — there is no index on last_active_at), so a Session created long ago but+ * active today sits on a later page and cannot climb into the sidebar's first page until+ * "More" pulls that page in; fixing that needs a server-side ordering + index change.+ */+export function orderSessionRows<T>(+ rows: readonly T[],+ keyOf: (row: T) => string,+ opts: {+ pinned: ReadonlySet<string>;+ sortMode: SessionSortMode;+ order: readonly string[];+ /** Recency key of a row (the sidebar passes `lastActiveAt`). Omitted = keep the caller's order. */+ recencyOf?: (row: T) => string;+ },+): T[] {+ const recencyOf = opts.recencyOf;+ const byRecency = recencyOf+ ? [...rows].sort(+ (a, b) => recencyOf(b).localeCompare(recencyOf(a)) || keyOf(b).localeCompare(keyOf(a)),+ )+ : rows;+ const byPin = pinnedFirst(byRecency, keyOf, opts.pinned);+ if (opts.sortMode !== "manual") return byPin;+ const pin = byPin.filter((r) => opts.pinned.has(keyOf(r)));+ const rest = byPin.filter((r) => !opts.pinned.has(keyOf(r)));+ return [+ ...applyManualOrder(pin, keyOf, opts.order),+ ...applyManualOrder(rest, keyOf, opts.order),+ ];+}++/**+ * Moves `dragId` next to `targetId` (after it when `after`, else before) in a displayed+ * sequence. Returns the INPUT array unchanged (same reference) for every no-op — a+ * missing id, a self-drop, or a drop that lands the row exactly where it already sat+ * (dropping just above your next neighbour) — so callers skip the state update and the+ * storage write instead of persisting a freshly allocated identical array.+ */+export function moveInSequence(+ sequence: readonly string[],+ dragId: string,+ targetId: string,+ after: boolean,+): readonly string[] {+ if (dragId === targetId || !sequence.includes(dragId)) return sequence;+ const without = sequence.filter((id) => id !== dragId);+ const at = without.indexOf(targetId);+ if (at < 0) return sequence;+ without.splice(after ? at + 1 : at, 0, dragId);+ return without.every((id, i) => id === sequence[i]) ? sequence : without;+}++/**+ * Commits one partition's displayed sequence into the stored order after a drop: the+ * sequence goes to the FRONT, the remaining stored ids follow unchanged. Correct+ * because only the relative order of ids that co-render in one partition is ever+ * read — ids of other groups keep their relative order among themselves.+ */+export function applyManualReorder(+ order: readonly string[],+ partitionSequence: readonly string[],+): string[] {+ const inPartition = new Set(partitionSequence);+ return [...partitionSequence, ...order.filter((id) => !inPartition.has(id))];+}++/** Prune on Session delete: drops the id, returning the INPUT array unchanged (same reference) when absent — callers skip the state update and storage write then. */+export function removeFromSessionOrder(+ order: readonly string[],+ sessionId: string,+): readonly string[] {+ return order.includes(sessionId) ? order.filter((id) => id !== sessionId) : order;+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex ee242ed4..16071fff 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -864,6 +864,26 @@ export const en: Strings = {/** Sidebar conversation-list grouping toggle (workspace is the default) + workspace groups. */groupByWorkspace: "Group by workspace",groupByAgent: "Group by agent",+ /** Session-list section header controls: search / list settings / mode-dependent create (the created object follows the grouping mode). */+ searchSessions: "Search chats",+ searchSessionsPlaceholder: "Search chats…",+ searchClear: "Clear search",+ /** Zero hits: the filter only sees already-loaded conversations, so the copy says so rather than claiming none exist. */+ searchNoMatches: "No matches among loaded chats",+ listSettings: "List options",+ groupModeSection: "Group by",+ sortModeSection: "Sort by",+ sortManual: "Manual order",+ sortRecent: "Most recent",+ newWorkspaceEntity: "New workspace",+ /** Registry-backed workspace group's overflow (… right of the header "+"): alias rename + sidebar-only removal. */+ workspaceMenu: "Workspace options",+ renameWorkspace: "Rename workspace",+ renameWorkspaceLabel: "Name",+ renameWorkspaceHint: "Leave empty to use the folder name",+ deleteWorkspace: "Remove workspace",+ deleteWorkspaceConfirm: (name: string) =>+ `Remove "${name}"? This only removes the workspace group from the sidebar — the directory on disk and existing chats are untouched, and it can be re-added anytime.`,tempWorkspaces: "Temporary workspaces",newSessionInWorkspace: "New chat in this workspace",draftSubtitle: "The self-evolving agent that excels at AI development tasks",@@ -1222,6 +1242,11 @@ Scenarios:`Delete draft "${title}"? Unsent content will be discarded.`,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",/** Sidebar group "reveal/load next page" row (display cap + server paging). */loadMore: "More",/** Collapsed sidebar folders inside a group (lazy-loaded); the count is the group's exact server share. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 518ae6a7..e501fc92 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -819,6 +819,26 @@ export const zh = {/** Grouping toggle of the sidebar conversation list (workspace grouping is the default) and the workspace groups. */groupByWorkspace: "按工作区分组",groupByAgent: "按 Agent 分组",+ /** Session-list section header controls: search / list settings / mode-dependent create (具体新建的对象按分组方式决定). */+ searchSessions: "搜索会话",+ searchSessionsPlaceholder: "搜索会话…",+ searchClear: "清除搜索",+ /** Zero hits: the filter only sees already-loaded conversations, so the copy says so rather than claiming none exist. */+ searchNoMatches: "已加载的会话中无匹配",+ listSettings: "列表选项",+ groupModeSection: "分组方式",+ sortModeSection: "排序方式",+ sortManual: "手动排序",+ sortRecent: "最近更新",+ newWorkspaceEntity: "新建工作区",+ /** Registry-backed workspace group's overflow (… right of the header "+"): alias rename + sidebar-only removal. */+ workspaceMenu: "工作区选项",+ renameWorkspace: "重命名工作区",+ renameWorkspaceLabel: "名称",+ renameWorkspaceHint: "留空则使用目录名",+ deleteWorkspace: "删除工作区",+ deleteWorkspaceConfirm: (name: string) =>+ `确定移除「${name}」?仅从侧边栏移除该工作区分组,不影响磁盘目录与已有会话,可随时重新添加。`,tempWorkspaces: "临时工作区",newSessionInWorkspace: "在此工作区新建对话",draftSubtitle: "最擅长 AI 开发任务的自进化 Agent",@@ -1173,6 +1193,11 @@ Benchmark:deleteDraftConfirm: (title: string) => `确定删除草稿「${title}」?未发送的内容将被丢弃。`,archiveSession: "归档",unarchiveSession: "取消归档",+ /** Per-row ellipsis overflow menu (pin / rename / archive / delete live inside it) and the row-level pin. */+ sessionMenu: "对话选项",+ pinSession: "置顶",+ unpinSession: "取消置顶",+ pinnedSession: "已置顶",/** Sidebar group "reveal/load next page" row (display cap + server paging). */loadMore: "更多",/** Collapsed sidebar folders inside a group (lazy-loaded); the count is the group's exact server share. */diff --git a/packages/web/src/lib/workspace-registry.ts b/packages/web/src/lib/workspace-registry.tsnew file mode 100644index 00000000..58e6a9ff--- /dev/null+++ b/packages/web/src/lib/workspace-registry.ts@@ -0,0 +1,198 @@+/**+ * Manually-added Workspaces of the sidebar (pure decisions, unit tested): the header's+ * 新建工作区 button lets the user browse to a directory, and the picked path must show+ * up as a workspace group IMMEDIATELY — even with zero Sessions. There is no Workspace+ * entity on the server (groups are otherwise derived purely from Session paths), so the+ * picked paths persist frontend-side per Project (`penguin.…` key naming, injectable+ * storage — the model-group-expansion.ts convention) and merge into the grouping as+ * empty groups.+ *+ * An entry is `{ path, alias? }`: the alias is a display name set via the group's+ * 重命名工作区 (it replaces the basename as the group label — for session-backed groups+ * too — while the full path stays in the tooltip; an empty alias reverts to the+ * basename). Loads stay tolerant of the branch's earlier string-only stored shape.+ *+ * Lifecycle: an entry stays until 删除工作区 unregisters it (sidebar-only — disk and+ * Sessions are never touched; with Sessions present the group simply persists as+ * session-derived). Once Sessions exist the entry mostly dedups away at merge, but it+ * still carries the alias and keeps the group visible after those Sessions are gone.+ */+import { isTempWorkspace, workspaceGroupKey, workspaceLabel } from "./session-grouping";+import type { WorkspaceGroup } from "./session-grouping";++/** One registered Workspace: the normalized path, plus an optional display alias. */+export interface WorkspaceEntry {+ path: string;+ /** Display name overriding the path basename (set via 重命名工作区; absent = basename). */+ alias?: string;+}++/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory implementation. */+export interface WorkspaceRegistryStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+}++/** Storage key of one Project's manually-added Workspaces (sidebar key-naming convention). */+export const workspaceRegistryKey = (projectId: string): string =>+ `penguin.sidebarWorkspaces.${projectId}`;++/**+ * Canonical form of a picked path: trimmed, trailing separators dropped (the server+ * hands back resolved paths without them, so `/srv/app/` must dedup against+ * `/srv/app`), roots kept whole. Both root shapes are preserved: posix `/`, and a+ * win32 DRIVE root — stripping `C:\` down to `C:` would turn an absolute path into a+ * drive-RELATIVE one, so the registry would hold `C:` while Sessions key `C:\`+ * (phantom duplicate group, and a new chat resolving somewhere else entirely).+ * win32 is a supported target (ci-windows + the `--win` desktop build).+ * Empty in → empty out (never registered).+ */+export function normalizeWorkspacePath(path: string): string {+ let p = path.trim();+ while (p.length > 1 && (p.endsWith("/") || p.endsWith("\\"))) {+ // `C:\` / `C:/` is a root: one more strip would leave the drive-relative `C:`.+ if (/^[A-Za-z]:[/\\]$/.test(p)) break;+ p = p.slice(0, -1);+ }+ return p;+}++/** Parses one stored element: a plain string (the branch's earlier shape) or an entry object; junk yields null. */+function parseEntry(x: unknown): WorkspaceEntry | null {+ if (typeof x === "string") {+ const p = normalizeWorkspacePath(x);+ return p === "" ? null : { path: p };+ }+ if (typeof x === "object" && x !== null && typeof (x as { path?: unknown }).path === "string") {+ const p = normalizeWorkspacePath((x as { path: string }).path);+ if (p === "") return null;+ const rawAlias = (x as { alias?: unknown }).alias;+ const alias = typeof rawAlias === "string" ? rawAlias.trim() : "";+ return alias === "" ? { path: p } : { path: p, alias };+ }+ return null;+}++/** Reads a Project's registered Workspaces; no Project, nothing stored, or corrupted storage degrade to empty. Junk elements are dropped, entries re-normalized and deduped (first wins), and the old string-only shape still loads. */+export function loadWorkspaceRegistry(+ projectId: string | null,+ storage?: WorkspaceRegistryStorage,+): WorkspaceEntry[] {+ if (projectId === null) return [];+ try {+ // localStorage resolved INSIDE the try (see pinned-sessions.ts): touching it throws+ // a SecurityError with site data blocked, and this runs from a useState initializer.+ const store = storage ?? localStorage;+ const parsed: unknown = JSON.parse(store.getItem(workspaceRegistryKey(projectId)) ?? "[]");+ if (!Array.isArray(parsed)) return [];+ const out: WorkspaceEntry[] = [];+ for (const x of parsed) {+ const entry = parseEntry(x);+ if (entry !== null && !out.some((e) => e.path === entry.path)) out.push(entry);+ }+ return out;+ } catch {+ return [];+ }+}++/** Writes a Project's registered Workspaces (best-effort: quota limits / private browsing fail silently). */+export function saveWorkspaceRegistry(+ projectId: string | null,+ entries: readonly WorkspaceEntry[],+ storage?: WorkspaceRegistryStorage,+): void {+ if (projectId === null) return;+ try {+ (storage ?? localStorage).setItem(workspaceRegistryKey(projectId), JSON.stringify(entries));+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}++/**+ * Registers a picked path: normalized and prepended (newest registration first).+ * Returns the INPUT array unchanged (same reference) for anything unregisterable —+ * callers skip the state update and storage write. Besides the empty path and an+ * already-registered one, a TEMPORARY-workspace path is rejected: the merge below can+ * never give it a group (the merged temp group owns that space), so accepting it would+ * store an entry whose group never appears — no rename/remove overflow to undo it, and+ * re-picking would hit the already-registered exit, leaving a ghost only a+ * localStorage wipe could clear.+ */+export function registerWorkspace(+ entries: readonly WorkspaceEntry[],+ path: string,+): readonly WorkspaceEntry[] {+ const p = normalizeWorkspacePath(path);+ if (p === "" || isTempWorkspace(p) || entries.some((e) => e.path === p)) return entries;+ return [{ path: p }, ...entries];+}++/**+ * Sets (or, with a blank alias, clears) a registered Workspace's display alias.+ * Returns the INPUT array unchanged (same reference) when the path isn't registered+ * or the alias doesn't actually change.+ */+export function setWorkspaceAlias(+ entries: readonly WorkspaceEntry[],+ path: string,+ alias: string,+): readonly WorkspaceEntry[] {+ const a = alias.trim();+ const entry = entries.find((e) => e.path === path);+ if (!entry || (entry.alias ?? "") === a) return entries;+ return entries.map((e) =>+ e.path === path ? (a === "" ? { path: e.path } : { path: e.path, alias: a }) : e,+ );+}++/** 删除工作区: drops the registry entry (sidebar-only — disk and Sessions are untouched). Same-reference fast exit when the path isn't registered. */+export function unregisterWorkspace(+ entries: readonly WorkspaceEntry[],+ path: string,+): readonly WorkspaceEntry[] {+ return entries.some((e) => e.path === path) ? entries.filter((e) => e.path !== path) : entries;+}++/**+ * Merges the registered Workspaces into the session-derived grouping: registered-only+ * paths become EMPTY groups, labelled by alias ?? basename; paths whose group already+ * exists dedup away (matched by workspaceGroupKey, so trailing-separator variants+ * collide correctly) but still apply their alias to that group's label; a path that+ * reads as a temporary workspace never forms a group (the merged temp group owns that+ * space — registerWorkspace rejects those up front).+ *+ * The empty groups sort AFTER the session-derived ones (in registration order, newest+ * first). They hold no conversations, and the list renders behind a 10-group display+ * cap: fronting them would push every group with real chats behind 更多分组 as soon as+ * a handful of Workspaces were registered. The sidebar widens the cap when it registers+ * one, so a just-added Workspace is still revealed immediately.+ */+export function mergeRegisteredWorkspaces<T>(+ groups: readonly WorkspaceGroup<T>[],+ registered: readonly WorkspaceEntry[],+): WorkspaceGroup<T>[] {+ const aliasByKey = new Map(+ registered.filter((e) => e.alias !== undefined).map((e) => [e.path, e.alias as string]),+ );+ const existing = new Set(groups.map((g) => g.key));+ const added: WorkspaceGroup<T>[] = [];+ for (const { path, alias } of registered) {+ const key = workspaceGroupKey(path);+ if (existing.has(key) || key !== path) continue; // already grouped, or a temp-shaped path+ existing.add(key);+ added.push({+ key,+ label: alias ?? workspaceLabel(path),+ fullPath: path,+ temp: false,+ sessions: [],+ });+ }+ const relabelled = groups.map((g) => {+ const alias = aliasByKey.get(g.key);+ return alias === undefined ? g : { ...g, label: alias };+ });+ return added.length === 0 ? relabelled : [...relabelled, ...added];+}diff --git a/packages/web/test/format.test.ts b/packages/web/test/format.test.tsindex 31fed936..79f0f66b 100644--- a/packages/web/test/format.test.ts+++ b/packages/web/test/format.test.ts@@ -12,6 +12,7 @@ import {formatPercent,formatRelativeDate,formatRelativeDays,+ formatRelativeShort,formatScore,formatTps,humanizeDuration,@@ -241,6 +242,44 @@ describe("formatRelativeDays", () => {});});+describe("formatRelativeShort", () => {+ // Fix "now" (the sidebar row's compact last-active time is measured from it).+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 6, 15, 12, 0, 0));+ });+ afterEach(() => {+ vi.useRealTimers();+ });+ const at = (mo: number, d: number, h: number, mi: number) =>+ new Date(2026, mo, d, h, mi).toISOString();++ it("under a minute reads as just-now", () => {+ expect(formatRelativeShort(new Date(2026, 6, 15, 11, 59, 30).toISOString(), "zh")).toBe("刚刚");+ expect(formatRelativeShort(at(6, 15, 12, 0), "en")).toBe("now");+ });++ it("minute / hour / day steps, floored: zh dictionary wording, en ultra-short", () => {+ expect(formatRelativeShort(at(6, 15, 11, 55), "zh")).toBe("5 分钟前");+ expect(formatRelativeShort(at(6, 15, 11, 1), "en")).toBe("59m");+ expect(formatRelativeShort(at(6, 15, 9, 30), "zh")).toBe("2 小时前");+ expect(formatRelativeShort(at(6, 14, 12, 30), "en")).toBe("23h");+ expect(formatRelativeShort(at(6, 14, 11, 0), "zh")).toBe("1 天前");+ expect(formatRelativeShort(at(6, 9, 12, 0), "en")).toBe("6d");+ });++ it("a week or older — and future times (clock skew) — fall back to the absolute month-day", () => {+ expect(formatRelativeShort("2026-07-01T00:00:00.000Z", "zh")).toBe("7 月 1 日");+ expect(formatRelativeShort("2026-01-02T00:00:00.000Z", "en")).toBe("Jan 2");+ expect(formatRelativeShort("2026-07-20T00:00:00.000Z", "en")).toBe("Jul 20");+ });++ it("unparsable input yields the empty string (the row hides the slot instead of showing garbage)", () => {+ expect(formatRelativeShort("not-a-date", "zh")).toBe("");+ expect(formatRelativeShort("", "en")).toBe("");+ });+});+describe("formatRelativeDate (semantic update time on Skill cards)", () => {// Fix "now" to local 2026-07-15 12:00 (same convention as formatRelativeDays).beforeEach(() => {diff --git a/packages/web/test/group-list.test.ts b/packages/web/test/group-list.test.tsnew file mode 100644index 00000000..27c287a3--- /dev/null+++ b/packages/web/test/group-list.test.ts@@ -0,0 +1,17 @@+/**+ * group-list.tsx pure helpers: the sidebar header's mode-dependent create button —+ * the created object follows the grouping mode (用户口径: 具体新建的对象按分组方式决定).+ * Agent grouping creates an Agent (the Agents page's existing create dialog, reached+ * 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).+ */+import { describe, expect, it } from "vitest";+import { newEntityForGroupMode } from "../src/components/ui/group-list";++describe("newEntityForGroupMode", () => {+ it("agent grouping creates an Agent; workspace grouping (the default) creates a Workspace", () => {+ expect(newEntityForGroupMode("agent")).toBe("agent");+ expect(newEntityForGroupMode("workspace")).toBe("workspace");+ });+});diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.tsnew file mode 100644index 00000000..b18b777b--- /dev/null+++ b/packages/web/test/nav-group-collapse.test.ts@@ -0,0 +1,135 @@+/**+ * 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.+ */+import { describe, expect, it } from "vitest";+import {+ NAV_GROUP_COLLAPSED_KEY,+ NAV_GROUP_KEYS,+ initialNavGroupCollapsed,+ storeNavGroupCollapsed,+ visibleNavKeys,+} from "../src/lib/nav-group-collapse";+import type { NavCollapseStorage } from "../src/lib/nav-group-collapse";+import { NAV_ICONS } from "../src/components/ui/icons";+import { zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */+function memStorage(): NavCollapseStorage & { map: Map<string, string> } {+ const map = new Map<string, string>();+ return {+ map,+ getItem: (k) => map.get(k) ?? null,+ setItem: (k, v) => void map.set(k, v),+ };+}++describe("NAV_GROUP_KEYS", () => {+ it("covers exactly the 智能体 → 评估中心 range, in rendered order", () => {+ expect([...NAV_GROUP_KEYS]).toEqual([+ "agents",+ "skills",+ "models",+ "usage",+ "traces",+ "benchmark",+ ]);+ // Pin the endpoints by label: a manifest edit that shifts the range shows up here.+ expect(zh.nav[NAV_GROUP_KEYS[0]]).toBe("智能体");+ expect(zh.nav[NAV_GROUP_KEYS[NAV_GROUP_KEYS.length - 1]!]).toBe("评估中心");+ });++ it("every entry has a zh label, an en label, and a nav icon (the sidebar renders straight off the manifest)", () => {+ for (const key of NAV_GROUP_KEYS) {+ expect(zh.nav[key]).toBeTruthy();+ expect(en.nav[key]).toBeTruthy();+ expect(NAV_ICONS[key]).toBeTruthy();+ }+ });++ 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.+ expect(NAV_GROUP_KEYS as readonly string[]).not.toContain("newChat");+ expect(NAV_GROUP_KEYS as readonly string[]).not.toContain("chat");+ expect(zh.chat.newSessionMenu).toBe("新建对话");+ });+});++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(NAV_GROUP_KEYS);+ expect(visibleNavKeys(true)).toEqual([]);+ });++ it("the chevron-button toggle's accessible names exist in both languages (icon-only button: aria + tooltip carry them)", () => {+ expect(zh.nav.collapseGroup).toBe("折叠");+ expect(zh.nav.expandGroup).toBe("展开");+ expect(en.nav.collapseGroup).toBe("Collapse");+ expect(en.nav.expandGroup).toBe("Expand");+ });+});++describe("persisted collapse state (one global localStorage key)", () => {+ it("default is expanded with nothing stored, and reading never writes", () => {+ const s = memStorage();+ expect(initialNavGroupCollapsed(s)).toBe(false);+ expect(s.map.size).toBe(0);+ });++ 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 …+ 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([]);+ // 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(NAV_GROUP_KEYS);+ });++ it("unrecognized stored values fall back to expanded", () => {+ const s = memStorage();+ for (const raw of ["", "true", "1", "COLLAPSED", "yes"]) {+ s.map.set(NAV_GROUP_COLLAPSED_KEY, raw);+ expect(initialNavGroupCollapsed(s)).toBe(false);+ }+ });++ 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);+ });++ 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);+ });+});diff --git a/packages/web/test/pinned-sessions.test.ts b/packages/web/test/pinned-sessions.test.tsnew file mode 100644index 00000000..8a28d2b2--- /dev/null+++ b/packages/web/test/pinned-sessions.test.ts@@ -0,0 +1,168 @@+/**+ * pinned-sessions.ts unit tests: the sidebar conversation list's row-level pin. Pinned+ * ids persist per Project in localStorage (injectable storage; no server field exists —+ * SessionPatchRequest accepts no pin, so persistence is deliberately frontend-side):+ * nothing stored or corrupted storage degrades to "nothing pinned", junk array elements+ * are dropped, Projects are isolated, and deleting a Session prunes its id (other stale+ * ids stay inert — a pin is a pure membership test). Ordering composes with the group+ * lists through the same pinnedFirst helper the group pins use: the pinned cluster+ * sits at the top of a group's ACTIVE rows in either grouping mode, keeping each+ * partition's own recency order; folder rows are untouched.+ */+import { describe, expect, it } from "vitest";+import type { SessionInfo } from "@prismshadow/penguin-server/api";+import {+ loadPinnedSessions,+ pinnedSessionsKey,+ removePinnedSession,+ savePinnedSessions,+ togglePinnedSession,+} from "../src/lib/pinned-sessions";+import type { PinnedSessionsStorage } from "../src/lib/pinned-sessions";+import { partitionSessions, pinnedFirst } from "../src/lib/session-grouping";++/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */+function memStorage(): PinnedSessionsStorage & { map: Map<string, string> } {+ const map = new Map<string, string>();+ return {+ map,+ getItem: (k) => map.get(k) ?? null,+ setItem: (k, v) => void map.set(k, v),+ };+}++/** Minimal SessionInfo (session-grouping.test.ts convention: only the fields the logic reads matter). */+function session(+ sessionId: string,+ over: { archived?: boolean; source?: "schedule" | "subagent" } = {},+): SessionInfo {+ return {+ sessionId,+ projectId: "proj",+ agentId: "default_agent",+ provider: "custom",+ modelId: "claude-4-8",+ workspace: "/w",+ approvalMode: "allow-all",+ createdAt: "2026-08-13T00:00:00.000Z",+ lastActiveAt: "2026-08-13T00:00:00.000Z",+ status: "idle",+ pendingApprovalCount: 0,+ pendingFollowUpCount: 0,+ hasTrace: false,+ archived: over.archived ?? false,+ ...(over.source ? { source: over.source } : {}),+ };+}++describe("persisted pins (per-Project localStorage)", () => {+ it("nothing stored — or no Project yet — is the empty set, and reading never writes", () => {+ const s = memStorage();+ expect(loadPinnedSessions("p1", s).size).toBe(0);+ expect(loadPinnedSessions(null, s).size).toBe(0);+ expect(s.map.size).toBe(0); // load never writes; save without a Project is a no-op+ savePinnedSessions(null, new Set(["a"]), s);+ expect(s.map.size).toBe(0);+ });++ it("toggle → save → load round-trips the user's set (fresh instance per load)", () => {+ const s = memStorage();+ let set = loadPinnedSessions("p1", s);+ set = togglePinnedSession(set, "session-a");+ set = togglePinnedSession(set, "session-b");+ savePinnedSessions("p1", set, s);+ const restored = loadPinnedSessions("p1", s);+ expect(restored).toEqual(new Set(["session-a", "session-b"]));+ expect(restored).not.toBe(set);+ });++ it("Projects are isolated: each key holds its own set", () => {+ const s = memStorage();+ savePinnedSessions("p1", new Set(["a"]), s);+ savePinnedSessions("p2", new Set(["b", "c"]), s);+ expect([...loadPinnedSessions("p1", s)]).toEqual(["a"]);+ expect(loadPinnedSessions("p2", s)).toEqual(new Set(["b", "c"]));+ expect(loadPinnedSessions("p3", s).size).toBe(0);+ });++ it("malformed JSON / non-array shapes degrade to empty; junk array elements are dropped", () => {+ const s = memStorage();+ for (const raw of ["{not json", '"a"', "42", "null", "{}", ""]) {+ s.map.set(pinnedSessionsKey("p1"), raw);+ expect(loadPinnedSessions("p1", s).size).toBe(0);+ }+ s.map.set(pinnedSessionsKey("p1"), '["a", 7, null, {"x": 1}]');+ expect([...loadPinnedSessions("p1", s)]).toEqual(["a"]);+ });++ it("storage throwing (quota/private mode): save does not throw, load yields empty", () => {+ const broken: PinnedSessionsStorage = {+ getItem: () => {+ throw new Error("denied");+ },+ setItem: () => {+ throw new Error("denied");+ },+ };+ expect(() => savePinnedSessions("p1", new Set(["a"]), broken)).not.toThrow();+ expect(loadPinnedSessions("p1", broken).size).toBe(0);+ });++ it("storage whose GETTER throws (blocked site data / partitioned iframe) degrades instead of escaping", () => {+ // These loaders run from useState initializers, so an escaping SecurityError would+ // take the sidebar's first render down — hence localStorage is resolved inside the try.+ const hostile = {+ get getItem(): never {+ throw new Error("SecurityError");+ },+ setItem: () => undefined,+ } as unknown as PinnedSessionsStorage;+ expect(() => loadPinnedSessions("p1", hostile)).not.toThrow();+ expect(loadPinnedSessions("p1", hostile).size).toBe(0);+ });+});++describe("togglePinnedSession / removePinnedSession", () => {+ it("toggle adds an absent id and removes a present one, without mutating the input", () => {+ const initial = new Set(["a"]);+ const withB = togglePinnedSession(initial, "b");+ expect(withB).toEqual(new Set(["a", "b"]));+ expect(initial.has("b")).toBe(false); // input untouched (React state discipline)+ expect(togglePinnedSession(withB, "a")).toEqual(new Set(["b"]));+ });++ it("remove prunes a pinned id and returns the SAME set when it wasn't pinned (delete-path fast exit)", () => {+ const pins: ReadonlySet<string> = new Set(["a", "b"]);+ expect(removePinnedSession(pins, "a")).toEqual(new Set(["b"]));+ expect(removePinnedSession(pins, "zzz")).toBe(pins); // same reference: caller skips state + storage writes+ });+});++describe("pinned ordering composes with the group lists", () => {+ it("the pinned cluster tops a group's active rows, each partition keeping its own order; stale ids are inert", () => {+ const rows = [+ session("s1"),+ session("s2"),+ session("s3"),+ session("s4", { archived: true }),+ session("s5", { source: "subagent" }),+ ];+ // Both grouping modes feed the shared group body the same way: partition first,+ // then pinnedFirst over the ACTIVE rows only (pinning is an active-list priority).+ const parts = partitionSessions(rows);+ const pins = new Set(["s3", "deleted-elsewhere"]);+ const active = pinnedFirst(parts.active, (s) => s.sessionId, pins);+ expect(active.map((s) => s.sessionId)).toEqual(["s3", "s1", "s2"]);+ // Folder rows keep chronological order and membership regardless of pins …+ expect(parts.archived.map((s) => s.sessionId)).toEqual(["s4"]);+ expect(parts.subagent.map((s) => s.sessionId)).toEqual(["s5"]);+ // … and a stored id of a Session deleted elsewhere never surfaces a row.+ expect(active.some((s) => s.sessionId === "deleted-elsewhere")).toBe(false);+ });++ it("no pins = the group's original order, untouched", () => {+ const rows = [session("s1"), session("s2")];+ const active = pinnedFirst(partitionSessions(rows).active, (s) => s.sessionId, new Set());+ expect(active.map((s) => s.sessionId)).toEqual(["s1", "s2"]);+ });+});diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.tsindex 96e619a5..abd4d404 100644--- a/packages/web/test/session-grouping.test.ts+++ b/packages/web/test/session-grouping.test.ts@@ -14,6 +14,7 @@ import {SIDEBAR_PAGE_SIZE,TEMP_WORKSPACE_GROUP_KEY,aggregateWorkspaceCounts,+ matchesSessionQuery,groupSessionsByWorkspace,isTempWorkspace,latestConversation,@@ -349,3 +350,28 @@ describe("pinnedFirst (stable pinned-before-unpinned partition)", () => {]);});});++describe("matchesSessionQuery (sidebar live title search)", () => {+ const titled = (title: string): SessionInfo => ({+ ...session("/w", "2026-08-13T00:00:00Z"),+ title,+ });++ it("matches case-insensitive substrings of the title, ignoring surrounding whitespace in the query", () => {+ const s = titled("Fix login bug");+ expect(matchesSessionQuery(s, "login")).toBe(true);+ expect(matchesSessionQuery(s, "FIX")).toBe(true);+ expect(matchesSessionQuery(s, " bug ")).toBe(true);+ expect(matchesSessionQuery(s, "logout")).toBe(false);+ });++ it("a blank or whitespace-only query matches everything (search inactive)", () => {+ expect(matchesSessionQuery(titled("anything"), "")).toBe(true);+ expect(matchesSessionQuery(titled("anything"), " ")).toBe(true);+ expect(matchesSessionQuery(session("/w", "2026-08-13T00:00:00Z"), "")).toBe(true);+ });++ it("untitled Sessions never match a non-empty query (no stored title to search)", () => {+ expect(matchesSessionQuery(session("/w", "2026-08-13T00:00:00Z"), "new")).toBe(false);+ });+});diff --git a/packages/web/test/session-order.test.ts b/packages/web/test/session-order.test.tsnew file mode 100644index 00000000..d741b78c--- /dev/null+++ b/packages/web/test/session-order.test.ts@@ -0,0 +1,285 @@+/**+ * session-order.ts unit tests: the sidebar's row sort mode and manual drag order. The+ * sort mode is one global preference defaulting to "recent" (a fresh profile looks+ * unchanged); the manual order is one per-Project id array where only the relative+ * order of ids co-rendered in a partition matters. Ordering composes with the row+ * pins: the pinned cluster is always first, manual order applies within each pin+ * partition independently, and a drop commits the partition's sequence to the front+ * of the stored array without disturbing other groups' relative order. Newcomers+ * (ids not stored) surface at the TOP of their partition in recency order; stale+ * stored ids are inert; deletion prunes with a same-reference fast path.+ */+import { describe, expect, it } from "vitest";+import {+ SESSION_SORT_MODE_KEY,+ applyManualOrder,+ applyManualReorder,+ initialSessionSortMode,+ loadSessionOrder,+ moveInSequence,+ orderSessionRows,+ removeFromSessionOrder,+ saveSessionOrder,+ sessionOrderKey,+ storeSessionSortMode,+} from "../src/lib/session-order";+import type { SessionOrderStorage } from "../src/lib/session-order";++/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */+function memStorage(): SessionOrderStorage & { map: Map<string, string> } {+ const map = new Map<string, string>();+ return {+ map,+ getItem: (k) => map.get(k) ?? null,+ setItem: (k, v) => void map.set(k, v),+ };+}++const id = (x: string) => x;++describe("sort-mode store (one global preference)", () => {+ it("default is recent: nothing stored, unrecognized values, and throwing storage all read as recent", () => {+ const s = memStorage();+ expect(initialSessionSortMode(s)).toBe("recent");+ for (const raw of ["", "MANUAL", "drag", "true"]) {+ s.map.set(SESSION_SORT_MODE_KEY, raw);+ expect(initialSessionSortMode(s)).toBe("recent");+ }+ const broken: SessionOrderStorage = {+ getItem: () => {+ throw new Error("denied");+ },+ setItem: () => {+ throw new Error("denied");+ },+ };+ expect(initialSessionSortMode(broken)).toBe("recent");+ expect(() => storeSessionSortMode("manual", broken)).not.toThrow();+ });++ it("round-trips manual and back", () => {+ const s = memStorage();+ storeSessionSortMode("manual", s);+ expect(s.map.get(SESSION_SORT_MODE_KEY)).toBe("manual");+ expect(initialSessionSortMode(s)).toBe("manual");+ storeSessionSortMode("recent", s);+ expect(initialSessionSortMode(s)).toBe("recent");+ });+});++describe("manual-order store (per-Project × grouping-mode localStorage)", () => {+ it("nothing stored — or no Project yet — is empty, reading never writes, saving without a Project is a no-op", () => {+ const s = memStorage();+ expect(loadSessionOrder("p1", "workspace", s)).toEqual([]);+ expect(loadSessionOrder(null, "workspace", s)).toEqual([]);+ expect(s.map.size).toBe(0);+ saveSessionOrder(null, "workspace", ["a"], s);+ expect(s.map.size).toBe(0);+ });++ it("save → load round-trips per Project; Projects are isolated", () => {+ const s = memStorage();+ saveSessionOrder("p1", "workspace", ["b", "a"], s);+ saveSessionOrder("p2", "workspace", ["c"], s);+ expect(loadSessionOrder("p1", "workspace", s)).toEqual(["b", "a"]);+ expect(loadSessionOrder("p2", "workspace", s)).toEqual(["c"]);+ expect(loadSessionOrder("p3", "workspace", s)).toEqual([]);+ });++ it("the two grouping modes keep separate orders (their partitions differ, so one array would scramble the other)", () => {+ const s = memStorage();+ saveSessionOrder("p1", "workspace", ["b", "a"], s);+ saveSessionOrder("p1", "agent", ["a", "b"], s);+ expect(loadSessionOrder("p1", "workspace", s)).toEqual(["b", "a"]);+ expect(loadSessionOrder("p1", "agent", s)).toEqual(["a", "b"]);+ expect(sessionOrderKey("p1", "workspace")).not.toBe(sessionOrderKey("p1", "agent"));+ });++ it("malformed JSON / non-array shapes degrade to empty; junk array elements are dropped", () => {+ const s = memStorage();+ for (const raw of ["{not json", '"a"', "42", "null", "{}", ""]) {+ s.map.set(sessionOrderKey("p1", "workspace"), raw);+ expect(loadSessionOrder("p1", "workspace", s)).toEqual([]);+ }+ s.map.set(sessionOrderKey("p1", "workspace"), '["a", 7, null, {"x": 1}, "b"]');+ expect(loadSessionOrder("p1", "workspace", s)).toEqual(["a", "b"]);+ });++ it("storage whose GETTER throws (blocked site data / partitioned iframe) degrades instead of escaping — these run from useState initializers", () => {+ // The throw must be caught even when it comes from resolving the store itself, which+ // is why localStorage is never a default parameter here.+ const hostile = {+ get getItem(): never {+ throw new Error("SecurityError");+ },+ setItem: () => undefined,+ } as unknown as SessionOrderStorage;+ expect(() => loadSessionOrder("p1", "workspace", hostile)).not.toThrow();+ expect(loadSessionOrder("p1", "workspace", hostile)).toEqual([]);+ expect(() => initialSessionSortMode(hostile)).not.toThrow();+ expect(initialSessionSortMode(hostile)).toBe("recent");+ });+});++describe("applyManualOrder", () => {+ it("orders listed rows by their stored position; unlisted newcomers come FIRST keeping recency order", () => {+ // Input arrives newest-first; stored order says c before a; b and d are new.+ expect(applyManualOrder(["b", "a", "d", "c"], id, ["c", "a"])).toEqual(["b", "d", "c", "a"]);+ });++ it("an empty stored order leaves the input order untouched (fresh copy); stale stored ids are inert", () => {+ const rows = ["x", "y"];+ const out = applyManualOrder(rows, id, []);+ expect(out).toEqual(rows);+ expect(out).not.toBe(rows);+ expect(applyManualOrder(["x", "y"], id, ["ghost", "y", "gone"])).toEqual(["x", "y"]);+ });+});++describe("orderSessionRows recency (最近更新 = last ACTIVITY, not creation)", () => {+ /** Rows whose activity order deliberately disagrees with their creation order. */+ const rows = [+ { id: "old-but-busy", createdAt: "2026-01-01T00:00:00Z", lastActiveAt: "2026-08-14T09:00:00Z" },+ { id: "new-but-idle", createdAt: "2026-08-13T00:00:00Z", lastActiveAt: "2026-08-13T00:00:00Z" },+ { id: "middle", createdAt: "2026-06-01T00:00:00Z", lastActiveAt: "2026-08-14T08:00:00Z" },+ ];+ const key = (r: (typeof rows)[number]) => r.id;+ const plain = { pinned: new Set<string>(), order: [] as string[] };++ it("sorts by lastActiveAt desc — the createdAt order the old code produced is NOT the answer", () => {+ const out = orderSessionRows(rows, key, {+ ...plain,+ sortMode: "recent",+ recencyOf: (r) => r.lastActiveAt,+ });+ expect(out.map(key)).toEqual(["old-but-busy", "middle", "new-but-idle"]);+ // Sorting the same rows by creation would put the freshly created idle one on top.+ expect(+ orderSessionRows(rows, key, {+ ...plain,+ sortMode: "recent",+ recencyOf: (r) => r.createdAt,+ }).map(key),+ ).toEqual(["new-but-idle", "middle", "old-but-busy"]);+ });++ it("ties break by key descending (the store's stable tiebreaker) and the input array is never mutated", () => {+ const tied = [+ { id: "a", lastActiveAt: "2026-08-14T09:00:00Z" },+ { id: "c", lastActiveAt: "2026-08-14T09:00:00Z" },+ { id: "b", lastActiveAt: "2026-08-14T09:00:00Z" },+ ];+ const out = orderSessionRows(tied, (r) => r.id, {+ ...plain,+ sortMode: "recent",+ recencyOf: (r) => r.lastActiveAt,+ });+ expect(out.map((r) => r.id)).toEqual(["c", "b", "a"]);+ expect(tied.map((r) => r.id)).toEqual(["a", "c", "b"]); // input untouched+ });++ it("recency also decides where manual-mode newcomers land, and never crosses the pin boundary", () => {+ const out = orderSessionRows(rows, key, {+ pinned: new Set(["new-but-idle"]),+ sortMode: "manual",+ order: ["middle"], // only `middle` has a stored place+ recencyOf: (r) => r.lastActiveAt,+ });+ // Pinned cluster first; among the rest the unlisted newcomer (most recently active)+ // precedes the stored one.+ expect(out.map(key)).toEqual(["new-but-idle", "old-but-busy", "middle"]);+ });++ it("omitting recencyOf keeps the caller's order (the composition tests below rely on it)", () => {+ const out = orderSessionRows(rows, key, { ...plain, sortMode: "recent" });+ expect(out.map(key)).toEqual(["old-but-busy", "new-but-idle", "middle"]);+ });+});++describe("orderSessionRows (pin × sort composition)", () => {+ const pinned = new Set(["p1", "p2"]);++ it("recent mode is exactly pinnedFirst: pinned cluster first, each partition keeping input order", () => {+ const out = orderSessionRows(["a", "p2", "b", "p1"], id, {+ pinned,+ sortMode: "recent",+ order: ["b", "a"], // present but ignored in recent mode+ });+ expect(out).toEqual(["p2", "p1", "a", "b"]);+ });++ it("manual mode applies the stored order WITHIN each pin partition; the pin boundary is never crossed", () => {+ const out = orderSessionRows(["a", "p2", "b", "p1"], id, {+ pinned,+ sortMode: "manual",+ // Stored order interleaves pinned and unpinned ids: the cluster split still wins.+ order: ["b", "p1", "a", "p2"],+ });+ expect(out).toEqual(["p1", "p2", "b", "a"]);+ });++ it("manual mode surfaces unlisted newcomers at the top of THEIR partition", () => {+ const out = orderSessionRows(["new1", "a", "pNew", "p1", "b"], id, {+ pinned: new Set(["p1", "pNew"]),+ sortMode: "manual",+ order: ["b", "a", "p1"],+ });+ // Pinned partition: newcomer pNew first, then stored p1; rest: newcomer new1 first, then b, a.+ expect(out).toEqual(["pNew", "p1", "new1", "b", "a"]);+ });+});++describe("moveInSequence / applyManualReorder (drop commit)", () => {+ it("moves the dragged id before or after the target", () => {+ expect(moveInSequence(["a", "b", "c"], "c", "a", false)).toEqual(["c", "a", "b"]);+ expect(moveInSequence(["a", "b", "c"], "a", "c", true)).toEqual(["b", "c", "a"]);+ });++ it("every no-op returns the INPUT reference, so the caller skips the state + storage write", () => {+ const seq: readonly string[] = ["a", "b", "c"];+ expect(moveInSequence(seq, "a", "a", true)).toBe(seq); // self-drop+ expect(moveInSequence(seq, "zzz", "a", true)).toBe(seq); // dragged id absent+ expect(moveInSequence(seq, "a", "zzz", true)).toBe(seq); // target absent+ // Landing exactly where the row already sat, from either side of the neighbour.+ expect(moveInSequence(seq, "a", "b", false)).toBe(seq);+ expect(moveInSequence(seq, "b", "a", true)).toBe(seq);+ // A real move still allocates.+ expect(moveInSequence(seq, "c", "a", false)).not.toBe(seq);+ });++ it("a drop commits the FULL partition, so display-capped rows keep their places (the reordering regression)", () => {+ // 15 loaded rows, only 10 visible: committing the visible slice used to drop s11..s15+ // out of the stored order, and applyManualOrder then fronted them as "newcomers".+ const all = Array.from({ length: 15 }, (_, i) => `s${i + 1}`);+ const moved = moveInSequence(all, "s3", "s1", false); // drag s3 above s1+ const stored = applyManualReorder([], moved);+ expect(applyManualOrder(all, id, stored)).toEqual([+ "s3",+ "s1",+ "s2",+ ...all.slice(3), // s4…s15 untouched, none promoted to the top+ ]);+ });++ it("committing a partition sequence fronts it and keeps every other stored id's relative order", () => {+ const stored = ["x", "a", "y", "b", "z"];+ // The partition (a, b) was reordered to (b, a): x/y/z keep their relative order behind it.+ expect(applyManualReorder(stored, ["b", "a"])).toEqual(["b", "a", "x", "y", "z"]);+ });++ it("a drop in one group leaves another group's relative order readable", () => {+ let stored: readonly string[] = ["g1a", "g1b", "g2a", "g2b"];+ stored = applyManualReorder(stored, ["g2b", "g2a"]);+ // Group 2 flipped; group 1's pair still reads g1a before g1b.+ const g1 = applyManualOrder(["g1b", "g1a"], id, stored);+ expect(g1).toEqual(["g1a", "g1b"]);+ });+});++describe("removeFromSessionOrder", () => {+ it("prunes a present id and returns the SAME array when absent (delete-path fast exit)", () => {+ const order: readonly string[] = ["a", "b"];+ expect(removeFromSessionOrder(order, "a")).toEqual(["b"]);+ expect(removeFromSessionOrder(order, "zzz")).toBe(order);+ });+});diff --git a/packages/web/test/workspace-registry.test.ts b/packages/web/test/workspace-registry.test.tsnew file mode 100644index 00000000..94a003a8--- /dev/null+++ b/packages/web/test/workspace-registry.test.ts@@ -0,0 +1,218 @@+/**+ * workspace-registry.ts unit tests: manually-added Workspaces (the header's 新建工作区+ * browse pick) persisted per Project and merged into the sidebar's workspace grouping+ * as EMPTY groups — a picked directory shows up immediately, Sessions or not. Entries+ * are `{ path, alias? }`: the alias (重命名工作区) replaces the basename as the group+ * label — for session-backed groups too — and a blank alias reverts to the basename;+ * loads keep accepting the branch's earlier string-only stored shape. 删除工作区+ * unregisters the entry only (sidebar-side; disk and Sessions untouched — a group with+ * Sessions simply persists as session-derived). Paths normalize (trim + trailing+ * separators dropped, root kept) so picker output dedups against server-resolved+ * Session paths; storage is tolerant of junk; temp-shaped paths never form a group.+ */+import { describe, expect, it } from "vitest";+import {+ loadWorkspaceRegistry,+ mergeRegisteredWorkspaces,+ normalizeWorkspacePath,+ registerWorkspace,+ saveWorkspaceRegistry,+ setWorkspaceAlias,+ unregisterWorkspace,+ workspaceRegistryKey,+} from "../src/lib/workspace-registry";+import type { WorkspaceEntry, WorkspaceRegistryStorage } from "../src/lib/workspace-registry";+import { TEMP_WORKSPACE_GROUP_KEY } from "../src/lib/session-grouping";+import type { WorkspaceGroup } from "../src/lib/session-grouping";++/** In-memory storage (vitest runs in a Node environment, no localStorage; draft-cache.test.ts convention). */+function memStorage(): WorkspaceRegistryStorage & { map: Map<string, string> } {+ const map = new Map<string, string>();+ return {+ map,+ getItem: (k) => map.get(k) ?? null,+ setItem: (k, v) => void map.set(k, v),+ };+}++/** Minimal session-derived group (only the fields the merge reads matter). */+function group(key: string, over: Partial<WorkspaceGroup<{ id: string }>> = {}) {+ return {+ key,+ label: key.split("/").filter(Boolean).pop() ?? "/",+ fullPath: key,+ temp: false,+ sessions: [] as { id: string }[],+ ...over,+ };+}++describe("normalizeWorkspacePath", () => {+ it("trims and drops trailing separators; the filesystem root survives; empty stays empty", () => {+ expect(normalizeWorkspacePath(" /srv/app/ ")).toBe("/srv/app");+ expect(normalizeWorkspacePath("/srv/app///")).toBe("/srv/app");+ expect(normalizeWorkspacePath("C:\\work\\repo\\")).toBe("C:\\work\\repo");+ expect(normalizeWorkspacePath("/")).toBe("/");+ expect(normalizeWorkspacePath(" ")).toBe("");+ });++ it("a win32 DRIVE root keeps its separator (stripping it would make the path drive-relative)", () => {+ // `C:` resolves against the drive's current directory, so the registry would hold a+ // different location than the user picked — and never dedup with Sessions keyed `C:\`.+ expect(normalizeWorkspacePath("C:\\")).toBe("C:\\");+ expect(normalizeWorkspacePath("c:/")).toBe("c:/");+ expect(normalizeWorkspacePath(" D:\\ ")).toBe("D:\\");+ // Deeper win32 paths still lose their trailing separator.+ expect(normalizeWorkspacePath("C:\\work\\")).toBe("C:\\work");+ });+});++describe("registerWorkspace / unregisterWorkspace", () => {+ it("register prepends the normalized pick (newest first) and dedups by normalized form with a same-reference fast exit", () => {+ const empty: readonly WorkspaceEntry[] = [];+ const one = registerWorkspace(empty, "/srv/app/");+ expect(one).toEqual([{ path: "/srv/app" }]);+ const two = registerWorkspace(one, "/srv/beta");+ expect(two.map((e) => e.path)).toEqual(["/srv/beta", "/srv/app"]);+ // Already registered (under a trailing-separator variant) or empty: the INPUT array returns.+ expect(registerWorkspace(two, "/srv/app///")).toBe(two);+ expect(registerWorkspace(two, " ")).toBe(two);+ });++ it("rejects a temporary-workspace path: the merge can never group it, so an entry would be an unremovable ghost", () => {+ const entries: readonly WorkspaceEntry[] = [];+ const temp = "/home/u/.penguin/agents/a/workspaces/tmp-0123abcd";+ expect(registerWorkspace(entries, temp)).toBe(entries);+ expect(registerWorkspace(entries, `${temp}/`)).toBe(entries);+ });++ it("unregister drops the entry — alias and all — and returns the SAME array when the path isn't registered", () => {+ const entries: readonly WorkspaceEntry[] = [{ path: "/a", alias: "Alpha" }, { path: "/b" }];+ expect(unregisterWorkspace(entries, "/a")).toEqual([{ path: "/b" }]);+ expect(unregisterWorkspace(entries, "/zzz")).toBe(entries);+ });+});++describe("setWorkspaceAlias", () => {+ const entries: readonly WorkspaceEntry[] = [{ path: "/a" }, { path: "/b" }];++ it("sets a trimmed alias, clears it on blank (revert to basename), and never mutates the input", () => {+ const named = setWorkspaceAlias(entries, "/a", " My App ");+ expect(named).toEqual([{ path: "/a", alias: "My App" }, { path: "/b" }]);+ expect(entries[0]).toEqual({ path: "/a" }); // input untouched (React state discipline)+ expect(setWorkspaceAlias(named, "/a", " ")).toEqual([{ path: "/a" }, { path: "/b" }]);+ });++ it("same-reference fast exit: unknown path, unchanged alias, or clearing an alias that isn't set", () => {+ expect(setWorkspaceAlias(entries, "/zzz", "X")).toBe(entries);+ expect(setWorkspaceAlias(entries, "/a", "")).toBe(entries);+ const named = setWorkspaceAlias(entries, "/a", "X");+ expect(setWorkspaceAlias(named, "/a", " X ")).toBe(named);+ });+});++describe("persisted registry (per-Project localStorage)", () => {+ it("round-trips entries (alias included) per Project; nothing stored / no Project is empty; reading never writes", () => {+ const s = memStorage();+ expect(loadWorkspaceRegistry("p1", s)).toEqual([]);+ expect(loadWorkspaceRegistry(null, s)).toEqual([]);+ expect(s.map.size).toBe(0);+ saveWorkspaceRegistry(null, [{ path: "/x" }], s);+ expect(s.map.size).toBe(0);+ saveWorkspaceRegistry("p1", [{ path: "/srv/beta", alias: "Beta" }, { path: "/srv/app" }], s);+ saveWorkspaceRegistry("p2", [{ path: "/other" }], s);+ expect(loadWorkspaceRegistry("p1", s)).toEqual([+ { path: "/srv/beta", alias: "Beta" },+ { path: "/srv/app" },+ ]);+ expect(loadWorkspaceRegistry("p2", s)).toEqual([{ path: "/other" }]);+ });++ it("still loads the branch's earlier string-only shape, mixed with entry objects", () => {+ const s = memStorage();+ s.map.set(+ workspaceRegistryKey("p1"),+ '["/old/one/", {"path": "/new/two", "alias": " Two "}, "/old/one"]',+ );+ expect(loadWorkspaceRegistry("p1", s)).toEqual([+ { path: "/old/one" },+ { path: "/new/two", alias: "Two" },+ ]);+ });++ it("malformed values degrade to empty; junk elements and junk aliases are dropped", () => {+ const s = memStorage();+ for (const raw of ["{not json", '"x"', "42", "null", "{}", ""]) {+ s.map.set(workspaceRegistryKey("p1"), raw);+ expect(loadWorkspaceRegistry("p1", s)).toEqual([]);+ }+ s.map.set(+ workspaceRegistryKey("p1"),+ '[7, null, " ", {"alias": "orphan"}, {"path": "/a", "alias": 5}, {"path": "/b", "alias": " "}]',+ );+ expect(loadWorkspaceRegistry("p1", s)).toEqual([{ path: "/a" }, { path: "/b" }]);+ });++ it("storage throwing (quota/private mode): save does not throw, load yields empty", () => {+ const broken: WorkspaceRegistryStorage = {+ getItem: () => {+ throw new Error("denied");+ },+ setItem: () => {+ throw new Error("denied");+ },+ };+ expect(() => saveWorkspaceRegistry("p1", [{ path: "/x" }], broken)).not.toThrow();+ expect(loadWorkspaceRegistry("p1", broken)).toEqual([]);+ });++ 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 WorkspaceRegistryStorage;+ expect(() => loadWorkspaceRegistry("p1", hostile)).not.toThrow();+ expect(loadWorkspaceRegistry("p1", hostile)).toEqual([]);+ });+});++describe("mergeRegisteredWorkspaces", () => {+ it("empty registered groups sort AFTER the session-backed ones, so real conversations keep the capped window", () => {+ // Fronting them pushed every group holding chats behind 更多分组 (10-group cap) as+ // soon as a few Workspaces were registered.+ const groups = [group("/srv/app", { sessions: [{ id: "s1" }] }), group("/srv/beta")];+ const merged = mergeRegisteredWorkspaces(groups, [+ { path: "/new/ws", alias: "Fancy" },+ { path: "/srv/app" },+ { path: "/another" },+ ]);+ expect(merged.map((g) => g.key)).toEqual(["/srv/app", "/srv/beta", "/new/ws", "/another"]);+ // Session-derived groups pass through untouched (same members, same order) …+ expect(merged[0]!.sessions).toEqual([{ id: "s1" }]);+ // … and the registered-only ones follow in registration order, labelled alias ?? basename.+ expect(merged[2]).toMatchObject({ label: "Fancy", fullPath: "/new/ws", temp: false });+ expect(merged[2]!.sessions).toEqual([]);+ expect(merged[3]!.label).toBe("another");+ });++ it("an alias relabels a session-backed group too (the entry dedups away but its name wins)", () => {+ const groups = [group("/srv/app", { sessions: [{ id: "s1" }] })];+ const merged = mergeRegisteredWorkspaces(groups, [{ path: "/srv/app", alias: "Prod" }]);+ expect(merged.map((g) => g.key)).toEqual(["/srv/app"]);+ expect(merged[0]!.label).toBe("Prod");+ expect(merged[0]!.fullPath).toBe("/srv/app"); // tooltip keeps the full path+ });++ it("temp-shaped registered paths never form a group (the merged temp group owns that space); no registrations = groups pass through", () => {+ const tempPath = "/home/u/.penguin/agents/a/workspaces/tmp-0123abcd";+ const groups = [group(TEMP_WORKSPACE_GROUP_KEY, { temp: true, fullPath: null, label: "" })];+ expect(mergeRegisteredWorkspaces(groups, [{ path: tempPath }]).map((g) => g.key)).toEqual([+ TEMP_WORKSPACE_GROUP_KEY,+ ]);+ expect(mergeRegisteredWorkspaces(groups, []).map((g) => g.key)).toEqual([+ TEMP_WORKSPACE_GROUP_KEY,+ ]);+ });+});