* 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
538 lines
34 KiB
TypeScript
538 lines
34 KiB
TypeScript
import { act, render, renderHook, screen, waitFor, within } from "@testing-library/react";
|
|
import { createRef, type ReactNode } from "react";
|
|
import { beforeEach, expect, it, vi } from "vitest";
|
|
import { usePromptHistory } from "@/hooks/usePromptHistory";
|
|
import * as api from "@/lib/api";
|
|
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";
|
|
|
|
vi.mock("@/lib/api", async (original) => ({ ...await original<typeof api>(), fetchPromptIndex: vi.fn(), fetchWebuiThread: vi.fn() }));
|
|
const index = Array.from({ length: 2000 }, (_, index) => ({ id: `u${index}`, preview: `question ${index}`,
|
|
answerPreview: "answer", createdAt: index + 1, cursor: String(index), turnId: `turn${index}` }));
|
|
const latest: UIMessage[] = [{ id: "u1999", content: "question 1999", role: "user", createdAt: 2000 }];
|
|
function page(start: number): WebuiThreadPersistedPayload {
|
|
return { schemaVersion: 3, projection: "events", events: [
|
|
{ event: "user_message", chat_id: "a", projection_id: `u${start}`, text: `question ${start}`, starts_turn: true },
|
|
{ event: "message", chat_id: "a", projection_id: `a${start}`, text: "answer" },
|
|
], page: { before_cursor: String(start), after_cursor: String(start + 1), user_message_offset: start,
|
|
has_more_before: start > 0, has_more_after: start < 1999 } };
|
|
}
|
|
function wrapper(enabled = true) {
|
|
const client = new NanobotClient({ url: "ws://localhost:8765", reconnect: false });
|
|
return ({ children }: { children: ReactNode }) => <ClientProvider client={client} token="test"
|
|
webuiCapabilities={enabled ? ["webui.prompt-navigation.v1"] : []}>{children}</ClientProvider>;
|
|
}
|
|
beforeEach(() => {
|
|
vi.mocked(api.fetchPromptIndex).mockReset().mockResolvedValue({ prompts: index, revision: "first" });
|
|
vi.mocked(api.fetchWebuiThread).mockReset().mockImplementation(async (_token, _key, options) => {
|
|
if (typeof options === "string") throw new Error("expected page options");
|
|
return page(Number(options?.after ?? Number(options?.before) - 1));
|
|
});
|
|
});
|
|
|
|
it("loads the complete index without bodies, reads bounded windows and leaves live history alone", async () => {
|
|
const { result, rerender } = renderHook(({ messages }) => usePromptHistory("a", 1, messages), {
|
|
wrapper: wrapper(), initialProps: { messages: latest },
|
|
});
|
|
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
|
|
expect(api.fetchWebuiThread).not.toHaveBeenCalled();
|
|
await act(async () => result.current.jump("u500"));
|
|
expect(result.current.window?.userMessageOffset).toBe(500);
|
|
expect(result.current.target?.id).toBe("u500");
|
|
rerender({ messages: [...latest, { id: "live", role: "assistant", content: "new output", createdAt: 2001 }] });
|
|
expect(result.current.window?.messages).toHaveLength(2);
|
|
for (let i = 0; i < 8; i++) await act(async () => result.current.newer());
|
|
expect(result.current.window?.messages).toHaveLength(6);
|
|
expect(result.current.window?.userMessageOffset).toBe(506);
|
|
await act(async () => result.current.older());
|
|
expect(result.current.window?.userMessageOffset).toBe(505);
|
|
expect(result.current.window?.messages).toHaveLength(6);
|
|
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ before: "506", limit: 24 }));
|
|
act(() => result.current.latest());
|
|
expect(result.current.window).toBeNull();
|
|
expect(latest).toHaveLength(1);
|
|
});
|
|
|
|
it("reprojects adjacent pages of a long turn when navigating forward", async () => {
|
|
const events = [
|
|
{ event: "user_message" as const, chat_id: "a", projection_id: "u10", turn_id: "long", turn_seq: 1, text: "question", starts_turn: true },
|
|
{ event: "stream_end" as const, chat_id: "a", projection_id: "answer-1", turn_id: "long", turn_seq: 2, stream_id: "wire", text: "First", resuming: true, merge_next: true },
|
|
{ event: "message" as const, chat_id: "a", projection_id: "tool", turn_id: "long", turn_seq: 3, kind: "progress" as const, text: "tool()" },
|
|
{ event: "stream_end" as const, chat_id: "a", projection_id: "answer-2", turn_id: "long", turn_seq: 4, stream_id: "wire", text: "First second" },
|
|
{ event: "turn_end" as const, chat_id: "a", projection_id: "end", turn_id: "long", turn_seq: 5 },
|
|
];
|
|
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [{ ...index[10], id: "u10", turnId: "long" }] });
|
|
vi.mocked(api.fetchWebuiThread).mockImplementation(async (_token, _key, options) => {
|
|
if (typeof options === "string") throw new Error("expected page options");
|
|
const newer = options?.after === "next";
|
|
return { schemaVersion: 3, projection: "events", events: newer ? events.slice(2) : events.slice(0, 2),
|
|
page: { before_cursor: newer ? "next" : null, after_cursor: newer ? null : "next",
|
|
has_more_before: newer, has_more_after: !newer, truncated_oversized_turn: true,
|
|
record_range: { turn: 0, start: newer ? 2 : 0, end: newer ? 5 : 2 } } };
|
|
});
|
|
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
|
|
await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u10"));
|
|
await act(async () => result.current.jump("u10"));
|
|
await act(async () => result.current.newer());
|
|
const visible = (rows: UIMessage[]) => rows.map((row) => ({
|
|
role: row.role, kind: row.kind, content: row.content, reasoning: row.reasoning, traces: row.traces,
|
|
}));
|
|
expect(visible(result.current.window!.messages)).toEqual(visible(projectWebuiThreadMessages(projectThreadEvents(events))));
|
|
expect(result.current.window?.messages.filter((row) => row.role === "user")).toHaveLength(1);
|
|
});
|
|
|
|
it("continues through telemetry-only fragments until another message is visible", async () => {
|
|
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [{ ...index[10], id: "u10", turnId: "long" }] });
|
|
vi.mocked(api.fetchWebuiThread).mockImplementation(async (_token, _key, options) => {
|
|
if (typeof options === "string") throw new Error("expected page options");
|
|
const part = Number(options?.after === "10" ? 0 : options?.after);
|
|
const events = part === 0
|
|
? [{ event: "user_message" as const, chat_id: "a", projection_id: "u10", turn_id: "long", turn_seq: 1, text: "question", starts_turn: true }]
|
|
: part === 4
|
|
? [{ event: "message" as const, chat_id: "a", projection_id: "answer", turn_id: "long", turn_seq: 5, text: "Visible answer" }]
|
|
: [{ event: "model_request" as const, chat_id: "a", projection_id: `request-${part}`, turn_id: "long", turn_seq: part + 1,
|
|
request_id: `r${part}`, run_id: "run", sequence: part, phase: "started" as const }];
|
|
return { schemaVersion: 3, projection: "events", events,
|
|
page: { before_cursor: part ? String(part) : null, after_cursor: part < 4 ? String(part + 1) : null,
|
|
has_more_before: part > 0, has_more_after: part < 4, truncated_oversized_turn: true,
|
|
record_range: { turn: 0, start: part, end: part + 1 } } };
|
|
});
|
|
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
|
|
await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u10"));
|
|
await act(async () => result.current.jump("u10"));
|
|
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" } });
|
|
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
|
|
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
|
|
await act(async () => result.current.jump("u10"));
|
|
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11),
|
|
page: { ...page(11).page, history_generation: "new" } });
|
|
await act(async () => result.current.newer());
|
|
expect(result.current.error).toBe("History changed; select the message again");
|
|
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question 10", "answer"]);
|
|
});
|
|
|
|
it.each(["older", "newer"] as const)("keeps one pending %s page when boundary inputs arrive before the next render", async (operation) => {
|
|
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 finish!: (body: WebuiThreadPersistedPayload) => void;
|
|
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
|
|
const load = result.current[operation];
|
|
act(() => {
|
|
load();
|
|
load();
|
|
});
|
|
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2);
|
|
const options = vi.mocked(api.fetchWebuiThread).mock.lastCall?.[2];
|
|
if (typeof options !== "object") throw new Error("expected page options");
|
|
expect(options.signal?.aborted).toBe(false);
|
|
expect(result.current.loading).toBe(true);
|
|
await act(async () => finish(page(operation === "older" ? 9 : 11)));
|
|
expect(result.current.loading).toBe(false);
|
|
expect(result.current.window?.messages).toHaveLength(4);
|
|
});
|
|
|
|
it("keeps the current page on failure and offers retry; superseded jumps and session reads cannot win", async () => {
|
|
const { result, rerender } = renderHook(({ key }) => usePromptHistory(key, 1, latest), {
|
|
wrapper: wrapper(), initialProps: { key: "a" },
|
|
});
|
|
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
|
|
await act(async () => result.current.jump("u10"));
|
|
vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));
|
|
await act(async () => result.current.jump("u20"));
|
|
expect(result.current.error).toBe("offline");
|
|
expect(result.current.window?.userMessageOffset).toBe(10);
|
|
await act(async () => result.current.retry());
|
|
expect(result.current.window?.userMessageOffset).toBe(20);
|
|
let resolve!: (body: WebuiThreadPersistedPayload) => void;
|
|
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
|
act(() => result.current.jump("u30"));
|
|
await act(async () => result.current.jump("u40"));
|
|
await act(async () => resolve(page(30)));
|
|
expect(result.current.window?.userMessageOffset).toBe(40);
|
|
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
|
act(() => result.current.jump("u50"));
|
|
rerender({ key: "b" });
|
|
await act(async () => resolve(page(50)));
|
|
expect(result.current.window).toBeNull();
|
|
expect(result.current.loading).toBe(false);
|
|
});
|
|
|
|
it("does not request new endpoints from an older compatible host", () => {
|
|
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper(false) });
|
|
expect(result.current.prompts[0].id).toBe("u1999");
|
|
expect(api.fetchPromptIndex).not.toHaveBeenCalled();
|
|
expect(api.fetchWebuiThread).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([false, true])("a local jump supersedes a pending history read without discarding the current window (history=%s)", async (history) => {
|
|
const viewport = createRef<ThreadViewportHandle>();
|
|
function Conversation() {
|
|
const navigation = usePromptHistory("a", 1, latest);
|
|
return <ThreadViewport ref={viewport} messages={latest} navigation={navigation} isStreaming={false} />;
|
|
}
|
|
render(<Conversation />, { wrapper: wrapper() });
|
|
await waitFor(() => expect(screen.getByTestId("prompt-rail-scroll")).toBeInTheDocument());
|
|
if (history) {
|
|
await act(async () => viewport.current?.jumpToUserPrompt("u10"));
|
|
}
|
|
const visible = history ? 10 : 1999;
|
|
const body = within(screen.getByTestId("thread-message-region"));
|
|
expect(body.getByText(`question ${visible}`)).toBeInTheDocument();
|
|
let finish!: (body: WebuiThreadPersistedPayload) => void;
|
|
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
|
|
act(() => viewport.current?.jumpToUserPrompt("u20"));
|
|
const options = vi.mocked(api.fetchWebuiThread).mock.lastCall?.[2];
|
|
if (typeof options !== "object") throw new Error("expected history read");
|
|
act(() => viewport.current?.jumpToUserPrompt(`u${visible}`));
|
|
await act(async () => finish(page(20)));
|
|
expect(body.getByText(`question ${visible}`)).toBeInTheDocument();
|
|
expect(body.queryByText("question 20")).not.toBeInTheDocument();
|
|
expect(options.signal?.aborted).toBe(true);
|
|
});
|
|
|
|
it("keeps legacy backfilled and newly sent prompts navigable without a transcript cursor", async () => {
|
|
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [] });
|
|
const { result, rerender } = renderHook(({ messages }) => usePromptHistory("a", 1, messages), {
|
|
wrapper: wrapper(), initialProps: { messages: latest },
|
|
});
|
|
await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u1999"));
|
|
rerender({ messages: [...latest, { id: "live-user", role: "user", content: "new question", createdAt: 2001 }] });
|
|
expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["u1999", "live-user"]);
|
|
act(() => result.current.jump("live-user"));
|
|
expect(api.fetchWebuiThread).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("reuses the full directory during token updates and conditional revalidation", async () => {
|
|
const user: UIMessage = { id: "live", role: "user", content: "new question", createdAt: 2001 };
|
|
const { result, rerender } = renderHook(({ version, messages }) => usePromptHistory("a", version, messages), {
|
|
wrapper: wrapper(), initialProps: { version: 1, messages: [...latest, user] },
|
|
});
|
|
await waitFor(() => expect(result.current.prompts).toHaveLength(2001));
|
|
const anchors = result.current.prompts;
|
|
for (let chunk = 0; chunk < 100; chunk++) {
|
|
rerender({ version: 1, messages: [...latest, user, { id: "answer", role: "assistant", content: String(chunk), createdAt: 2002 }] });
|
|
expect(result.current.prompts).toBe(anchors);
|
|
}
|
|
expect(api.fetchPromptIndex).toHaveBeenCalledTimes(1);
|
|
rerender({ version: 2, messages: [...latest, user] });
|
|
await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(2));
|
|
expect(api.fetchPromptIndex).toHaveBeenLastCalledWith("test", "a", expect.any(AbortSignal), { prompts: index, revision: "first" });
|
|
expect(result.current.prompts).toBe(anchors);
|
|
});
|
|
|
|
|
|
it("merges a live input by transport identity without adding an anchor or reordering unknown-time prompts", async () => {
|
|
const recovered = [
|
|
{ id: "old", preview: "older", answerPreview: "", createdAt: 1000, cursor: "0", turnId: "old-input" },
|
|
{ id: "persisted", preview: "same", answerPreview: "answer", createdAt: 0, cursor: "1", turnId: "input" },
|
|
];
|
|
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: recovered, revision: "recovered" });
|
|
const users: UIMessage[] = [
|
|
{ id: "optimistic", role: "user", content: "same", createdAt: 2000, turnId: "input" },
|
|
{ id: "distinct", role: "user", content: "same", createdAt: 3000, turnId: "other-input" },
|
|
];
|
|
const { result, rerender } = renderHook(({ key, version }) => usePromptHistory(key, version, users), {
|
|
wrapper: wrapper(), initialProps: { key: "a", version: 1 },
|
|
});
|
|
await waitFor(() => expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]));
|
|
vi.mocked(api.fetchWebuiThread).mockResolvedValue({ schemaVersion: 3, projection: "events", events: [
|
|
{ event: "user_message", chat_id: "a", text: "same", starts_turn: true, projection_id: "persisted", turn_id: "input", created_at_ms: 0 },
|
|
{ event: "message", chat_id: "a", text: "answer", projection_id: "answer" },
|
|
] });
|
|
await act(async () => result.current.jump("persisted"));
|
|
expect(result.current.target?.id).toBe("persisted");
|
|
expect(result.current.window?.messages[0].createdAt).toBe(0);
|
|
rerender({ key: "a", version: 2 });
|
|
await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(2));
|
|
expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]);
|
|
rerender({ key: "b", version: 1 });
|
|
await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(3));
|
|
expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["old", "persisted", "distinct"]);
|
|
expect(result.current.window).toBeNull();
|
|
expect(result.current.target).toBeNull();
|
|
});
|
|
|
|
|
|
it("keeps the request operation with failures and retries", async () => {
|
|
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
|
|
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
|
|
let finish!: (body: WebuiThreadPersistedPayload) => void;
|
|
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
|
|
act(() => result.current.jump("u10"));
|
|
expect(result.current.operation).toBe("jump");
|
|
expect(result.current.loading).toBe(true);
|
|
await act(async () => finish(page(10)));
|
|
expect(result.current.operation).toBeNull();
|
|
|
|
for (const operation of ["older", "newer"] as const) {
|
|
vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));
|
|
await act(async () => result.current[operation]());
|
|
expect(result.current.operation).toBe(operation);
|
|
expect(result.current.error).toBe("offline");
|
|
await act(async () => result.current.retry());
|
|
expect(result.current.operation).toBeNull();
|
|
expect(result.current.error).toBeNull();
|
|
}
|
|
act(() => result.current.cancel());
|
|
expect(result.current.operation).toBeNull();
|
|
});
|
|
|
|
|
|
it("associates live answers and merges the persisted directory by input ID across turns", async () => {
|
|
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [], revision: "empty" });
|
|
const users: UIMessage[] = [
|
|
{ id: "local-original", inputId: "user:original", role: "user", content: "same", createdAt: 1 },
|
|
{ id: "local-session", inputId: "session-message:received", role: "user", content: "same", createdAt: 2 },
|
|
];
|
|
const { result, rerender } = renderHook(({ messages, version }) => usePromptHistory("a", version, messages), {
|
|
wrapper: wrapper(), initialProps: { messages: users, version: 1 },
|
|
});
|
|
await waitFor(() => expect(result.current.prompts).toHaveLength(2));
|
|
const messages: UIMessage[] = [...users,
|
|
{ id: "original-answer", role: "assistant", content: "Original answer", createdAt: 3, responseInputIds: ["user:original"] },
|
|
];
|
|
rerender({ messages, version: 1 });
|
|
expect(result.current.prompts.map((prompt) => prompt.answerPreview)).toEqual(["Original answer", ""]);
|
|
messages.push({ id: "session-answer", role: "assistant", content: "Session answer", createdAt: 4,
|
|
responseInputIds: ["session-message:received"] });
|
|
rerender({ messages: [...messages], version: 1 });
|
|
expect(result.current.prompts.map((prompt) => prompt.answerPreview)).toEqual(["Original answer", "Session answer"]);
|
|
const persisted = result.current.prompts.map((prompt, index) => ({ ...prompt, id: `persisted-${index}`,
|
|
cursor: String(index), turnId: `execution-${index}` }));
|
|
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: persisted, revision: "persisted" });
|
|
rerender({ messages, version: 2 });
|
|
await waitFor(() => expect(result.current.prompts.map((prompt) => prompt.id)).toEqual(["persisted-0", "persisted-1"]));
|
|
expect(result.current.prompts.map((prompt) => prompt.answerPreview)).toEqual(["Original answer", "Session answer"]);
|
|
});
|