From 37941aea198fd92947cacec2f2f3c022f02359f1 Mon Sep 17 00:00:00 2001 From: yuez Date: Tue, 27 Oct 2026 19:08:47 +0800 Subject: [PATCH] feat(web): order the chat session list like :PiSessions The sidebar rendered whatever order the plugin payload happened to carry (disk mtime desc, then Lua hash order). It now mirrors pi2.nvim: - roots ranked by the tab's visual position (`tabRank`, falling back to the `tab` handle), a lineage occupying the earliest tab it occupies; - siblings (real sub-session rows and manifest subagents merged into one list) by `createdAt` desc with the id as tie-break, a session row inheriting its manifest entry's `createdAt`, matching `manifest.lua`; - deterministic code-unit comparisons plus a root tie-break chain, so WS arrivals and payload order can no longer shuffle rows. `session-order.ts` is the single owner of the rule; the tree model renders it and the /chat index default is the sidebar's top root. --- web/src/features/chat/data.ts | 5 +- web/src/features/chat/session-order.ts | 224 ++++++++++++++++++++ web/src/features/chat/session-tree-model.ts | 92 ++++---- 3 files changed, 276 insertions(+), 45 deletions(-) create mode 100644 web/src/features/chat/session-order.ts diff --git a/web/src/features/chat/data.ts b/web/src/features/chat/data.ts index c3141cd..a436324 100644 --- a/web/src/features/chat/data.ts +++ b/web/src/features/chat/data.ts @@ -16,6 +16,7 @@ import { normalizeSnapshotState, tabSessionRows, } from "./session-state"; +import { firstRootSession } from "./session-order"; import { setSessionMeta } from "./history"; import { migrateSessionId } from "./migration"; import { useChatStore } from "./store"; @@ -330,7 +331,7 @@ export interface SessionLookup { * A non-empty `sessionId` that the loaded list does not contain resolves to * `undefined` — falling back to `sessions[0]` would silently show a different * session for an unknown deep link. The first-session fallback stays for the - * `/chat` index (no id), which means "the workspace's most recent root session" + * `/chat` index (no id), which means "the sidebar's top row: the root in canonical order" * (a sub-session row is never the index default). * * @param sessionId Route session id (`undefined` on `/chat`). @@ -343,7 +344,7 @@ export function useSessionLookup( loaded: boolean, ): SessionLookup { return useMemo(() => { - if (!sessionId) return { session: sessions.find((session) => !session.parentId) ?? sessions[0], missing: false }; + if (!sessionId) return { session: firstRootSession(sessions), missing: false }; const match = sessions.find((session) => session.sessionId === sessionId); if (match) return { session: match, missing: false }; return { session: undefined, missing: loaded }; diff --git a/web/src/features/chat/session-order.ts b/web/src/features/chat/session-order.ts new file mode 100644 index 0000000..3b9c511 --- /dev/null +++ b/web/src/features/chat/session-order.ts @@ -0,0 +1,224 @@ +import type { SessionState } from "@protocol/types"; + +/** + * Canonical ordering for workspace session trees in the pi2d web console. + * + * Rules taken from pi2.nvim: + * - Root order: visual tabline position of live attached tabs (`lua/pi/sessions/manager.lua`). + * A lineage occupies the earliest tab slot of the root and all its descendants (`lua/pi/ui/sessions.lua`), + * so in a child view the parent row occupies that tab's slot. + * - Sibling order: children of the same parent (merged real child session rows and + * synthetic manifest subagents) are sorted by `createdAt` DESC (missing last), + * tie-break `id` ASC (`lua/pi/subsessions/manifest.lua`). Real session rows win over + * same-id subagents, but inherit the manifest entry's `createdAt`. + * + * Console-side determinism & edge-case additions: + * - Tie-break chain: `createdAt` DESC (missing last) → `lastActiveAt` DESC (missing last) → + * `sessionId` ASC (plain code-unit comparison). In Neovim each session has at most one + * attached tab and ranks are distinct, so it needs no tie-break; the console defines this + * chain to ensure total, deterministic ordering across WS arrivals. + * - Tab-less roots: Neovim's `Sessions.list()` excludes detached/tab-less sessions entirely. + * The console keeps a tab-less root when it is the parent of a live child-view tab (or + * an orphaned/promoted row); assigning it rank `+Infinity` (placed last) is a console rule. + * - Rank unit: rows prefer `tabRank` (1-based visual tabline position in `nvim_list_tabpages()`), + * falling back to `tab` (creation-ordered tab handle). Handle order diverges from visual order + * after `:tabmove` or mid-tabline insertions (`:PiNewTab` from tab 1). + * - Comparisons are plain code-unit `<`/`>` (never `localeCompare`) and numeric for + * timestamps, guaranteeing total, deterministic ordering. + */ + +export interface SiblingItem { + createdAt?: number | null; + id: string; +} + +/** + * Effective parent id: the parent must exist in `index`, must not point to + * itself, and must not form a parent-pointer cycle. Any invalid parent promotes + * the session to a root so a row is never lost. + */ +export function effectiveParentOf(session: SessionState, index: Map): string | null { + const parentId = session.parentId ?? null; + if (!parentId || parentId === session.sessionId || !index.has(parentId)) return null; + const seen = new Set([session.sessionId]); + let cursor: string | null = parentId; + while (cursor) { + if (seen.has(cursor)) return null; + seen.add(cursor); + const next: string | null = index.get(cursor)?.parentId ?? null; + if (!next || next === cursor) break; + cursor = next; + } + return parentId; +} + +/** + * Sibling comparator: `createdAt` DESC (missing last), tie-break `id` ASC. + * Comparisons are plain string `<`/`>` (never `localeCompare`). + */ +export function compareSiblings(a: SiblingItem, b: SiblingItem): number { + const ca = typeof a.createdAt === "number" && Number.isFinite(a.createdAt) ? a.createdAt : null; + const cb = typeof b.createdAt === "number" && Number.isFinite(b.createdAt) ? b.createdAt : null; + if (ca !== null && cb !== null) { + if (ca !== cb) return cb - ca; + } else if (ca !== null) { + return -1; + } else if (cb !== null) { + return 1; + } + if (a.id < b.id) return -1; + if (a.id > b.id) return 1; + return 0; +} + +function positiveNum(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined; +} + +/** + * Tab position rank for a single row: prefer visual tabline rank (`tabRank`, 1-based + * position in `nvim_list_tabpages()`), fall back to tab handle (`tab`, creation-ordered). + * Visual rank reflects `:tabmove` and mid-tabline insertions; handle is legacy fallback. + */ +function rowTabRank(session: SessionState): number | undefined { + return positiveNum(session.tabRank) ?? positiveNum(session.tab); +} + +/** + * Calculate the rank of a root session: the earliest tab position occupied across + * its whole lineage (root itself and all descendants), or `Infinity` if tab-less. + * pi2.nvim places a lineage at its earliest live tab slot (`lua/pi/ui/sessions.lua`). + */ +function rootRank(session: SessionState, childSessions: Map): number { + const ownRank = rowTabRank(session); + + let minTab = Infinity; + const visited = new Set([session.sessionId]); + const stack = [...(childSessions.get(session.sessionId) ?? [])]; + while (stack.length > 0) { + const child = stack.pop()!; + if (visited.has(child.sessionId)) continue; + visited.add(child.sessionId); + const childRank = rowTabRank(child); + if (childRank !== undefined && childRank < minTab) { + minTab = childRank; + } + for (const grandchild of childSessions.get(child.sessionId) ?? []) { + stack.push(grandchild); + } + } + return Math.min(ownRank ?? Infinity, minTab); +} + +/** + * Compare two root sessions: + * 1. `rank` ASC + * 2. `createdAt` DESC (missing last) + * 3. `lastActiveAt` DESC (missing last) + * 4. `sessionId` ASC (code-unit comparison) + */ +function compareRoots( + a: SessionState, + b: SessionState, + rankA: number, + rankB: number, +): number { + if (rankA !== rankB) { + return rankA - rankB; + } + const ca = typeof a.createdAt === "number" && Number.isFinite(a.createdAt) ? a.createdAt : null; + const cb = typeof b.createdAt === "number" && Number.isFinite(b.createdAt) ? b.createdAt : null; + if (ca !== null && cb !== null) { + if (ca !== cb) return cb - ca; + } else if (ca !== null) { + return -1; + } else if (cb !== null) { + return 1; + } + + const la = typeof a.lastActiveAt === "number" && Number.isFinite(a.lastActiveAt) ? a.lastActiveAt : null; + const lb = typeof b.lastActiveAt === "number" && Number.isFinite(b.lastActiveAt) ? b.lastActiveAt : null; + if (la !== null && lb !== null) { + if (la !== lb) return lb - la; + } else if (la !== null) { + return -1; + } else if (lb !== null) { + return 1; + } + + if (a.sessionId < b.sessionId) return -1; + if (a.sessionId > b.sessionId) return 1; + return 0; +} + +/** + * Flatten sessions into canonical document order: + * Each root (Rule 1: rank ASC, createdAt DESC, lastActiveAt DESC, sessionId ASC) + * followed by its subtree in Rule 3 sibling order (createdAt DESC, id ASC). + * + * Input is deduped by `sessionId` (first wins) and cycle-guarded. + */ +export function orderSessions(sessions: readonly SessionState[]): SessionState[] { + const index = new Map(); + const deduped: SessionState[] = []; + for (const session of sessions) { + if (!session.sessionId || index.has(session.sessionId)) continue; + index.set(session.sessionId, session); + deduped.push(session); + } + if (deduped.length === 0) return []; + + const childSessions = new Map(); + for (const session of deduped) { + const parentId = effectiveParentOf(session, index); + const list = childSessions.get(parentId); + if (list) list.push(session); + else childSessions.set(parentId, [session]); + } + + const roots = [...(childSessions.get(null) ?? [])]; + const ranks = new Map(); + for (const root of roots) { + ranks.set(root.sessionId, rootRank(root, childSessions)); + } + roots.sort((a, b) => compareRoots(a, b, ranks.get(a.sessionId)!, ranks.get(b.sessionId)!)); + + for (const [parentId, children] of childSessions.entries()) { + if (parentId === null) continue; + children.sort((a, b) => + compareSiblings( + { createdAt: a.createdAt, id: a.sessionId }, + { createdAt: b.createdAt, id: b.sessionId }, + ), + ); + } + + const result: SessionState[] = []; + const visited = new Set(); + + function appendSubtree(session: SessionState) { + if (visited.has(session.sessionId)) return; + visited.add(session.sessionId); + result.push(session); + const children = childSessions.get(session.sessionId) ?? []; + for (const child of children) { + appendSubtree(child); + } + } + + for (const root of roots) { + appendSubtree(root); + } + + return result; +} + +/** + * Return the top root session of the sidebar (for the `/chat` index default). + */ +export function firstRootSession(sessions: readonly SessionState[]): SessionState | undefined { + const ordered = orderSessions(sessions); + if (ordered.length === 0) return undefined; + const index = new Map(ordered.map((s) => [s.sessionId, s])); + return ordered.find((s) => effectiveParentOf(s, index) === null) ?? ordered[0]; +} diff --git a/web/src/features/chat/session-tree-model.ts b/web/src/features/chat/session-tree-model.ts index eddc0de..6563324 100644 --- a/web/src/features/chat/session-tree-model.ts +++ b/web/src/features/chat/session-tree-model.ts @@ -1,5 +1,6 @@ import type { SessionState, Subagent } from "@protocol/types"; +import { compareSiblings, effectiveParentOf, orderSessions } from "./session-order"; import { sessionTitle, subagentTitle } from "./session-title"; /** @@ -168,34 +169,13 @@ function matches(label: string, model: string | undefined, needle: string): bool return label.toLowerCase().includes(needle) || (model ?? "").toLowerCase().includes(needle); } -/** - * The parent a row is grouped under, or `null` when it is a root. - * - * A `parentId` that is not in the list is promoted to a root (a filtered-out - * parent must never lose its children), and a cycle is cut by rendering every - * member of the cycle as a root. - */ -function effectiveParent(session: SessionState, index: Map): string | null { - const parentId = session.parentId ?? null; - if (!parentId || parentId === session.sessionId || !index.has(parentId)) return null; - const seen = new Set([session.sessionId]); - let cursor: string | null = parentId; - while (cursor) { - if (seen.has(cursor)) return null; - seen.add(cursor); - const next: string | null = index.get(cursor)?.parentId ?? null; - if (!next || next === cursor) break; - cursor = next; - } - return parentId; -} - /** * Build the render tree for one workspace. * - * Input order is preserved (never sorted): root sessions and siblings keep the - * order the list delivered; a session's synthetic subagent rows follow its real - * child sessions, in manifest order. + * Input is put into canonical order first (roots by tab rank asc, siblings by + * createdAt desc then id asc, per pi2.nvim `:PiSessions`), and only then grouped: + * a session's real child sessions and synthetic manifest subagent rows are merged + * into one sorted sibling list (real child sessions win over same-id subagents). */ export function buildSessionTreeView( sessions: SessionState[], @@ -206,19 +186,18 @@ export function buildSessionTreeView( const selectedId = options.selectedId ?? null; const needle = (options.filter ?? "").trim().toLowerCase(); + const ordered = orderSessions(sessions); const index = new Map(); - for (const session of sessions) { - // Duplicate ids (a list/payload race) must not render twice or key twice. - if (!index.has(session.sessionId)) index.set(session.sessionId, session); + for (const session of ordered) { + index.set(session.sessionId, session); } let hiddenByPolicy = 0; - // Children grouped by their effective parent, in list order. + // Children grouped by their effective parent, in canonical order. const childSessions = new Map(); - for (const session of sessions) { - if (index.get(session.sessionId) !== session) continue; - const parentId = effectiveParent(session, index); + for (const session of ordered) { + const parentId = effectiveParentOf(session, index); const siblings = childSessions.get(parentId); if (siblings) siblings.push(session); else childSessions.set(parentId, [session]); @@ -252,16 +231,42 @@ export function buildSessionTreeView( const nextPath = new Set(path).add(session.sessionId); const children: TreeNode[] = []; let hiddenCount = 0; - for (const child of childSessions.get(session.sessionId) ?? []) { - const node = buildSessionNode(child, depth + 1, nextPath); - if (node) children.push(node); - else if (activeOnly && needle === "" && child.visible !== false) hiddenCount += 1; - } - for (const subagent of session.subagents ?? []) { - const node = buildSubagentNode(session, subagent, depth + 1, nextPath); - if (node) children.push(node); - else if (activeOnly && needle === "" && !isSubagentActive(subagent) && subagent.visible !== false) { - hiddenCount += 1; + + type SiblingCandidate = + | { kind: "session"; session: SessionState; id: string; createdAt?: number | null } + | { kind: "subagent"; subagent: Subagent; id: string; createdAt?: number | null }; + + const manifestById = new Map((session.subagents ?? []).map((s) => [s.id, s])); + + const candidates: SiblingCandidate[] = [ + ...(childSessions.get(session.sessionId) ?? []).map((child) => ({ + kind: "session" as const, + session: child, + id: child.sessionId, + createdAt: manifestById.get(child.sessionId)?.createdAt ?? child.createdAt, + })), + ...(session.subagents ?? []) + .filter((subagent) => !index.has(subagent.id)) + .map((subagent) => ({ + kind: "subagent" as const, + subagent, + id: subagent.id, + createdAt: subagent.createdAt, + })), + ]; + candidates.sort(compareSiblings); + + for (const candidate of candidates) { + if (candidate.kind === "session") { + const node = buildSessionNode(candidate.session, depth + 1, nextPath); + if (node) children.push(node); + else if (activeOnly && needle === "" && candidate.session.visible !== false) hiddenCount += 1; + } else { + const node = buildSubagentNode(session, candidate.subagent, depth + 1, nextPath); + if (node) children.push(node); + else if (activeOnly && needle === "" && !isSubagentActive(candidate.subagent) && candidate.subagent.visible !== false) { + hiddenCount += 1; + } } } if (!keepSession(session, children.length)) { @@ -299,7 +304,8 @@ export function buildSessionTreeView( const nextPath = new Set(path).add(subagent.id); const children: TreeNode[] = []; let hiddenCount = 0; - for (const child of subagent.children ?? []) { + const subChildren = [...(subagent.children ?? [])].sort(compareSiblings); + for (const child of subChildren) { const node = buildSubagentNode(session, child, depth + 1, nextPath); if (node) children.push(node); else if (activeOnly && needle === "" && !isSubagentActive(child) && child.visible !== false) {