fix(webui): stabilize earlier-history loading and reclaim space (#6349)
* fix(webui): retain smoothly revealed history loading headers * refactor(webui): simplify history loading feedback * fix(webui): keep retained history headers clear of preceding text * fix(webui): reclaim completed history loading space * refactor(webui): group history projection handoff with navigation * test(webui): synchronize history motion observations * fix(webui): collapse history completion geometry handoff
This commit is contained in:
1 parent
73a55e0b2f
commit
743c51e81f
24 files changed
+1658
-356
No files matched your search
@@ -381,7 +381,7 @@ describe("session-owned task UI", () => {
|
||||
expect(screen.getByText("Check more").compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
|
||||
it("keeps legacy work with an unknown origin separate from the latest request after refresh", async () => {
|
||||
it("keeps legacy work separate after refresh and preserves its disclosure through local history prepends", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([
|
||||
task({ task_id: "legacy", revision: 0, label: "Nanjing weather", state: "done", completed_at: 102,
|
||||
origin_turn_id: "websocket:a:1791046873588004336", result: "## Nanjing\n\n- **Rain**" }),
|
||||
@@ -402,6 +402,13 @@ describe("session-owned task UI", () => {
|
||||
expect(within(detail).getByRole("heading", { name: "Nanjing" })).toBeVisible();
|
||||
expect(within(detail).getByRole("list")).toHaveTextContent("Rain");
|
||||
await user.keyboard("{Escape}");
|
||||
view.rerender(layout({ threadMessages: [
|
||||
{ id: "cached-prompt", role: "user", content: "Earlier cached prompt", createdAt: 99_000 },
|
||||
...messages,
|
||||
] }));
|
||||
const expanded = screen.getByRole("region", { name: "Other tasks" });
|
||||
expect(within(expanded).getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");
|
||||
expect(within(expanded).getByRole("button", { name: /Nanjing weather Completed/ })).toBeVisible();
|
||||
view.unmount();
|
||||
render(layout());
|
||||
const restored = await screen.findByRole("region", { name: "Other tasks" });
|
||||
|
||||
@@ -1,32 +1,38 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { HISTORY_PULL_LIMIT_PX, ThreadHistorySpring } from "@/components/thread/thread-history-spring";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { waitFor } from "@testing-library/react";
|
||||
import {
|
||||
HISTORY_HOLD_PX,
|
||||
HISTORY_PULL_LIMIT_PX,
|
||||
HISTORY_PULL_TRIGGER_PX,
|
||||
ThreadHistorySpring,
|
||||
type HistoryRevealPhase,
|
||||
} from "@/components/thread/thread-history-spring";
|
||||
|
||||
const springs = new Set<ThreadHistorySpring>();
|
||||
|
||||
function harness(reduced = false) {
|
||||
let now = 0;
|
||||
let nextId = 0;
|
||||
let distance = 0;
|
||||
const frames = new Map<number, FrameRequestCallback>();
|
||||
const scheduler = {
|
||||
now: () => now,
|
||||
request: vi.fn((callback: FrameRequestCallback) => { frames.set(++nextId, callback); return nextId; }),
|
||||
cancel: (id: number) => { frames.delete(id); },
|
||||
const phase = vi.fn<(phase: HistoryRevealPhase) => void>();
|
||||
const update = vi.fn((next: number) => { distance = next; });
|
||||
const spring = new ThreadHistorySpring({ onPhaseChange: phase, onUpdate: update, prefersReducedMotion: () => reduced });
|
||||
springs.add(spring);
|
||||
const expectBounded = () => {
|
||||
for (const [next] of update.mock.calls) {
|
||||
expect(next).toBeGreaterThanOrEqual(0);
|
||||
expect(next).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);
|
||||
}
|
||||
};
|
||||
const feedback = vi.fn();
|
||||
const spring = new ThreadHistorySpring({ scheduler, prefersReducedMotion: () => reduced,
|
||||
onFeedbackChange: feedback, onUpdate: (next) => { distance = next; } });
|
||||
const advance = (milliseconds = 16) => {
|
||||
now += milliseconds;
|
||||
const callbacks = [...frames.values()];
|
||||
frames.clear();
|
||||
callbacks.forEach((callback) => callback(now));
|
||||
return distance;
|
||||
};
|
||||
const settle = () => { for (let i = 0; i < 100 && frames.size; i++) advance(); };
|
||||
return { spring, scheduler, advance, settle, frames, feedback, distance: () => distance };
|
||||
return { spring, phase, update, expectBounded, distance: () => distance };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const spring of springs) spring.reset();
|
||||
springs.clear();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("history boundary spring", () => {
|
||||
it("resists a short touch and returns continuously without triggering a request", () => {
|
||||
it("resists short touch, reverses continuously, and settles transient feedback at zero", async () => {
|
||||
const h = harness();
|
||||
h.spring.startTouch();
|
||||
h.spring.moveTouch(40);
|
||||
@@ -35,77 +41,125 @@ describe("history boundary spring", () => {
|
||||
expect(pulled).toBeLessThan(40);
|
||||
expect(h.spring.endTouch()).toBe(false);
|
||||
expect(h.distance()).toBe(pulled);
|
||||
expect(h.advance()).toBeGreaterThan(0);
|
||||
h.spring.startTouch();
|
||||
expect(h.distance()).toBeCloseTo(pulled);
|
||||
h.spring.moveTouch(-20);
|
||||
expect(h.distance()).toBeLessThan(pulled);
|
||||
h.settle();
|
||||
h.spring.moveTouch(2_000);
|
||||
expect(h.distance()).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);
|
||||
expect(h.spring.endTouch(true)).toBe(false);
|
||||
await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));
|
||||
expect(h.distance()).toBe(0);
|
||||
expect(h.frames.size).toBe(0);
|
||||
expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);
|
||||
h.expectBounded();
|
||||
});
|
||||
|
||||
it("holds actual loading still, lets a new touch take over, and converges immediately after long frame gaps", () => {
|
||||
it("uses the 56px touch threshold and keeps a request's 48px slot after completion", async () => {
|
||||
const h = harness();
|
||||
h.spring.startTouch();
|
||||
h.spring.moveTouch(120);
|
||||
expect(h.spring.endTouch()).toBe(true);
|
||||
h.spring.setLoading(true);
|
||||
h.settle();
|
||||
expect(h.distance()).toBe(20);
|
||||
expect(h.frames.size).toBe(0);
|
||||
expect(h.distance()).toBeGreaterThan(HISTORY_HOLD_PX);
|
||||
expect(h.distance()).toBeLessThan(HISTORY_PULL_TRIGGER_PX);
|
||||
expect(h.spring.endTouch()).toBe(false);
|
||||
await waitFor(() => expect(h.distance()).toBe(0));
|
||||
h.spring.startTouch();
|
||||
expect(h.distance()).toBe(20);
|
||||
h.spring.moveTouch(20);
|
||||
expect(h.distance()).toBeGreaterThan(20);
|
||||
h.spring.endTouch();
|
||||
h.spring.setLoading(false);
|
||||
h.advance(30_000);
|
||||
expect(h.distance()).toBe(0);
|
||||
expect(h.frames.size).toBe(0);
|
||||
h.spring.moveTouch(160);
|
||||
expect(h.spring.endTouch()).toBe(true);
|
||||
h.spring.hold();
|
||||
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
|
||||
expect(h.spring.wheel(20)).toBe(false);
|
||||
h.expectBounded();
|
||||
});
|
||||
|
||||
it("merges decelerating wheel input into one bounded spring and one boundary request", () => {
|
||||
it("rearms after leaving the boundary and restores held geometry after touch takeover/cancel", async () => {
|
||||
const h = harness();
|
||||
expect(h.spring.wheel(100)).toBe(true);
|
||||
h.spring.hold();
|
||||
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
|
||||
h.spring.leaveBoundary();
|
||||
expect(h.distance()).toBe(HISTORY_HOLD_PX);
|
||||
expect(h.spring.wheel(100)).toBe(true);
|
||||
expect(h.spring.wheel(20)).toBe(false);
|
||||
await waitFor(() => expect(h.distance()).toBeGreaterThan(HISTORY_HOLD_PX));
|
||||
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
|
||||
h.spring.startTouch();
|
||||
expect(h.distance()).toBeCloseTo(HISTORY_HOLD_PX);
|
||||
h.spring.moveTouch(120);
|
||||
expect(h.distance()).toBeGreaterThan(HISTORY_PULL_TRIGGER_PX);
|
||||
expect(h.spring.endTouch(true)).toBe(false);
|
||||
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
|
||||
expect(h.phase.mock.calls.filter(([phase]) => phase === "held")).toHaveLength(1);
|
||||
h.expectBounded();
|
||||
});
|
||||
|
||||
it("decays wheel pressure without duplicate requests and is bounded under sustained reversals", async () => {
|
||||
const h = harness();
|
||||
let requests = 0;
|
||||
for (const delta of [100, 70, 48, 32, 20, 12, 6, 2]) {
|
||||
if (h.spring.wheel(delta)) requests++;
|
||||
expect(h.frames.size).toBe(1);
|
||||
h.advance();
|
||||
}
|
||||
expect(requests).toBe(1);
|
||||
expect(h.feedback.mock.calls).toEqual([[true]]);
|
||||
expect(h.distance()).toBeLessThan(HISTORY_PULL_LIMIT_PX);
|
||||
h.settle();
|
||||
await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));
|
||||
expect(h.distance()).toBe(0);
|
||||
expect(h.feedback.mock.calls).toEqual([[true], [false]]);
|
||||
expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);
|
||||
expect(h.spring.wheel(100)).toBe(true);
|
||||
h.spring.hold();
|
||||
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
|
||||
for (const direction of [1, -1, 1, -1]) {
|
||||
for (let i = 0; i < 12; i++) {
|
||||
for (let packet = 0; packet < 4; packet++) expect(h.spring.wheel(direction * 2_000)).toBe(false);
|
||||
await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
|
||||
expect(h.distance()).toBeGreaterThanOrEqual(0);
|
||||
expect(h.distance()).toBeLessThanOrEqual(HISTORY_PULL_LIMIT_PX);
|
||||
}
|
||||
}
|
||||
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
|
||||
h.expectBounded();
|
||||
});
|
||||
|
||||
it("cancels task-owned motion on conversation changes", () => {
|
||||
it("cancels stale completion on reset and supports immediate reuse", async () => {
|
||||
const h = harness();
|
||||
h.spring.wheel(100);
|
||||
h.spring.setLoading(true);
|
||||
h.spring.hold();
|
||||
await waitFor(() => expect(h.distance()).toBeGreaterThan(0));
|
||||
h.spring.reset();
|
||||
expect(h.frames.size).toBe(0);
|
||||
expect(h.distance()).toBe(0);
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
expect(h.distance()).toBe(0);
|
||||
expect(h.phase).toHaveBeenLastCalledWith("hidden");
|
||||
expect(h.spring.wheel(100)).toBe(true);
|
||||
h.spring.hold();
|
||||
await waitFor(() => expect(h.distance()).toBe(HISTORY_HOLD_PX));
|
||||
});
|
||||
|
||||
it("keeps the touch trigger functional with reduced motion and no display travel", () => {
|
||||
it("keeps reduced-motion transient input functional and settles its lifecycle without travel", async () => {
|
||||
const h = harness(true);
|
||||
h.spring.startTouch();
|
||||
h.spring.moveTouch(120);
|
||||
h.spring.moveTouch(160);
|
||||
expect(h.distance()).toBe(0);
|
||||
expect(h.spring.endTouch()).toBe(true);
|
||||
h.spring.setLoading(true);
|
||||
await waitFor(() => expect(h.phase).toHaveBeenLastCalledWith("hidden"));
|
||||
expect(h.phase.mock.calls).toEqual([["feedback"], ["hidden"]]);
|
||||
expect(h.spring.wheel(100)).toBe(true);
|
||||
expect(h.spring.wheel(20)).toBe(false);
|
||||
expect(h.distance()).toBe(0);
|
||||
h.settle();
|
||||
expect(h.frames.size).toBe(0);
|
||||
h.spring.setLoading(false);
|
||||
h.settle();
|
||||
expect(h.feedback.mock.calls).toEqual([[true], [false]]);
|
||||
h.spring.wheel(100);
|
||||
expect(h.feedback).toHaveBeenLastCalledWith(true);
|
||||
h.settle();
|
||||
h.spring.leaveBoundary();
|
||||
expect(h.phase).toHaveBeenLastCalledWith("hidden");
|
||||
expect(h.update.mock.calls.every(([next]) => next === 0)).toBe(true);
|
||||
});
|
||||
|
||||
it("reveals and restores the reduced-motion committed slot immediately", () => {
|
||||
const h = harness(true);
|
||||
expect(h.spring.wheel(100)).toBe(true);
|
||||
h.spring.hold();
|
||||
expect(h.distance()).toBe(HISTORY_HOLD_PX);
|
||||
h.spring.startTouch();
|
||||
h.spring.moveTouch(120);
|
||||
expect(h.spring.endTouch()).toBe(true);
|
||||
expect(h.distance()).toBe(HISTORY_HOLD_PX);
|
||||
expect(h.spring.wheel(100)).toBe(false);
|
||||
h.spring.reset();
|
||||
expect(h.distance()).toBe(0);
|
||||
expect(h.feedback).toHaveBeenLastCalledWith(false);
|
||||
h.expectBounded();
|
||||
});
|
||||
});
|
||||
@@ -16,17 +16,34 @@ describe("ThreadHistoryStatus", () => {
|
||||
expect(container.firstElementChild).toHaveAttribute("data-state", "exhausted");
|
||||
});
|
||||
|
||||
it("uses one loading display before and during a request while preserving keyboard activation", () => {
|
||||
it("hides completed feedback without offering another loading action", () => {
|
||||
const onRetry = vi.fn();
|
||||
const { container, rerender } = render(<ThreadHistoryStatus loading={false} error={null} onRetry={onRetry} />);
|
||||
const { container, rerender } = render(<ThreadHistoryStatus loading error={null} onRetry={onRetry} />);
|
||||
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
|
||||
const load = screen.getByRole("button", { name: "Load earlier messages" });
|
||||
expect(load.querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
|
||||
fireEvent.click(load);
|
||||
expect(onRetry).toHaveBeenCalledTimes(1);
|
||||
rerender(<ThreadHistoryStatus loading={false} error={null} onRetry={onRetry} />);
|
||||
expect(container.firstElementChild).toHaveAttribute("data-state", "ready");
|
||||
expect(container.firstElementChild).toHaveAttribute("aria-hidden", "true");
|
||||
expect(container.firstElementChild).toHaveClass("invisible");
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||
expect(onRetry).not.toHaveBeenCalled();
|
||||
rerender(<ThreadHistoryStatus loading error={null} onRetry={onRetry} />);
|
||||
expect(container.firstElementChild).toHaveAttribute("data-state", "loading");
|
||||
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
|
||||
expect(container.firstElementChild).not.toHaveClass("invisible");
|
||||
expect(screen.getByRole("status")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows decorative Blocks while previewing a pull without offering a loading action", () => {
|
||||
const onRetry = vi.fn();
|
||||
const { container } = render(<ThreadHistoryStatus loading={false} error={null} preview onRetry={onRetry} />);
|
||||
expect(container.firstElementChild).toHaveAttribute("data-state", "ready");
|
||||
expect(container.firstElementChild).not.toHaveClass("invisible");
|
||||
const blocks = screen.getByRole("status").querySelector(".thread-history-blocks")!;
|
||||
expect(blocks.children).toHaveLength(9);
|
||||
expect(blocks).toHaveAttribute("aria-hidden", "true");
|
||||
fireEvent.click(blocks);
|
||||
expect(onRetry).not.toHaveBeenCalled();
|
||||
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("status").textContent).toBe("");
|
||||
});
|
||||
|
||||
it("offers error Blocks with the actual failure on keyboard focus and resumes loading on retry", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { type ThreadCameraFollowResult } from "@/components/thread/thread-camera";
|
||||
import {
|
||||
ThreadMotionCoordinator,
|
||||
type ThreadMotionGeometry,
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
|
||||
let nextFrameId = 1;
|
||||
let cameraFollowing = false;
|
||||
let nextNavigationResult: ThreadCameraFollowResult = "started";
|
||||
const frames = new Map<number, FrameRequestCallback>();
|
||||
let geometry: ThreadMotionGeometry = {
|
||||
scrollTop: 400,
|
||||
@@ -39,8 +41,8 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
|
||||
followTo: vi.fn(() => "settled" as const),
|
||||
isFollowing: vi.fn(() => cameraFollowing),
|
||||
navigateTo: vi.fn(() => {
|
||||
cameraFollowing = true;
|
||||
return "started" as const;
|
||||
cameraFollowing = nextNavigationResult === "started";
|
||||
return nextNavigationResult;
|
||||
}),
|
||||
};
|
||||
const onGeometry = vi.fn();
|
||||
@@ -69,6 +71,9 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
|
||||
const setCameraFollowing = (following: boolean) => {
|
||||
cameraFollowing = following;
|
||||
};
|
||||
const setNextNavigationResult = (result: ThreadCameraFollowResult) => {
|
||||
nextNavigationResult = result;
|
||||
};
|
||||
|
||||
return {
|
||||
camera,
|
||||
@@ -81,6 +86,7 @@ function motionHarness(initial?: Partial<ThreadMotionGeometry>) {
|
||||
advanceFrame,
|
||||
setCameraFollowing,
|
||||
setGeometry,
|
||||
setNextNavigationResult,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -708,4 +714,56 @@ describe("ThreadMotionCoordinator", () => {
|
||||
|
||||
expect(camera.jumpTo.mock.calls).toEqual([[430], [458], [490]]);
|
||||
});
|
||||
|
||||
it("retargets a prompt navigation from authoritative geometry without restarting the camera", () => {
|
||||
const { camera, coordinator, measure, setGeometry } = motionHarness();
|
||||
coordinator.navigateHistoryToPrompt("prompt-46");
|
||||
expect(measure).toHaveBeenCalledWith("prompt-46");
|
||||
expect(camera.navigateTo).toHaveBeenLastCalledWith(404);
|
||||
expect(coordinator.snapshot().mode).toBe("navigating-history");
|
||||
|
||||
camera.cancel.mockClear();
|
||||
setGeometry({ promptTop: 520 });
|
||||
coordinator.reconcileObservedGeometry();
|
||||
|
||||
expect(camera.navigateTo).toHaveBeenLastCalledWith(520);
|
||||
expect(camera.cancel).not.toHaveBeenCalled();
|
||||
expect(coordinator.snapshot().mode).toBe("navigating-history");
|
||||
});
|
||||
|
||||
it("releases prompt retarget ownership on composer input and user takeover", () => {
|
||||
const { camera, coordinator, setGeometry } = motionHarness();
|
||||
coordinator.navigateHistoryToPrompt("prompt-46");
|
||||
camera.cancel.mockClear();
|
||||
coordinator.handleComposerInput();
|
||||
expect(camera.cancel).toHaveBeenCalledTimes(1);
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
const callsAfterComposer = camera.navigateTo.mock.calls.length;
|
||||
setGeometry({ promptTop: 600 });
|
||||
coordinator.reconcileObservedGeometry();
|
||||
expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterComposer);
|
||||
|
||||
coordinator.navigateHistoryToPrompt("prompt-47");
|
||||
camera.cancel.mockClear();
|
||||
coordinator.handleUserScrollIntent(true);
|
||||
expect(camera.cancel).toHaveBeenCalledTimes(1);
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
const callsAfterTouch = camera.navigateTo.mock.calls.length;
|
||||
setGeometry({ promptTop: 700 });
|
||||
coordinator.reconcileObservedGeometry();
|
||||
expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterTouch);
|
||||
});
|
||||
|
||||
it("drops prompt identity when an aligned navigation settles immediately", () => {
|
||||
const { camera, coordinator, measure, setGeometry, setNextNavigationResult } = motionHarness();
|
||||
setNextNavigationResult("settled");
|
||||
expect(coordinator.navigateHistoryToPrompt("prompt-46")).toBe("settled");
|
||||
expect(measure).toHaveBeenCalledWith("prompt-46");
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
const callsAfterSettle = camera.navigateTo.mock.calls.length;
|
||||
setGeometry({ promptTop: 720 });
|
||||
coordinator.reconcileObservedGeometry();
|
||||
expect(camera.navigateTo).toHaveBeenCalledTimes(callsAfterSettle);
|
||||
expect(coordinator.snapshot().mode).toBe("browsing-history");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { StrictMode, type ReactNode } from "react";
|
||||
import { Profiler, StrictMode, type ReactNode } from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
@@ -4002,6 +4002,89 @@ describe("ThreadShell", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ name: "visible rows after a hidden command prefix", rows: [
|
||||
{ role: "user" as const, content: "/model hidden", turnId: "webui-system:model" },
|
||||
{ role: "assistant" as const, content: "hidden model response", turnId: "webui-system:model" },
|
||||
{ role: "user" as const, content: "older question", turnId: "older-turn" },
|
||||
{ role: "assistant" as const, content: "older answer", turnId: "older-turn" },
|
||||
], expectVisible: true },
|
||||
{ name: "a page containing only hidden command rows", rows: [
|
||||
{ role: "user" as const, content: "/model hidden", turnId: "webui-system:model" },
|
||||
{ role: "assistant" as const, content: "hidden model response", turnId: "webui-system:model" },
|
||||
], expectVisible: false },
|
||||
{ name: "an empty successful page", rows: [], expectVisible: false },
|
||||
{ name: "a failed page", rows: [], expectVisible: false, error: true },
|
||||
])("releases older-page loading after ThreadShell handles $name", async ({ rows, expectVisible, error = false }) => {
|
||||
const client = makeClient();
|
||||
const chatId = `older-projection-${expectVisible ? "visible" : "hidden"}`;
|
||||
let resolveOlder!: (response: Response) => void;
|
||||
let olderReturned = false;
|
||||
const commits: Array<{ loading: boolean; olderVisible: boolean }> = [];
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (!url.includes(`websocket%3A${chatId}/webui-thread`)) {
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
}
|
||||
if (url.includes("before=")) {
|
||||
return new Promise<Response>((resolve) => { resolveOlder = resolve; });
|
||||
}
|
||||
return httpJson({
|
||||
...transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "current question", turnId: "current-turn" },
|
||||
]),
|
||||
has_pending_tool_calls: expectVisible,
|
||||
active_turn_id: expectVisible ? "current-turn" : null,
|
||||
completed_turn_ids: [],
|
||||
page: { before_cursor: "older-page", has_more_before: true, user_message_offset: 1 },
|
||||
});
|
||||
}));
|
||||
const capture = () => {
|
||||
if (!olderReturned) return;
|
||||
commits.push({
|
||||
loading: document.querySelector('.thread-history-status[data-state="loading"]') !== null,
|
||||
olderVisible: document.body.textContent?.includes("older answer") ?? false,
|
||||
});
|
||||
};
|
||||
const { container } = render(wrap(client, <Profiler id="older-history" onRender={capture}>
|
||||
<ThreadShell session={session(chatId)} title="Older projection" onToggleSidebar={() => {}} />
|
||||
</Profiler>));
|
||||
await screen.findByText("current question");
|
||||
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 waitFor(() => expect(resolveOlder).toBeTypeOf("function"));
|
||||
await screen.findByText("Loading earlier messages…");
|
||||
if (expectVisible) {
|
||||
act(() => client._emitChat(chatId, {
|
||||
event: "delta", chat_id: chatId, turn_id: "current-turn", text: "live during pagination",
|
||||
}));
|
||||
await screen.findByText("live during pagination");
|
||||
}
|
||||
const olderPayload = rows.length > 0
|
||||
? transcriptFromSimpleMessages(rows)
|
||||
: { schemaVersion: 3, projection: "events", events: [], page: { before_cursor: null, has_more_before: false } };
|
||||
olderReturned = true;
|
||||
await act(async () => {
|
||||
resolveOlder(error
|
||||
? new Response("History unavailable", { status: 503 })
|
||||
: httpJson({ ...olderPayload, page: { before_cursor: null, has_more_before: false } }));
|
||||
});
|
||||
if (expectVisible) await screen.findByText("older answer");
|
||||
await waitFor(() => expect(container.querySelector('.thread-history-status[data-state="loading"]')).toBeNull());
|
||||
expect(commits.some((commit) => commit.loading && !commit.olderVisible)).toBe(expectVisible);
|
||||
if (error) {
|
||||
expect(container.querySelector('.thread-history-status[data-state="error"]')).toBeInTheDocument();
|
||||
expect(container.querySelector(".thread-history-slot")).toBeInTheDocument();
|
||||
} else {
|
||||
expect(container.querySelector(".thread-history-slot")).not.toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it("prepends earlier history while preserving the active answer cursor", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "running-paged-history";
|
||||
|
||||
@@ -49,7 +49,7 @@ function dispatchHistoryInput(scroller: HTMLElement, input: "wheel" | "touch" |
|
||||
if (input === "keyboard") fireEvent.keyDown(scroller, { key: "PageUp" });
|
||||
if (input === "touch") {
|
||||
fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 200 }] });
|
||||
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 300 }] });
|
||||
fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 380 }] });
|
||||
fireEvent.touchEnd(scroller);
|
||||
}
|
||||
}
|
||||
@@ -1517,7 +1517,6 @@ describe("ThreadViewport", () => {
|
||||
expect(screen.queryByText(`message ${firstVisible - 1}`)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(`message ${firstVisible}`)).toBeInTheDocument();
|
||||
expect(screen.getByText("message 299")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Load earlier messages" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("automatically expands earlier local history near the top", () => {
|
||||
@@ -1677,7 +1676,6 @@ describe("ThreadViewport", () => {
|
||||
describe.each(["wheel", "touch"] as const)("%s history boundary", (input) => {
|
||||
it.each([
|
||||
{ loadingOlder: true },
|
||||
{ olderError: "offline" },
|
||||
{ conversationReady: false },
|
||||
{ hasMoreBefore: false },
|
||||
])("keeps history blocked: %o", (blocked) => {
|
||||
@@ -1714,7 +1712,7 @@ describe("ThreadViewport", () => {
|
||||
expect(onLoadOlder).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("pauses automatic history requests after a failure and exposes retry", () => {
|
||||
it.each(["wheel", "touch", "keyboard"] as const)("pauses automatic requests after failure but accepts another %s boundary gesture", (input) => {
|
||||
const onLoadOlder = vi.fn();
|
||||
|
||||
const { container } = render(
|
||||
@@ -1737,7 +1735,8 @@ describe("ThreadViewport", () => {
|
||||
});
|
||||
|
||||
expect(onLoadOlder).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Loading failed. Retry" }));
|
||||
expect(screen.getByRole("button", { name: "Loading failed. Retry" }).querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
|
||||
dispatchHistoryInput(scroller, input);
|
||||
expect(onLoadOlder).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -1774,13 +1773,14 @@ describe("ThreadViewport", () => {
|
||||
fireEvent.touchMove(scroller, touch(240));
|
||||
expect(historyPull(scroller)).toBeGreaterThan(0);
|
||||
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
|
||||
expect(container.querySelector(".thread-history-status")).not.toHaveClass("invisible");
|
||||
expect(onLoadOlder).not.toHaveBeenCalled();
|
||||
fireEvent.touchEnd(scroller);
|
||||
expect(historyPull(scroller)).toBeGreaterThan(0);
|
||||
await waitFor(() => expect(historyPull(scroller)).toBe(0));
|
||||
|
||||
fireEvent.touchStart(scroller, touch(200));
|
||||
fireEvent.touchMove(scroller, touch(300));
|
||||
fireEvent.touchMove(scroller, touch(380));
|
||||
expect(onLoadOlder).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("status").querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
|
||||
fireEvent.touchEnd(scroller);
|
||||
@@ -1789,8 +1789,19 @@ describe("ThreadViewport", () => {
|
||||
fireEvent.scroll(scroller);
|
||||
expect(onLoadOlder).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByText("Loading earlier messages…")).toBeInTheDocument();
|
||||
rerender(<ThreadViewport {...props} />);
|
||||
rerender(<ThreadViewport {...props} loadingOlder />);
|
||||
expect(container.querySelector(".thread-history-slot")).toBeInTheDocument();
|
||||
const prepended = [
|
||||
{ ...messages[0], id: "older-u0", content: "Earlier message" },
|
||||
...messages,
|
||||
];
|
||||
rerender(<ThreadViewport {...props} messages={prepended} />);
|
||||
await waitFor(() => expect(historyPull(scroller)).toBe(0));
|
||||
expect(container.querySelector(".thread-history-slot")).not.toBeInTheDocument();
|
||||
expect(container.querySelector(".thread-history-status")).toHaveAttribute("data-state", "ready");
|
||||
expect(container.querySelector(".thread-history-status")).toHaveClass("invisible");
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not fetch on touch scroll alone or horizontal gestures and clears pull on session change", () => {
|
||||
@@ -2009,7 +2020,7 @@ describe("ThreadViewport", () => {
|
||||
const navigation = { prompts: [{ id: "u1", label: "hello", preview: "hello", answerPreview: "", createdAt: 1, index: 0 }],
|
||||
window: { messages: [{ id: "old", role: "user" as const, content: "old question", createdAt: 0 }],
|
||||
userMessageOffset: 0, hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },
|
||||
target: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() };
|
||||
target: null, operation: null, loading: false, error: null, jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest, retry: vi.fn(), updateMessages: vi.fn() };
|
||||
const view = render(<ThreadViewport ref={viewportRef} messages={messages} isStreaming={false} composer={<div />} navigation={navigation} />);
|
||||
act(() => viewportRef.current?.jumpToUserPrompt("u1"));
|
||||
expect(latest).toHaveBeenCalledOnce();
|
||||
@@ -2025,7 +2036,7 @@ describe("ThreadViewport", () => {
|
||||
render(<ThreadViewport messages={messages} isStreaming={false} composer={<div />}
|
||||
navigation={{ prompts: [], window: { messages: history, userMessageOffset: 0,
|
||||
hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },
|
||||
target: { id: "old-user", sequence: 1 }, loading: false, error: null,
|
||||
target: { id: "old-user", sequence: 1 }, operation: null, loading: false, error: null,
|
||||
jump: vi.fn(), older: vi.fn(), newer: vi.fn(), cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn() }} />);
|
||||
await waitFor(() => expect(screen.getByText("Large old turn")).toBeInTheDocument());
|
||||
});
|
||||
@@ -2099,17 +2110,17 @@ describe("ThreadViewport", () => {
|
||||
expect(navigateTo).toHaveBeenLastCalledWith(Math.max(0, (count - 1) * 40 - 48));
|
||||
});
|
||||
|
||||
it("keeps prompt jumps aligned when the header changes between a row and an overlay", async () => {
|
||||
it("aligns prompt jumps with the scroll inset independently of message layout", async () => {
|
||||
const navigateTo = vi.spyOn(ThreadCameraController.prototype, "navigateTo")
|
||||
.mockReturnValue("started");
|
||||
const { scroller } = await renderPromptRailViewport();
|
||||
const marker = screen.getByRole("button", { name: "Jump to message: message 1" });
|
||||
|
||||
scroller.style.paddingTop = "16px";
|
||||
scroller.style.scrollPaddingTop = "16px";
|
||||
fireEvent.click(marker);
|
||||
expect(navigateTo).toHaveBeenLastCalledWith(344);
|
||||
|
||||
scroller.style.paddingTop = "48px";
|
||||
scroller.style.scrollPaddingTop = "48px";
|
||||
fireEvent.click(marker);
|
||||
expect(navigateTo).toHaveBeenLastCalledWith(312);
|
||||
});
|
||||
|
||||
@@ -55,6 +55,27 @@ it("loads the complete index without bodies, reads bounded windows and leaves li
|
||||
expect(latest).toHaveLength(1);
|
||||
});
|
||||
|
||||
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" },
|
||||
@@ -175,3 +196,28 @@ it("merges a live input by transport identity without adding an anchor or reorde
|
||||
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();
|
||||
});
|
||||
Reference in new issue
Block a user