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.
This commit is contained in:
1 parent
92f844d694
commit
37941aea19
3 files changed
+276
-45
No files matched your search
@@ -16,6 +16,7 @@ import {
|
|||||||
normalizeSnapshotState,
|
normalizeSnapshotState,
|
||||||
tabSessionRows,
|
tabSessionRows,
|
||||||
} from "./session-state";
|
} from "./session-state";
|
||||||
|
import { firstRootSession } from "./session-order";
|
||||||
import { setSessionMeta } from "./history";
|
import { setSessionMeta } from "./history";
|
||||||
import { migrateSessionId } from "./migration";
|
import { migrateSessionId } from "./migration";
|
||||||
import { useChatStore } from "./store";
|
import { useChatStore } from "./store";
|
||||||
@@ -330,7 +331,7 @@ export interface SessionLookup {
|
|||||||
* A non-empty `sessionId` that the loaded list does not contain resolves to
|
* A non-empty `sessionId` that the loaded list does not contain resolves to
|
||||||
* `undefined` — falling back to `sessions[0]` would silently show a different
|
* `undefined` — falling back to `sessions[0]` would silently show a different
|
||||||
* session for an unknown deep link. The first-session fallback stays for the
|
* 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).
|
* (a sub-session row is never the index default).
|
||||||
*
|
*
|
||||||
* @param sessionId Route session id (`undefined` on `/chat`).
|
* @param sessionId Route session id (`undefined` on `/chat`).
|
||||||
@@ -343,7 +344,7 @@ export function useSessionLookup(
|
|||||||
loaded: boolean,
|
loaded: boolean,
|
||||||
): SessionLookup {
|
): SessionLookup {
|
||||||
return useMemo(() => {
|
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);
|
const match = sessions.find((session) => session.sessionId === sessionId);
|
||||||
if (match) return { session: match, missing: false };
|
if (match) return { session: match, missing: false };
|
||||||
return { session: undefined, missing: loaded };
|
return { session: undefined, missing: loaded };
|
||||||
|
|||||||
@@ -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, SessionState>): string | null {
|
||||||
|
const parentId = session.parentId ?? null;
|
||||||
|
if (!parentId || parentId === session.sessionId || !index.has(parentId)) return null;
|
||||||
|
const seen = new Set<string>([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<string | null, SessionState[]>): number {
|
||||||
|
const ownRank = rowTabRank(session);
|
||||||
|
|
||||||
|
let minTab = Infinity;
|
||||||
|
const visited = new Set<string>([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<string, SessionState>();
|
||||||
|
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<string | null, SessionState[]>();
|
||||||
|
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<string, number>();
|
||||||
|
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<string>();
|
||||||
|
|
||||||
|
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];
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { SessionState, Subagent } from "@protocol/types";
|
import type { SessionState, Subagent } from "@protocol/types";
|
||||||
|
|
||||||
|
import { compareSiblings, effectiveParentOf, orderSessions } from "./session-order";
|
||||||
import { sessionTitle, subagentTitle } from "./session-title";
|
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);
|
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, SessionState>): string | null {
|
|
||||||
const parentId = session.parentId ?? null;
|
|
||||||
if (!parentId || parentId === session.sessionId || !index.has(parentId)) return null;
|
|
||||||
const seen = new Set<string>([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.
|
* Build the render tree for one workspace.
|
||||||
*
|
*
|
||||||
* Input order is preserved (never sorted): root sessions and siblings keep the
|
* Input is put into canonical order first (roots by tab rank asc, siblings by
|
||||||
* order the list delivered; a session's synthetic subagent rows follow its real
|
* createdAt desc then id asc, per pi2.nvim `:PiSessions`), and only then grouped:
|
||||||
* child sessions, in manifest order.
|
* 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(
|
export function buildSessionTreeView(
|
||||||
sessions: SessionState[],
|
sessions: SessionState[],
|
||||||
@@ -206,19 +186,18 @@ export function buildSessionTreeView(
|
|||||||
const selectedId = options.selectedId ?? null;
|
const selectedId = options.selectedId ?? null;
|
||||||
const needle = (options.filter ?? "").trim().toLowerCase();
|
const needle = (options.filter ?? "").trim().toLowerCase();
|
||||||
|
|
||||||
|
const ordered = orderSessions(sessions);
|
||||||
const index = new Map<string, SessionState>();
|
const index = new Map<string, SessionState>();
|
||||||
for (const session of sessions) {
|
for (const session of ordered) {
|
||||||
// Duplicate ids (a list/payload race) must not render twice or key twice.
|
index.set(session.sessionId, session);
|
||||||
if (!index.has(session.sessionId)) index.set(session.sessionId, session);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let hiddenByPolicy = 0;
|
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<string | null, SessionState[]>();
|
const childSessions = new Map<string | null, SessionState[]>();
|
||||||
for (const session of sessions) {
|
for (const session of ordered) {
|
||||||
if (index.get(session.sessionId) !== session) continue;
|
const parentId = effectiveParentOf(session, index);
|
||||||
const parentId = effectiveParent(session, index);
|
|
||||||
const siblings = childSessions.get(parentId);
|
const siblings = childSessions.get(parentId);
|
||||||
if (siblings) siblings.push(session);
|
if (siblings) siblings.push(session);
|
||||||
else childSessions.set(parentId, [session]);
|
else childSessions.set(parentId, [session]);
|
||||||
@@ -252,16 +231,42 @@ export function buildSessionTreeView(
|
|||||||
const nextPath = new Set(path).add(session.sessionId);
|
const nextPath = new Set(path).add(session.sessionId);
|
||||||
const children: TreeNode[] = [];
|
const children: TreeNode[] = [];
|
||||||
let hiddenCount = 0;
|
let hiddenCount = 0;
|
||||||
for (const child of childSessions.get(session.sessionId) ?? []) {
|
|
||||||
const node = buildSessionNode(child, depth + 1, nextPath);
|
type SiblingCandidate =
|
||||||
if (node) children.push(node);
|
| { kind: "session"; session: SessionState; id: string; createdAt?: number | null }
|
||||||
else if (activeOnly && needle === "" && child.visible !== false) hiddenCount += 1;
|
| { kind: "subagent"; subagent: Subagent; id: string; createdAt?: number | null };
|
||||||
}
|
|
||||||
for (const subagent of session.subagents ?? []) {
|
const manifestById = new Map((session.subagents ?? []).map((s) => [s.id, s]));
|
||||||
const node = buildSubagentNode(session, subagent, depth + 1, nextPath);
|
|
||||||
if (node) children.push(node);
|
const candidates: SiblingCandidate[] = [
|
||||||
else if (activeOnly && needle === "" && !isSubagentActive(subagent) && subagent.visible !== false) {
|
...(childSessions.get(session.sessionId) ?? []).map((child) => ({
|
||||||
hiddenCount += 1;
|
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)) {
|
if (!keepSession(session, children.length)) {
|
||||||
@@ -299,7 +304,8 @@ export function buildSessionTreeView(
|
|||||||
const nextPath = new Set(path).add(subagent.id);
|
const nextPath = new Set(path).add(subagent.id);
|
||||||
const children: TreeNode[] = [];
|
const children: TreeNode[] = [];
|
||||||
let hiddenCount = 0;
|
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);
|
const node = buildSubagentNode(session, child, depth + 1, nextPath);
|
||||||
if (node) children.push(node);
|
if (node) children.push(node);
|
||||||
else if (activeOnly && needle === "" && !isSubagentActive(child) && child.visible !== false) {
|
else if (activeOnly && needle === "" && !isSubagentActive(child) && child.visible !== false) {
|
||||||
|
|||||||
Reference in new issue
Block a user