fix(webui): cache and defer thread history
This commit is contained in:
1 parent
7ba60c2ef0
commit
a490cd629b
30 files changed
+1306
-145
No files matched your search
@@ -140,6 +140,36 @@ function installReducedMotion() {
|
||||
}
|
||||
|
||||
describe("AgentActivityCluster", () => {
|
||||
it("loads deferred trace details only after completed activity is expanded", async () => {
|
||||
const onLoadTraceDetails = vi.fn();
|
||||
render(
|
||||
<AgentActivityCluster
|
||||
messages={[{
|
||||
id: "t-deferred",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "exec(…)",
|
||||
traces: ["exec(…)"],
|
||||
traceDetail: {
|
||||
ref: "9.tr-deadbeefdeadbeef",
|
||||
bytes: 40_000,
|
||||
traceCount: 1,
|
||||
},
|
||||
createdAt: 1,
|
||||
}]}
|
||||
isTurnStreaming={false}
|
||||
hasBodyBelow={false}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(onLoadTraceDetails).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: /Worked/ }));
|
||||
await waitFor(() => {
|
||||
expect(onLoadTraceDetails).toHaveBeenCalledWith(["9.tr-deadbeefdeadbeef"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("shows model retries in the existing live activity header", () => {
|
||||
render(
|
||||
<AgentActivityCluster
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
fetchSkills,
|
||||
fetchTrendingMarketplaceSkills,
|
||||
fetchWebuiThread,
|
||||
fetchWebuiThreadTraceDetail,
|
||||
fetchWorkspaces,
|
||||
importMcpConfig,
|
||||
installMarketplaceSkill,
|
||||
@@ -117,6 +118,47 @@ describe("webui API helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("revalidates a cached WebUI thread and reuses it on 304", async () => {
|
||||
const cached = {
|
||||
schemaVersion: 3,
|
||||
revision: "rev-1",
|
||||
messages: [],
|
||||
};
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 304,
|
||||
} as Response);
|
||||
|
||||
await expect(fetchWebuiThread("tok", "websocket:chat-1", {
|
||||
revision: cached.revision,
|
||||
cached,
|
||||
})).resolves.toBe(cached);
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Achat-1/webui-thread",
|
||||
expect.objectContaining({
|
||||
headers: {
|
||||
Authorization: "Bearer tok",
|
||||
"If-None-Match": '"rev-1"',
|
||||
},
|
||||
cache: "no-store",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("fetches deferred trace details with encoded session and ref", async () => {
|
||||
await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef");
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Achat-1/webui-thread/trace-detail?ref=9.tr-deadbeefdeadbeef",
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok" },
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("aborts a WebUI thread request when its caller signal is aborted", async () => {
|
||||
let requestSignal: AbortSignal | null = null;
|
||||
vi.mocked(fetch).mockImplementation((_input, init) => new Promise((_resolve, reject) => {
|
||||
|
||||
@@ -8,8 +8,15 @@ import { ThreadShell } from "@/components/thread/ThreadShell";
|
||||
import i18n from "@/i18n";
|
||||
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
|
||||
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import type { CliAppsPayload, ConnectionStatus, SettingsPayload, UIMessage } from "@/lib/types";
|
||||
import type {
|
||||
CliAppsPayload,
|
||||
ConnectionStatus,
|
||||
SettingsPayload,
|
||||
UIMessage,
|
||||
WebuiThreadPersistedPayload,
|
||||
} from "@/lib/types";
|
||||
|
||||
const HERO_GREETING_PATTERN =
|
||||
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
|
||||
@@ -262,6 +269,36 @@ function httpJson(body: unknown) {
|
||||
};
|
||||
}
|
||||
|
||||
function traceDetailThread(
|
||||
deferred: boolean,
|
||||
answer: string,
|
||||
revision?: string,
|
||||
): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 3,
|
||||
...(revision ? { revision } : {}),
|
||||
messages: [
|
||||
{
|
||||
id: "trace-shared",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: deferred ? "exec(…)" : 'exec({"command":"echo full"})',
|
||||
traces: [deferred ? "exec(…)" : 'exec({"command":"echo full"})'],
|
||||
...(deferred
|
||||
? { traceDetail: { ref: "1.trace-shared", bytes: 40_000, traceCount: 1 } }
|
||||
: {}),
|
||||
createdAt: 1_000,
|
||||
},
|
||||
{
|
||||
id: "answer-shared",
|
||||
role: "assistant",
|
||||
content: answer,
|
||||
createdAt: 2_000,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function setDocumentVisibility(value: DocumentVisibilityState): void {
|
||||
Object.defineProperty(document, "visibilityState", {
|
||||
configurable: true,
|
||||
@@ -417,6 +454,7 @@ function settingsWithFastPreset(): SettingsPayload {
|
||||
|
||||
describe("ThreadShell", () => {
|
||||
beforeEach(() => {
|
||||
webuiThreadCache.clear();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue({
|
||||
@@ -427,6 +465,153 @@ describe("ThreadShell", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("surfaces and retries a deferred trace-detail request failure", async () => {
|
||||
const client = makeClient();
|
||||
let detailCalls = 0;
|
||||
const fetchMock = vi.fn((input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/webui-thread/trace-detail?")) {
|
||||
detailCalls += 1;
|
||||
if (detailCalls === 1) {
|
||||
return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });
|
||||
}
|
||||
return Promise.resolve(httpJson({
|
||||
message_id: "trace-deferred",
|
||||
content: 'exec({"command":"echo full"})',
|
||||
traces: ['exec({"command":"echo full"})'],
|
||||
}));
|
||||
}
|
||||
if (url.includes("websocket%3Atrace-detail-retry/webui-thread")) {
|
||||
return Promise.resolve(httpJson({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{
|
||||
id: "trace-deferred",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "exec(…)",
|
||||
traces: ["exec(…)"],
|
||||
traceDetail: { ref: "1.trace-deferred", bytes: 40_000, traceCount: 1 },
|
||||
createdAt: 1_000,
|
||||
},
|
||||
{ id: "answer", role: "assistant", content: "done", createdAt: 2_000 },
|
||||
],
|
||||
}));
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
render(wrap(
|
||||
client,
|
||||
<ThreadShell
|
||||
session={session("trace-detail-retry")}
|
||||
title="Trace detail retry"
|
||||
onToggleSidebar={() => {}}
|
||||
/>,
|
||||
));
|
||||
|
||||
const activity = await screen.findByRole("button", { name: /Worked/ });
|
||||
fireEvent.click(activity);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Full activity details could not be loaded.",
|
||||
);
|
||||
expect(detailCalls).toBe(1);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
|
||||
await waitFor(() => expect(detailCalls).toBe(2));
|
||||
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
|
||||
|
||||
fireEvent.click(activity);
|
||||
fireEvent.click(activity);
|
||||
await act(async () => Promise.resolve());
|
||||
expect(detailCalls).toBe(2);
|
||||
});
|
||||
|
||||
it("ignores a deferred trace-detail failure after switching sessions", async () => {
|
||||
const client = makeClient();
|
||||
const detailUrls: string[] = [];
|
||||
let rejectDetail!: (reason: Error) => void;
|
||||
const pendingDetail = new Promise<Response>((_resolve, reject) => {
|
||||
rejectDetail = reject;
|
||||
});
|
||||
const cachedB = traceDetailThread(false, "done-b", "rev-b");
|
||||
webuiThreadCache.set("websocket:trace-failure-b", cachedB);
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/webui-thread/trace-detail?")) {
|
||||
detailUrls.push(url);
|
||||
return pendingDetail;
|
||||
}
|
||||
if (url.includes("websocket%3Atrace-failure-a/webui-thread")) {
|
||||
return Promise.resolve(httpJson(traceDetailThread(true, "done-a")));
|
||||
}
|
||||
if (url.includes("websocket%3Atrace-failure-b/webui-thread")) {
|
||||
return Promise.resolve(httpJson(cachedB));
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
}));
|
||||
|
||||
const view = (chatId: string) => wrap(
|
||||
client,
|
||||
<ThreadShell
|
||||
session={session(chatId)}
|
||||
title={`Trace ${chatId}`}
|
||||
onToggleSidebar={() => {}}
|
||||
/>,
|
||||
);
|
||||
const { rerender } = render(view("trace-failure-a"));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
|
||||
|
||||
rerender(view("trace-failure-b"));
|
||||
await screen.findByText("done-b");
|
||||
await act(async () => rejectDetail(new Error("late failure")));
|
||||
|
||||
expect(detailUrls).toHaveLength(1);
|
||||
expect(detailUrls[0]).toContain("websocket%3Atrace-failure-a");
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not carry a visible trace-detail failure into a cached session", async () => {
|
||||
const client = makeClient();
|
||||
const detailUrls: string[] = [];
|
||||
const cachedB = traceDetailThread(false, "cached-b", "rev-visible-b");
|
||||
webuiThreadCache.set("websocket:visible-failure-b", cachedB);
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/webui-thread/trace-detail?")) {
|
||||
detailUrls.push(url);
|
||||
return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });
|
||||
}
|
||||
if (url.includes("websocket%3Avisible-failure-a/webui-thread")) {
|
||||
return Promise.resolve(httpJson(traceDetailThread(true, "failed-a")));
|
||||
}
|
||||
if (url.includes("websocket%3Avisible-failure-b/webui-thread")) {
|
||||
return Promise.resolve(httpJson(cachedB));
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
}));
|
||||
|
||||
const view = (chatId: string) => wrap(
|
||||
client,
|
||||
<ThreadShell
|
||||
session={session(chatId)}
|
||||
title={`Trace ${chatId}`}
|
||||
onToggleSidebar={() => {}}
|
||||
/>,
|
||||
);
|
||||
const { rerender } = render(view("visible-failure-a"));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
|
||||
expect(await screen.findByRole("alert")).toBeInTheDocument();
|
||||
|
||||
rerender(view("visible-failure-b"));
|
||||
await screen.findByText("cached-b");
|
||||
|
||||
expect(detailUrls).toHaveLength(1);
|
||||
expect(detailUrls[0]).toContain("websocket%3Avisible-failure-a");
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders each logical round in a completed turn as its own usage bar", async () => {
|
||||
const client = makeClient();
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
|
||||
@@ -1461,6 +1461,7 @@ describe("ThreadViewport", () => {
|
||||
|
||||
it("renders only the tail window for long history by default", () => {
|
||||
const longMessages = makeLongMessages(300);
|
||||
const firstVisible = longMessages.length - INITIAL_HISTORY_WINDOW;
|
||||
|
||||
render(
|
||||
<ThreadViewport
|
||||
@@ -1470,8 +1471,8 @@ describe("ThreadViewport", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByText("message 139")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("message 140")).toBeInTheDocument();
|
||||
expect(screen.queryByText(`message ${firstVisible - 1}`)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(`message ${firstVisible}`)).toBeInTheDocument();
|
||||
expect(screen.getByText("message 299")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Load earlier messages" })).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -1509,6 +1510,7 @@ describe("ThreadViewport", () => {
|
||||
});
|
||||
|
||||
it("prefetches earlier history within half a viewport of the top", () => {
|
||||
const expandedFirstVisible = 300 - INITIAL_HISTORY_WINDOW - HISTORY_WINDOW_INCREMENT;
|
||||
const { container } = render(
|
||||
<ThreadViewport
|
||||
messages={makeLongMessages(300)}
|
||||
@@ -1527,14 +1529,16 @@ describe("ThreadViewport", () => {
|
||||
act(() => {
|
||||
dispatchUserScroll(scroller);
|
||||
});
|
||||
expect(screen.queryByText("message 139")).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(`message ${300 - INITIAL_HISTORY_WINDOW - 1}`),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
scroller.scrollTop = 250;
|
||||
act(() => {
|
||||
dispatchUserScroll(scroller);
|
||||
});
|
||||
expect(screen.getByText("message 20")).toBeInTheDocument();
|
||||
expect(screen.queryByText("message 19")).not.toBeInTheDocument();
|
||||
expect(screen.getByText(`message ${expandedFirstVisible}`)).toBeInTheDocument();
|
||||
expect(screen.queryByText(`message ${expandedFirstVisible - 1}`)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the first visible history item fixed while deferred rows materialize", () => {
|
||||
@@ -1562,7 +1566,8 @@ describe("ThreadViewport", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const anchor = screen.getByText("message 140")
|
||||
const firstVisible = 300 - INITIAL_HISTORY_WINDOW;
|
||||
const anchor = screen.getByText(`message ${firstVisible}`)
|
||||
.closest<HTMLElement>("[data-thread-display-unit]");
|
||||
expect(anchor).not.toBeNull();
|
||||
hitTarget = anchor;
|
||||
@@ -1913,15 +1918,16 @@ describe("ThreadViewport", () => {
|
||||
|
||||
it("expands the window start to avoid cutting an agent activity cluster", () => {
|
||||
const clustered = makeLongMessages(200);
|
||||
const boundary = clustered.length - INITIAL_HISTORY_WINDOW;
|
||||
clustered.splice(
|
||||
38,
|
||||
boundary - 2,
|
||||
3,
|
||||
{
|
||||
id: "r0",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
reasoning: "first reasoning",
|
||||
createdAt: 38,
|
||||
createdAt: boundary - 2,
|
||||
},
|
||||
{
|
||||
id: "t0",
|
||||
@@ -1929,14 +1935,14 @@ describe("ThreadViewport", () => {
|
||||
kind: "trace",
|
||||
content: "tool()",
|
||||
traces: ["tool()"],
|
||||
createdAt: 39,
|
||||
createdAt: boundary - 1,
|
||||
},
|
||||
{
|
||||
id: "r1",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
reasoning: "second reasoning",
|
||||
createdAt: 40,
|
||||
createdAt: boundary,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSessions";
|
||||
import * as api from "@/lib/api";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
|
||||
vi.mock("@/lib/api", async (importOriginal) => {
|
||||
@@ -93,6 +94,7 @@ describe("useSessions", () => {
|
||||
vi.mocked(api.listSessions).mockReset();
|
||||
vi.mocked(api.deleteSession).mockReset();
|
||||
vi.mocked(api.fetchWebuiThread).mockReset();
|
||||
webuiThreadCache.clear();
|
||||
});
|
||||
|
||||
it("does not use low-information greetings as fallback session titles", () => {
|
||||
@@ -566,6 +568,70 @@ describe("useSessions", () => {
|
||||
expect(result.current.messages[2]!.content).toBe("summary");
|
||||
});
|
||||
|
||||
it("shows a cached transcript immediately while revalidating it", async () => {
|
||||
const cached = {
|
||||
schemaVersion: 3,
|
||||
revision: "rev-cached",
|
||||
messages: [
|
||||
{ id: "a1", role: "assistant" as const, content: "cached answer", createdAt: 1 },
|
||||
],
|
||||
};
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(cached);
|
||||
|
||||
const first = renderHook(() => useSessionHistory("websocket:cached"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
await waitFor(() => expect(first.result.current.loading).toBe(false));
|
||||
first.unmount();
|
||||
|
||||
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise(() => {}));
|
||||
const second = renderHook(() => useSessionHistory("websocket:cached"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
|
||||
expect(second.result.current.loading).toBe(false);
|
||||
expect(second.result.current.messages[0]?.content).toBe("cached answer");
|
||||
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith(
|
||||
"tok",
|
||||
"websocket:cached",
|
||||
expect.objectContaining({
|
||||
limit: 40,
|
||||
direction: "latest",
|
||||
revision: "rev-cached",
|
||||
cached,
|
||||
}),
|
||||
);
|
||||
second.unmount();
|
||||
});
|
||||
|
||||
it("keeps rendered history visible when its LRU entry was evicted before refresh", async () => {
|
||||
const loaded = {
|
||||
schemaVersion: 3,
|
||||
revision: "rev-loaded",
|
||||
messages: [
|
||||
{ id: "a1", role: "assistant" as const, content: "still visible", createdAt: 1 },
|
||||
],
|
||||
};
|
||||
vi.mocked(api.fetchWebuiThread)
|
||||
.mockResolvedValueOnce(loaded)
|
||||
.mockImplementationOnce(() => new Promise(() => {}));
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSessionHistory("websocket:evicted"),
|
||||
{ wrapper: wrap(fakeClient()) },
|
||||
);
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.messages[0]?.content).toBe("still visible");
|
||||
|
||||
webuiThreadCache.delete("websocket:evicted");
|
||||
act(() => result.current.refresh());
|
||||
await waitFor(() => expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2));
|
||||
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.messages[0]?.content).toBe("still visible");
|
||||
unmount();
|
||||
});
|
||||
|
||||
it("flags transcript ending with a trace row as pending", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
@@ -785,7 +851,7 @@ describe("useSessions", () => {
|
||||
"tok",
|
||||
"websocket:paged",
|
||||
expect.objectContaining({
|
||||
limit: 80,
|
||||
limit: 40,
|
||||
direction: "latest",
|
||||
signal: expect.any(AbortSignal),
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { WebuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import type { WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
|
||||
function payload(id: string): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 3,
|
||||
revision: `rev-${id}`,
|
||||
messages: [{ id, role: "assistant", content: id, createdAt: 1 }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("WebuiThreadCache", () => {
|
||||
it("evicts the least recently used session", () => {
|
||||
const cache = new WebuiThreadCache(10_000, 2);
|
||||
cache.set("a", payload("a"));
|
||||
cache.set("b", payload("b"));
|
||||
expect(cache.get("a")).toBeDefined();
|
||||
|
||||
cache.set("c", payload("c"));
|
||||
|
||||
expect(cache.get("a")?.revision).toBe("rev-a");
|
||||
expect(cache.get("b")).toBeUndefined();
|
||||
expect(cache.get("c")?.revision).toBe("rev-c");
|
||||
});
|
||||
|
||||
it("does not retain a payload larger than the byte budget", () => {
|
||||
const cache = new WebuiThreadCache(64, 2);
|
||||
cache.set("large", payload("x".repeat(100)));
|
||||
|
||||
expect(cache.get("large")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user