fix(webui): keep history loading until content is ready (#6659)

* fix(webui): keep history loading until content is ready

* fix(webui): preserve history content and retry state

Share final activity filtering with history readiness and retain completion and fork metadata across bookkeeping pages. Route boundary retries to the failed cursor and publish navigation pages synchronously so concurrent trace details are preserved. Cover real retry gestures, metadata traversal, batched details, and fork boundaries in both directions.

* fix(webui): reduce history admission work and release retry pages
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-14 22:52:44 +08:00
1 parent 40e4e8a3fd
commit efec4a608d
14 files changed
+751 -103

No files matched your search

@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { deriveTitle, isModelCommandText, visibleSessionPreview } from "@/lib/format";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { historyContentSnapshot, projectWebuiThreadMessages, sameHistoryContent } from "@/lib/thread-display-projection";
import type { UIMessage } from "@/lib/types";
const STARTED_AT = Date.UTC(2026, 6, 25, 12, 34, 0);
@@ -147,3 +147,66 @@ describe("projectWebuiThreadMessages", () => {
expect(visible[1]?.completedAt).toBeUndefined();
});
});
describe("history content admission", () => {
it("compares displayed answers independently of replay identities and completion telemetry", () => {
const before = historyContentSnapshot([message("assistant", { content: "First\n\nSecond" })], null);
const after = historyContentSnapshot([
message("assistant", { id: "slice-1", content: "First", turnId: "turn-1", turnSeq: 1 }),
message("assistant", { id: "slice-2", content: "Second", turnId: "turn-1", turnSeq: 2,
completedAt: STARTED_AT + 1000, latencyMs: 1000, usage: { total_tokens: 42 } }),
], null);
expect(sameHistoryContent(before, after)).toBe(true);
expect(sameHistoryContent(after, historyContentSnapshot([
message("assistant", { content: "First\n\nSecond\n\nThird" }),
], null))).toBe(false);
});
it("ignores hidden task creation and transport placeholders", () => {
const prompt = message("user");
const before = historyContentSnapshot([prompt], null);
const after = historyContentSnapshot([prompt,
message("assistant", { content: 'subagent({"action":"create"})', kind: "trace",
toolEvents: [{ name: "subagent", phase: "end", arguments: { action: "create" } }] }),
message("assistant", { content: "", completedAt: STARTED_AT + 1000 }),
], null);
expect(sameHistoryContent(before, after)).toBe(true);
});
it("recognizes a visible fork boundary without treating a leading marker as content", () => {
const rows = [message("user"), message("assistant")];
const before = historyContentSnapshot(rows, null);
expect(sameHistoryContent(before, historyContentSnapshot(rows, 0))).toBe(true);
expect(sameHistoryContent(before, historyContentSnapshot(rows, 1))).toBe(false);
});
it("compares nested tool payloads by content, including results and attachments", () => {
const tool = { name: "read_file", phase: "end", arguments: { path: "test.txt" },
result: { lines: ["first", "second"], truncated: false } };
const trace = message("assistant", { content: "read_file(test.txt)", kind: "trace", toolEvents: [tool] });
const before = historyContentSnapshot([trace], null);
const replay = { ...trace, id: "replayed", toolEvents: [{ ...tool,
arguments: { path: "test.txt" }, result: { truncated: false, lines: ["first", "second"] } }] };
expect(sameHistoryContent(before, historyContentSnapshot([replay], null))).toBe(true);
for (const changed of [
{ ...tool, result: { lines: ["first", "changed"], truncated: false } },
{ ...tool, result: { lines: ["first"], truncated: false } },
{ ...tool, result: null, error: "Not found" },
{ ...tool, files: [{ name: "test.txt", url: "/files/test.txt" }] },
]) {
expect(sameHistoryContent(before, historyContentSnapshot([{ ...trace, toolEvents: [changed] }], null))).toBe(false);
}
});
it("detects newly available media without relying on new message identities", () => {
const original = message("user", { images: [{ name: "picture.png" }] });
const before = historyContentSnapshot([original], null);
expect(sameHistoryContent(before, historyContentSnapshot([
{ ...original, images: [{ name: "picture.png", url: undefined }] },
], null))).toBe(true);
expect(sameHistoryContent(before, historyContentSnapshot([
{ ...original, images: [{ name: "picture.png", url: "/files/picture.png" }] },
], null))).toBe(false);
});
});
+219 -2
View File
@@ -7,6 +7,7 @@ import { NanobotClient } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider";
import type { UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
@@ -105,12 +106,228 @@ it("continues through telemetry-only fragments until another message is visible"
await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u10"));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.newer());
await act(async () => result.current.newer());
await act(async () => result.current.newer());
await waitFor(() => expect(result.current.window?.messages.map((row) => row.content)).toContain("Visible answer"));
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(5);
});
it("keeps loading through task-create fragments hidden by the message list", async () => {
const initial = page(10);
initial.events = [{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "long",
turn_seq: 1, text: "question", starts_turn: true }];
initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 1 } };
const hidden: WebuiThreadPersistedPayload = { ...page(11), events: [
{ event: "message", chat_id: "a", projection_id: "create", turn_id: "long", turn_seq: 2,
kind: "progress", text: 'subagent({"action":"create"})',
tool_events: [{ call_id: "create", name: "subagent", phase: "end", arguments: { action: "create" } }] },
], page: { ...page(11).page, record_range: { turn: 0, start: 1, end: 2 } } };
let finish!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial).mockResolvedValueOnce(hidden)
.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
const list = render(<ThreadMessages messages={result.current.window!.messages} />);
const text = list.container.textContent;
await act(async () => result.current.newer());
list.rerender(<ThreadMessages messages={result.current.window!.messages} />);
expect(list.container.textContent).toBe(text);
expect(result.current.loading).toBe(true);
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ after: "12" }));
await act(async () => finish({ ...page(12), events: [
{ event: "message", chat_id: "a", projection_id: "answer", turn_id: "long", turn_seq: 3, text: "Visible answer" },
], page: { has_more_after: false, record_range: { turn: 0, start: 2, end: 3 } } }));
list.rerender(<ThreadMessages messages={result.current.window!.messages} />);
expect(list.getByText("Visible answer")).toBeVisible();
expect(result.current.loading).toBe(false);
});
it.each([[0, "exhausted"], [4, "exhausted"], [4, "error"]] as const)("retains completion metadata after %s bookkeeping fragments end in %s", async (count, outcome) => {
const initial = page(10);
initial.events = [
{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "long", turn_seq: 1, text: "question", starts_turn: true },
{ event: "message", chat_id: "a", projection_id: "a10", turn_id: "long", turn_seq: 2, text: "answer" },
];
initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 2 } };
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial);
for (let part = 0; part < count; part++) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11 + part), events: [
{ event: "model_request", chat_id: "a", request_id: `r${part}`, run_id: "run", sequence: part,
phase: "completed", turn_id: "long", turn_seq: part + 3 },
], page: { ...page(11 + part).page, record_range: { turn: 0, start: part + 2, end: part + 3 } } });
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11 + count), events: [
{ event: "turn_end", chat_id: "a", projection_id: "end", turn_id: "long", turn_seq: count + 3,
latency_ms: 1234, usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } },
], page: { has_more_after: outcome === "error", after_cursor: outcome === "error" ? "continue" : null,
record_range: { turn: 0, start: count + 2, end: count + 3 } } });
if (outcome === "error") vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.newer());
expect(result.current.loading).toBe(false);
expect(result.current.window?.hasMoreAfter).toBe(outcome === "error");
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question", "answer"]);
expect(result.current.window?.messages.find((message) => message.id === "a10")).toMatchObject({
latencyMs: 1234, completedAt: 1234, usage: { total_tokens: 15 },
});
if (outcome === "error") {
expect(result.current.error).toBe("offline");
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(page(20));
await act(async () => result.current.newer());
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ after: "continue" }));
expect(result.current.window?.messages.map((message) => message.content)).toContain("question 20");
}
});
it.each([0, 4])("admits a fork-marker-only page after %s bookkeeping fragments without losing the readable window", async (count) => {
const initial = page(10);
initial.events = [
{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "forked", text: "Forked prompt", starts_turn: true },
...Array.from({ length: 24 }, (_, i) => ({ event: "message" as const, chat_id: "a", projection_id: `a${i}`,
turn_id: "forked", text: `answer ${i}` })),
];
const completion = { event: "turn_end" as const, chat_id: "a", turn_id: "forked", latency_ms: 1234 };
if (count) initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 25 } };
else {
initial.events.push(completion);
initial.page = { ...initial.page, after_cursor: "fork" };
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial);
for (let part = 0; part < count; part++) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11 + part), events: [
{ event: "model_request", chat_id: "a", turn_id: "forked", request_id: `r${part}`, run_id: "run",
sequence: part, phase: "completed" },
], page: { ...page(11 + part).page, record_range: { turn: 0, start: 25 + part, end: 26 + part } } });
}
if (count) vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(15), events: [completion],
page: { ...page(15).page, after_cursor: "fork", record_range: { turn: 0, start: 29, end: 30 } } });
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(16), events: [], fork_boundary_event_index: 0,
page: { before_cursor: "fork", has_more_before: true, after_cursor: null, has_more_after: false } });
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.newer());
expect(result.current.loading).toBe(false);
expect(result.current.window?.hasMoreAfter).toBe(false);
expect(result.current.window?.messages).toHaveLength(25);
expect(result.current.window?.forkBoundaryMessageCount).toBe(25);
const list = render(<ThreadMessages messages={result.current.window!.messages}
forkBoundaryMessageCount={result.current.window!.forkBoundaryMessageCount} />);
expect(list.getByText("Forked from history")).toBeVisible();
});
it("keeps a crossed fork boundary while reading from the first child prompt into its parent history", async () => {
const child = page(10);
child.page = { ...child.page, record_range: { turn: 1, start: 1, end: 4 } };
child.events.push({ event: "turn_end", chat_id: "a" });
const marker: WebuiThreadPersistedPayload = { ...page(9), events: [], fork_boundary_event_index: 0,
page: { ...page(9).page, record_range: { turn: 1, start: 0, end: 1 } } };
let finish!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(child).mockResolvedValueOnce(marker)
.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.older());
expect(result.current.loading).toBe(true);
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question 10", "answer"]);
await act(async () => finish(page(8)));
expect(result.current.loading).toBe(false);
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question 8", "answer", "question 10", "answer"]);
expect(result.current.window?.forkBoundaryMessageCount).toBe(2);
const list = render(<ThreadMessages messages={result.current.window!.messages}
forkBoundaryMessageCount={result.current.window!.forkBoundaryMessageCount} />);
expect(list.getByText("Forked from history")).toBeVisible();
});
it("retains a terminal record until its answer arrives while scanning backward", async () => {
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u20"));
for (let part = 6; part >= 2; part--) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(10 + part), events: part === 6
? [{ event: "turn_end", chat_id: "a", turn_id: "long", latency_ms: 1234, usage: { total_tokens: 15 } }]
: [{ event: "model_request", chat_id: "a", turn_id: "long", request_id: `r${part}`, run_id: "run",
sequence: part, phase: "completed" }],
page: { ...page(10 + part).page, record_range: { turn: 0, start: part, end: part + 1 } } });
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(10), events: [
{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "long", text: "question", starts_turn: true },
{ event: "message", chat_id: "a", projection_id: "a10", turn_id: "long", text: "answer" },
], page: { ...page(10).page, record_range: { turn: 0, start: 0, end: 2 } } });
await act(async () => result.current.older());
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(7);
expect(result.current.loading).toBe(false);
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question", "answer"]);
expect(result.current.window?.messages.find((message) => message.id === "a10")).toMatchObject({
latencyMs: 1234, completedAt: 1234, usage: { total_tokens: 15 },
});
});
it.each([false, true])("preserves trace details arriving during a multi-page read (fragment=%s)", async (fragment) => {
const ref = "1.history-aaaaaaaaaaaaaaaaaaaa";
const initial = page(10);
initial.events.splice(1, 0, { event: "message", chat_id: "a", projection_id: "trace", kind: "progress",
text: "exec(…)", trace_detail: { ref, bytes: 40_000, traceCount: 1 } });
const bookkeeping: WebuiThreadPersistedPayload = { ...page(11), events: [{ event: "model_request", chat_id: "a",
request_id: "r1", run_id: "run", sequence: 1, phase: "started" }] };
const ready: WebuiThreadPersistedPayload = { ...page(12), events: [
{ event: "message", chat_id: "a", projection_id: "continuation", text: "continued answer" },
] };
if (fragment) {
initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 3 } };
bookkeeping.page = { ...bookkeeping.page, record_range: { turn: 0, start: 3, end: 4 } };
ready.page = { ...ready.page, record_range: { turn: 0, start: 4, end: 5 } };
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial);
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
let finishBookkeeping!: (body: WebuiThreadPersistedPayload) => void;
let finishContent!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread)
.mockImplementationOnce(() => new Promise((resolve) => { finishBookkeeping = resolve; }))
.mockImplementationOnce(() => new Promise((resolve) => { finishContent = resolve; }));
act(() => result.current.newer());
const details = projectThreadEvents([{ event: "message", chat_id: "a", projection_id: "trace", kind: "progress",
text: 'exec({"command":"echo historical"})' }]);
await act(async () => finishBookkeeping(bookkeeping));
expect(result.current.loading).toBe(true);
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ after: "12" }));
// Both HTTP completions can land in one React batch.
await act(async () => {
result.current.expandTraceDetail(ref, details);
finishContent(ready);
});
expect(result.current.loading).toBe(false);
const contents = result.current.window!.messages.map((message) => message.content);
expect(contents).toContain("continued answer");
expect(contents).toContain('exec({"command":"echo historical"})');
});
it.each(["exhausted", "error"] as const)("preserves readable navigation after several bookkeeping pages end in %s", async (outcome) => {
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
const original = result.current.window!.messages;
for (let cursor = 9; cursor >= 6; cursor--) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(cursor), events: [] });
}
if (outcome === "error") vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));
else vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(0), events: [] });
await act(async () => result.current.older());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.window!.messages).toEqual(original);
if (outcome === "error") {
expect(result.current.error).toBe("offline");
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(page(5));
await act(async () => result.current.retry());
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ before: "6" }));
expect(result.current.window!.messages.map((row) => row.content)).toContain("question 5");
} else expect(result.current.window?.hasMoreBefore).toBe(false);
});
it("does not mix navigation pages from a replaced session", async () => {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(10),
page: { ...page(10).page, history_generation: "old" } });
+11 -3
View File
@@ -343,11 +343,14 @@ describe("durable run recovery", () => {
const initial = page(1, 3, [chunk(2, "B"), chunk(3, "C")]);
const latest = page(6, 9, [chunk(8, "H"), chunk(9, "I"),
{ event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 10, projection_id: "history-end" }], true);
const missing = page(3, 6, [chunk(5, "E"), chunk(6, "F"), chunk(7, "G")]);
const middle = page(5, 6, [chunk(7, "G")]);
const missing = page(3, 5, [chunk(5, "E"), chunk(6, "F")]);
let finishLatest!: (value: Response) => void;
let finishMiddle!: (value: Response) => void;
let finishMissing!: (value: Response) => void;
let latestReads = 0;
vi.stubGlobal("fetch", vi.fn((url: string) => {
if (url.includes("before=before-6")) return new Promise<Response>((resolve) => { finishMiddle = resolve; });
if (url.includes("before=")) return new Promise<Response>((resolve) => { finishMissing = resolve; });
const read = latestReads++;
if (read === 0) return Promise.resolve(response(initial));
@@ -382,7 +385,7 @@ describe("durable run recovery", () => {
expect(webuiThreadCache.get(`websocket:${chatId}`)).toEqual(latest);
expect(mounted.result.current.history.error).toBeNull();
expect(mounted.result.current.history.loadingOlder).toBe(true);
expect(finishMissing).toBeTypeOf("function");
expect(finishMiddle).toBeTypeOf("function");
expect(reconcile).not.toHaveBeenCalled();
expect(fence).not.toHaveBeenCalled();
expect(client.getRunState(chatId).active).toBe(true);
@@ -391,8 +394,13 @@ describe("durable run recovery", () => {
turn_seq: 5, stream_id: "wire", text: "E" }));
await act(async () => { await vi.advanceTimersByTimeAsync(100); });
expect(mounted.result.current.messages.at(-1)?.content).toBe("BCDE");
await act(async () => { finishMiddle(response(middle)); });
expect(mounted.result.current.history.loadingOlder).toBe(true);
expect(mounted.result.current.messages.map((row) => row.content)).toEqual(["BCDE"]);
expect(finishMissing).toBeTypeOf("function");
await act(async () => { finishMissing(response(missing)); });
expect(mounted.result.current.messages.at(-1)?.content).toBe("BCDEFGHI");
expect(mounted.result.current.messages.map((row) => row.content)).toEqual(["BCDEFGHI"]);
expect(mounted.result.current.history.loadingOlder).toBe(false);
expect(client.getRunState(chatId).active).toBe(false);
expect(mounted.result.current.isStreaming).toBe(false);
const late = { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 11,
+44
View File
@@ -8,6 +8,7 @@ import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
import { ClientProvider } from "@/providers/ClientProvider";
import { canonicalThreadPayload } from "./thread-test-payload";
import type { WebuiThreadPersistedPayload } from "@/lib/types";
vi.mock("@/lib/api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api")>();
@@ -1168,6 +1169,49 @@ describe("useSessions", () => {
expect(result.current.hasMoreBefore).toBe(false);
});
it("keeps one pull pending through telemetry pages and retries from its failed continuation", async () => {
const initial: WebuiThreadPersistedPayload = {
schemaVersion: 3, projection: "events",
events: [{ event: "message", chat_id: "ready", projection_id: "answer", turn_id: "turn", turn_seq: 1, text: "Visible answer" }],
page: { before_cursor: "telemetry", has_more_before: true },
};
let fail!: (error: Error) => void;
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial).mockResolvedValueOnce({
...initial, events: [
{ event: "model_request", chat_id: "ready", projection_id: "request", turn_id: "turn", turn_seq: 2,
request_id: "request", run_id: "run", sequence: 1, phase: "completed" },
{ event: "turn_end", chat_id: "ready", projection_id: "end", turn_id: "turn", turn_seq: 3, latency_ms: 1000 },
], page: { before_cursor: "content", has_more_before: true },
}).mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject; }));
const loading: boolean[] = [];
const { result } = renderHook(() => {
const history = useSessionHistory("websocket:ready");
loading.push(history.loadingOlder);
return history;
}, { wrapper: wrap(fakeClient()) });
await waitFor(() => expect(result.current.messages[0]?.content).toBe("Visible answer"));
loading.length = 0;
let finished = false;
act(() => { void result.current.loadOlder().then(() => { finished = true; }); });
await waitFor(() => expect(api.fetchWebuiThread).toHaveBeenCalledTimes(3));
expect(finished).toBe(false);
expect(result.current.loadingOlder).toBe(true);
expect(loading).not.toContain(false);
expect(result.current.messages.map((row) => row.content)).toEqual(["Visible answer"]);
await act(async () => { fail(new Error("offline")); });
expect(finished).toBe(true);
expect(result.current.olderError).toBe("offline");
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...initial,
events: [{ event: "user_message", chat_id: "ready", projection_id: "old", text: "Earlier question", starts_turn: true }],
page: { before_cursor: null, has_more_before: false },
});
await act(async () => { await result.current.loadOlder(); });
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("tok", "websocket:ready", expect.objectContaining({ before: "content" }));
expect(result.current.messages.map((row) => row.content)).toEqual(["Earlier question", "Visible answer"]);
expect(result.current.loadingOlder).toBe(false);
expect(result.current.olderError).toBeNull();
});
it("keeps older-history failures separate and retries them explicitly", async () => {
vi.mocked(api.fetchWebuiThread)
.mockResolvedValueOnce(canonicalThreadPayload({