feat: session-scoped entries query, session title tree and message stream updates
This commit is contained in:
1 parent
bef8a35632
commit
e910e75849
37 files changed
+1409
-75
No files matched your search
@@ -0,0 +1,77 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { fetchEntriesPage, HISTORY_PAGE_SIZE, setSessionMeta } from "@/features/chat/history";
|
||||
|
||||
import { mockApi } from "./helpers/api-mock";
|
||||
|
||||
const ENTRIES_PATH = /^\/api\/v1\/sessions\/[^/]+\/entries$/;
|
||||
|
||||
function page(entries: unknown[] = [], cursor: Record<string, unknown> = { hasMore: false }) {
|
||||
return { status: 200, body: { entries, cursor } };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
// `sessionMeta` is module state; keep each case's rows isolated.
|
||||
for (const id of ["s-hint", "s-meta", "s-cursor", "s-response"]) {
|
||||
setSessionMeta(id, { workspaceId: undefined, sessionFile: undefined });
|
||||
}
|
||||
});
|
||||
|
||||
describe("history page request", () => {
|
||||
it("routes with the caller's workspace hint and the row's session file", async () => {
|
||||
setSessionMeta("s-hint", { workspaceId: "ws-meta", sessionFile: "/tmp/s-hint.jsonl" });
|
||||
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
|
||||
await fetchEntriesPage("s-hint", { workspaceId: "ws-page" });
|
||||
|
||||
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
|
||||
expect(url.pathname).toBe("/api/v1/sessions/s-hint/entries");
|
||||
// The page's workspace wins: it is known before the list effect lands.
|
||||
expect(url.searchParams.get("workspaceId")).toBe("ws-page");
|
||||
expect(url.searchParams.get("sessionFile")).toBe("/tmp/s-hint.jsonl");
|
||||
expect(url.searchParams.get("limit")).toBe(String(HISTORY_PAGE_SIZE));
|
||||
expect(url.searchParams.has("before")).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the row's workspace when the caller has none", async () => {
|
||||
setSessionMeta("s-meta", { workspaceId: "ws-meta" });
|
||||
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
|
||||
await fetchEntriesPage("s-meta", {});
|
||||
|
||||
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
|
||||
expect(url.searchParams.get("workspaceId")).toBe("ws-meta");
|
||||
expect(url.searchParams.has("sessionFile")).toBe(false);
|
||||
});
|
||||
|
||||
it("forwards the before cursor for older pages", async () => {
|
||||
const fetchMock = mockApi([{ path: ENTRIES_PATH, handler: () => page() }]);
|
||||
await fetchEntriesPage("s-cursor", { before: "e9", limit: 25, workspaceId: "ws-page" });
|
||||
|
||||
const url = new URL(String(fetchMock.mock.calls[0]?.[0]), "http://localhost");
|
||||
expect(url.searchParams.get("before")).toBe("e9");
|
||||
expect(url.searchParams.get("limit")).toBe("25");
|
||||
});
|
||||
|
||||
it("projects raw entries and keeps the plugin's cursor", async () => {
|
||||
mockApi([
|
||||
{
|
||||
path: ENTRIES_PATH,
|
||||
handler: () =>
|
||||
page(
|
||||
[
|
||||
{
|
||||
type: "message",
|
||||
id: "u1",
|
||||
message: { role: "user", content: "hi", timestamp: 1_733_234_400_000 },
|
||||
},
|
||||
],
|
||||
{ before: "u1", hasMore: true },
|
||||
),
|
||||
},
|
||||
]);
|
||||
const result = await fetchEntriesPage("s-response", { workspaceId: "ws-page" });
|
||||
|
||||
expect(result.entries.map((entry) => entry.id)).toEqual(["u1"]);
|
||||
expect(result.entries[0]?.role).toBe("user");
|
||||
expect(result.cursor).toEqual({ before: "u1", hasMore: true });
|
||||
});
|
||||
});
|
||||
@@ -338,3 +338,111 @@ describe("chat message stream — layout contract", () => {
|
||||
expect(css).toMatch(/@media \(prefers-reduced-motion: reduce\)/);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Auto-follow: content growth must never look like a user scroll. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("chat message stream — auto-follow", () => {
|
||||
/**
|
||||
* jsdom has no layout: give the scroll container a fake viewport so the
|
||||
* distance heuristic can be exercised (2000px of content, 600px visible).
|
||||
*/
|
||||
function renderWithViewport(props: Partial<MessageStreamProps> = {}) {
|
||||
const utils = renderStream(props);
|
||||
const scroll = utils.container.querySelector<HTMLElement>(".stream-scroll");
|
||||
if (!scroll) throw new Error("the chat layout did not render a stream scroll");
|
||||
const box = { top: 0, height: 2000, client: 600 };
|
||||
Object.defineProperty(scroll, "scrollHeight", { configurable: true, get: () => box.height });
|
||||
Object.defineProperty(scroll, "clientHeight", { configurable: true, get: () => box.client });
|
||||
Object.defineProperty(scroll, "scrollTop", {
|
||||
configurable: true,
|
||||
get: () => box.top,
|
||||
set: (value: number) => {
|
||||
box.top = value;
|
||||
},
|
||||
});
|
||||
const scrollTo = vi.fn((options?: ScrollToOptions) => {
|
||||
box.top = Number(options?.top ?? box.height);
|
||||
});
|
||||
(scroll as unknown as { scrollTo: typeof scrollTo }).scrollTo = scrollTo;
|
||||
const latest = () => utils.container.querySelector(".fab--latest.is-visible");
|
||||
return { ...utils, scroll, box, scrollTo, latest };
|
||||
}
|
||||
|
||||
it("keeps following when the stream grew under the viewport (no user input)", () => {
|
||||
const { scroll, box, latest } = renderWithViewport();
|
||||
|
||||
// The virtualizer measured taller items after the pin: the scroll
|
||||
// position is now far from the bottom, but nobody scrolled.
|
||||
box.top = 900;
|
||||
fireEvent.scroll(scroll);
|
||||
expect(latest()).toBeNull();
|
||||
|
||||
// An explicit wheel up that moves the view up does stop following.
|
||||
fireEvent.wheel(scroll, { deltaY: -120 });
|
||||
box.top = 800;
|
||||
fireEvent.scroll(scroll);
|
||||
expect(latest()).not.toBeNull();
|
||||
|
||||
// Returning to the bottom (by wheel) re-arms it.
|
||||
fireEvent.wheel(scroll, { deltaY: 4000 });
|
||||
box.top = box.height - box.client;
|
||||
fireEvent.scroll(scroll);
|
||||
expect(latest()).toBeNull();
|
||||
});
|
||||
|
||||
it("re-pins to the newest item on every content resize while following", () => {
|
||||
const observed: (() => void)[] = [];
|
||||
const original = globalThis.ResizeObserver;
|
||||
class RecordingObserver {
|
||||
constructor(callback: () => void) {
|
||||
observed.push(callback);
|
||||
}
|
||||
observe(): void {}
|
||||
unobserve(): void {}
|
||||
disconnect(): void {}
|
||||
}
|
||||
globalThis.ResizeObserver = RecordingObserver as unknown as typeof ResizeObserver;
|
||||
try {
|
||||
const { box, scrollTo } = renderWithViewport();
|
||||
expect(observed.length).toBeGreaterThan(0);
|
||||
|
||||
box.height = 3200;
|
||||
for (const callback of observed) callback();
|
||||
expect(scrollTo).toHaveBeenCalled();
|
||||
expect(box.top).toBe(3200);
|
||||
} finally {
|
||||
globalThis.ResizeObserver = original;
|
||||
}
|
||||
});
|
||||
|
||||
it("stops re-pinning once the user scrolled away", () => {
|
||||
const observed: (() => void)[] = [];
|
||||
const original = globalThis.ResizeObserver;
|
||||
class RecordingObserver {
|
||||
constructor(callback: () => void) {
|
||||
observed.push(callback);
|
||||
}
|
||||
observe(): void {}
|
||||
unobserve(): void {}
|
||||
disconnect(): void {}
|
||||
}
|
||||
globalThis.ResizeObserver = RecordingObserver as unknown as typeof ResizeObserver;
|
||||
try {
|
||||
const { scroll, box, scrollTo, latest } = renderWithViewport();
|
||||
|
||||
fireEvent.wheel(scroll, { deltaY: -200 });
|
||||
box.top = 400;
|
||||
fireEvent.scroll(scroll);
|
||||
expect(latest()).not.toBeNull();
|
||||
|
||||
scrollTo.mockClear();
|
||||
box.height = 3600;
|
||||
for (const callback of observed) callback();
|
||||
expect(scrollTo).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
globalThis.ResizeObserver = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -510,10 +510,12 @@ function workspaceBody() {
|
||||
}
|
||||
|
||||
function sessionsBody() {
|
||||
// Two live tabs. `tab` is the plugin's live projection of `attached_tab`;
|
||||
// without it a row is disk history, not a tab.
|
||||
return {
|
||||
sessions: [
|
||||
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle" },
|
||||
{ sessionId: "s2", name: "Beta", workspaceId: "W1", cwd: "/work/w1", status: "busy" },
|
||||
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle", tab: 1, live: true },
|
||||
{ sessionId: "s2", name: "Beta", workspaceId: "W1", cwd: "/work/w1", status: "busy", tab: 2, live: true },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -531,7 +533,16 @@ function subSessionBody() {
|
||||
parentId: "s1",
|
||||
visible: false,
|
||||
},
|
||||
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle", visible: true },
|
||||
{
|
||||
sessionId: "s1",
|
||||
name: "Alpha",
|
||||
workspaceId: "W1",
|
||||
cwd: "/work/w1",
|
||||
status: "idle",
|
||||
visible: true,
|
||||
tab: 1,
|
||||
live: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -724,3 +735,68 @@ describe("chat session deep link", () => {
|
||||
expect(await screen.findByTestId("session-not-found")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* The list is the nvim tab set, not the workspace's JSONL history. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** What `workspace.query{kind:"sessions"}` answers: live tabs ∪ every JSONL on disk. */
|
||||
function mixedBody() {
|
||||
return {
|
||||
sessions: [
|
||||
{ sessionId: "hist", name: "Yesterday", workspaceId: "W1", cwd: "/work/w1", status: "done", modified: 2 },
|
||||
{
|
||||
sessionId: "s1",
|
||||
name: "Alpha",
|
||||
workspaceId: "W1",
|
||||
cwd: "/work/w1",
|
||||
status: "idle",
|
||||
tab: 1,
|
||||
live: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("chat session list mirrors the nvim tabs", () => {
|
||||
beforeEach(() => {
|
||||
useSessionsStore.getState().reset();
|
||||
useChatStore.setState({ history: {}, sending: null });
|
||||
silentSocket();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("renders the tab-backed session and never a disk-only historical row", async () => {
|
||||
mockApi([
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
|
||||
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: mixedBody() }) },
|
||||
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
|
||||
{ path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Alpha first message") }) },
|
||||
]);
|
||||
|
||||
await renderPage(chatRoutes(), "/chat?workspace=W1");
|
||||
|
||||
expect(await screen.findByText("Alpha first message")).toBeInTheDocument();
|
||||
await waitFor(() => expect(document.querySelector('[data-session-id="s1"]')).not.toBeNull());
|
||||
expect(document.querySelector('[data-session-id="hist"]')).toBeNull();
|
||||
expect(screen.queryByText("Yesterday")).toBeNull();
|
||||
});
|
||||
|
||||
it("answers a deep link into history with not-found and no composer", async () => {
|
||||
const fetchMock = mockApi([
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
|
||||
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: mixedBody() }) },
|
||||
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
|
||||
]);
|
||||
|
||||
await renderPage(chatRoutes(), "/chat/hist?workspace=W1");
|
||||
|
||||
expect(await screen.findByTestId("session-not-found")).toBeInTheDocument();
|
||||
// A historical row has no live owner: replying must not be offered.
|
||||
expect(within(streamPane()).queryByLabelText("Message input")).toBeNull();
|
||||
expect(requestedUrls(fetchMock).some((url) => url.includes("/sessions/hist/entries"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { act } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { renderPage, type TestRoute } from "./helpers/render-page";
|
||||
|
||||
import { ServerChip } from "@/components/shared/server-chip";
|
||||
import type { InfoResponse } from "@/lib/api";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
/** Realistic daemon /info response payload without `status` field. */
|
||||
const realisticInfo: InfoResponse = {
|
||||
v: 1,
|
||||
daemonId: "daemon-test-1",
|
||||
machineId: "machine-test-1",
|
||||
platform: "linux",
|
||||
hostname: "devbook-eos",
|
||||
os: "Linux 6.12.0",
|
||||
version: "0.1.3",
|
||||
uptimeMs: 123456,
|
||||
port: 7676,
|
||||
capabilities: ["read", "steer"],
|
||||
limits: { maxInstances: 5 },
|
||||
};
|
||||
|
||||
const routes = (): TestRoute[] => [
|
||||
{
|
||||
path: "/",
|
||||
component: () => <ServerChip />,
|
||||
},
|
||||
{
|
||||
path: "/status",
|
||||
component: () => <div>Status Page</div>,
|
||||
},
|
||||
];
|
||||
|
||||
describe("ServerChip", () => {
|
||||
beforeEach(() => {
|
||||
setLanguage("en");
|
||||
useConnectionStore.getState().disconnect();
|
||||
useConnectionStore.getState().connect({ endpoint: "http://127.0.0.1:7676" });
|
||||
});
|
||||
|
||||
it("renders dot--ok and Online in English / 在线 in Chinese when serverStatus is online with status-less info payload", async () => {
|
||||
// Explicitly assert that realisticInfo does not contain a wire `status` field.
|
||||
expect("status" in realisticInfo).toBe(false);
|
||||
|
||||
const { container } = await renderPage(routes(), "/", { paired: true });
|
||||
|
||||
act(() => {
|
||||
const store = useConnectionStore.getState();
|
||||
store.setServer(realisticInfo);
|
||||
store.setServerStatus("online");
|
||||
});
|
||||
|
||||
const dot = container.querySelector(".server-chip .dot");
|
||||
expect(dot).not.toBeNull();
|
||||
expect(dot).toHaveClass("dot--ok");
|
||||
expect(dot).not.toHaveClass("dot--exited");
|
||||
expect(dot?.getAttribute("title")).toBe("Online");
|
||||
expect(dot?.getAttribute("aria-label")).toBe("Online");
|
||||
|
||||
// Verify Chinese localization
|
||||
act(() => {
|
||||
setLanguage("zh");
|
||||
});
|
||||
expect(dot?.getAttribute("title")).toBe("在线");
|
||||
expect(dot?.getAttribute("aria-label")).toBe("在线");
|
||||
});
|
||||
|
||||
it("renders dot--idle and Unknown / 未知 when serverStatus is unknown", async () => {
|
||||
const { container } = await renderPage(routes(), "/", { paired: true });
|
||||
|
||||
act(() => {
|
||||
const store = useConnectionStore.getState();
|
||||
store.setServer(realisticInfo);
|
||||
store.setServerStatus("unknown");
|
||||
});
|
||||
|
||||
const dot = container.querySelector(".server-chip .dot");
|
||||
expect(dot).not.toBeNull();
|
||||
expect(dot).toHaveClass("dot--idle");
|
||||
expect(dot?.getAttribute("title")).toBe("Unknown");
|
||||
expect(dot?.getAttribute("aria-label")).toBe("Unknown");
|
||||
|
||||
act(() => {
|
||||
setLanguage("zh");
|
||||
});
|
||||
expect(dot?.getAttribute("title")).toBe("未知");
|
||||
expect(dot?.getAttribute("aria-label")).toBe("未知");
|
||||
});
|
||||
|
||||
it("renders dot--exited and Offline / 离线 when serverStatus is offline", async () => {
|
||||
const { container } = await renderPage(routes(), "/", { paired: true });
|
||||
|
||||
act(() => {
|
||||
const store = useConnectionStore.getState();
|
||||
store.setServer(realisticInfo);
|
||||
store.setServerStatus("offline");
|
||||
});
|
||||
|
||||
const dot = container.querySelector(".server-chip .dot");
|
||||
expect(dot).not.toBeNull();
|
||||
expect(dot).toHaveClass("dot--exited");
|
||||
expect(dot?.getAttribute("title")).toBe("Offline");
|
||||
expect(dot?.getAttribute("aria-label")).toBe("Offline");
|
||||
|
||||
act(() => {
|
||||
setLanguage("zh");
|
||||
});
|
||||
expect(dot?.getAttribute("title")).toBe("离线");
|
||||
expect(dot?.getAttribute("aria-label")).toBe("离线");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveServerStatus, type ServerStatusInput } from "@/features/status/server";
|
||||
import type { InfoResponse } from "@/lib/api";
|
||||
|
||||
/** Exact real payload shape from the daemon: no `status` field present. */
|
||||
const realisticInfo: InfoResponse = {
|
||||
v: 1,
|
||||
daemonId: "daemon-test-1",
|
||||
machineId: "machine-test-1",
|
||||
platform: "linux",
|
||||
hostname: "devbook-eos",
|
||||
os: "Linux 6.12.0",
|
||||
version: "0.1.3",
|
||||
uptimeMs: 123456,
|
||||
port: 7676,
|
||||
capabilities: ["read", "steer"],
|
||||
limits: { maxInstances: 5 },
|
||||
};
|
||||
|
||||
describe("resolveServerStatus", () => {
|
||||
it("resolves unpaired client to offline", () => {
|
||||
const input: ServerStatusInput = {
|
||||
paired: false,
|
||||
info: realisticInfo,
|
||||
healthOk: true,
|
||||
};
|
||||
expect(resolveServerStatus(input)).toBe("offline");
|
||||
expect(resolveServerStatus({ paired: false })).toBe("offline");
|
||||
});
|
||||
|
||||
it("resolves infoError to offline", () => {
|
||||
const input: ServerStatusInput = {
|
||||
paired: true,
|
||||
infoError: true,
|
||||
healthOk: true,
|
||||
};
|
||||
expect(resolveServerStatus(input)).toBe("offline");
|
||||
});
|
||||
|
||||
it("resolves info present + healthOk === false to degraded", () => {
|
||||
const input: ServerStatusInput = {
|
||||
paired: true,
|
||||
info: realisticInfo,
|
||||
healthOk: false,
|
||||
};
|
||||
expect(resolveServerStatus(input)).toBe("degraded");
|
||||
});
|
||||
|
||||
it("resolves info present in exact real payload shape (no status field) to online", () => {
|
||||
// Assert property absence so the regression contract is explicitly guarded.
|
||||
expect("status" in realisticInfo).toBe(false);
|
||||
|
||||
expect(
|
||||
resolveServerStatus({
|
||||
paired: true,
|
||||
info: realisticInfo,
|
||||
}),
|
||||
).toBe("online");
|
||||
|
||||
expect(
|
||||
resolveServerStatus({
|
||||
paired: true,
|
||||
info: realisticInfo,
|
||||
healthOk: true,
|
||||
}),
|
||||
).toBe("online");
|
||||
});
|
||||
|
||||
it("resolves nothing yet to unknown", () => {
|
||||
expect(
|
||||
resolveServerStatus({
|
||||
paired: true,
|
||||
}),
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("resolves paired with info: null, healthOk: true to unknown", () => {
|
||||
expect(
|
||||
resolveServerStatus({
|
||||
paired: true,
|
||||
info: null,
|
||||
healthOk: true,
|
||||
}),
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("resolves paired with info: null, healthOk: null to unknown", () => {
|
||||
expect(
|
||||
resolveServerStatus({
|
||||
paired: true,
|
||||
info: null,
|
||||
healthOk: null,
|
||||
}),
|
||||
).toBe("unknown");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeSessionsPayload, tabSessionRows } from "@/features/chat/session-state";
|
||||
|
||||
/**
|
||||
* `workspace.query{kind:"sessions"}` rows come from the plugin as a union of the
|
||||
* workspace's JSONL history and its live sessions. Only the tab-backed component
|
||||
* is the nvim session list; everything else is history.
|
||||
*/
|
||||
|
||||
function ids(rows: Record<string, unknown>[]): string[] {
|
||||
return rows.map((row) => String(row.sessionId ?? row.session_id ?? row.id));
|
||||
}
|
||||
|
||||
describe("tabSessionRows", () => {
|
||||
it("drops disk-only history and keeps the tab-backed row", () => {
|
||||
const raw = {
|
||||
sessions: [
|
||||
{ sessionId: "old-1", name: "history one", status: "done" },
|
||||
{ sessionId: "tab-1", name: "the only tab", tab: 1, live: true, status: "idle" },
|
||||
{ sessionId: "old-2", name: "history two" },
|
||||
],
|
||||
};
|
||||
|
||||
expect(ids(tabSessionRows(raw))).toEqual(["tab-1"]);
|
||||
});
|
||||
|
||||
it("drops a live session that owns no tab", () => {
|
||||
// A detached background session is not an nvim tab: `:PiSessions` renders
|
||||
// it as a child row, never as a root.
|
||||
const raw = {
|
||||
sessions: [
|
||||
{ sessionId: "tab-1", tab: 1, live: true },
|
||||
{ sessionId: "detached", live: true, status: "busy" },
|
||||
],
|
||||
};
|
||||
|
||||
expect(ids(tabSessionRows(raw))).toEqual(["tab-1"]);
|
||||
});
|
||||
|
||||
it("keeps the sub-sessions linked to a tab, at any depth", () => {
|
||||
const raw = {
|
||||
sessions: [
|
||||
{ sessionId: "child", parentId: "tab-1", status: "interrupted" },
|
||||
{ sessionId: "grandchild", parentId: "child", status: "done" },
|
||||
{ sessionId: "tab-1", tab: 1, live: true },
|
||||
{ sessionId: "orphan-history", parentId: "gone", status: "done" },
|
||||
],
|
||||
};
|
||||
|
||||
expect(ids(tabSessionRows(raw))).toEqual(["child", "grandchild", "tab-1"]);
|
||||
});
|
||||
|
||||
it("keeps the parent row when the tab is in a child view", () => {
|
||||
// `view_parent_id`: the tab is attached to the child session, the parent
|
||||
// row anchors the tree and its other children stay in the list.
|
||||
const raw = {
|
||||
sessions: [
|
||||
{ sessionId: "root", live: true, status: "idle" },
|
||||
{ sessionId: "viewed-child", parentId: "root", tab: 2, live: true },
|
||||
{ sessionId: "sibling", parentId: "root", status: "completed" },
|
||||
],
|
||||
};
|
||||
|
||||
expect(ids(tabSessionRows(raw))).toEqual(["root", "viewed-child", "sibling"]);
|
||||
});
|
||||
|
||||
it("accepts a bare array payload and the snake_case aliases", () => {
|
||||
const raw = [
|
||||
{ session_id: "old" },
|
||||
{ session_id: "child", parent_id: "tab-1" },
|
||||
{ session_id: "tab-1", tab: 3 },
|
||||
];
|
||||
|
||||
expect(ids(tabSessionRows(raw))).toEqual(["child", "tab-1"]);
|
||||
});
|
||||
|
||||
it("returns no rows when nothing is attached to a tab", () => {
|
||||
expect(tabSessionRows({ sessions: [{ sessionId: "old-1" }, { sessionId: "old-2" }] })).toEqual([]);
|
||||
expect(tabSessionRows({ sessions: [] })).toEqual([]);
|
||||
expect(tabSessionRows(undefined)).toEqual([]);
|
||||
});
|
||||
|
||||
it("feeds the render states so a historical row never reaches the tree", () => {
|
||||
const states = normalizeSessionsPayload(
|
||||
tabSessionRows({
|
||||
sessions: [
|
||||
{ sessionId: "old-1", name: "history", status: "done" },
|
||||
{ sessionId: "tab-1", name: "the only tab", tab: 1, live: true, status: "idle" },
|
||||
],
|
||||
}),
|
||||
"w1",
|
||||
);
|
||||
|
||||
expect(states.map((state) => state.sessionId)).toEqual(["tab-1"]);
|
||||
expect(states[0]?.name).toBe("the only tab");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { FALLBACK_NAME_CHARS, sessionTitle, subagentTitle } from "@/features/chat/session-title";
|
||||
|
||||
const phrases = { unnamed: "(unnamed)", subagentUnnamed: "sub-session" };
|
||||
|
||||
describe("sessionTitle", () => {
|
||||
it("prefers the session's own name", () => {
|
||||
expect(sessionTitle({ name: "Fix login", firstMessage: "hello" }, phrases)).toEqual({
|
||||
text: "Fix login",
|
||||
kind: "name",
|
||||
provisional: false,
|
||||
spinner: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("trims the name and falls through when it is blank", () => {
|
||||
expect(sessionTitle({ name: " Fix login " }, phrases).text).toBe("Fix login");
|
||||
expect(sessionTitle({ name: " ", firstMessage: "hello" }, phrases).text).toBe("hello");
|
||||
expect(sessionTitle({ name: "", firstMessage: "" }, phrases).text).toBe("(unnamed)");
|
||||
});
|
||||
|
||||
it("falls back to the first user message (pi2.nvim's first_message)", () => {
|
||||
expect(sessionTitle({ name: null, firstMessage: " Fix the auth bug " }, phrases)).toEqual({
|
||||
text: "Fix the auth bug",
|
||||
kind: "first-message",
|
||||
provisional: false,
|
||||
spinner: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows (unnamed) when nothing is known — never an id", () => {
|
||||
const title = sessionTitle({ name: null, firstMessage: null }, phrases);
|
||||
expect(title).toEqual({ text: "(unnamed)", kind: "unnamed", provisional: true, spinner: false });
|
||||
});
|
||||
|
||||
it("suppresses the first message and spins while the backend generates a title", () => {
|
||||
expect(sessionTitle({ name: null, firstMessage: "Fix the auth bug", titleGenerating: true }, phrases)).toEqual({
|
||||
text: "(unnamed)",
|
||||
kind: "generating",
|
||||
provisional: true,
|
||||
spinner: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("drops the spinner the moment a real name arrives", () => {
|
||||
const title = sessionTitle({ name: "Fix login", titleGenerating: true }, phrases);
|
||||
expect(title.kind).toBe("name");
|
||||
expect(title.spinner).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("subagentTitle", () => {
|
||||
it("prefers the sub-session name", () => {
|
||||
expect(subagentTitle({ name: "researcher", task: "Research the auth flow" }, phrases).text).toBe("researcher");
|
||||
});
|
||||
|
||||
it("derives the name from the task prompt, capped like Manifest.fallback_name", () => {
|
||||
const task = "x".repeat(FALLBACK_NAME_CHARS + 25);
|
||||
const title = subagentTitle({ name: null, task }, phrases);
|
||||
expect(title.text).toBe("x".repeat(FALLBACK_NAME_CHARS));
|
||||
expect(title.kind).toBe("task");
|
||||
expect(FALLBACK_NAME_CHARS).toBe(40);
|
||||
});
|
||||
|
||||
it("falls back to sub-session — never the subagent id", () => {
|
||||
expect(subagentTitle({ name: " ", task: "" }, phrases)).toEqual({
|
||||
text: "sub-session",
|
||||
kind: "unnamed",
|
||||
provisional: true,
|
||||
spinner: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { SessionTree } from "@/features/chat/session-tree";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import type { SessionState } from "@/lib/protocol";
|
||||
|
||||
import { sessionFixture, subagentFixture } from "./chat-fixtures";
|
||||
|
||||
beforeAll(async () => {
|
||||
await setLanguage("en");
|
||||
});
|
||||
|
||||
/** The title of the row for `sessionId` (`null` when the row is absent). */
|
||||
function rowTitleText(container: HTMLElement, sessionId: string): string | null {
|
||||
const row = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"]`);
|
||||
return row?.querySelector<HTMLElement>(".t-name")?.textContent?.trim() ?? null;
|
||||
}
|
||||
|
||||
function renderTree(overrides: Partial<ComponentProps<typeof SessionTree>> = {}) {
|
||||
const sessions = overrides.sessions ?? [];
|
||||
return render(
|
||||
<SessionTree
|
||||
sessions={sessions}
|
||||
workspaces={[
|
||||
{
|
||||
workspaceId: "W1",
|
||||
cwd: "/work/w1",
|
||||
name: "W1",
|
||||
trusted: true,
|
||||
exists: true,
|
||||
sessionCount: sessions.length,
|
||||
liveCount: 0,
|
||||
lastActiveAt: 0,
|
||||
instance: null,
|
||||
},
|
||||
]}
|
||||
activeWorkspaceId="W1"
|
||||
selectedId={null}
|
||||
activeSubagentId={null}
|
||||
filter=""
|
||||
collapsed={{}}
|
||||
activeOnly={false}
|
||||
showHidden={false}
|
||||
connected
|
||||
creating={false}
|
||||
onFilter={vi.fn()}
|
||||
onToggleCollapse={vi.fn()}
|
||||
onToggleAll={vi.fn()}
|
||||
onToggleActiveOnly={vi.fn()}
|
||||
onToggleShowHidden={vi.fn()}
|
||||
onSelectSession={vi.fn()}
|
||||
onSelectWorkspace={vi.fn()}
|
||||
onSelectSubagent={vi.fn()}
|
||||
onNewSession={vi.fn()}
|
||||
onRenameSession={vi.fn()}
|
||||
onCloseSession={vi.fn()}
|
||||
onDispatchSubagent={vi.fn()}
|
||||
onRenameSubagent={vi.fn()}
|
||||
{...overrides}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("session list titles (pi2.nvim parity)", () => {
|
||||
it("renders (unnamed) for a session without a name and never the session id", () => {
|
||||
const sessionId = "9f8c1d2e-0000-4000-8000-aaaaaaaaaaaa";
|
||||
const { container } = renderTree({
|
||||
sessions: [sessionFixture({ sessionId, name: null, firstMessage: null })],
|
||||
});
|
||||
|
||||
expect(rowTitleText(container, sessionId)).toBe("(unnamed)");
|
||||
expect(container.textContent ?? "").not.toContain(sessionId);
|
||||
// Identity still rides on the DOM attribute (routing/select handlers).
|
||||
expect(container.querySelector(`[data-session-id="${sessionId}"]`)).not.toBeNull();
|
||||
});
|
||||
|
||||
it("marks the placeholder so it renders as the muted, non-animated state", () => {
|
||||
const sessionId = "s-unnamed";
|
||||
const { container } = renderTree({
|
||||
sessions: [sessionFixture({ sessionId, name: null, firstMessage: null })],
|
||||
});
|
||||
const name = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"] .t-name`);
|
||||
expect(name?.classList.contains("is-unnamed")).toBe(true);
|
||||
expect(name?.classList.contains("is-generating")).toBe(false);
|
||||
});
|
||||
|
||||
it("prefers the first user message over the placeholder", () => {
|
||||
const sessionId = "s-first";
|
||||
const { container } = renderTree({
|
||||
sessions: [sessionFixture({ sessionId, name: null, firstMessage: "Fix the auth bug" })],
|
||||
});
|
||||
expect(rowTitleText(container, sessionId)).toBe("Fix the auth bug");
|
||||
});
|
||||
|
||||
it("keeps (unnamed) and prefixes the braille spinner while a title is generated", () => {
|
||||
const sessionId = "s-generating";
|
||||
// The plugin's `pi-title` status is not on the wire yet, so the flag is
|
||||
// injected here: the row must already react the way pi2.nvim does.
|
||||
const session = {
|
||||
...sessionFixture({ sessionId, name: null, firstMessage: "Fix the auth bug" }),
|
||||
titleGenerating: true,
|
||||
} as SessionState;
|
||||
const { container } = renderTree({ sessions: [session] });
|
||||
|
||||
const row = container.querySelector<HTMLElement>(`[data-session-id="${sessionId}"]`);
|
||||
// Spinner is a prefix, the name stays the placeholder (no first message).
|
||||
expect(row?.querySelector(".t-spinner")).not.toBeNull();
|
||||
expect(rowTitleText(container, sessionId)).toBe("(unnamed)");
|
||||
expect(row?.querySelector(".t-name")?.classList.contains("is-generating")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the real name when there is one", () => {
|
||||
const { container } = renderTree({
|
||||
sessions: [sessionFixture({ sessionId: "s-named", name: "Alpha", subagents: [] })],
|
||||
});
|
||||
expect(rowTitleText(container, "s-named")).toBe("Alpha");
|
||||
});
|
||||
|
||||
it("labels a nameless sub-session by its task prompt, not its id", () => {
|
||||
const subagent = subagentFixture({ id: "sub-uuid-1234", name: undefined, task: "Survey the plugin bridge" });
|
||||
const { container } = renderTree({
|
||||
sessions: [sessionFixture({ sessionId: "s-parent", name: "Alpha", subagents: [subagent] })],
|
||||
});
|
||||
|
||||
const sub = container.querySelector<HTMLElement>('[data-subagent-id="sub-uuid-1234"] .t-name');
|
||||
expect(sub?.textContent?.trim()).toBe("Survey the plugin bridge");
|
||||
expect(container.textContent ?? "").not.toContain("sub-uuid-1234");
|
||||
});
|
||||
|
||||
it("falls back to sub-session when the manifest carries no name or task", () => {
|
||||
const subagent = subagentFixture({ id: "sub-empty", name: undefined, task: undefined });
|
||||
const { container } = renderTree({
|
||||
sessions: [sessionFixture({ sessionId: "s-parent", name: "Alpha", subagents: [subagent] })],
|
||||
});
|
||||
expect(screen.getByText("sub-session")).toBeTruthy();
|
||||
expect(container.textContent ?? "").not.toContain("sub-empty");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user