fix(web): render the chat session tree from parent/sub-session lineage

The sidebar treated every workspace session as a root and only nested the
manifest sub-agents, so sub-session files showed up as siblings (the same child
twice); sub-sessions the plugin marked hidden were listed anyway.

- build the tree from `parentId` in a pure `buildSessionTree` model: orphans are
  promoted to roots, cycles and duplicate ids are guarded, real child-session
  rows win over the manifest projection, and the routed row force-opens its
  ancestors
- honour the plugin's `:PiSessions` visibility (`visible: false`) with a "show
  hidden sub-sessions" toggle, the routed-row exception and a dedicated
  all-hidden empty state
- keep tree metadata across WS snapshots, reducer events, id migration and
  parent removal; prefer a root row for the `/chat` index and add a "back to
  parent" action
- document the session-row and `pi2:subagents` list metadata in the protocol
This commit is contained in:
yuez committed 2026-10-22 16:45:09 +08:00
1 parent 7e780515ac
commit 06e70204e7
15 files changed
+1133 -240

No files matched your search

+173 -30
View File
@@ -15,32 +15,49 @@ beforeAll(async () => {
await setLanguage("en");
});
function renderTree(props: Partial<ComponentProps<typeof SessionTree>> = {}) {
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<ComponentProps<typeof SessionTree>> = {}) {
return (
<SessionTree
sessions={sessions}
sessions={defaultSessions()}
selectedId="s1"
filter=""
collapsed={{}}
showHidden={false}
connected
onFilter={vi.fn()}
onToggleCollapse={onToggleCollapse}
onToggleAll={onToggleAll}
onSelectSession={onSelectSession}
onToggleCollapse={vi.fn()}
onToggleAll={vi.fn()}
onToggleShowHidden={vi.fn()}
onSelectSession={vi.fn()}
onNewSession={vi.fn()}
onRenameSession={vi.fn()}
onCloseSession={vi.fn()}
{...props}
/>,
/>
);
return { ...utils, sessions, onSelectSession, onToggleCollapse, onToggleAll };
}
function renderTree(props: Partial<ComponentProps<typeof SessionTree>> = {}) {
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<typeof sessionFixture>[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(
<SessionTree
sessions={sessions}
selectedId="s1"
filter=""
collapsed={{ s1: true }}
onFilter={vi.fn()}
onToggleCollapse={vi.fn()}
onToggleAll={vi.fn()}
onSelectSession={vi.fn()}
onNewSession={vi.fn()}
onRenameSession={vi.fn()}
onCloseSession={vi.fn()}
/>,
);
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<void>((resolve) => {
+182
View File
@@ -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<typeof sessionFixture>[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");
});
});
+138
View File
@@ -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);
});
});