perf(subagent): read saved task history by loaded turns (#6634)
This commit is contained in:
1 parent
1196698ecb
commit
eb8546c321
20 files changed
+893
-97
No files matched your search
@@ -34,6 +34,7 @@ import {
|
||||
fetchTrendingMarketplaceSkills,
|
||||
fetchWebuiThread,
|
||||
fetchSubagentThread,
|
||||
fetchSubagentTasks,
|
||||
fetchWebuiThreadTraceDetail,
|
||||
fetchWorkspaces,
|
||||
importMcpConfig,
|
||||
@@ -105,6 +106,20 @@ describe("webui API helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("splits a large subagent window into bounded reads", async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({ ok: true, json: async () => ({ tasks: [] }) } as Response);
|
||||
const turnIds = Array.from({ length: 400 }, (_, index) => `turn-${index}-${"x".repeat(32)}`);
|
||||
await expect(fetchSubagentTasks("tok", "websocket:chat-1", {
|
||||
turnIds, trackedIds: ["task-1"],
|
||||
})).resolves.toEqual({ tasks: [] });
|
||||
const urls = vi.mocked(fetch).mock.calls.map(([url]) => new URL(String(url), "http://localhost"));
|
||||
expect(urls.length).toBeGreaterThan(1);
|
||||
expect(urls.every((url) => url.search.length <= 5001)).toBe(true);
|
||||
expect(urls.every((url) => url.searchParams.get("scope") === "window")).toBe(true);
|
||||
expect(urls.flatMap((url) => url.searchParams.getAll("turn_id"))).toEqual(turnIds);
|
||||
expect(urls.flatMap((url) => url.searchParams.getAll("track"))).toEqual(["task-1"]);
|
||||
});
|
||||
|
||||
it("percent-encodes websocket keys when fetching webui-thread snapshot", async () => {
|
||||
await fetchWebuiThread("tok", "websocket:chat-1");
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ function mockFetchRoutes(routes: Record<string, unknown>): void {
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const route = routes[String(input)]
|
||||
?? (String(input) === "/api/webui/sidebar-state" ? {} : undefined)
|
||||
?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(String(input)) ? { tasks: [] } : undefined);
|
||||
?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(new URL(String(input), "http://localhost").pathname) ? { tasks: [] } : undefined);
|
||||
const body =
|
||||
typeof route === "function"
|
||||
? await (route as () => unknown | Promise<unknown>)()
|
||||
@@ -415,7 +415,7 @@ describe("App layout", () => {
|
||||
terminal: { webui: { capabilities: supported ? ["webui.core.v1", "webui.subagents.v1"] : ["webui.core.v1"] } },
|
||||
});
|
||||
mockFetchRoutes({
|
||||
"/api/sessions/websocket%3Achat-a/subagents": { tasks: [{
|
||||
"/api/sessions/websocket%3Achat-a/subagents?scope=window": { tasks: [{
|
||||
task_id: "task-1", label: "Config check", task_description: "Inspect configuration",
|
||||
state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1,
|
||||
tool_events: [], usage: null, receipts: {}, result: null, partial: false,
|
||||
@@ -434,7 +434,7 @@ describe("App layout", () => {
|
||||
await userEvent.setup().click(trigger);
|
||||
expect(await screen.findByRole("button", { name: /Config check Running/ })).toBeVisible();
|
||||
} else expect(screen.queryByRole("button", { name: /Subtasks/ })).not.toBeInTheDocument();
|
||||
const reads = vi.mocked(fetch).mock.calls.filter(([url]) => String(url).endsWith("/subagents"));
|
||||
const reads = vi.mocked(fetch).mock.calls.filter(([url]) => new URL(String(url), "http://localhost").pathname.endsWith("/subagents"));
|
||||
expect(reads).toHaveLength(supported ? 1 : 0);
|
||||
expect(requestMutationSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -67,7 +67,7 @@ describe("transcript replay with real task and stream subscriptions", () => {
|
||||
const tree = (showThread: boolean) => (
|
||||
<ClientProvider client={client} token="test">
|
||||
<SubagentTasksProvider client={client} sessionKey={`websocket:${CHAT_ID}`}
|
||||
token="test" enabled liveEvents>{showThread && <Thread />}</SubagentTasksProvider>
|
||||
token="test" enabled liveEvents turnIds={[TURN_ID]}>{showThread && <Thread />}</SubagentTasksProvider>
|
||||
</ClientProvider>
|
||||
);
|
||||
const view = render(tree(false));
|
||||
@@ -103,7 +103,7 @@ describe("transcript replay with real task and stream subscriptions", () => {
|
||||
socket.receive(toolMessage("while-away-c"));
|
||||
const tasks = (children?: ReactNode) => (
|
||||
<SubagentTasksProvider client={client} sessionKey={`websocket:${CHAT_ID}`}
|
||||
token="test" enabled liveEvents>{children}</SubagentTasksProvider>
|
||||
token="test" enabled liveEvents turnIds={[TURN_ID]}>{children}</SubagentTasksProvider>
|
||||
);
|
||||
const view = render(
|
||||
<ClientProvider client={client} token="test">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { act, cleanup, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { StrictMode } from "react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -7,17 +8,22 @@ import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults"
|
||||
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
|
||||
import type { InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types";
|
||||
import type { ConnectionStatus, InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types";
|
||||
|
||||
const requestMutation = vi.fn();
|
||||
const chatHandlers = new Set<(event: InboundEvent) => void>();
|
||||
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
|
||||
const client = {
|
||||
requestMutation,
|
||||
onChat: vi.fn((_chatId: string, handler: (event: InboundEvent) => void) => {
|
||||
chatHandlers.add(handler);
|
||||
return () => { chatHandlers.delete(handler); };
|
||||
}),
|
||||
onStatus: vi.fn(() => () => {}),
|
||||
onStatus: vi.fn((handler: (status: ConnectionStatus) => void) => {
|
||||
statusHandlers.add(handler);
|
||||
handler("open");
|
||||
return () => { statusHandlers.delete(handler); };
|
||||
}),
|
||||
};
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "prompt-a", role: "user", content: "Inspect config", turnId: "turn-a", createdAt: 100_000 },
|
||||
@@ -47,14 +53,17 @@ function emitTask(snapshot: SubagentTaskSnapshot) {
|
||||
chatHandlers.forEach((handler) => handler({ event: "subagent_task", chat_id: "a", task: snapshot }));
|
||||
});
|
||||
}
|
||||
function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEvents = true, historyEnabled = false, onActivityToggle }: {
|
||||
function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEvents = true, historyEnabled = false, active = true, onActivityToggle }: {
|
||||
threadMessages?: UIMessage[];
|
||||
sessionKey?: string;
|
||||
liveEvents?: boolean;
|
||||
historyEnabled?: boolean;
|
||||
active?: boolean;
|
||||
onActivityToggle?: () => void;
|
||||
} = {}) {
|
||||
return <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled}>
|
||||
return <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled} active={active}
|
||||
turnIds={[...new Set(threadMessages.filter((message) => message.role === "user" && message.turnId)
|
||||
.map((message) => message.turnId as string))]}>
|
||||
<div data-testid="messages"><SubagentThreadMessages messages={threadMessages} onActivityToggle={onActivityToggle} /></div>
|
||||
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock /><textarea aria-label="Message" /></div>
|
||||
</SubagentTasksProvider>;
|
||||
@@ -74,6 +83,7 @@ describe("subagent result archives", () => {
|
||||
client.onChat.mockClear();
|
||||
client.onStatus.mockClear();
|
||||
chatHandlers.clear();
|
||||
statusHandlers.clear();
|
||||
vi.stubGlobal("fetch", vi.fn(async () => response([task()])));
|
||||
});
|
||||
afterEach(() => {
|
||||
@@ -231,6 +241,172 @@ describe("subagent result archives", () => {
|
||||
expect(screen.getByTestId("messages").querySelectorAll("[data-subagent-id]")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "loaded", threadMessages: [messages[0]], turnIds: ["turn-a"] },
|
||||
{ name: "empty", threadMessages: [], turnIds: [] },
|
||||
])("reads the $name history window while keeping active tasks available", async ({ threadMessages, turnIds }) => {
|
||||
const old: UIMessage = { id: "old", role: "user", content: "Earlier prompt", turnId: "old", createdAt: 99_000 };
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
return response([
|
||||
task({ task_id: "live", label: "Live", state: "running", completed_at: null, origin_message_id: "elsewhere", origin_turn_id: "elsewhere" }),
|
||||
...(url.searchParams.getAll("turn_id").includes("old")
|
||||
? [task({ task_id: "old", label: "Earlier check", origin_message_id: "old", origin_turn_id: "old" })] : []),
|
||||
]);
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout({ threadMessages }));
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
expect(screen.getByTestId("messages").querySelector("[data-subagent-results]")).toBeNull();
|
||||
expect(seen[0].searchParams.get("scope")).toBe("window");
|
||||
expect(seen[0].searchParams.getAll("turn_id")).toEqual(turnIds);
|
||||
view.rerender(layout({ threadMessages: [old, messages[0]] }));
|
||||
const archive = await screen.findByRole("region", { name: "Subtasks" });
|
||||
await user.click(summary(archive));
|
||||
expect(within(archive).getByRole("button", { name: /Earlier check/ })).toBeVisible();
|
||||
expect(seen.some((url) => url.searchParams.getAll("turn_id").includes("old"))).toBe(true);
|
||||
expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
});
|
||||
|
||||
it("coalesces window changes and refreshes while reads are in flight, retaining the newest task revision", async () => {
|
||||
const first = messages[0];
|
||||
const second: UIMessage = { id: "second", role: "user", content: "Second prompt", turnId: "turn-second", createdAt: 1 };
|
||||
const seen: URL[] = [];
|
||||
let resolveFirst!: (response: Response) => void;
|
||||
let resolveSecond!: (response: Response) => void;
|
||||
const running = task({ state: "running", completed_at: null, origin_message_id: "elsewhere", origin_turn_id: "elsewhere" });
|
||||
vi.mocked(fetch).mockImplementation((input) => {
|
||||
seen.push(new URL(String(input), "http://localhost"));
|
||||
if (seen.length === 1) return new Promise<Response>((resolve) => { resolveFirst = resolve; });
|
||||
if (seen.length === 2) return new Promise<Response>((resolve) => { resolveSecond = resolve; });
|
||||
return Promise.resolve(response([task({ revision: 3, label: "Live revision 3", origin_message_id: "elsewhere", origin_turn_id: "elsewhere" })]));
|
||||
});
|
||||
const tree = (threadMessages: UIMessage[], active = true) => <StrictMode>{layout({ threadMessages, active })}</StrictMode>;
|
||||
const view = render(tree([first]));
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
view.rerender(tree([second]));
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(seen).toHaveLength(1);
|
||||
emitTask({ ...running, revision: 2, label: "Live revision 2" });
|
||||
await act(async () => resolveFirst(response([running])));
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
expect(seen[1].searchParams.getAll("turn_id")).toEqual(["turn-second"]);
|
||||
expect(seen[1].searchParams.getAll("track")).toEqual(["task-1"]);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByTestId("subagent-task-dock-trigger"));
|
||||
expect(screen.getByRole("button", { name: /Live revision 2 Running/ })).toBeVisible();
|
||||
view.rerender(tree([first]));
|
||||
await act(async () => resolveSecond(response([running])));
|
||||
// Focus invalidated the first page while its original read was in flight;
|
||||
// revisiting it must not treat that old response as fresh.
|
||||
await waitFor(() => expect(seen).toHaveLength(3));
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
expect(seen[2].searchParams.getAll("track")).toEqual(["task-1"]);
|
||||
expect(await screen.findByRole("button", { name: /Live revision 3 Completed/ })).toBeVisible();
|
||||
act(() => statusHandlers.forEach((handler) => handler("open")));
|
||||
await waitFor(() => expect(seen).toHaveLength(4));
|
||||
expect(seen[3].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
expect(seen[3].searchParams.getAll("track")).toEqual([]);
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(seen).toHaveLength(5));
|
||||
expect(seen[4].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
view.rerender(tree([first], false));
|
||||
view.rerender(tree([first]));
|
||||
await waitFor(() => expect(seen).toHaveLength(6));
|
||||
expect(seen[5].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
});
|
||||
|
||||
it("retries a failed history page when revisited without rereading a cached page", async () => {
|
||||
const first = messages[0];
|
||||
const second: UIMessage = { id: "second", role: "user", content: "Second prompt", turnId: "turn-second", createdAt: 1 };
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
if (seen.length === 2) return new Response("unavailable", { status: 503 });
|
||||
return response(url.searchParams.getAll("turn_id").includes("turn-second")
|
||||
? [task({ origin_message_id: "second", origin_turn_id: "turn-second", label: "Recovered result" })] : []);
|
||||
});
|
||||
const view = render(layout({ threadMessages: [first] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
view.rerender(layout({ threadMessages: [second] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
view.rerender(layout({ threadMessages: [first] }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(seen).toHaveLength(2);
|
||||
view.rerender(layout({ threadMessages: [second] }));
|
||||
const archive = await screen.findByRole("region", { name: "Subtasks" });
|
||||
await userEvent.setup().click(summary(archive));
|
||||
expect(within(archive).getByRole("button", { name: /Recovered result/ })).toBeVisible();
|
||||
expect(seen).toHaveLength(3);
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(["turn-second"]);
|
||||
});
|
||||
|
||||
it("revalidates a cached off-window page after reconnect misses a completed task", async () => {
|
||||
const first = messages[0];
|
||||
const second: UIMessage = { id: "second", role: "user", content: "Second prompt", turnId: "turn-second", createdAt: 1 };
|
||||
const seen: URL[] = [];
|
||||
let completedWhileOffline = false;
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
return response(completedWhileOffline && url.searchParams.getAll("turn_id").includes("turn-a")
|
||||
? [task({ origin_message_id: "prompt-a", label: "Completed while offline" })] : []);
|
||||
});
|
||||
const view = render(layout({ threadMessages: [first] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
view.rerender(layout({ threadMessages: [second] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
completedWhileOffline = true;
|
||||
act(() => statusHandlers.forEach((handler) => handler("open")));
|
||||
await waitFor(() => expect(seen).toHaveLength(3));
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(["turn-second"]);
|
||||
view.rerender(layout({ threadMessages: [first] }));
|
||||
const archive = await screen.findByRole("region", { name: "Subtasks" });
|
||||
await userEvent.setup().click(summary(archive));
|
||||
expect(within(archive).getByRole("button", { name: /Completed while offline/ })).toBeVisible();
|
||||
expect(seen[3].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
});
|
||||
|
||||
it("does not let an old session's delayed scoped read contaminate the new session", async () => {
|
||||
let resolveOld!: (response: Response) => void;
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation((input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
if (url.pathname.includes("websocket%3Aa")) return new Promise<Response>((resolve) => { resolveOld = resolve; });
|
||||
return Promise.resolve(response([task({ task_id: "new", label: "New session", state: "running", completed_at: null })]));
|
||||
});
|
||||
const view = render(layout());
|
||||
await waitFor(() => expect(resolveOld).toBeTypeOf("function"));
|
||||
view.rerender(layout({ sessionKey: "websocket:b" }));
|
||||
const user = userEvent.setup();
|
||||
await user.click(await screen.findByTestId("subagent-task-dock-trigger"));
|
||||
expect(await screen.findByRole("button", { name: /New session Running/ })).toBeVisible();
|
||||
await act(async () => resolveOld(response([task({ label: "Old session", state: "running", completed_at: null })])));
|
||||
expect(screen.queryByRole("button", { name: /Old session/ })).not.toBeInTheDocument();
|
||||
expect(seen).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("reconciles a previously active off-window task after focus", async () => {
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
return response(url.searchParams.getAll("track").includes("task-1")
|
||||
? [task({ revision: 2, origin_message_id: "other", origin_turn_id: "other" })]
|
||||
: [task({ state: "running", completed_at: null, origin_message_id: "other", origin_turn_id: "other" })]);
|
||||
});
|
||||
render(layout({ threadMessages: [messages[0]] }));
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
act(() => { window.dispatchEvent(new Event("focus")); });
|
||||
await waitFor(() => expect(seen.some((url) => url.searchParams.getAll("track").includes("task-1"))).toBe(true));
|
||||
await waitFor(() => expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Completed: 1"));
|
||||
expect(screen.getByTestId("messages").querySelector("[data-subagent-results]")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows older results only with their loaded prompt and preserves details through history navigation", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([
|
||||
task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt",
|
||||
|
||||
@@ -72,7 +72,8 @@ interface LayoutOptions {
|
||||
}
|
||||
function layout({ enabled = true, liveEvents = true, historyEnabled = false, sessionKey = "websocket:a", visible = true, active = true, inputKey = null, threadMessages = messages }: LayoutOptions = {}) {
|
||||
return <ThreadVisibilityContext.Provider value={visible}>
|
||||
<SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled={enabled} liveEvents={liveEvents} historyEnabled={historyEnabled} active={active}>
|
||||
<SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled={enabled} liveEvents={liveEvents} historyEnabled={historyEnabled} active={active}
|
||||
turnIds={[...new Set(threadMessages.flatMap(message => message.role === "user" && message.turnId ? [message.turnId] : []))]}>
|
||||
<div data-testid="messages"><SubagentThreadMessages messages={threadMessages} /></div>
|
||||
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock inputKey={inputKey ?? latestSubagentInputKey(threadMessages)} /><textarea aria-label="Message" /></div>
|
||||
</SubagentTasksProvider>
|
||||
@@ -117,7 +118,7 @@ describe("session-owned task UI", () => {
|
||||
const user = userEvent.setup();
|
||||
render(layout());
|
||||
const trigger = await screen.findByTestId("subagent-task-dock-trigger");
|
||||
expect(fetch).toHaveBeenCalledWith("/api/sessions/websocket%3Aa/subagents", expect.any(Object));
|
||||
expect(fetch).toHaveBeenCalledWith("/api/sessions/websocket%3Aa/subagents?scope=window&turn_id=turn-a", expect.any(Object));
|
||||
expect(screen.getAllByTestId("subagent-task-dock-trigger")).toEqual([trigger]);
|
||||
expect(screen.getByTestId("composer")).toContainElement(trigger);
|
||||
expect(trigger).toHaveTextContent("Running: 1");
|
||||
@@ -824,6 +825,7 @@ describe("session-owned task UI", () => {
|
||||
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout());
|
||||
await waitFor(() => expect(resolveOld).toBeTypeOf("function"));
|
||||
vi.mocked(fetch).mockResolvedValue(response([task({ task_id: "task-b", label: "Other work" })]));
|
||||
view.rerender(layout({ sessionKey: "websocket:b" }));
|
||||
const list = await openTaskList(user);
|
||||
@@ -980,6 +982,7 @@ describe("session-owned task UI", () => {
|
||||
const list = await openTaskList(user);
|
||||
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(resolveOld).toBeTypeOf("function"));
|
||||
emitTask(task({ revision: 3, state: "cancelled", completed_at: 102 }));
|
||||
vi.mocked(fetch).mockImplementationOnce(async () => response([
|
||||
task({ revision: 2 }), task({ task_id: "task-2", label: "Recovered check", created_at: 101 }),
|
||||
|
||||
@@ -544,6 +544,81 @@ describe("ThreadShell", () => {
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("queries only rendered task history as loaded pages and navigation windows change", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "task-window-pages";
|
||||
const rows = (prefix: string, count: number) => Array.from({ length: count }, (_, index) => ({
|
||||
id: `${prefix}${index}`, role: "user" as const, content: `${prefix} prompt ${index}`, turnId: `${prefix}t${index}`,
|
||||
}));
|
||||
let resolveInitial!: (response: Response) => void;
|
||||
const seen: URL[] = [];
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
if (url.pathname.endsWith("/subagents")) {
|
||||
seen.push(url);
|
||||
return Promise.resolve(httpJson({ tasks: [] }));
|
||||
}
|
||||
if (url.pathname.endsWith("/prompts")) return Promise.resolve(httpJson({ prompts: [{
|
||||
id: "nav2", preview: "nav prompt 2", answerPreview: "", createdAt: 1,
|
||||
cursor: "nav", turnId: "navt2",
|
||||
}] }));
|
||||
if (url.pathname.endsWith("/webui-thread")) {
|
||||
if (url.searchParams.get("before") === "older") return Promise.resolve(httpJson({
|
||||
...transcriptFromSimpleMessages(rows("old", 5)),
|
||||
page: { has_more_before: false, user_message_offset: 0 },
|
||||
}));
|
||||
if (url.searchParams.get("after") === "nav") return Promise.resolve(httpJson({
|
||||
...transcriptFromSimpleMessages(rows("nav", 3)),
|
||||
page: { has_more_before: false, has_more_after: true },
|
||||
}));
|
||||
return new Promise<Response>((resolve) => { resolveInitial = resolve; });
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }));
|
||||
}));
|
||||
const { container } = render(<StrictMode>{wrap(client, <ThreadShell session={session(chatId)} title="Task pages"
|
||||
onToggleSidebar={() => {}} />, null, "tok", ["webui.prompt-navigation.v1", "webui.subagents.v1", "webui.subagents.events.v1"])}</StrictMode>);
|
||||
await waitFor(() => expect(resolveInitial).toBeTypeOf("function"));
|
||||
expect(seen).toHaveLength(0);
|
||||
act(() => client._emitChat(chatId, { event: "subagent_task", chat_id: chatId, task: {
|
||||
task_id: "live-during-load", revision: 1, label: "Live during load", task_description: "Background work",
|
||||
origin_turn_id: "elsewhere", origin_message_id: null, created_at: 100, completed_at: null,
|
||||
state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1, tool_events: [],
|
||||
usage: null, receipts: {}, result: null, partial: false, stop_reason: null, error: null,
|
||||
} }));
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
await act(async () => resolveInitial(httpJson({ ...transcriptFromSimpleMessages(rows("new", 5)),
|
||||
page: { before_cursor: "older", has_more_before: true, user_message_offset: 5 },
|
||||
})));
|
||||
await screen.findByText("new prompt 4");
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
expect(seen[0].searchParams.getAll("turn_id")).toEqual(rows("new", 5).map(row => row.turnId));
|
||||
expect(seen[0].searchParams.getAll("track")).toEqual(["live-during-load"]);
|
||||
|
||||
const scroller = container.querySelector(".thread-message-viewport") as HTMLElement;
|
||||
Object.defineProperties(scroller, {
|
||||
scrollHeight: { configurable: true, value: 2400 }, clientHeight: { configurable: true, value: 600 },
|
||||
scrollTop: { configurable: true, writable: true, value: 0 },
|
||||
});
|
||||
fireEvent.keyDown(scroller, { key: "Home" });
|
||||
await screen.findByText("old prompt 0");
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
expect(seen[1].searchParams.getAll("turn_id")).toEqual(rows("old", 5).map(row => row.turnId));
|
||||
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Message navigation" }));
|
||||
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Jump to message: nav prompt 2" }));
|
||||
await screen.findByText("nav prompt 2");
|
||||
await waitFor(() => expect(seen).toHaveLength(3));
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(rows("nav", 3).map(row => row.turnId));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Scroll to bottom" }));
|
||||
await screen.findByText("new prompt 4");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(seen).toHaveLength(3);
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(seen).toHaveLength(4));
|
||||
const latest = [...rows("old", 5), ...rows("new", 5)];
|
||||
expect(seen[3].searchParams.getAll("turn_id")).toEqual(latest.map(row => row.turnId));
|
||||
});
|
||||
|
||||
it("keeps the dock and task events alive after the parent response finishes", async () => {
|
||||
const client = makeClient();
|
||||
const snapshot: SubagentTaskSnapshot = {
|
||||
@@ -553,7 +628,7 @@ describe("ThreadShell", () => {
|
||||
usage: null, receipts: {}, result: null, partial: false, stop_reason: null, error: null,
|
||||
};
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input).endsWith("/subagents")) return httpJson({ tasks: [snapshot] });
|
||||
if (new URL(String(input), "http://localhost").pathname.endsWith("/subagents")) return httpJson({ tasks: [snapshot] });
|
||||
if (String(input).includes("/webui-thread")) return httpJson(transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "Delegate inspection", turnId: "parent-turn" },
|
||||
]));
|
||||
@@ -583,7 +658,7 @@ describe("ThreadShell", () => {
|
||||
it("renders one persisted task entry at the initiating prompt through the full shell", async () => {
|
||||
const client = makeClient();
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input).endsWith("/subagents")) return httpJson({ tasks: [{
|
||||
if (new URL(String(input), "http://localhost").pathname.endsWith("/subagents")) return httpJson({ tasks: [{
|
||||
task_id: "completed-task", label: "Inspect settings", task_description: "Inspect settings",
|
||||
origin_turn_id: "delegation-turn", origin_message_id: null, created_at: 100, completed_at: 102,
|
||||
state: "done", phase: "done", elapsed_seconds: 2, iteration: 1, tool_events: [],
|
||||
|
||||
Reference in new issue
Block a user