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
@@ -7,7 +7,7 @@ import {
|
||||
InterruptedTaskIcon,
|
||||
ErrorTaskIcon,
|
||||
} from "@/components/icons/product-icons";
|
||||
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -47,11 +47,13 @@ interface SubagentTasksProviderProps {
|
||||
enabled: boolean;
|
||||
liveEvents: boolean;
|
||||
historyEnabled?: boolean;
|
||||
turnIds: string[];
|
||||
windowReady?: boolean;
|
||||
active?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, active = true, children }: SubagentTasksProviderProps) {
|
||||
export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, turnIds, windowReady = true, active = true, children }: SubagentTasksProviderProps) {
|
||||
const { t } = useTranslation("common");
|
||||
const pageVisible = usePageVisibility();
|
||||
const paneVisible = useThreadVisibility();
|
||||
@@ -64,9 +66,29 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
|
||||
const trigger = useRef<HTMLButtonElement | null>(null);
|
||||
const buttons = useRef(new Map<string, HTMLButtonElement>());
|
||||
const detailPanel = useRef<HTMLDivElement | null>(null);
|
||||
const taskRef = useRef(tasks);
|
||||
taskRef.current = tasks;
|
||||
const windowScope = { turnIds };
|
||||
const windowKey = JSON.stringify(windowScope);
|
||||
const windowRef = useRef(windowScope);
|
||||
windowRef.current = windowScope;
|
||||
const windowKeyRef = useRef(windowKey);
|
||||
windowKeyRef.current = windowKey;
|
||||
const readState = useMemo(() => ({
|
||||
turnIds: new Set<string>(), inFlight: false, force: false, epoch: 0,
|
||||
}), [client, sessionKey]);
|
||||
const readStateRef = useRef(readState);
|
||||
readStateRef.current = readState;
|
||||
const refreshRef = useRef<((force: boolean, invalidate?: boolean) => void) | null>(null);
|
||||
const mergeTasks = (incoming: SubagentTaskSnapshot[]) => {
|
||||
const next = mergeSubagentTasks(taskRef.current, incoming);
|
||||
taskRef.current = next;
|
||||
setTasks(next);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
scopeGeneration.current += 1;
|
||||
taskRef.current = [];
|
||||
setTasks([]);
|
||||
setSelectedId(null);
|
||||
setStoppingId(null);
|
||||
@@ -84,46 +106,80 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
|
||||
}, [active, paneVisible]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token) return;
|
||||
if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token || !liveEvents) return;
|
||||
let subscribing = true;
|
||||
const unsubscribeChat = client.onChat(sessionKey.slice("websocket:".length), (event) => {
|
||||
if (readStateRef.current === readState && event.event === "subagent_task" && isSubagentTask(event.task)) mergeTasks([event.task]);
|
||||
});
|
||||
const unsubscribeStatus = client.onStatus((status) => {
|
||||
if (!subscribing && status === "open") refreshRef.current?.(true, true);
|
||||
});
|
||||
subscribing = false;
|
||||
return () => { unsubscribeChat(); unsubscribeStatus(); };
|
||||
}, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible, readState]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token || !windowReady) return;
|
||||
let cancelled = false;
|
||||
let refreshing = false;
|
||||
let refreshPending = false;
|
||||
const refresh = async () => {
|
||||
if (refreshing) { refreshPending = true; return; }
|
||||
refreshing = true;
|
||||
try {
|
||||
const payload = await fetchSubagentTasks(token, sessionKey);
|
||||
if (!cancelled) {
|
||||
setTasks((current) => mergeSubagentTasks(current, payload.tasks));
|
||||
let scheduled = false;
|
||||
const read = () => {
|
||||
if (readState.inFlight) return;
|
||||
const full = readState.force;
|
||||
const current = windowRef.current;
|
||||
const requested = {
|
||||
turnIds: current.turnIds.filter((id) => full || !readState.turnIds.has(id)),
|
||||
};
|
||||
if (!full && requested.turnIds.length === 0) return;
|
||||
readState.force = false;
|
||||
readState.inFlight = true;
|
||||
const requestedKey = windowKeyRef.current;
|
||||
const requestedEpoch = readState.epoch;
|
||||
const window = {
|
||||
...requested,
|
||||
trackedIds: taskRef.current.filter(isActiveSubagentTask).map((task) => task.task_id),
|
||||
};
|
||||
let succeeded = false;
|
||||
void fetchSubagentTasks(token, sessionKey, window).then((payload) => {
|
||||
if (!mounted.current || readStateRef.current !== readState) return;
|
||||
succeeded = true;
|
||||
if (requestedEpoch === readState.epoch) {
|
||||
for (const id of requested.turnIds) readState.turnIds.add(id);
|
||||
}
|
||||
} catch {
|
||||
// Background read failures retain the last task snapshot.
|
||||
} finally {
|
||||
refreshing = false;
|
||||
if (refreshPending && !cancelled) {
|
||||
refreshPending = false;
|
||||
void refresh();
|
||||
}
|
||||
}
|
||||
mergeTasks(payload.tasks);
|
||||
}).catch(() => {
|
||||
// Background read failures retain the last task snapshot and remain retryable.
|
||||
}).finally(() => {
|
||||
readState.inFlight = false;
|
||||
if (readStateRef.current === readState
|
||||
&& (succeeded || readState.force || requestedKey !== windowKeyRef.current)) refreshRef.current?.(false);
|
||||
});
|
||||
};
|
||||
const unsubscribeChat = liveEvents ? client.onChat(sessionKey.slice("websocket:".length), (event) => {
|
||||
if (cancelled || event.event !== "subagent_task") return;
|
||||
if (!isSubagentTask(event.task)) return;
|
||||
setTasks((current) => mergeSubagentTasks(current, [event.task]));
|
||||
}) : undefined;
|
||||
const unsubscribeStatus = liveEvents ? client.onStatus((status) => {
|
||||
if (status === "open") void refresh();
|
||||
}) : undefined;
|
||||
if (!refreshing) void refresh();
|
||||
const focus = () => void refresh();
|
||||
const refresh = (force: boolean, invalidate = false) => {
|
||||
if (cancelled) return;
|
||||
if (invalidate) {
|
||||
// Events may have been missed on any previously viewed page. Mark all
|
||||
// pages stale, then refresh only the current one and revisit others lazily.
|
||||
readState.epoch += 1;
|
||||
readState.turnIds.clear();
|
||||
}
|
||||
if (force) readState.force = true;
|
||||
if (scheduled) return;
|
||||
scheduled = true;
|
||||
// Coalesce layout-driven window changes and Strict Mode effect replays.
|
||||
queueMicrotask(() => { scheduled = false; if (!cancelled) read(); });
|
||||
};
|
||||
refreshRef.current = refresh;
|
||||
refresh(true, true);
|
||||
const focus = () => refresh(true, true);
|
||||
window.addEventListener("focus", focus);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribeChat?.();
|
||||
unsubscribeStatus?.();
|
||||
refreshRef.current = null;
|
||||
window.removeEventListener("focus", focus);
|
||||
};
|
||||
}, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible]);
|
||||
}, [client, enabled, active, sessionKey, token, pageVisible, paneVisible, windowReady, readState]);
|
||||
|
||||
useEffect(() => { refreshRef.current?.(false); }, [windowKey]);
|
||||
|
||||
const stop = async (task: SubagentTaskSnapshot) => {
|
||||
if (!sessionKey) return;
|
||||
@@ -133,7 +189,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
|
||||
try {
|
||||
const next = await cancelSubagentTask(client, sessionKey, task.task_id);
|
||||
if (!mounted.current || generation !== scopeGeneration.current) return;
|
||||
setTasks((current) => mergeSubagentTasks(current, [next]));
|
||||
mergeTasks([next]);
|
||||
} catch (reason) {
|
||||
if (mounted.current && generation === scopeGeneration.current) setStopError(reason instanceof Error ? reason.message : t("thread.subagents.stopFailed"));
|
||||
} finally {
|
||||
|
||||
@@ -485,6 +485,17 @@ export function ThreadShell({
|
||||
const { t } = useTranslation();
|
||||
const chatId = session?.chatId ?? null;
|
||||
const historyKey = temporary ? null : session?.key ?? null;
|
||||
const [visibleWindow, setVisibleWindow] = useState<{ key: string | null; turnIds: string[]; hasMessages: boolean } | null>(null);
|
||||
const reportVisibleMessages = useCallback((messages: UIMessage[]) => {
|
||||
// Saved results attach to turns, so only the rendered user turns matter here.
|
||||
const turnIds = [...new Set(messages.flatMap((message) => (
|
||||
message.role === "user" && message.turnId ? [message.turnId] : []
|
||||
)))];
|
||||
setVisibleWindow((current) => current?.key === historyKey && current.hasMessages === (messages.length > 0)
|
||||
&& current.turnIds.length === turnIds.length
|
||||
&& current.turnIds.every((turnId, index) => turnId === turnIds[index])
|
||||
? current : { key: historyKey, turnIds, hasMessages: messages.length > 0 });
|
||||
}, [historyKey]);
|
||||
const previewSessionKey = session?.key ?? null;
|
||||
const mentionSessions = useMemo(
|
||||
() => sessions.filter((candidate) => candidate.key !== historyKey).map((candidate) => {
|
||||
@@ -1527,6 +1538,8 @@ export function ThreadShell({
|
||||
sessionKey={session?.key ?? null}
|
||||
liveEvents={webuiCapabilities.includes("webui.subagents.events.v1")}
|
||||
historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
|
||||
turnIds={visibleWindow?.key === historyKey ? visibleWindow.turnIds : []}
|
||||
windowReady={messagesReady && visibleWindow?.key === historyKey && (!initialHistoryLoading || visibleWindow.hasMessages)}
|
||||
active={composerActive}
|
||||
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
|
||||
<section ref={setSidebarHost} style={{ "--sidebar-enter-width": `${sidebarEnterWidth}px`, "--sidebar-enter-mobile-width": sidebarEnterWidth ? "100%" : "0px" } as CSSProperties} data-preview-open={sidebarOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
@@ -1573,6 +1586,7 @@ export function ThreadShell({
|
||||
activeTurnStartedHere={activeTurnStartedHere}
|
||||
conversationKey={historyKey}
|
||||
conversationReady={messagesReady}
|
||||
onVisibleMessagesChange={reportVisibleMessages}
|
||||
showScrollToBottomButton={!!session}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
|
||||
@@ -60,6 +60,7 @@ interface ThreadViewportProps {
|
||||
/** Override when message ownership changes after the selected conversation. */
|
||||
messagesKey?: string | null;
|
||||
conversationReady?: boolean;
|
||||
onVisibleMessagesChange?: (messages: UIMessage[]) => void;
|
||||
showScrollToBottomButton?: boolean;
|
||||
cliApps?: CliAppInfo[];
|
||||
mcpPresets?: McpPresetInfo[];
|
||||
@@ -287,6 +288,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
conversationKey = null,
|
||||
messagesKey = conversationKey,
|
||||
conversationReady = true,
|
||||
onVisibleMessagesChange,
|
||||
showScrollToBottomButton = true,
|
||||
cliApps = [],
|
||||
mcpPresets = [],
|
||||
@@ -471,6 +473,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
() => windowMessages(messages, visibleMessageCount),
|
||||
[messages, visibleMessageCount],
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
if (conversationReady) onVisibleMessagesChange?.(visibleMessages);
|
||||
}, [conversationReady, onVisibleMessagesChange, visibleMessages]);
|
||||
const hiddenMessageCount = messages.length - visibleMessages.length;
|
||||
const historyUnknown = hasMoreBefore === null;
|
||||
const historyExhausted = hasMoreBefore === false && hiddenMessageCount === 0;
|
||||
|
||||
+46
-8
@@ -696,15 +696,53 @@ export async function updateAutomation(
|
||||
return mutation<AutomationsPayload>(transport, "automation.update", { id, values });
|
||||
}
|
||||
|
||||
export async function fetchSubagentTasks(token: string, sessionKey: string): Promise<SubagentTasksPayload> {
|
||||
const payload = await request<unknown>(
|
||||
`/api/sessions/${encodeURIComponent(sessionKey)}/subagents`, token, undefined, API_READ_TIMEOUT_MS,
|
||||
);
|
||||
if (!isRecord(payload) || !Array.isArray(payload.tasks) || !payload.tasks.every(isSubagentTask)
|
||||
|| new Set(payload.tasks.map((task) => task.task_id)).size !== payload.tasks.length) {
|
||||
throw new Error("Invalid subagent tasks response");
|
||||
export interface SubagentTaskWindow {
|
||||
turnIds: string[];
|
||||
trackedIds: string[];
|
||||
}
|
||||
|
||||
export async function fetchSubagentTasks(
|
||||
token: string, sessionKey: string, window: SubagentTaskWindow,
|
||||
): Promise<SubagentTasksPayload> {
|
||||
const path = `/api/sessions/${encodeURIComponent(sessionKey)}/subagents`;
|
||||
const queries: URLSearchParams[] = [];
|
||||
let query = new URLSearchParams({ scope: "window" });
|
||||
// Track the encoded length as it grows; re-serializing the whole target per id would be quadratic.
|
||||
let length = query.toString().length;
|
||||
let count = 0;
|
||||
for (const [key, values] of [
|
||||
["turn_id", window.turnIds], ["track", window.trackedIds],
|
||||
] as const) {
|
||||
for (const value of values) {
|
||||
const pair = new URLSearchParams({ [key]: value }).toString();
|
||||
// Keep request targets bounded, including percent-encoded identifiers.
|
||||
if (count && (length + 1 + pair.length > 5000 || count >= 400)) {
|
||||
queries.push(query);
|
||||
query = new URLSearchParams({ scope: "window" });
|
||||
length = query.toString().length;
|
||||
count = 0;
|
||||
}
|
||||
query.append(key, value);
|
||||
length += 1 + pair.length;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return { tasks: payload.tasks };
|
||||
queries.push(query);
|
||||
const tasks = new Map<string, SubagentTasksPayload["tasks"][number]>();
|
||||
for (const query of queries) {
|
||||
const payload = await request<unknown>(
|
||||
`${path}?${query}`, token, undefined, API_READ_TIMEOUT_MS,
|
||||
);
|
||||
if (!isRecord(payload) || !Array.isArray(payload.tasks) || !payload.tasks.every(isSubagentTask)
|
||||
|| new Set(payload.tasks.map((task) => task.task_id)).size !== payload.tasks.length) {
|
||||
throw new Error("Invalid subagent tasks response");
|
||||
}
|
||||
for (const task of payload.tasks) {
|
||||
const previous = tasks.get(task.task_id);
|
||||
if (!previous || (task.revision ?? 0) > (previous.revision ?? 0)) tasks.set(task.task_id, task);
|
||||
}
|
||||
}
|
||||
return { tasks: [...tasks.values()] };
|
||||
}
|
||||
|
||||
export async function fetchSubagentThread(
|
||||
|
||||
@@ -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