diff --git a/docs/protocol.md b/docs/protocol.md index d2ebc60..4b08e37 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -82,7 +82,7 @@ Plugin obligations: | `GET /api/v1/info` | `{v, daemonId, machineId, platform, hostname, os, version, uptimeMs, pid, port, capabilities, limits}` | | `GET /api/v1/health` | `{ok, items:[{name, ok, detail}]}` | | `GET /api/v1/workspaces` | `WorkspaceInfo[]` (registry + disk index + instance state) | -| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` | +| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) | | `GET /api/v1/sessions/:sid/entries?before=&limit=` | relayed; plugin paginates | | `GET /api/v1/attention?workspaceId=` | pending attention for one workspace | | `GET /api/v1/devices` | paired devices (daemon-owned) | @@ -90,6 +90,32 @@ Plugin obligations: | `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice | | `GET /api/v1/diagnostics` | connections, event rates, slow queries, instance table | +Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionState` plus list metadata (`usage`, `flags`, `entries` and `attention` arrive via snapshot/events, not on this row): + +| Field | Notes | +|---|---| +| `sessionId`, `sessionFile?`, `name?`, `cwd?`, `timestamp?`, `modified?`, `firstMessage?` | identity + disk projection | +| `tab?`, `live?` | live projection | +| `status?` | live status when `live` (`busy`, `compacting`, `idle`, `exited`); otherwise the child's manifest status (`dormant`, `done`, `error`, `interrupted`, `exited`). Absent on a non-live root. | +| `model?`, `thinking?` | per-session model pin; the child's manifest thinking level | +| `visible: boolean` | always present; the plugin's `:PiSessions` visibility decision | +| `parentId?: string` | sub-session rows only: the parent session id (normally present in the same list) | +| `task?`, `agentSpawned?`, `reported?` | sub-session rows only, carried through from the spawn request | +| `createdAt?`, `lastActiveAt?` | epoch ms; ordering/aging hints, never required | + +Sub-session rows sit in the same flat list as their parent: build the tree from `parentId` +(an unknown `parentId`, or one whose row was pruned, promotes the row to a root so a row is +never lost). `status` of a non-live child is one of `dormant|done|error|interrupted|exited`; +a live child reports its live status. + +Visibility follows the plugin's `:PiSessions` policy (`visible: false` = hidden), but the +field is advisory: a client may still render hidden rows on request (pi2 web's “show hidden +sub-sessions” toggle) or when the row is the routed/selected session. An active search filter +takes precedence over the routed row in pi2 web (a non-matching row stays out, even when it is +selected). A manifest `pi2:subagents` entry that also has a session row (same id) must render +as that row only — the session row wins. `pi2:subagents` entries may additionally carry +`parentId?`, `visible?`, `createdAt?`, `lastActiveAt?`. + ### 3.2 Commands (writes) `POST /api/v1/cmd` with `{method, params, sessionId?, clientRequestId?}` → `202 {accepted, disposition}`. @@ -136,11 +162,18 @@ interface SessionState { items: { ref: string; name?: string; status: string; error?: string }[]; summary?: { total: number; done: number; ok: number; failed: number; cancelled: number; running: number } }[]; subagents: { id: string; name?: string; status: "active" | "completed" | "failed" | "interrupted" | "dormant"; - model?: string; thinking?: string; task?: string; children?: unknown[] }[]; + model?: string; thinking?: string; task?: string; children?: unknown[]; + parentId?: string; visible?: boolean }[]; attention: { requestId: string; method: string; title?: string; message?: string; options?: { id: string; label: string }[]; payload?: unknown; timeoutSec?: number; createdAt: number; receivedAt: number }[]; entries: Entry[]; + + // List metadata — enriched by the session list (`§3.1`) / snapshot from the + // web client's cached row, never emitted by the reducer. + parentId?: string | null; // null = root (client-side only; the plugin omits the field) + visible?: boolean; // plugin `:PiSessions` visibility decision + task?: string; // subagent task description from the spawn request } type Block = diff --git a/src/protocol/types.ts b/src/protocol/types.ts index 51bb5d1..15a2fd2 100644 --- a/src/protocol/types.ts +++ b/src/protocol/types.ts @@ -131,6 +131,16 @@ export interface Subagent { createdAt?: number; lastActiveAt?: number; live?: boolean; + /** + * List metadata only: the manifest parent (lineage) id of this subagent. + * Never emitted by the reducer. + */ + parentId?: string; + /** + * List metadata only: the plugin's `:PiSessions` visibility decision for this + * subagent (`false` = hidden by default). Never emitted by the reducer. + */ + visible?: boolean; children?: Subagent[]; } @@ -176,6 +186,19 @@ export interface SessionState { subagents: Subagent[]; attention: AttentionItem[]; entries: Entry[]; + /** + * List metadata only (REST session row / snapshot enrichment), never emitted + * by the reducer: the parent session id; `null` marks a root session. + */ + parentId?: string | null; + /** + * List metadata only: the plugin's `:PiSessions` visibility decision for this + * session (`false` = hidden unless the user asks for hidden rows). Never + * emitted by the reducer. + */ + visible?: boolean; + /** List metadata only: the subagent task description carried by the list row. Never emitted by the reducer. */ + task?: string; } /* ------------------------------------------------------------------ */ diff --git a/web/src/features/chat/data.ts b/web/src/features/chat/data.ts index 2d5c306..20055d4 100644 --- a/web/src/features/chat/data.ts +++ b/web/src/features/chat/data.ts @@ -244,12 +244,19 @@ export function useChatSocket(workspaceId: string | undefined, sessionIds: strin setWsState(state); }, onSnapshot: (message) => { - const state = normalizeSnapshotState(message.sessionId, workspaceId, message.payload); + const store = useSessionsStore.getState(); + const state = normalizeSnapshotState( + message.sessionId, + workspaceId, + message.payload, + // The snapshot never carries list metadata (`parentId` / + // `visible` / `task`); the cached row owns it, so pass it in. + store.getSession(message.sessionId), + ); if (!state.entries.length) { const raw = snapshotEntries(message.payload); if (raw.length) state.entries = projectEntries(raw); } - const store = useSessionsStore.getState(); store.upsertSession(state); }, onEvent: (message) => { @@ -316,7 +323,8 @@ 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 session". + * `/chat` index (no id), which means "the workspace's most recent root session" + * (a sub-session row is never the index default). * * @param sessionId Route session id (`undefined` on `/chat`). * @param sessions Sessions of the active workspace. @@ -328,7 +336,7 @@ export function useSessionLookup( loaded: boolean, ): SessionLookup { return useMemo(() => { - if (!sessionId) return { session: sessions[0], missing: false }; + if (!sessionId) return { session: sessions.find((session) => !session.parentId) ?? sessions[0], 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-state.ts b/web/src/features/chat/session-state.ts index ae01c61..85d2ba3 100644 --- a/web/src/features/chat/session-state.ts +++ b/web/src/features/chat/session-state.ts @@ -32,6 +32,9 @@ export interface EmptySessionInput { status?: SessionState["status"]; model?: ModelRef | null; thinking?: ThinkingLevel | null; + parentId?: string | null; + visible?: boolean; + task?: string; } export function emptySessionState(input: EmptySessionInput): SessionState { @@ -53,6 +56,12 @@ export function emptySessionState(input: EmptySessionInput): SessionState { subagents: [], attention: [], entries: [], + // `parentId`/`visible` are list metadata with an `undefined` = "not + // carried" meaning: a fresh/empty state must not clobber the cached + // row's tree position when it is upserted over it. + ...(input.parentId !== undefined ? { parentId: input.parentId } : {}), + ...(input.visible !== undefined ? { visible: input.visible } : {}), + ...(input.task !== undefined ? { task: input.task } : {}), }; } @@ -226,8 +235,19 @@ export function applySessionEvent(state: SessionState, event: SessionEvent): Ses return next; } +/** `parentId` as carried by a list row: string → value, explicit null → `null`. */ +function summaryParentId(record: Record, base: SessionState): string | null { + if (!("parentId" in record) && !("parent_id" in record)) return base.parentId ?? null; + return str(record.parentId) ?? str(record.parent_id) ?? null; +} + /** Enrich a snapshot with its separately-carried entry tail. */ -export function normalizeSnapshotState(sessionId: string, workspaceId: string, payload: unknown): SessionState { +export function normalizeSnapshotState( + sessionId: string, + workspaceId: string, + payload: unknown, + existing?: SessionState, +): SessionState { const record = rec(payload); const candidate = rec(record?.state) ?? record ?? {}; const base = emptySessionState({ @@ -235,11 +255,19 @@ export function normalizeSnapshotState(sessionId: string, workspaceId: string, p workspaceId: str(candidate.workspaceId) ?? workspaceId, cwd: str(candidate.cwd) ?? "", }); + // The list row owns the tree metadata; a snapshot without it (the normal + // case — the reducer never emits these) must not turn a child into a root. + const parentId = str(candidate.parentId ?? candidate.parent_id) ?? existing?.parentId ?? null; + const visible = typeof candidate.visible === "boolean" ? candidate.visible : (existing?.visible ?? true); + const task = str(candidate.task) ?? existing?.task; const state: SessionState = { ...base, ...candidate, sessionId, workspaceId: str(candidate.workspaceId) ?? workspaceId, + parentId, + visible, + ...(task !== undefined ? { task } : {}), flags: { attention: candidate.flags ? rec(candidate.flags)?.attention === true : false, done: rec(candidate.flags)?.done === true, @@ -292,6 +320,7 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist const thinkingValue = str(record.thinking); const hasQueue = Array.isArray(record.queue); + const task = str(record.task) ?? base.task; return { ...base, sessionId, @@ -314,6 +343,9 @@ export function normalizeSessionSummary(raw: unknown, workspaceId: string, exist subagents: Array.isArray(record.subagents) ? arr(record.subagents) : base.subagents, attention: Array.isArray(record.attention) ? arr(record.attention) : base.attention, entries: Array.isArray(record.entries) ? arr(record.entries) : base.entries, + parentId: summaryParentId(record, base), + visible: typeof record.visible === "boolean" ? record.visible : base.visible, + ...(task !== undefined ? { task } : {}), }; } diff --git a/web/src/features/chat/session-tree-model.ts b/web/src/features/chat/session-tree-model.ts new file mode 100644 index 0000000..a7e180e --- /dev/null +++ b/web/src/features/chat/session-tree-model.ts @@ -0,0 +1,208 @@ +import type { SessionState, Subagent } from "@protocol/types"; + +/** + * The session tree the sidebar renders: workspace sessions nest under their + * `parentId` (sub-sessions are separate rows of the same REST list), and a + * manifest subagent only renders as a synthetic row when it has no row of its + * own (the child session row always wins). + * + * Pure and React-free, so the shape is unit-testable without a DOM. + */ + +export interface SessionTreeNode { + kind: "session"; + session: SessionState; + depth: number; + children: TreeNode[]; + /** Number of children actually rendered, so a `(N)` badge matches the UI. */ + childCount: number; + /** True when the row is hidden by the plugin's visibility policy. */ + hidden: boolean; + /** Keep this row open even when the user folded it (selected/filtered descendant). */ + forcedOpen: boolean; +} + +export interface SubagentTreeNode { + kind: "subagent"; + /** The session that owns the manifest entry. */ + session: SessionState; + subagent: Subagent; + depth: number; + children: TreeNode[]; + /** Number of children actually rendered, so a `(N)` badge matches the UI. */ + childCount: number; + /** True when the row is hidden by the plugin's visibility policy. */ + hidden: boolean; + /** Keep this row open even when the user folded it (search match below). */ + forcedOpen: boolean; +} + +export type TreeNode = SessionTreeNode | SubagentTreeNode; + +export interface SessionTreeOptions { + /** Case-insensitive name needle; empty (or absent) means "no filter". */ + filter?: string; + /** Render rows the plugin marked `visible: false`. */ + showHidden?: boolean; + /** The routed session; always rendered, even when it is hidden/filtered out. */ + selectedId?: string | null; +} + +/** Stable key for a node (manifest ids are not unique across sessions). */ +export function treeNodeKey(node: TreeNode): string { + return node.kind === "session" ? `s:${node.session.sessionId}` : `a:${node.session.sessionId}:${node.subagent.id}`; +} + +/** Id a node addresses (`data-session-id` / `data-subagent-id`). */ +export function treeNodeId(node: TreeNode): string { + return node.kind === "session" ? node.session.sessionId : node.subagent.id; +} + +/** Does this subtree contain `id` (used to expand the path to the routed row)? */ +function containsNode(node: TreeNode, id: string): boolean { + if (treeNodeId(node) === id) return true; + return node.children.some((child) => containsNode(child, id)); +} + +function sessionLabel(session: SessionState): string { + return session.name?.trim() || session.sessionId; +} + +function subagentLabel(subagent: Subagent): string { + return subagent.name?.trim() || subagent.id; +} + +/** + * 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. + */ +export function buildSessionTree(sessions: SessionState[], options: SessionTreeOptions = {}): TreeNode[] { + const showHidden = options.showHidden === true; + const selectedId = options.selectedId ?? null; + const needle = (options.filter ?? "").trim().toLowerCase(); + + 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); + } + + // Children grouped by their effective parent, in list order. + const childSessions = new Map(); + for (const session of sessions) { + if (index.get(session.sessionId) !== session) continue; + const parentId = effectiveParent(session, index); + const siblings = childSessions.get(parentId); + if (siblings) siblings.push(session); + else childSessions.set(parentId, [session]); + } + + /** + * Selection, search and ancestry; visibility is only one of the inputs. + * + * Selection overrides the visibility policy (a deep-linked hidden row always + * renders) but NOT an explicit search: the filter is the user's intent and a + * non-matching row stays out. + */ + function keepRow(id: string, label: string, selfVisible: boolean, children: TreeNode[]): boolean { + if (needle !== "") { + // Search is an explicit intent: a matching hidden row IS shown. + if (label.toLowerCase().includes(needle)) return true; + return children.length > 0; + } + if (selectedId !== null && id === selectedId) return true; + if (showHidden || selfVisible) return true; + // Hidden, but kept because a rendered descendant needs its ancestor. + return children.length > 0; + } + + function buildSessionNode(session: SessionState, depth: number, path: Set): SessionTreeNode | null { + if (path.has(session.sessionId)) return null; + const nextPath = new Set(path).add(session.sessionId); + const children: TreeNode[] = []; + for (const child of childSessions.get(session.sessionId) ?? []) { + const node = buildSessionNode(child, depth + 1, nextPath); + if (node) children.push(node); + } + for (const subagent of session.subagents ?? []) { + const node = buildSubagentNode(session, subagent, depth + 1, nextPath); + if (node) children.push(node); + } + const selfVisible = session.visible !== false; + if (!keepRow(session.sessionId, sessionLabel(session), selfVisible, children)) return null; + return { + kind: "session", + session, + depth, + children, + childCount: children.length, + hidden: !selfVisible, + // A folded parent must still reveal the routed row or a search hit + // inside it; otherwise the selection would silently disappear. + forcedOpen: + children.length > 0 && + (needle !== "" || (selectedId !== null && children.some((child) => containsNode(child, selectedId)))), + }; + } + + function buildSubagentNode( + session: SessionState, + subagent: Subagent, + depth: number, + path: Set, + ): SubagentTreeNode | null { + // Dedupe: a manifest entry with a session row of its own is that row. + if (index.has(subagent.id) || path.has(subagent.id)) return null; + const nextPath = new Set(path).add(subagent.id); + const children: TreeNode[] = []; + for (const child of subagent.children ?? []) { + const node = buildSubagentNode(session, child, depth + 1, nextPath); + if (node) children.push(node); + } + const selfVisible = subagent.visible !== false; + if (!keepRow(subagent.id, subagentLabel(subagent), selfVisible, children)) return null; + return { + kind: "subagent", + session, + subagent, + depth, + children, + childCount: children.length, + hidden: !selfVisible, + forcedOpen: children.length > 0 && needle !== "", + }; + } + + const roots: TreeNode[] = []; + const emptyPath = new Set(); + for (const session of childSessions.get(null) ?? []) { + const node = buildSessionNode(session, 0, emptyPath); + if (node) roots.push(node); + } + return roots; +} diff --git a/web/src/features/chat/session-tree.tsx b/web/src/features/chat/session-tree.tsx index 4c7fd42..83cdc1a 100644 --- a/web/src/features/chat/session-tree.tsx +++ b/web/src/features/chat/session-tree.tsx @@ -1,4 +1,5 @@ import type { SessionState, Subagent, WorkspaceInfo } from "@protocol/types"; +import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { Icon } from "@/components/icons"; @@ -8,6 +9,14 @@ import { Input } from "@/components/ui/input"; import { StatusDot, subagentDotClass } from "@/components/ui/status-dot"; import { cn } from "@/lib/utils"; import { flattenSubagents, sessionDot, sessionStatusKey } from "./session-state"; +import { + buildSessionTree, + treeNodeId, + treeNodeKey, + type SessionTreeNode, + type SubagentTreeNode, + type TreeNode, +} from "./session-tree-model"; export interface SessionTreeProps { sessions: SessionState[]; @@ -16,11 +25,14 @@ export interface SessionTreeProps { selectedId?: string | null; filter: string; collapsed: Record; + /** Render sub-sessions the plugin marked `visible: false`. */ + showHidden: boolean; connected?: boolean; creating?: boolean; onFilter: (value: string) => void; onToggleCollapse: (id: string) => void; onToggleAll: () => void; + onToggleShowHidden: () => void; onSelectSession: (id: string) => void; onSelectWorkspace?: (id: string) => void; onNewSession: () => void; @@ -36,15 +48,6 @@ function sessionName(session: SessionState, fallback: string): string { return session.name?.trim() || fallback; } -function matchesFilter(session: SessionState, filter: string, fallback: string): boolean { - if (!filter) return true; - const needle = filter.toLowerCase(); - if (sessionName(session, fallback).toLowerCase().includes(needle)) return true; - return flattenSubagents(session.subagents).some(({ subagent }) => - (subagent.name ?? "").toLowerCase().includes(needle), - ); -} - function ChevronToggle({ hasChildren, collapsed, @@ -72,93 +75,50 @@ function ChevronToggle({ ); } -function SubagentRow({ - session, - subagent, - collapsed, - onToggleCollapse, - onOpenSubagent, - onRenameSubagent, -}: { - session: SessionState; - subagent: Subagent; - collapsed: Record; +interface TreeHandlers { onToggleCollapse: (id: string) => void; + onSelectSession: (id: string) => void; + onRenameSession: (session: SessionState) => void; + onCloseSession: (session: SessionState) => void; onOpenSubagent?: (session: SessionState, subagent: Subagent) => void; onRenameSubagent?: (subagent: Subagent) => void; -}) { - const { t } = useTranslation(); - const children = subagent.children ?? []; - const isCollapsed = collapsed[subagent.id] === true; - const status = t(`state.${subagent.status}`); - const name = subagent.name ?? subagent.id; +} + +/** + * One row of the session tree plus its children. + * + * A real child session renders as a `tree-row--sub` (indent only, no vertical + * guides) and navigates to its own transcript; a manifest subagent keeps the + * eye/rename affordances of the subagent preview. + */ +function TreeRow({ + node, + selectedId, + collapsed, + ...handlers +}: TreeHandlers & { node: TreeNode; selectedId?: string | null; collapsed: Record }) { + const isCollapsed = collapsed[treeNodeId(node)] === true && !node.forcedOpen; return (
  • -
    onOpenSubagent?.(session, subagent)} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault(); - onOpenSubagent?.(session, subagent); - } - }} - > - 0} + {node.kind === "session" ? ( + onToggleCollapse(subagent.id)} + selected={node.session.sessionId === selectedId} + {...handlers} /> - - - {name} - - {subagent.model ?? "—"} - {subagent.thinking ? ` · ${subagent.thinking}` : ""} - - - - - - -
    - {children.length && !isCollapsed ? ( + ) : ( + + )} + {node.children.length && !isCollapsed ? (
      - {children.map((child) => ( - ( + ))}
    @@ -167,116 +127,168 @@ function SubagentRow({ ); } -function SessionRow({ - session, - selected, +function SessionNodeRow({ + node, collapsed, + selected, onToggleCollapse, onSelectSession, onRenameSession, onCloseSession, - onOpenSubagent, - onRenameSubagent, }: { - session: SessionState; + node: SessionTreeNode; + collapsed: boolean; selected: boolean; - collapsed: Record; - onToggleCollapse: (id: string) => void; - onSelectSession: (id: string) => void; - onRenameSession: (session: SessionState) => void; - onCloseSession: (session: SessionState) => void; - onOpenSubagent?: (session: SessionState, subagent: Subagent) => void; - onRenameSubagent?: (subagent: Subagent) => void; -}) { +} & Pick) { const { t } = useTranslation(); - const subagents = session.subagents ?? []; - const isCollapsed = collapsed[session.sessionId] === true; - const dot = sessionDot(session); + const session = node.session; const status = t(`state.${sessionStatusKey(session)}`); const name = sessionName(session, session.sessionId); return ( -
  • -
    onSelectSession(session.sessionId)} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault(); - onSelectSession(session.sessionId); - } - }} - > - 0} - collapsed={isCollapsed} - onClick={() => onToggleCollapse(session.sessionId)} - /> - - - - {name} - {session.flags.attention && session.attention.length ? ( - {`!${session.attention.length}`} - ) : null} - - - {session.model?.id ?? "—"} - {session.thinking ? ` · ${session.thinking}` : ""} - +
    0 && "tree-row--sub", selected && "selected")} + role="button" + tabIndex={0} + aria-label={name} + aria-current={selected ? "true" : undefined} + data-session-id={session.sessionId} + data-hidden={node.hidden ? "true" : undefined} + onClick={() => onSelectSession(session.sessionId)} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + onSelectSession(session.sessionId); + } + }} + > + 0} + collapsed={collapsed} + onClick={() => onToggleCollapse(session.sessionId)} + /> + + + + {name} + {session.flags.attention && session.attention.length ? ( + {`!${session.attention.length}`} + ) : null} - {subagents.length ? ( - - {`(${subagents.length})`} - - ) : null} - - - + + {session.model?.id ?? "—"} + {session.thinking ? ` · ${session.thinking}` : ""} + + + {node.childCount ? ( + + {`(${node.childCount})`} -
    - {subagents.length && !isCollapsed ? ( -
      - {subagents.map((subagent) => ( - - ))} -
    ) : null} -
  • + + + + + + ); +} + +function SubagentNodeRow({ + node, + collapsed, + onToggleCollapse, + onOpenSubagent, + onRenameSubagent, +}: { + node: SubagentTreeNode; + collapsed: boolean; +} & Pick) { + const { t } = useTranslation(); + const { session, subagent } = node; + const status = t(`state.${subagent.status}`); + const name = subagent.name ?? subagent.id; + return ( +
    onOpenSubagent?.(session, subagent)} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + onOpenSubagent?.(session, subagent); + } + }} + > + 0} + collapsed={collapsed} + onClick={() => onToggleCollapse(subagent.id)} + /> + + + {name} + + {subagent.model ?? "—"} + {subagent.thinking ? ` · ${subagent.thinking}` : ""} + + + {node.childCount ? ( + + {`(${node.childCount})`} + + ) : null} + + + + +
    ); } @@ -288,11 +300,13 @@ export function SessionTree({ selectedId, filter, collapsed, + showHidden, connected = false, creating = false, onFilter, onToggleCollapse, onToggleAll, + onToggleShowHidden, onSelectSession, onSelectWorkspace, onNewSession, @@ -304,7 +318,12 @@ export function SessionTree({ className, }: SessionTreeProps) { const { t } = useTranslation(); - const visible = sessions.filter((session) => matchesFilter(session, filter, session.sessionId)); + const nodes = useMemo( + () => buildSessionTree(sessions, { filter, showHidden, selectedId }), + [sessions, filter, showHidden, selectedId], + ); + // Every id — including rows the visibility policy or the filter dropped — so + // "collapse all" also folds folded-away parents. const allIds = sessions.flatMap((session) => [ session.sessionId, ...flattenSubagents(session.subagents).map(({ subagent }) => subagent.id), @@ -375,6 +394,16 @@ export function SessionTree({ {t(connected ? "state.online" : "state.offline")} + + } + /> ) : ( } diff --git a/web/src/features/chat/store.ts b/web/src/features/chat/store.ts index d506338..1690c0b 100644 --- a/web/src/features/chat/store.ts +++ b/web/src/features/chat/store.ts @@ -47,6 +47,8 @@ export interface ChatStore { tab: PanelTab; filter: string; collapsed: Record; + /** Render sub-sessions the plugin hid (`:PiSessions` policy). */ + showHidden: boolean; treeOpen: boolean; panelOpen: boolean; treeCollapsed: boolean; @@ -62,6 +64,7 @@ export interface ChatStore { setFilter: (filter: string) => void; toggleCollapsed: (id: string) => void; setAllCollapsed: (ids: string[], collapsed: boolean) => void; + toggleShowHidden: () => void; setTreeOpen: (open: boolean) => void; setPanelOpen: (open: boolean) => void; setTreeCollapsed: (collapsed: boolean) => void; @@ -105,6 +108,7 @@ export const useChatStore = create((set) => ({ tab: "subagents", filter: "", collapsed: {}, + showHidden: false, treeOpen: false, panelOpen: false, treeCollapsed: false, @@ -127,6 +131,7 @@ export const useChatStore = create((set) => ({ }), setAllCollapsed: (ids, collapsed) => set(() => ({ collapsed: collapsed ? Object.fromEntries(ids.map((id) => [id, true])) : {} })), + toggleShowHidden: () => set((state) => ({ showHidden: !state.showHidden })), setTreeOpen: (treeOpen) => set({ treeOpen }), setPanelOpen: (panelOpen) => set({ panelOpen }), setTreeCollapsed: (treeCollapsed) => set({ treeCollapsed }), diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 2cadb79..4decdc8 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -7,6 +7,8 @@ "chat.acceptedAll": "Accepted all {n} files", "chat.addAttachment": "Add attachment", "chat.allowOnce": "Allow once", + "chat.allHidden": "All sub-sessions are hidden", + "chat.allHiddenText": "Turn on “Show hidden sub-sessions” to list them.", "chat.attachTitle": "Add attachment", "chat.attachmentAdded": "Added attachment {name}", "chat.attachmentFailed": "Could not read attachment: {name}", @@ -20,6 +22,7 @@ "chat.batchFailed": "{n} failed", "chat.batchRunning": "{n} running", "chat.cancelSiblingsLabel": "Cancel sibling subagents on failure (cancel_siblings_on_fail)", + "chat.childCount": "{n} children", "chat.closePanel": "Close panel", "chat.closeProcess": "Close process", "chat.closeSessionText": "This ends the pi process for session \"{name}\". History is kept and it can be revived.", @@ -103,6 +106,8 @@ "chat.sendTitle": "Send (Enter)", "chat.sending": "Sending…", "chat.sessions": "Sessions", + "chat.showHidden": "Show hidden sub-sessions", + "chat.showHiddenAria": "Show hidden sub-sessions", "chat.source": "Source: {name}", "chat.status": "Status", "chat.steer": "Steer", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index adba93b..6805450 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -7,6 +7,8 @@ "chat.acceptedAll": "已接受全部 {n} 个文件", "chat.addAttachment": "添加附件", "chat.allowOnce": "允许一次", + "chat.allHidden": "所有子会话均已隐藏", + "chat.allHiddenText": "开启「显示隐藏的子会话」即可显示。", "chat.attachTitle": "添加附件", "chat.attachmentAdded": "已添加附件 {name}", "chat.attachmentFailed": "附件读取失败:{name}", @@ -20,6 +22,7 @@ "chat.batchFailed": "{n} 失败", "chat.batchRunning": "{n} 运行中", "chat.cancelSiblingsLabel": "失败时取消同级子代理(cancel_siblings_on_fail)", + "chat.childCount": "{n} 个子项", "chat.closePanel": "关闭面板", "chat.closeProcess": "关闭进程", "chat.closeSessionText": "将结束 session「{name}」的 pi 进程。会话历史仍保留,可重新唤醒。", @@ -103,6 +106,8 @@ "chat.sendTitle": "发送(Enter)", "chat.sending": "发送中…", "chat.sessions": "会话", + "chat.showHidden": "显示隐藏的子会话", + "chat.showHiddenAria": "显示隐藏的子会话", "chat.source": "来源:{name}", "chat.status": "状态", "chat.steer": "Steer", diff --git a/web/src/pages/chat.tsx b/web/src/pages/chat.tsx index 345598d..b06ed3e 100644 --- a/web/src/pages/chat.tsx +++ b/web/src/pages/chat.tsx @@ -111,6 +111,8 @@ function ChatExperience({ sessionId }: { sessionId?: string }) { const setFilter = useChatStore((state) => state.setFilter); const collapsed = useChatStore((state) => state.collapsed); const toggleCollapsed = useChatStore((state) => state.toggleCollapsed); + const showHidden = useChatStore((state) => state.showHidden); + const toggleShowHidden = useChatStore((state) => state.toggleShowHidden); const setAllCollapsed = useChatStore((state) => state.setAllCollapsed); const tab = useChatStore((state) => state.tab); const setTab = useChatStore((state) => state.setTab); @@ -322,6 +324,12 @@ function ChatExperience({ sessionId }: { sessionId?: string }) { [sessions], ); const anyOpen = allIds.some((id) => !collapsed[id]); + // Only offer the way back when the parent is actually in this workspace list; + // a pruned/archived parent would otherwise dead-end on the not-found page. + const parentSessionId = + active?.parentId && sessions.some((session) => session.sessionId === active.parentId) + ? active.parentId + : null; const streamHead = (
    @@ -342,6 +350,17 @@ function ChatExperience({ sessionId }: { sessionId?: string }) { > + {parentSessionId ? ( + // A sub-session row is reachable from the tree and by deep link; + // this is the way back up without opening the tree. + + ) : null}
    {active ? : null} @@ -394,11 +413,13 @@ function ChatExperience({ sessionId }: { sessionId?: string }) { selectedId={active?.sessionId ?? null} filter={filter} collapsed={collapsed} + showHidden={showHidden} connected={connected} creating={creating} onFilter={setFilter} onToggleCollapse={toggleCollapsed} onToggleAll={() => setAllCollapsed(allIds, anyOpen)} + onToggleShowHidden={toggleShowHidden} onSelectSession={navigateSession} onSelectWorkspace={navigateWorkspace} onNewSession={() => void handleNewSession()} diff --git a/web/src/stores/sessions.ts b/web/src/stores/sessions.ts index f006b94..ae031c1 100644 --- a/web/src/stores/sessions.ts +++ b/web/src/stores/sessions.ts @@ -42,7 +42,22 @@ export const useSessionsStore = create((set, get) => ({ set((state) => { const list = state.byWorkspace[session.workspaceId] ?? []; const index = list.findIndex((s) => s.sessionId === session.sessionId); - const next = index === -1 ? [...list, session] : list.map((s, i) => (i === index ? session : s)); + if (index === -1) { + return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: [...list, session] } }; + } + // Tree metadata is list metadata: a live update (`pi2:session`, + // reducer events, a rename) carries no `parentId`/`visible`/`task` and + // must not orphan the row. Explicit `undefined` is the only + // "not carried" marker — an explicit `parentId: null` means root and + // wins, which `??` would invert. + const previous = list[index] as SessionState; + const merged: SessionState = { + ...session, + parentId: session.parentId !== undefined ? session.parentId : previous.parentId, + visible: session.visible !== undefined ? session.visible : previous.visible, + task: session.task !== undefined ? session.task : previous.task, + }; + const next = list.map((s, i) => (i === index ? merged : s)); return { byWorkspace: { ...state.byWorkspace, [session.workspaceId]: next } }; }), @@ -53,18 +68,32 @@ export const useSessionsStore = create((set, get) => ({ let moved = false; for (const [workspaceId, list] of Object.entries(state.byWorkspace)) { const index = list.findIndex((session) => session.sessionId === from); - if (index === -1) { - byWorkspace[workspaceId] = list; - continue; - } - moved = true; - byWorkspace[workspaceId] = list - .map((session, position) => - position === index ? { ...session, sessionId: to } : session, - ) + let changed = false; + let next = list.map((session, position) => { + let row = session; + if (position === index) { + row = { ...row, sessionId: to }; + changed = true; + } + // `tmp-N` → real id migration: children (sub-session rows) keep + // pointing at their parent, now under its real id. + if (row.parentId === from) { + row = { ...row, parentId: to }; + changed = true; + } + return row; + }); + if (index !== -1) { // A row already cached under the new id would now duplicate the // migrated one (the REST list can be ahead of the event). - .filter((session, position) => position === index || session.sessionId !== to); + const deduped = next.filter( + (session, position) => position === index || session.sessionId !== to, + ); + if (deduped.length !== next.length) changed = true; + next = deduped; + } + if (changed) moved = true; + byWorkspace[workspaceId] = next; } if (!moved) return state; return { @@ -77,7 +106,11 @@ export const useSessionsStore = create((set, get) => ({ set((state) => { const byWorkspace: Record = {}; for (const [workspaceId, list] of Object.entries(state.byWorkspace)) { - byWorkspace[workspaceId] = list.filter((s) => s.sessionId !== sessionId); + byWorkspace[workspaceId] = list + .filter((s) => s.sessionId !== sessionId) + // Never orphan a child: a removed parent promotes its children to + // roots instead of hiding them behind a missing row. + .map((s) => (s.parentId === sessionId ? { ...s, parentId: null } : s)); } return { byWorkspace, selectedSessionId: state.selectedSessionId === sessionId ? null : state.selectedSessionId }; }), diff --git a/web/src/styles/pages/chat.css b/web/src/styles/pages/chat.css index 50f82a7..4155800 100644 --- a/web/src/styles/pages/chat.css +++ b/web/src/styles/pages/chat.css @@ -138,6 +138,22 @@ .tree-row .badge { margin-left: var(--space-1); } +/* Child sessions: indentation only, no vertical guides — muted and smaller. */ +.tree-row--sub .t-name { + font-size: 0.8125rem; + font-weight: 500; +} +.tree-row--sub:not(.selected) .t-name { + color: var(--muted-foreground); +} +.tree-row[data-hidden="true"] .t-name { + /* Muted, not illegible: keep body text above the WCAG AA contrast floor. */ + opacity: 0.85; +} +.icon-btn.is-on { + background: var(--accent); + color: var(--foreground); +} .tree-toggle { align-items: center; width: 1.1rem; diff --git a/web/tests/chat.tree.test.tsx b/web/tests/chat.tree.test.tsx index 2c941d3..18e72ee 100644 --- a/web/tests/chat.tree.test.tsx +++ b/web/tests/chat.tree.test.tsx @@ -15,32 +15,49 @@ beforeAll(async () => { await setLanguage("en"); }); -function renderTree(props: Partial> = {}) { - const onSelectSession = vi.fn(); - const onToggleCollapse = vi.fn(); - const onToggleAll = vi.fn(); - const sessions = props.sessions ?? [ - sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [subagentFixture()] }), - sessionFixture({ sessionId: "s2", name: "Beta", subagents: [] }), - ]; - const utils = render( +const defaultSessions = () => [ + sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [subagentFixture()] }), + sessionFixture({ sessionId: "s2", name: "Beta", subagents: [] }), +]; + +/** The tree element with inert handlers, so a test can rerender with new props. */ +function treeElement(props: Partial> = {}) { + return ( , + /> ); - return { ...utils, sessions, onSelectSession, onToggleCollapse, onToggleAll }; +} + +function renderTree(props: Partial> = {}) { + const onSelectSession = vi.fn(); + const onToggleCollapse = vi.fn(); + const onToggleAll = vi.fn(); + const onToggleShowHidden = vi.fn(); + const sessions = props.sessions ?? defaultSessions(); + const utils = render( + treeElement({ sessions, onSelectSession, onToggleCollapse, onToggleAll, onToggleShowHidden, ...props }), + ); + return { ...utils, sessions, onSelectSession, onToggleCollapse, onToggleAll, onToggleShowHidden }; +} + +/** `SessionState` for a sub-session row (`parentId` set, `visible` defaults true). */ +function childSession(overrides: Parameters[0] = {}) { + return sessionFixture({ sessionId: "c1", name: "Child session", parentId: "s1", ...overrides }); } describe("session tree", () => { @@ -58,21 +75,7 @@ describe("session tree", () => { fireEvent.click(within(row).getByLabelText("Collapse")); expect(onToggleCollapse).toHaveBeenCalledWith("s1"); - rerender( - , - ); + rerender(treeElement({ sessions, collapsed: { s1: true } })); expect(screen.queryByText("researcher")).not.toBeInTheDocument(); }); @@ -84,6 +87,86 @@ describe("session tree", () => { fireEvent.click(screen.getByRole("button", { name: "Collapse or expand all" })); expect(onToggleAll).toHaveBeenCalledTimes(1); }); + + it("nests a child session row under its parent and opens its own transcript", () => { + const { onSelectSession } = renderTree({ + sessions: [sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [] }), childSession()], + }); + + const parentRow = document.querySelector('[data-session-id="s1"]'); + const childRow = document.querySelector('[data-session-id="c1"]'); + expect(childRow).not.toBeNull(); + expect(childRow).toHaveClass("tree-row", "tree-row--sub"); + // Nested under the parent row instead of a flat sibling. + expect(parentRow?.closest("li")).toContainElement(childRow as HTMLElement); + expect(parentRow?.parentElement?.querySelector("ul")).toContainElement(childRow as HTMLElement); + expect(screen.getByText("(1)")).toBeInTheDocument(); + + fireEvent.click(childRow as HTMLElement); + expect(onSelectSession).toHaveBeenCalledWith("c1"); + }); + + it("hides hidden sub-sessions by default and reveals them with the toggle", () => { + const sessions = [ + sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [] }), + childSession({ visible: false }), + ]; + const { rerender, onToggleShowHidden } = renderTree({ sessions }); + + expect(document.querySelector('[data-session-id="c1"]')).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Show hidden sub-sessions" })); + expect(onToggleShowHidden).toHaveBeenCalledTimes(1); + + rerender(treeElement({ sessions, showHidden: true })); + const childRow = document.querySelector('[data-session-id="c1"]'); + expect(childRow).not.toBeNull(); + expect(childRow).toHaveAttribute("data-hidden", "true"); + }); + + it("renders a sub-session once when the manifest lists it too", () => { + renderTree({ + sessions: [ + sessionFixture({ + sessionId: "s1", + name: "Alpha", + subagents: [subagentFixture({ id: "c1" })], + }), + childSession(), + ], + }); + + expect(document.querySelectorAll('[data-session-id="c1"]')).toHaveLength(1); + expect(document.querySelectorAll("[data-subagent-id]")).toHaveLength(0); + }); + + it("keeps the routed sub-session visible under a folded parent", () => { + renderTree({ + sessions: [sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [] }), childSession()], + collapsed: { s1: true }, + selectedId: "c1", + }); + + // A fold must never hide the row the route points at. + const childRow = document.querySelector('[data-session-id="c1"]'); + expect(childRow).not.toBeNull(); + expect(childRow).toHaveAttribute("aria-current", "true"); + }); + + it("explains an all-hidden list instead of reporting no matches", () => { + renderTree({ + sessions: [sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [] }), childSession({ visible: false })], + filter: "", + }); + + // The only child is hidden by policy; the parent is still shown, so the + // "no matching sessions" copy would be wrong. (Parent row present.) + expect(document.querySelector('[data-session-id="s1"]')).not.toBeNull(); + + renderTree({ sessions: [childSession({ visible: false, parentId: null })] }); + expect(screen.getByText("All sub-sessions are hidden")).toBeInTheDocument(); + // Both the toolbar toggle and the empty-state action expose the label. + expect(screen.getAllByRole("button", { name: /Show hidden sub-sessions/i }).length).toBeGreaterThan(0); + }); }); /* ------------------------------------------------------------------ */ @@ -134,6 +217,24 @@ function sessionsBody() { }; } +function subSessionBody() { + // The child row arrives first and carries the sub-session metadata. + return { + sessions: [ + { + sessionId: "c1", + name: "Child session", + workspaceId: "W1", + cwd: "/work/w1", + status: "busy", + parentId: "s1", + visible: false, + }, + { sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle", visible: true }, + ], + }; +} + function entriesBody(text: string) { return { entries: [ @@ -252,6 +353,48 @@ describe("chat session deep link", () => { expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Alpha"); }); + it("renders a deep-linked hidden sub-session and offers the way back to its parent", async () => { + mockApi([ + { path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) }, + { path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: subSessionBody() }) }, + { path: "/api/v1/models", handler: () => ({ body: [] }) }, + { path: /^\/api\/v1\/sessions\/c1\/entries/, handler: () => ({ body: entriesBody("Child first message") }) }, + { path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Parent first message") }) }, + ]); + + await renderPage(chatRoutes(), "/chat/c1?workspace=W1"); + + await waitFor(() => { + expect(document.querySelector('[data-session-id="c1"]')).toHaveAttribute("aria-current", "true"); + }); + // Hidden by the plugin policy, but the routed row still renders (muted). + expect(document.querySelector('[data-session-id="c1"]')).toHaveAttribute("data-hidden", "true"); + expect(await screen.findByText("Child first message")).toBeInTheDocument(); + expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Child session"); + + fireEvent.click(screen.getByRole("button", { name: "Back to parent" })); + expect(await screen.findByText("Parent first message")).toBeInTheDocument(); + expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Alpha"); + await waitFor(() => { + expect(document.querySelector('[data-session-id="s1"]')).toHaveAttribute("aria-current", "true"); + }); + }); + + it("prefers a root session for the /chat index when a child row comes first", async () => { + mockApi([ + { path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) }, + { path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: subSessionBody() }) }, + { path: "/api/v1/models", handler: () => ({ body: [] }) }, + { path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Parent first message") }) }, + ]); + + await renderPage(chatRoutes(), "/chat?workspace=W1"); + + expect(await screen.findByText("Parent first message")).toBeInTheDocument(); + expect(screen.queryByTestId("session-not-found")).toBeNull(); + expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Alpha"); + }); + it("does not flash the error state while the first session fetch is in flight", async () => { let release = () => {}; const gate = new Promise((resolve) => { diff --git a/web/tests/session-tree-model.test.ts b/web/tests/session-tree-model.test.ts new file mode 100644 index 0000000..beb6d2c --- /dev/null +++ b/web/tests/session-tree-model.test.ts @@ -0,0 +1,182 @@ +import type { TreeNode } from "@/features/chat/session-tree-model"; +import { buildSessionTree, treeNodeId } from "@/features/chat/session-tree-model"; +import { sessionFixture, subagentFixture } from "./chat-fixtures"; + +function ids(nodes: TreeNode[]): string[] { + return nodes.map((node) => treeNodeId(node)); +} + +function childOf(overrides: Parameters[0] = {}) { + return sessionFixture({ sessionId: "c1", name: "Child session", parentId: "s1", ...overrides }); +} + +describe("buildSessionTree", () => { + it("nests a sub-session under its parent instead of listing it flat", () => { + const tree = buildSessionTree([ + sessionFixture({ sessionId: "s1", name: "Alpha" }), + childOf(), + sessionFixture({ sessionId: "s2", name: "Beta" }), + ]); + + expect(ids(tree)).toEqual(["s1", "s2"]); + expect(tree[0]).toMatchObject({ kind: "session", depth: 0, childCount: 1, hidden: false }); + expect(ids(tree[0]?.children ?? [])).toEqual(["c1"]); + expect(tree[0]?.children[0]).toMatchObject({ kind: "session", depth: 1, hidden: false }); + expect(tree[0]?.children[0]?.session.sessionId).toBe("c1"); + }); + + it("hides a sub-session the plugin marked invisible by default", () => { + const tree = buildSessionTree([ + sessionFixture({ sessionId: "s1", name: "Alpha" }), + childOf({ visible: false }), + ]); + + expect(ids(tree)).toEqual(["s1"]); + expect(tree[0]?.children).toEqual([]); + expect(tree[0]?.childCount).toBe(0); + }); + + it("always renders the routed sub-session, even when it is hidden", () => { + const tree = buildSessionTree( + [sessionFixture({ sessionId: "s1", name: "Alpha" }), childOf({ visible: false })], + { selectedId: "c1" }, + ); + + expect(ids(tree)).toEqual(["s1"]); + expect(ids(tree[0]?.children ?? [])).toEqual(["c1"]); + // Kept only because it is selected: flagged hidden for a muted style. + expect(tree[0]?.children[0]?.hidden).toBe(true); + }); + + it("renders hidden sub-sessions when showHidden is on", () => { + const tree = buildSessionTree( + [sessionFixture({ sessionId: "s1", name: "Alpha" }), childOf({ visible: false })], + { showHidden: true }, + ); + + expect(ids(tree[0]?.children ?? [])).toEqual(["c1"]); + expect(tree[0]?.children[0]?.hidden).toBe(true); + }); + + it("dedupes a manifest subagent against its own child session row", () => { + const tree = buildSessionTree([ + sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [subagentFixture({ id: "c1" })] }), + childOf(), + ]); + + expect(tree).toHaveLength(1); + // The session row wins; the manifest entry is not rendered a second time. + expect(ids(tree[0]?.children ?? [])).toEqual(["c1"]); + expect(tree[0]?.children[0]?.kind).toBe("session"); + expect(tree[0]?.childCount).toBe(1); + }); + + it("renders a manifest subagent that has no session row as a synthetic node", () => { + const tree = buildSessionTree([ + sessionFixture({ sessionId: "s1", name: "Alpha", subagents: [subagentFixture({ id: "sa1" })] }), + ]); + + expect(tree[0]?.children[0]).toMatchObject({ kind: "subagent", depth: 1 }); + expect(ids(tree[0]?.children ?? [])).toEqual(["sa1"]); + }); + + it("promotes a child whose parent is not in the list to a root", () => { + const tree = buildSessionTree([childOf({ parentId: "gone" })]); + + expect(ids(tree)).toEqual(["c1"]); + expect(tree[0]).toMatchObject({ kind: "session", depth: 0, childCount: 0 }); + }); + + it("keeps grandchildren at depth 2 and survives a parent cycle", () => { + const tree = buildSessionTree([ + sessionFixture({ sessionId: "s1", name: "Alpha" }), + childOf(), + sessionFixture({ sessionId: "c2", name: "Grandchild", parentId: "c1" }), + ]); + expect(tree[0]?.children[0]?.children[0]).toMatchObject({ kind: "session", depth: 2 }); + expect(tree[0]?.children[0]?.childCount).toBe(1); + + const cyclic = buildSessionTree([ + sessionFixture({ sessionId: "a", parentId: "b" }), + sessionFixture({ sessionId: "b", parentId: "a" }), + ]); + expect(ids(cyclic).sort()).toEqual(["a", "b"]); + }); + + it("keeps the ancestor chain of a filter match, including a hidden child", () => { + const tree = buildSessionTree( + [ + sessionFixture({ sessionId: "s1", name: "Alpha" }), + childOf({ name: "hidden-worker", visible: false }), + sessionFixture({ sessionId: "s2", name: "Beta" }), + ], + { filter: "hidden-work" }, + ); + + expect(ids(tree)).toEqual(["s1"]); + expect(ids(tree[0]?.children ?? [])).toEqual(["c1"]); + expect(tree[0]?.children[0]?.hidden).toBe(true); + }); + + it("preserves input order and counts rendered children only", () => { + const tree = buildSessionTree([ + sessionFixture({ sessionId: "s2", name: "Beta" }), + sessionFixture({ sessionId: "s1", name: "Alpha" }), + childOf(), + childOf({ sessionId: "c2", visible: false }), + ]); + + // No sorting: roots keep the order the list delivered. + expect(ids(tree)).toEqual(["s2", "s1"]); + // The hidden child is not rendered, so it is not counted either. + expect(tree[1]?.childCount).toBe(1); + expect(ids(tree[1]?.children ?? [])).toEqual(["c1"]); + }); + + it("marks the ancestor chain of the routed row forced-open", () => { + const tree = buildSessionTree( + [ + sessionFixture({ sessionId: "s1", name: "Alpha" }), + childOf(), + sessionFixture({ sessionId: "c2", name: "Grandchild", parentId: "c1" }), + ], + { selectedId: "c2" }, + ); + + // The component folds children by default; the path to the routed row + // must stay open or the selection would silently disappear. + expect(tree[0]?.forcedOpen).toBe(true); + expect(tree[0]?.children[0]?.forcedOpen).toBe(true); + // The routed row itself may be folded by the user like any other row. + expect(tree[0]?.children[0]?.children[0]?.forcedOpen).toBe(false); + }); + + it("forces folded ancestors open while a filter is active", () => { + const tree = buildSessionTree( + [sessionFixture({ sessionId: "s1", name: "Alpha" }), childOf({ name: "child-match" })], + { filter: "child-match" }, + ); + + expect(tree[0]?.forcedOpen).toBe(true); + expect(ids(tree[0]?.children ?? [])).toEqual(["c1"]); + }); + + it("pins the filter over the routed row (an explicit search wins)", () => { + const tree = buildSessionTree( + [sessionFixture({ sessionId: "s1", name: "Alpha" }), childOf()], + { filter: "zzz", selectedId: "c1" }, + ); + + expect(tree).toEqual([]); + }); + + it("renders a duplicated session id once", () => { + const tree = buildSessionTree([ + sessionFixture({ sessionId: "s1", name: "Alpha" }), + sessionFixture({ sessionId: "s1", name: "Alpha again" }), + ]); + + expect(tree).toHaveLength(1); + expect(tree[0]?.session.name).toBe("Alpha"); + }); +}); diff --git a/web/tests/sessions-store.test.ts b/web/tests/sessions-store.test.ts new file mode 100644 index 0000000..1555f33 --- /dev/null +++ b/web/tests/sessions-store.test.ts @@ -0,0 +1,138 @@ +import { beforeEach, describe, expect, it } from "vitest"; + +import { emptySessionState, normalizeSnapshotState } from "@/features/chat/session-state"; +import { useSessionsStore } from "@/stores/sessions"; +import { sessionFixture } from "./chat-fixtures"; + +function state() { + return useSessionsStore.getState(); +} + +beforeEach(() => { + state().reset(); +}); + +describe("sessions store — tree metadata", () => { + it("keeps parentId/visible/task when an incoming update omits them", () => { + const child = sessionFixture({ + sessionId: "c1", + workspaceId: "w1", + parentId: "s1", + visible: false, + task: "Research the auth flow", + }); + state().setSessions("w1", [child]); + + // A reducer event / `pi2:session` row carries no list metadata. + state().upsertSession({ + ...emptySessionState({ sessionId: "c1", workspaceId: "w1" }), + parentId: undefined, + visible: undefined, + task: undefined, + status: "busy", + }); + + expect(state().getSession("c1")).toMatchObject({ + parentId: "s1", + visible: false, + task: "Research the auth flow", + status: "busy", + }); + }); + + it("lets an explicit parentId: null (root) win over the cached parent", () => { + state().setSessions("w1", [sessionFixture({ sessionId: "c1", workspaceId: "w1", parentId: "s1" })]); + + state().upsertSession({ + ...emptySessionState({ sessionId: "c1", workspaceId: "w1" }), + parentId: null, + visible: true, + }); + + expect(state().getSession("c1")?.parentId).toBeNull(); + expect(state().getSession("c1")?.visible).toBe(true); + }); + + it("rewrites child parentIds on the tmp-N → real-id migration", () => { + state().setSessions("w1", [ + sessionFixture({ sessionId: "tmp-1", workspaceId: "w1" }), + sessionFixture({ sessionId: "c1", workspaceId: "w1", parentId: "tmp-1" }), + ]); + + state().renameSessionId("tmp-1", "real-1"); + + const list = state().listFor("w1"); + expect(list.map((row) => row.sessionId)).toEqual(["real-1", "c1"]); + expect(list[1]?.parentId).toBe("real-1"); + }); + + it("re-parents children to root when their parent is removed", () => { + state().setSessions("w1", [ + sessionFixture({ sessionId: "s1", workspaceId: "w1" }), + sessionFixture({ sessionId: "c1", workspaceId: "w1", parentId: "s1" }), + ]); + + state().removeSession("s1"); + + const list = state().listFor("w1"); + expect(list.map((row) => row.sessionId)).toEqual(["c1"]); + expect(list[0]?.parentId).toBeNull(); + }); + + it("keeps parentId/visible/task from the cached row through a snapshot", () => { + state().setSessions("w1", [ + sessionFixture({ + sessionId: "c1", + workspaceId: "w1", + parentId: "s1", + visible: false, + task: "Research the auth flow", + }), + ]); + + const snapshot = normalizeSnapshotState( + "c1", + "w1", + { state: { status: "busy", entries: [] } }, + state().getSession("c1"), + ); + expect(snapshot).toMatchObject({ + parentId: "s1", + visible: false, + task: "Research the auth flow", + status: "busy", + }); + + state().upsertSession(snapshot); + expect(state().getSession("c1")).toMatchObject({ + parentId: "s1", + visible: false, + task: "Research the auth flow", + }); + }); + + it("does not turn a child into a root when the snapshot has no list metadata", () => { + const child = sessionFixture({ sessionId: "c1", workspaceId: "w1", parentId: "s1", visible: false }); + + // No cached row at all: the snapshot alone cannot invent a parent, and + // must not claim `visible: false` was revoked. + const bare = normalizeSnapshotState("c1", "w1", { state: { status: "idle" } }); + expect(bare.parentId).toBeNull(); + expect(bare.visible).toBe(true); + + const withRow = normalizeSnapshotState("c1", "w1", { state: { status: "idle" } }, child); + expect(withRow.parentId).toBe("s1"); + expect(withRow.visible).toBe(false); + }); + + it("does not clobber tree metadata when a fresh empty state is upserted", () => { + const child = sessionFixture({ sessionId: "c1", workspaceId: "w1", parentId: "s1", visible: false }); + state().setSessions("w1", [child]); + + // `emptySessionState` marks list metadata as "not carried" (undefined), + // so a cold-start update cannot silently flatten the row to a root. + state().upsertSession(emptySessionState({ sessionId: "c1", workspaceId: "w1" })); + expect(state().getSession("c1")?.parentId).toBe("s1"); + expect(state().getSession("c1")?.visible).toBe(false); + }); +});