A local-first multi-agent app development platform, built on PenguinHarness
feat(web): drag the sidebar's groups into your own order (#440)
Yaowei Zheng5ab93f3d0978
diff --git a/changelog/unreleased/2026-08-24-sidebar-group-order.md b/changelog/unreleased/2026-08-24-sidebar-group-order.mdnew file mode 100644index 00000000..a8392404--- /dev/null+++ b/changelog/unreleased/2026-08-24-sidebar-group-order.md@@ -0,0 +1,49 @@+# Drag the sidebar's groups into your own order++- **Date:** 2026-08-24+- **Type:** feature+- **Scope:** `web`+- **PR:** [#440](https://github.com/Prism-Shadow/penguin-harness/pull/440)++[中文版](2026-08-24-sidebar-group-order.zh.md)++The chat sidebar's groups — the Workspace folders and the Agents — can be dragged into a manual+order, the way the conversation rows inside them already could. The order is kept per Project and+per grouping mode, and it survives a reload.++## Details++- Dragging a group is itself the intent: there is no sort toggle for groups. A Project and mode+ with nothing stored renders exactly the automatic sort it did before — Workspace groups by their+ newest conversation with the merged temporary-workspace group last, Agents in their configured+ order.+- The merged temporary-workspace group drags like any other. Its trailing position remains the+ default; once it has been dragged, the chosen position wins.+- A group with no stored position sorts to the TOP of the list, keeping its automatic order among+ the other unplaced groups, so a Workspace used for the first time or a freshly created Agent does+ not appear at the bottom of a long list.+- The time grouping is excluded: its buckets are last day / last month / earlier, a fixed+ chronological ladder. `group-order.ts` refuses to read or write an order for that mode, so the+ exclusion does not depend on a check at the call site.+- The group order and the conversation-row order are separate arrays under separate storage key+ namespaces (`penguin.groupOrder.<projectId>.<mode>`), so a group drag never disturbs the rows+ inside a group and a row drag never moves a group.+- Group order composes with the existing group pins the way row order composes with the row pins:+ the pinned cluster stays first, and a drop stays inside its own pin partition, so dragging can+ reorder but never pin or unpin.+- The group header is the drag handle and the drop indicator is drawn against the whole group, so+ "below" means after that group and its conversations. Neither costs layout width, and the header+ keeps its actions at phone width.+- The gesture needs a pointer that can drag, so it is offered only where one exists — HTML5+ drag-and-drop never fires from touch. A stored order still applies on a touch device: there is no+ mode to degrade, so a phone renders the arrangement its owner made at a desk.+- A drop splices the dragged group in beside its target within the stored order, over the mode's+ full group list rather than the ten groups the display cap shows. A Workspace group exists only+ once one of its conversations has loaded, so the groups that have not loaded yet keep their+ stored positions rather than being pushed behind the ones on screen.+- Stored keys that match no group are ignored and are never pruned: deciding a group is gone needs+ the mode's complete key set, which the Web App cannot establish — the per-Workspace counts are+ filtered by the "show CLI sessions" preference, and a settled Agent list may be a failed fetch.+ A group that returns under the same key resumes its place. A malformed stored value degrades to+ the automatic sort.+- Manual order applies to the chat sidebar only; the Traces page's Workspace tree is unaffected.diff --git a/changelog/unreleased/2026-08-24-sidebar-group-order.zh.md b/changelog/unreleased/2026-08-24-sidebar-group-order.zh.mdnew file mode 100644index 00000000..43d2ae48--- /dev/null+++ b/changelog/unreleased/2026-08-24-sidebar-group-order.zh.md@@ -0,0 +1,24 @@+# 拖动侧边栏分组,排成自己的顺序++- **Date:** 2026-08-24+- **Type:** feature+- **Scope:** `web`+- **PR:** [#440](https://github.com/Prism-Shadow/penguin-harness/pull/440)++[English](2026-08-24-sidebar-group-order.md)++对话侧边栏的分组——工作区文件夹与 Agent——可以像组内的对话行那样拖动排序。该顺序按 Project 和分组方式分别保存,刷新后仍然保持。++## 细节++- 拖动分组本身就是意图:分组没有额外的排序开关。未存储过顺序的 Project 与分组方式,渲染结果与此前的自动排序完全一致——工作区分组按其最新对话排列、合并后的临时工作区分组排在最后,Agent 按既有顺序排列。+- 合并后的临时工作区分组与其他分组一样可拖动。排在末尾只是默认位置;一旦被拖动过,就以用户选择的位置为准。+- 没有存储位置的分组排在列表**最前**,并在同样未定位的分组之间保持其自动顺序,因此首次使用的工作区或刚创建的 Agent 不会出现在长列表的末尾。+- 按时间分组被排除在外:它的分桶是最近一天/最近一月/更早,是一条固定的时间阶梯。`group-order.ts` 拒绝为该模式读写顺序,因此这一排除不依赖调用处的检查。+- 分组顺序与对话行顺序是两个数组,存储键命名空间也各自独立(`penguin.groupOrder.<projectId>.<mode>`),因此拖动分组不会扰动组内的行,拖动行也不会移动分组。+- 分组顺序与既有的分组置顶的组合方式,同行顺序与行置顶的组合方式一致:置顶的一簇仍在最前,落点始终留在自身所属的置顶分区内,因此拖动只会重排,不会置顶或取消置顶。+- 分组标题栏即拖动手柄,落点指示线画在整个分组上,因此「下方」指的是该分组及其对话之后。两者都不占用布局宽度,标题栏在手机宽度下仍保留其操作按钮。+- 该手势需要能够拖动的指针,因此仅在存在此类指针时提供——HTML5 拖放在触屏上不会触发。已存储的顺序在触屏设备上仍然生效:这里没有需要降级的模式,手机会照常渲染其主人在桌面端排好的顺序。+- 一次落点是把被拖动的分组插入到目标分组旁边,作用范围是该模式的完整分组列表,而不是显示上限展示的那十个分组。工作区分组要等其中一个对话加载后才存在,因此尚未加载的分组会保留既有位置,不会被挤到已显示分组之后。+- 匹配不到分组的存储键会被忽略,且不做清理:判定一个分组已消失需要该模式的完整键集合,而 Web App 无法确立——按工作区计数受「显示 CLI 会话」偏好过滤,Agent 列表加载完成也可能是一次失败的请求。若某分组以同一个键回归,它会恢复原有位置。存储值损坏时退回自动排序。+- 手动顺序只作用于对话侧边栏;Trace 页面的工作区目录树不受影响。diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex d9f30377..dfb40e79 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -56,7 +56,6 @@ import {groupSessionsByWorkspace,matchesSessionQuery,partitionSessions,- pinnedFirst,sessionCategory,totalCategoryCounts,workspaceGroupKey,@@ -94,6 +93,13 @@ import {storeSessionSortMode,} from "../../lib/session-order";import type { SessionSortMode } from "../../lib/session-order";+import {+ commitGroupOrder,+ isOrderableGroupMode,+ loadGroupOrder,+ orderGroups,+ saveGroupOrder,+} from "../../lib/group-order";import { Dropdown } from "../ui/dropdown";import { useRowContextMenu } from "../ui/context-menu";import {@@ -185,6 +191,18 @@ const CLOSE_ICON = "M18 6L6 18M6 6l12 12";*/const SESSION_DRAG_MIME = "application/x-penguin-session-id";+/** Private drag payload type of a group reorder (same reasoning as SESSION_DRAG_MIME: never text/plain). */+const GROUP_DRAG_MIME = "application/x-penguin-group-key";++/**+ * Is the drag in flight one of our group reorders? `types` is readable during dragover+ * (unlike getData), so the payload GROUP_DRAG_MIME carries is what authorizes the drop+ * rather than React state alone: a `dragGroup` left behind by a source header that+ * unmounted mid-drag can no longer make the sidebar swallow an unrelated drag — a file+ * from the desktop, a Session row — paint a phantom drop line, and commit on release.+ */+const isGroupDrag = (e: ReactDragEvent): boolean => e.dataTransfer.types.includes(GROUP_DRAG_MIME);+/** 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)";@@ -374,6 +392,16 @@ export function Sidebar({const [sessionOrder, setSessionOrder] = useState<readonly string[]>(() =>loadSessionOrder(currentProjectId, initialGroupMode()),);+ /**+ * Manual GROUP order (Workspace keys / Agent ids), persisted per Project and grouping+ * mode like the row order. Independent of `sortMode`: dragging a group is itself the+ * intent, so there is no second toggle — an empty array is the identity and the list+ * keeps its automatic sort. Empty in time mode, whose buckets are chronological+ * (group-order.ts).+ */+ const [groupOrder, setGroupOrder] = useState<readonly string[]>(() =>+ loadGroupOrder(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),@@ -408,12 +436,16 @@ export function Sidebar({/** 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);+ /** Group header being dragged (its key) and the current group drop hint (target group + which edge). */+ const [dragGroup, setDragGroup] = useState<string | null>(null);+ const [groupDropHint, setGroupDropHint] = useState<{ key: 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));+ setGroupOrder(loadGroupOrder(currentProjectId, groupMode));setRegisteredWorkspaces(loadWorkspaceRegistry(currentProjectId));setGroupCap(SIDEBAR_GROUP_PAGE_SIZE);// eslint-disable-next-line react-hooks/exhaustive-deps@@ -446,6 +478,7 @@ export function Sidebar({// 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));+ setGroupOrder(loadGroupOrder(currentProjectId, mode));setGroupCap(SIDEBAR_GROUP_PAGE_SIZE);};@@ -468,15 +501,36 @@ export function Sidebar({[workspaceCountsByAgent],);- // Pinned groups first within each mode; inside each partition the existing order is kept- // (recency for Workspace groups, the configured Agent order for Agents).+ // Pinned groups first within each mode, then the manual drag order within each pin+ // partition. Nothing dragged yet = an empty order = the automatic sort untouched+ // (recency for Workspace groups with the temp group last, the configured Agent order+ // for Agents), which is also what a group with no stored place falls back to.+ // The stored array belongs to the mode it was loaded for: handing an Agent list an+ // order of Workspace keys is a no-op only as long as the two key namespaces cannot+ // collide, and it costs the empty-order fast path on every render of the other mode.const orderedAgents = useMemo(- () => pinnedFirst(agents, (a) => a.agentId, pinnedGroups),- [agents, pinnedGroups],+ () =>+ orderGroups(agents, (a) => a.agentId, {+ pinned: pinnedGroups,+ order: groupMode === "agent" ? groupOrder : [],+ }),+ [agents, pinnedGroups, groupOrder, groupMode],);const orderedWorkspaceGroups = useMemo(- () => pinnedFirst(workspaceGroups, (g) => g.key, pinnedGroups),- [workspaceGroups, pinnedGroups],+ () =>+ orderGroups(workspaceGroups, (g) => g.key, {+ pinned: pinnedGroups,+ order: groupMode === "workspace" ? groupOrder : [],+ }),+ [workspaceGroups, pinnedGroups, groupOrder, groupMode],+ );++ // The FULL displayed group sequences a drop commits — every group of the mode, not the+ // `groupCap` slice on screen (see groupDragProps).+ const agentGroupSequence = useMemo(() => orderedAgents.map((a) => a.agentId), [orderedAgents]);+ const workspaceGroupSequence = useMemo(+ () => orderedWorkspaceGroups.map((g) => g.key),+ [orderedWorkspaceGroups],);/** Group key a Session's FOLDERS hang off under the current mode (the archived-open state); time mode keeps one shared set for the whole Project. */@@ -583,6 +637,112 @@ export function Sidebar({saveSessionOrder(currentProjectId, groupMode, next);};+ /**+ * Drop of a group drag: splice the dragged group in beside its target and persist.+ *+ * `sequence` is the mode's FULL rendered key list — every group of the mode, not the+ * `groupCap` slice on screen — and commitGroupOrder folds it into the stored array+ * where those groups already render, so a Workspace whose Sessions have not paged in+ * yet keeps its stored place instead of being pushed behind the ones that have.+ *+ * Nothing prunes here. Deciding a stored key is DEAD needs the mode's complete live+ * key set, and this component cannot prove one — the per-Workspace counts that look+ * like a proof are filtered by the "show CLI sessions" preference, and a settled Agent+ * fetch may simply have failed. Stale keys are inert (group-order.ts), so the cost of+ * keeping them is a map entry; the cost of a wrong proof is an arrangement the user+ * cannot get back.+ */+ const commitGroupDrop = (sequence: readonly string[], targetKey: string, after: boolean) => {+ if (dragGroup === null) return;+ const next = commitGroupOrder(groupOrder, sequence, dragGroup, targetKey, after);+ // Identity guard, as for rows: a drop that changes nothing must not persist a fresh array.+ if (next === groupOrder) return;+ setGroupOrder(next);+ saveGroupOrder(currentProjectId, groupMode, next);+ };++ /**+ * Drag-reorder wiring of one group header, given the mode's FULL ordered key list+ * (not the `groupCap` slice on screen — committing only the visible groups would drop+ * the hidden ones out of the stored sequence and bring them back as newcomers).+ *+ * Offered only where the groups have an order to change (isOrderableGroupMode: time+ * mode's buckets are a fixed chronological ladder), never on a search-filtered view,+ * and only where a pointer that can drag exists — HTML5 drag-and-drop never fires+ * from touch. A stored order still APPLIES on such a device: unlike the rows' global+ * sort mode, a group order is per Project and implicit, so there is nothing to+ * degrade — a phone renders the arrangement its owner made at a desk.+ *+ * A drop stays inside the dragged group's own pin partition, so dragging can reorder+ * but never pin or unpin (the rows' rule, one axis up).+ */+ const groupDragProps = (key: string, sequence: readonly string[]) => {+ if (!canDrag || searching || !isOrderableGroupMode(groupMode)) {+ return { header: {}, dropEdge: null as "above" | "below" | null };+ }+ const dragging = dragGroup;+ const samePartition =+ dragging !== null && dragging !== key && pinnedGroups.has(dragging) === pinnedGroups.has(key);+ /** Which half of the header the pointer is in — the edge the drop would land on. */+ const edgeOf = (e: ReactDragEvent) => {+ const rect = e.currentTarget.getBoundingClientRect();+ return e.clientY - rect.top > rect.height / 2;+ };+ return {+ header: {+ draggable: true,+ onDragStart: (e: ReactDragEvent) => {+ e.dataTransfer.setData(GROUP_DRAG_MIME, key);+ e.dataTransfer.effectAllowed = "move" as const;+ setDragGroup(key);+ },+ onDragEnd: () => {+ setDragGroup(null);+ setGroupDropHint(null);+ },+ onDragOver: (e: ReactDragEvent) => {+ if (!samePartition || !isGroupDrag(e)) return;+ e.preventDefault();+ // preventDefault alone only says "a drop may land here"; the effect still has+ // to be one effectAllowed permits, or a modifier held during the drag resolves+ // it to "none" and the drop event never fires (drop-zone.tsx sets it too).+ e.dataTransfer.dropEffect = "move";+ const after = edgeOf(e);+ setGroupDropHint((prev) =>+ prev?.key === key && prev.after === after ? prev : { key, after },+ );+ },+ // dragleave also fires when the pointer merely crosses onto one of the header's+ // OWN children — the collapse toggle spans most of the row, and up to three+ // action buttons follow it — so clearing unconditionally strobes the indicator.+ // relatedTarget is where the drag is going: still inside means nothing changed+ // (the idiom features/chat/drop-zone.tsx already uses).+ onDragLeave: (e: ReactDragEvent) => {+ const to = e.relatedTarget;+ if (to instanceof Node && e.currentTarget.contains(to)) return;+ setGroupDropHint((prev) => (prev?.key === key ? null : prev));+ },+ onDrop: (e: ReactDragEvent) => {+ if (!samePartition || dragging === null || !isGroupDrag(e)) return;+ e.preventDefault();+ // The FULL sequence, not the drag's pin partition: commitGroupOrder splices+ // within one array, and samePartition has already refused a cross-boundary+ // drop, so filtering here would only hide the other partition's keys from the+ // splice and cost them their stored positions.+ commitGroupDrop(sequence, key, edgeOf(e));+ setDragGroup(null);+ setGroupDropHint(null);+ },+ },+ dropEdge:+ samePartition && groupDropHint?.key === key+ ? groupDropHint.after+ ? ("below" as const)+ : ("above" as const)+ : null,+ };+ };+/** Parked drafts through the live search (matched on their first-line title). */const shownDrafts = searching? draftEntries.filter((e) =>@@ -1605,10 +1765,12 @@ export function Sidebar({const parts = partitionSessions(groupRows);const collapsed = !searching && collapsedGroups.has(agent.agentId);const pinned = pinnedGroups.has(agent.agentId);+ const drag = groupDragProps(agent.agentId, agentGroupSequence);return (- <div key={agent.agentId} className="pt-2.5">- {/* Group header: collapse toggle (Agent name) + pin + new chat + Agent settings. */}+ <GroupBlock key={agent.agentId} dropEdge={drag.dropEdge}>+ {/* Group header: collapse toggle (Agent name) + pin + new chat + Agent settings; also the group's drag handle. */}<GroupHeader+ {...drag.header}open={!collapsed}onToggle={() => toggleGroup(agent.agentId)}icon={@@ -1655,7 +1817,7 @@ export function Sidebar({countsByAgent.get(agent.agentId),() => [agent.agentId],)}- </div>+ </GroupBlock>);}))@@ -1679,6 +1841,7 @@ export function Sidebar({const parts = partitionSessions(groupRows);const collapsed = !searching && collapsedGroups.has(group.key);const pinned = pinnedGroups.has(group.key);+ const drag = groupDragProps(group.key, workspaceGroupSequence);/** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */const counts = workspaceGroupCounts.get(group.key);const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];@@ -1686,12 +1849,13 @@ export function Sidebar({...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),];return (- <div key={group.key} className="pt-2.5">+ <GroupBlock key={group.key} dropEdge={drag.dropEdge}>{/* 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. */}+ pin + new chat in this Workspace; also the group's drag handle. */}<GroupHeader+ {...drag.header}open={!collapsed}onToggle={() => toggleGroup(group.key)}icon={@@ -1745,7 +1909,7 @@ export function Sidebar({{collapsed? null: renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}- </div>+ </GroupBlock>);}))}@@ -2162,6 +2326,39 @@ function DraftRow({);}+/**+ * One group's block — its header and body — carrying the manual group order's drop+ * indicator: a thin accent line in the gap the drop would land in, drawn against the+ * WHOLE group rather than its header, so "below" reads as "after this group and its+ * conversations" instead of "between the header and its own first row".+ *+ * The line is absolutely positioned and `inset-x-1` (matching the header's `px-1`), so+ * it consumes no layout width and cannot push the header's up-to-three action buttons+ * out of a narrow drawer.+ */+function GroupBlock({+ dropEdge,+ children,+}: {+ /** Which edge of this group a drop would land on while a group drag hovers it. */+ dropEdge: "above" | "below" | null;+ children: ReactNode;+}) {+ return (+ <div className="relative pt-2.5">+ {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-1" : "-bottom-1"+ }`}+ />+ )}+ {children}+ </div>+ );+}+/*** Group-header pin toggle, shared by both grouping modes: revealed on header hover (or* keyboard focus) while unpinned; once pinned it stays visible, doubling as the subtlediff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsxindex 36f2e0b0..6574a1f5 100644--- a/packages/web/src/components/ui/group-list.tsx+++ b/packages/web/src/components/ui/group-list.tsx@@ -6,7 +6,7 @@* markup and classes here ARE the sidebar's; callers pass the state the closures used* to capture.*/-import type { ReactNode } from "react";+import type { DragEvent as ReactDragEvent, ReactNode } from "react";import { S } from "../../lib/strings";import type { SessionSortMode } from "../../lib/session-order";import { Chevron } from "./chevron";@@ -234,6 +234,12 @@ export function FolderSection({* chevron) stretching across, with optional action buttons trailing outside it. The* toggle's hover pill spans the full row height set by any h-7 actions (self-stretch —* see the sidebar's header comments for where this first bit).+ *+ * The header doubles as the drag handle when the caller makes it draggable (the+ * sidebar's manual group order). The handle is the header rather than the whole group+ * block so that the Session rows inside keep their own row-level drag, and it is the+ * element itself rather than an added grip button so the row costs no extra width —+ * this list is a drawer at phone width and already carries up to three actions.*/export function GroupHeader({open,@@ -244,6 +250,12 @@ export function GroupHeader({count,title,actions,+ draggable = false,+ onDragStart,+ onDragEnd,+ onDragOver,+ onDragLeave,+ onDrop,}: {open: boolean;onToggle: () => void;@@ -258,9 +270,26 @@ export function GroupHeader({title?: string;/** Trailing header actions (pin / new chat / settings / import). */actions?: ReactNode;+ /** Manual group order: the header acts as the drag handle (the caller wires the handlers below). */+ draggable?: boolean;+ onDragStart?: (e: ReactDragEvent) => void;+ onDragEnd?: () => void;+ onDragOver?: (e: ReactDragEvent) => void;+ onDragLeave?: (e: ReactDragEvent) => void;+ onDrop?: (e: ReactDragEvent) => void;}) {return (- <div className="group/header flex items-center gap-0.5 px-1 pb-0.5">+ <div+ // cursor-grab while the header is a handle — the SessionRow treatment one axis up.+ // Groups have no sort toggle by design, so the cursor is the only thing on screen+ // that says this row can be dragged at all.+ className={`group/header flex items-center gap-0.5 px-1 pb-0.5${+ draggable ? " cursor-grab" : ""+ }`}+ {...(draggable+ ? { draggable: true, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }+ : {})}+ ><buttontype="button"onClick={onToggle}diff --git a/packages/web/src/lib/file-drop.ts b/packages/web/src/lib/file-drop.tsindex 5985f2bf..27332ae7 100644--- a/packages/web/src/lib/file-drop.ts+++ b/packages/web/src/lib/file-drop.ts@@ -5,8 +5,8 @@* attachment intake (after the "+" menu pickers and image paste); everything here is about* deciding, not doing:* - which drags count as file drags at all (`isFileDrag`) — text selections, in-app drags- * such as the sidebar's session reorder (a custom MIME for exactly this reason) and- * dragged page images must never light the overlay;+ * such as the sidebar's session and group reorders (each a custom MIME for exactly this+ * reason) and dragged page images must never light the overlay;* - what the chat area's drop zone should do with one drag event (`dropRegionAction`) —* show the overlay, claim the drag, take the files, or stand aside;* - which staged intake a dropped file belongs to (`splitDroppedFiles`) — images join the@@ -28,7 +28,8 @@/*** True when a drag carries OS files: `DataTransfer.types` contains `"Files"`. Every other* drag — text selections (`text/plain`), links, dragged `<img>` elements (`text/uri-list`),- * the sidebar's session reorder MIME — lacks it and must be left to its native behavior.+ * the sidebar's session-reorder and group-reorder MIMEs — lacks it and must be left to its+ * native behavior.* Accepts null/undefined because `dataTransfer` is nullable on the DOM event type.*/export function isFileDrag(types: readonly string[] | null | undefined): boolean {diff --git a/packages/web/src/lib/group-order.ts b/packages/web/src/lib/group-order.tsnew file mode 100644index 00000000..9ef3632d--- /dev/null+++ b/packages/web/src/lib/group-order.ts@@ -0,0 +1,172 @@+/**+ * Manual order of the sidebar's GROUPS — the Workspace folders and the Agents the+ * conversation list is cut into (pure decisions, unit tested). The row-level counterpart+ * is session-order.ts, whose sequence algebra this module reuses rather than restates:+ * `orderWithinPinPartitions` renders the order, `moveInSequence` performs a drop, and+ * `readStringArray` / `writeStringArray` are the storage body. What differs is the key+ * namespace, which modes may be ordered, that there is no sort-mode switch — and how a+ * drop is committed (commitGroupOrder, below).+ *+ * - **Implicit mode.** Dragging a group IS the intent — there is no second toggle beside+ * the rows' `recent | manual` one. A Project+mode with nothing stored keeps the+ * automatic sort untouched (an empty order is the identity), so a fresh profile looks+ * exactly as it did.+ * - **Workspace and Agent modes only.** The time mode's buckets are a fixed+ * chronological ladder: putting the older bucket above the newer one is not an order+ * anyone can mean. isOrderableGroupMode is the single gate — the store refuses to read+ * or write for "time", so the exclusion cannot be undone by forgetting a check at one+ * call site.+ * - **One array per Project AND grouping mode**, exactly like the rows: the modes cut+ * the list into different groups, so one shared array would let a drag in one mode+ * scramble the other.+ * - **Unknown keys go to the TOP**, keeping their automatic order among themselves —+ * the rule the rows use for new Sessions, so a Workspace used for the first time or a+ * freshly created Agent surfaces instead of hiding at the bottom of a long list.+ *+ * **Stale keys are inert, and nothing prunes them.** A stored key that matches no group+ * is only ever a failed membership lookup (applyManualOrder), so it costs a map entry+ * and changes nothing on screen. Pruning was tried at the drop and removed: deciding a+ * group is *gone* needs the mode's complete live key set, and the client cannot prove+ * one. In Workspace mode the per-Agent `workspaceCounts` look like such a proof but are+ * filtered by the "show CLI sessions" preference (the server builds its row set with+ * `webOnly: !includeCli` before counting), so a Workspace used only from the CLI is+ * absent from a complete-looking picture; in Agent mode `agentsLoading === false` is not+ * proof of a *successful* fetch, and an empty Agent list is indistinguishable from a+ * failed one. A wrong proof silently discards an arrangement the user cannot restore,+ * which is a bad trade against a few hundred short strings in localStorage. If a group+ * ever comes back under the same key it resumes its old place, which is the honest+ * reading of "same key, same group".+ *+ * Ordering composes with the group pins the same way the rows compose with theirs: the+ * pinned cluster renders first and the manual order applies within the pinned cluster+ * and within the rest independently, so a drag can never pin or unpin a group.+ *+ * Storage is injectable (model-group-expansion.ts convention: vitest runs in Node, no+ * localStorage); malformed values degrade to the defaults.+ */+import {+ moveInSequence,+ orderWithinPinPartitions,+ readStringArray,+ writeStringArray,+} from "./session-order";+import type { SessionOrderStorage } from "./session-order";+import type { GroupMode } from "../components/ui/group-list";++/**+ * The grouping modes whose groups can be dragged into a manual order. "time" is+ * deliberately absent — see the header.+ *+ * Deliberately NOT the same declaration as group-list.ts's `TreeGroupMode`, which names+ * the same two modes: that one exists because a Trace-file tree's rows carry no activity+ * timestamp to bucket on, this one because the time buckets are an order nobody can+ * mean. Same set today, different reasons — folding them together would let a change to+ * what a Traces tree can group by silently redefine what the sidebar may store.+ */+export const ORDERABLE_GROUP_MODES = ["workspace", "agent"] as const;+export type OrderableGroupMode = (typeof ORDERABLE_GROUP_MODES)[number];++/**+ * Whether a grouping mode's groups may be reordered at all (the one gate; time mode is+ * excluded). Derived from the list rather than restating it — a hand-written `||` chain+ * lets the exported array and "the single gate" drift, which is the exact failure this+ * gate exists to prevent.+ */+export function isOrderableGroupMode(mode: GroupMode): mode is OrderableGroupMode {+ return (ORDERABLE_GROUP_MODES as readonly GroupMode[]).includes(mode);+}++/** Minimal storage interface, shared with session-order.ts; tests inject an in-memory implementation. */+export type GroupOrderStorage = SessionOrderStorage;++/**+ * Storage key of one Project's manual GROUP order (sidebar key-naming convention,+ * `penguin.sessionOrder.<projectId>.<mode>` &c.), scoped by grouping mode for the same+ * reason the row order is: the modes have unrelated group lists.+ */+export const groupOrderKey = (projectId: string, mode: OrderableGroupMode): string =>+ `penguin.groupOrder.${projectId}.${mode}`;++/**+ * Reads a Project+mode's manual group order. No Project, an unorderable mode, nothing+ * stored, or corrupted storage all degrade to empty — which is the identity for+ * orderGroups, i.e. today's automatic sort. Junk array elements are dropped.+ */+export function loadGroupOrder(+ projectId: string | null,+ mode: GroupMode,+ storage?: GroupOrderStorage,+): string[] {+ if (projectId === null || !isOrderableGroupMode(mode)) return [];+ return readStringArray(groupOrderKey(projectId, mode), storage);+}++/** Writes a Project+mode's manual group order on every drop; an unorderable mode writes nothing. */+export function saveGroupOrder(+ projectId: string | null,+ mode: GroupMode,+ order: readonly string[],+ storage?: GroupOrderStorage,+): void {+ if (projectId === null || !isOrderableGroupMode(mode)) return;+ writeStringArray(groupOrderKey(projectId, mode), order, storage);+}++/**+ * The group-ordering pipeline, mirroring orderSessionRows one axis up:+ *+ * 1. the caller's automatic order arrives as the input (Workspace groups by their newest+ * Session with the temp group forced last, Agents in their configured order) — it+ * decides where groups with no stored place sit, and IS the whole answer while+ * nothing is stored;+ * 2. the pinned cluster first, then the stored order within the pinned cluster and+ * within the rest independently (orderWithinPinPartitions), so a drag can never move+ * a group across the pin boundary.+ *+ * An empty `order` returns the pinned-first list unchanged, which is exactly what the+ * sidebar rendered before any group was ever dragged.+ */+export function orderGroups<T>(+ groups: readonly T[],+ keyOf: (group: T) => string,+ opts: { pinned: ReadonlySet<string>; order: readonly string[] },+): T[] {+ return orderWithinPinPartitions(groups, keyOf, opts.pinned, opts.order);+}++/**+ * Commits one group drop into the stored order, as a SPLICE rather than a rewrite.+ *+ * The rows' applyManualReorder moves the dropped partition's sequence to the FRONT of+ * the stored array, which is sound for Sessions because a partition is one group's own+ * list and the ids it displaces are read only within *other* partitions. That does not+ * lift to the group axis: a Workspace group exists only once one of its Sessions has+ * paged in, so the keys a group drop would displace are its own peers — not yet on+ * screen, but ordered against the very groups being committed. Front-loading demoted+ * every unloaded Workspace to the tail, and (because the two pin partitions share one+ * array) it also flung a group the length of the sidebar the moment it was pinned or+ * unpinned.+ *+ * So: materialise the rendered keys into the stored array where they already RENDER —+ * unlisted ones at the front, which is where applyManualOrder puts them — then move the+ * dragged key next to its target inside that array. Keys that are stored but not+ * rendered keep their positions relative to everything else, so a group that has merely+ * not loaded comes back exactly where the user left it.+ *+ * Returns the INPUT array unchanged (same reference) when the drop moves nothing, so the+ * caller can skip the state update and the storage write.+ */+export function commitGroupOrder(+ order: readonly string[],+ rendered: readonly string[],+ dragKey: string,+ targetKey: string,+ after: boolean,+): readonly string[] {+ const stored = new Set(order);+ const materialised = [...rendered.filter((key) => !stored.has(key)), ...order];+ const next = moveInSequence(materialised, dragKey, targetKey, after);+ // moveInSequence hands back its input for every no-op (self-drop, missing key, or a+ // landing that changes nothing): nothing moved, so nothing is worth persisting.+ return next === materialised ? order : next;+}diff --git a/packages/web/src/lib/session-order.ts b/packages/web/src/lib/session-order.tsindex 4ae3b791..0f2d229d 100644--- a/packages/web/src/lib/session-order.ts+++ b/packages/web/src/lib/session-order.ts@@ -72,6 +72,38 @@ export function storeSessionSortMode(mode: SessionSortMode, storage?: SessionOrdexport const sessionOrderKey = (projectId: string, mode: GroupMode): string =>`penguin.sessionOrder.${projectId}.${mode}`;+/**+ * Reads a stored JSON string array, degrading to empty on anything unexpected: nothing+ * stored, malformed JSON, a non-array shape, or storage that throws. Junk elements are+ * dropped. `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 these run from useState initializers — an escaping throw+ * would take the sidebar's first render down. Shared with group-order.ts, which stores+ * the same shape under its own key namespace.+ */+export function readStringArray(key: string, storage?: SessionOrderStorage): string[] {+ try {+ const store = storage ?? localStorage;+ const parsed: unknown = JSON.parse(store.getItem(key) ?? "[]");+ return Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === "string") : [];+ } catch {+ return [];+ }+}++/** Writes a JSON string array, best-effort (quota limits / private browsing fail silently). Shared with group-order.ts. */+export function writeStringArray(+ key: string,+ value: readonly string[],+ storage?: SessionOrderStorage,+): void {+ try {+ (storage ?? localStorage).setItem(key, JSON.stringify(value));+ } catch {+ /* best-effort persistence (quota limits / private browsing) */+ }+}+/** 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,@@ -79,13 +111,7 @@ export function loadSessionOrder(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 [];- }+ return readStringArray(sessionOrderKey(projectId, mode), storage);}/** Writes a Project+mode's manual order on every drop (best-effort: quota limits / private browsing fail silently). */@@ -96,11 +122,7 @@ export function saveSessionOrder(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) */- }+ writeStringArray(sessionOrderKey(projectId, mode), order, storage);}/**@@ -122,6 +144,32 @@ export function applyManualOrder<T>(return [...unlisted, ...listed];}+/**+ * Applies a manual order WITHIN each pin partition: the pinned cluster renders first+ * (pinnedFirst), then the stored sequence is applied to the pinned cluster and to the+ * rest independently — so a drag can reorder but can never move an item across the pin+ * boundary. An empty `order` is the identity: the pinned-first list, untouched.+ *+ * The rows (orderSessionRows, below) and the sidebar's GROUPS (group-order.ts's+ * orderGroups) are the same operation one axis apart, so it lives here once. What+ * differs between them is upstream of this call — the rows sort by recency first and+ * gate on an explicit sort mode, the groups arrive in their own automatic order and have+ * no toggle — and that stays with each caller.+ */+export function orderWithinPinPartitions<T>(+ items: readonly T[],+ keyOf: (item: T) => string,+ pinned: ReadonlySet<string>,+ order: readonly string[],+): T[] {+ if (order.length === 0) return pinnedFirst(items, keyOf, pinned);+ // pinnedFirst's concat would be undone by the two filters below (it preserves input+ // order within each partition), so the manual path splits the input directly.+ const pin = items.filter((item) => pinned.has(keyOf(item)));+ const rest = items.filter((item) => !pinned.has(keyOf(item)));+ return [...applyManualOrder(pin, keyOf, order), ...applyManualOrder(rest, keyOf, order)];+}+/*** The full row-ordering pipeline of one group's active list:*@@ -155,14 +203,13 @@ export function orderSessionRows<T>((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),- ];+ // Recent mode passes an empty order, which is orderWithinPinPartitions's identity.+ return orderWithinPinPartitions(+ byRecency,+ keyOf,+ opts.pinned,+ opts.sortMode === "manual" ? opts.order : [],+ );}/**diff --git a/packages/web/test/file-drop.test.ts b/packages/web/test/file-drop.test.tsindex 07fd5362..b45f4b90 100644--- a/packages/web/test/file-drop.test.ts+++ b/packages/web/test/file-drop.test.ts@@ -30,8 +30,9 @@ describe("isFileDrag", () => {it("ignores every non-file drag: text selections, links, in-app drags", () => {expect(isFileDrag(["text/plain"])).toBe(false);expect(isFileDrag(["text/uri-list", "text/html"])).toBe(false);- // The sidebar's session reorder uses a private MIME precisely so nothing else reacts.+ // The sidebar's two reorder drags each use a private MIME precisely so nothing else reacts.expect(isFileDrag(["application/x-penguin-session-id"])).toBe(false);+ expect(isFileDrag(["application/x-penguin-group-key"])).toBe(false);expect(isFileDrag([])).toBe(false);});diff --git a/packages/web/test/group-order.test.ts b/packages/web/test/group-order.test.tsnew file mode 100644index 00000000..22d41059--- /dev/null+++ b/packages/web/test/group-order.test.ts@@ -0,0 +1,396 @@+/**+ * group-order.ts unit tests: the sidebar's manual order of the GROUPS themselves+ * (Workspace folders / Agents), one axis up from session-order.ts's row order.+ *+ * The mode is implicit — there is no second sort toggle — so an empty stored order must+ * be the identity: a Project that has never been dragged keeps the automatic sort+ * exactly. Beyond that: one array per Project AND grouping mode, "time" refused at the+ * store because its buckets are a fixed chronological ladder, groups with no stored+ * place surfacing at the TOP (including the merged temporary-workspace group, which is+ * otherwise forced last), stale keys inert, and pruning gated on a complete live set.+ */+import { describe, expect, it } from "vitest";+import {+ ORDERABLE_GROUP_MODES,+ commitGroupOrder,+ groupOrderKey,+ isOrderableGroupMode,+ loadGroupOrder,+ orderGroups,+ saveGroupOrder,+} from "../src/lib/group-order";+import type { GroupOrderStorage } from "../src/lib/group-order";+import { moveInSequence } from "../src/lib/session-order";+import {+ TEMP_WORKSPACE_GROUP_KEY,+ groupSessionsByWorkspace,+ groupSessionsByTime,+ timeGroupKey,+} from "../src/lib/session-grouping";++/** In-memory storage (vitest runs in a Node environment, no localStorage; session-order.test.ts convention). */+function memStorage(): GroupOrderStorage & { 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;+const noPins = { pinned: new Set<string>() };++/** Minimal row shape groupSessionsByWorkspace needs. */+const row = (workspace: string, createdAt: string) => ({ workspace, createdAt });++describe("orderable modes (time is excluded, at the store)", () => {+ it("exactly Workspace and Agent mode are orderable", () => {+ expect([...ORDERABLE_GROUP_MODES]).toEqual(["workspace", "agent"]);+ expect(isOrderableGroupMode("workspace")).toBe(true);+ expect(isOrderableGroupMode("agent")).toBe(true);+ expect(isOrderableGroupMode("time")).toBe(false);+ });++ it("time mode cannot store an order: saving writes nothing and loading stays empty", () => {+ const s = memStorage();+ saveGroupOrder("p1", "time", ["\0time-earlier", "\0time-day"], s);+ expect(s.map.size).toBe(0);+ expect(loadGroupOrder("p1", "time", s)).toEqual([]);+ });++ it("a value planted under the time-mode key is never read back", () => {+ const s = memStorage();+ // Hand-edited storage, or an older build: the gate is on the mode, so the read never+ // reaches the value. Guards against the gate drifting below the getItem call.+ s.map.set("penguin.groupOrder.p1.time", JSON.stringify(["\u0000time-earlier"]));+ expect(loadGroupOrder("p1", "time", s)).toEqual([]);+ // And the workspace key of the same Project is unaffected either way.+ saveGroupOrder("p1", "workspace", ["/a"], s);+ expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/a"]);+ expect(loadGroupOrder("p1", "time", s)).toEqual([]);+ });++ it("the time buckets keep their fixed chronological ladder — nothing in this module touches them", () => {+ const buckets = groupSessionsByTime(+ [+ { lastActiveAt: "2020-01-01T00:00:00Z" },+ { lastActiveAt: "2026-08-24T11:00:00Z" },+ { lastActiveAt: "2026-08-10T00:00:00Z" },+ ],+ Date.parse("2026-08-24T12:00:00Z"),+ );+ expect(buckets.map((b) => b.bucket)).toEqual(["day", "month", "earlier"]);+ // Even an order naming those keys cannot reach them: time mode never loads one.+ const s = memStorage();+ saveGroupOrder("p1", "time", [timeGroupKey("earlier"), timeGroupKey("day")], s);+ expect(loadGroupOrder("p1", "time", s)).toEqual([]);+ });+});++describe("group-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(loadGroupOrder("p1", "workspace", s)).toEqual([]);+ expect(loadGroupOrder(null, "workspace", s)).toEqual([]);+ expect(s.map.size).toBe(0);+ saveGroupOrder(null, "workspace", ["/a"], s);+ expect(s.map.size).toBe(0);+ });++ it("save → load round-trips per Project; Projects are isolated", () => {+ const s = memStorage();+ saveGroupOrder("p1", "workspace", ["/b", "/a"], s);+ saveGroupOrder("p2", "workspace", ["/c"], s);+ expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/b", "/a"]);+ expect(loadGroupOrder("p2", "workspace", s)).toEqual(["/c"]);+ expect(loadGroupOrder("p3", "workspace", s)).toEqual([]);+ });++ it("the two orderable modes keep separate orders (their group lists are unrelated)", () => {+ const s = memStorage();+ saveGroupOrder("p1", "workspace", ["/b", "/a"], s);+ saveGroupOrder("p1", "agent", ["a2", "a1"], s);+ expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/b", "/a"]);+ expect(loadGroupOrder("p1", "agent", s)).toEqual(["a2", "a1"]);+ expect(groupOrderKey("p1", "workspace")).not.toBe(groupOrderKey("p1", "agent"));+ });++ it("the group order lives under its own key namespace, clear of the row order's", () => {+ expect(groupOrderKey("p1", "workspace")).toBe("penguin.groupOrder.p1.workspace");+ });++ 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(groupOrderKey("p1", "workspace"), raw);+ expect(loadGroupOrder("p1", "workspace", s)).toEqual([]);+ }+ s.map.set(groupOrderKey("p1", "workspace"), '["/a", 7, null, {"x": 1}, "/b"]');+ expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/a", "/b"]);+ });++ it("storage whose GETTER throws (blocked site data / partitioned iframe) degrades instead of escaping — this runs from a useState initializer", () => {+ const hostile = {+ get getItem(): never {+ throw new Error("SecurityError");+ },+ setItem: () => undefined,+ } as unknown as GroupOrderStorage;+ expect(() => loadGroupOrder("p1", "workspace", hostile)).not.toThrow();+ expect(loadGroupOrder("p1", "workspace", hostile)).toEqual([]);+ const broken: GroupOrderStorage = {+ getItem: () => {+ throw new Error("denied");+ },+ setItem: () => {+ throw new Error("denied");+ },+ };+ expect(() => saveGroupOrder("p1", "workspace", ["/a"], broken)).not.toThrow();+ });++ it("with NO storage injected, resolving localStorage is itself inside the try", () => {+ // vitest runs this package in Node, where `localStorage` is not defined at all — the+ // same shape as a browser that throws on touching it (blocked site data, partitioned+ // iframe). Omitting the argument is the only way to reach that branch, and it is the+ // one that runs from the sidebar's useState initializer, where an escaping throw takes+ // the first render down. Resolve it as a default parameter instead and this fails.+ expect(() => loadGroupOrder("p1", "workspace")).not.toThrow();+ expect(loadGroupOrder("p1", "workspace")).toEqual([]);+ expect(() => saveGroupOrder("p1", "workspace", ["/a"])).not.toThrow();+ });+});++describe("orderGroups with nothing stored = today's automatic sort", () => {+ it("workspace groups keep newest-Session-first with the temp group forced last", () => {+ const groups = groupSessionsByWorkspace([+ row("/home/old", "2026-08-01T00:00:00Z"),+ row("/home/agent/workspaces/tmp-0123abcd", "2026-08-23T00:00:00Z"),+ row("/home/new", "2026-08-20T00:00:00Z"),+ ]);+ const auto = groups.map((g) => g.key);+ expect(auto).toEqual(["/home/new", "/home/old", TEMP_WORKSPACE_GROUP_KEY]);+ // Empty order is the identity: the sidebar renders exactly what it did before.+ expect(orderGroups(groups, (g) => g.key, { ...noPins, order: [] }).map((g) => g.key)).toEqual(+ auto,+ );+ });++ it("the pinned cluster still comes first, each partition keeping its automatic order", () => {+ const out = orderGroups(["a", "b", "c", "d"], id, {+ pinned: new Set(["c", "b"]),+ order: [],+ });+ expect(out).toEqual(["b", "c", "a", "d"]);+ });+});++describe("orderGroups with a stored order", () => {+ it("listed groups take their stored position; groups with NO stored place go to the TOP keeping their automatic order", () => {+ // Automatic order is w1, w2, w3, w4; only w3 and w1 have been dragged.+ expect(orderGroups(["w1", "w2", "w3", "w4"], id, { ...noPins, order: ["w3", "w1"] })).toEqual([+ "w2",+ "w4",+ "w3",+ "w1",+ ]);+ });++ it("a dragged order survives unknown and stale keys in storage", () => {+ // "ghost" was a Workspace that lost its last Session; "w9" has not loaded yet.+ const out = orderGroups(["w1", "w2", "w3"], id, {+ ...noPins,+ order: ["ghost", "w3", "w9", "w1", "gone"],+ });+ expect(out).toEqual(["w2", "w3", "w1"]);+ });++ it("the stored order applies WITHIN each pin partition; the pin boundary is never crossed", () => {+ const out = orderGroups(["a", "p2", "b", "p1"], id, {+ pinned: new Set(["p1", "p2"]),+ // The stored sequence interleaves pinned and unpinned keys: the cluster split still wins.+ order: ["b", "p1", "a", "p2"],+ });+ expect(out).toEqual(["p1", "p2", "b", "a"]);+ });++ it("a newly created group surfaces at the top of its own partition rather than hiding at the bottom", () => {+ const out = orderGroups(["fresh", "a", "pFresh", "p1", "b"], id, {+ pinned: new Set(["p1", "pFresh"]),+ order: ["b", "a", "p1"],+ });+ expect(out).toEqual(["pFresh", "p1", "fresh", "b", "a"]);+ });++ it("neither input array is mutated", () => {+ const groups = ["a", "b", "c"];+ const order = ["c", "a"];+ orderGroups(groups, id, { ...noPins, order });+ expect(groups).toEqual(["a", "b", "c"]);+ expect(order).toEqual(["c", "a"]);+ });+});++describe("the merged temporary-workspace group is draggable like any other", () => {+ const groups = groupSessionsByWorkspace([+ row("/home/a", "2026-08-01T00:00:00Z"),+ row("/home/b", "2026-08-20T00:00:00Z"),+ row("/home/agent/workspaces/tmp-0123abcd", "2026-08-23T00:00:00Z"),+ ]);+ const keys = groups.map((g) => g.key);++ it("its forced-last position is only the DEFAULT: dragging it to the front wins", () => {+ expect(keys).toEqual(["/home/b", "/home/a", TEMP_WORKSPACE_GROUP_KEY]);+ // Drag the temp group above /home/b, exactly as the sidebar commits a drop.+ const stored = commitGroupOrder([], keys, TEMP_WORKSPACE_GROUP_KEY, "/home/b", false);+ expect(+ orderGroups(groups, (g) => g.key, { ...noPins, order: stored }).map((g) => g.key),+ ).toEqual([TEMP_WORKSPACE_GROUP_KEY, "/home/b", "/home/a"]);+ });++ it("it can be dropped anywhere, including back into the middle", () => {+ const stored = commitGroupOrder([], keys, TEMP_WORKSPACE_GROUP_KEY, "/home/b", true);+ expect(+ orderGroups(groups, (g) => g.key, { ...noPins, order: stored }).map((g) => g.key),+ ).toEqual(["/home/b", TEMP_WORKSPACE_GROUP_KEY, "/home/a"]);+ });++ it("its key round-trips through storage like any other group key", () => {+ const s = memStorage();+ saveGroupOrder("p1", "workspace", [TEMP_WORKSPACE_GROUP_KEY, "/home/a"], s);+ expect(loadGroupOrder("p1", "workspace", s)).toEqual([TEMP_WORKSPACE_GROUP_KEY, "/home/a"]);+ });+});++describe("commitGroupOrder (a drop is a splice, not a rewrite)", () => {+ it("with nothing stored, the drop records the rendered list in the order it now reads", () => {+ expect(commitGroupOrder([], ["a", "b", "c"], "c", "a", false)).toEqual(["c", "a", "b"]);+ });++ it("a drop that moves nothing returns the INPUT array, so no write happens", () => {+ const order: readonly string[] = ["a", "b", "c"];+ expect(commitGroupOrder(order, ["a", "b", "c"], "a", "a", true)).toBe(order);+ expect(commitGroupOrder(order, ["a", "b", "c"], "a", "b", false)).toBe(order);+ expect(commitGroupOrder(order, ["a", "b", "c"], "b", "a", true)).toBe(order);+ });++ it("a group that has not loaded yet KEEPS its stored place instead of being demoted", () => {+ // A Workspace group exists only once one of its Sessions has paged in, so /w4../w6+ // are stored but not rendered. Dragging among the rendered three must not push them+ // behind the ones on screen.+ const stored = ["/w6", "/w5", "/w4", "/w3", "/w2", "/w1"];+ const rendered = ["/w3", "/w2", "/w1"];+ const next = commitGroupOrder(stored, rendered, "/w1", "/w3", false);+ expect(next).toEqual(["/w6", "/w5", "/w4", "/w1", "/w3", "/w2"]);+ // The drag did what it said on screen …+ expect(orderGroups(rendered, id, { ...noPins, order: next })).toEqual(["/w1", "/w3", "/w2"]);+ // … and the three that were merely unloaded come back exactly where they were.+ expect(orderGroups(["/w6", "/w5", "/w4", ...rendered], id, { ...noPins, order: next })).toEqual(+ ["/w6", "/w5", "/w4", "/w1", "/w3", "/w2"],+ );+ });++ it("a drop commits the FULL group list, so groups past the display cap keep their places", () => {+ // 15 groups, only 10 rendered: the display cap is a render concern, so the caller+ // hands the whole sequence and every key keeps an index.+ const all = Array.from({ length: 15 }, (_, i) => `g${i + 1}`);+ const next = commitGroupOrder([], all, "g3", "g1", false);+ expect(orderGroups(all, id, { ...noPins, order: next })).toEqual([+ "g3",+ "g1",+ "g2",+ ...all.slice(3),+ ]);+ });++ it("groups with no stored place are folded in where they RENDER — at the top", () => {+ // "fresh" has never been dragged, so it renders first; the commit must record that+ // rather than inventing a position for it.+ const next = commitGroupOrder(["b", "a"], ["fresh", "b", "a"], "a", "b", false);+ expect(next).toEqual(["fresh", "a", "b"]);+ expect(orderGroups(["fresh", "b", "a"], id, { ...noPins, order: next })).toEqual([+ "fresh",+ "a",+ "b",+ ]);+ });++ it("pinning and then unpinning does not fling a group down the list", () => {+ // The two pin partitions share one array, so a commit that front-loaded the dragged+ // partition used to bury the other one. Walk the whole gesture.+ let order = commitGroupOrder([], ["A", "B", "C", "D"], "D", "A", false);+ expect(order).toEqual(["D", "A", "B", "C"]);+ const pinnedD = { pinned: new Set(["D"]), order };+ expect(orderGroups(["A", "B", "C", "D"], id, pinnedD)).toEqual(["D", "A", "B", "C"]);+ // Drag C to the top of the UNPINNED cluster while D is pinned.+ order = commitGroupOrder(order, ["D", "A", "B", "C"], "C", "A", false);+ expect(orderGroups(["A", "B", "C", "D"], id, { pinned: new Set(["D"]), order })).toEqual([+ "D",+ "C",+ "A",+ "B",+ ]);+ // Unpin D: it must stay where the user last put it, not fall to the end.+ expect(orderGroups(["A", "B", "C", "D"], id, { ...noPins, order })).toEqual([+ "D",+ "C",+ "A",+ "B",+ ]);+ });++ it("stale keys are carried along untouched — nothing prunes them", () => {+ // A Workspace whose Sessions are all CLI Sessions, or an Agent deleted elsewhere:+ // the client cannot prove a key is dead, so it stays and simply matches nothing.+ const next = commitGroupOrder(["ghost", "w2", "w1"], ["w2", "w1"], "w1", "w2", false);+ expect(next).toEqual(["ghost", "w1", "w2"]);+ expect(orderGroups(["w2", "w1"], id, { ...noPins, order: next })).toEqual(["w1", "w2"]);+ // And if that group ever comes back under the same key, it resumes its place.+ expect(orderGroups(["ghost", "w2", "w1"], id, { ...noPins, order: next })).toEqual([+ "ghost",+ "w1",+ "w2",+ ]);+ });++ it("the underlying move is still the rows' own moveInSequence", () => {+ const seq: readonly string[] = ["a", "b", "c"];+ expect(moveInSequence(seq, "a", "a", true)).toBe(seq);+ expect(moveInSequence(seq, "c", "a", false)).toEqual(["c", "a", "b"]);+ });+});++describe("group order and row order are independent axes", () => {+ it("a group order names only group keys, so committing one cannot touch a row order array", () => {+ const s = memStorage();+ // Same Project, same mode, different key namespaces.+ saveGroupOrder("p1", "workspace", ["/w2", "/w1"], s);+ s.map.set("penguin.sessionOrder.p1.workspace", JSON.stringify(["s2", "s1"]));+ saveGroupOrder("p1", "workspace", ["/w1", "/w2"], s);+ expect(s.map.get("penguin.sessionOrder.p1.workspace")).toBe(JSON.stringify(["s2", "s1"]));+ expect(loadGroupOrder("p1", "workspace", s)).toEqual(["/w1", "/w2"]);+ });++ it("reordering the groups leaves each group's own Session sequence untouched", () => {+ const groups = groupSessionsByWorkspace([+ { workspace: "/w1", createdAt: "2026-08-02T00:00:00Z", sessionId: "s1b" },+ { workspace: "/w1", createdAt: "2026-08-03T00:00:00Z", sessionId: "s1a" },+ { workspace: "/w2", createdAt: "2026-08-01T00:00:00Z", sessionId: "s2a" },+ ]);+ const before = groups.map((g) => g.sessions.map((x) => x.sessionId));+ const reordered = orderGroups(groups, (g) => g.key, { ...noPins, order: ["/w2", "/w1"] });+ expect(reordered.map((g) => g.key)).toEqual(["/w2", "/w1"]);+ // Same group objects, same member sequences — orderGroups only permutes the outer+ // list, so compare each group's sequence by key rather than sorting both sides (which+ // would pass even if a member list had been reversed).+ const byKey = (gs: typeof groups) =>+ Object.fromEntries(gs.map((g) => [g.key, g.sessions.map((x) => x.sessionId)]));+ expect(byKey(reordered)).toEqual(byKey(groups));+ expect(before).toEqual(groups.map((g) => g.sessions.map((x) => x.sessionId)));+ expect(reordered.find((g) => g.key === "/w1")?.sessions.map((x) => x.sessionId)).toEqual([+ "s1a",+ "s1b",+ ]);+ });+});