feat(webui): inspect file context in a live graph sidebar (#6562)

* feat(webui): inspect file context in a live graph sidebar

* refactor(webui): place preview controls in the shared sidebar header

* fix(webui): synchronize npm lockfile for graph dependencies

* fix(webui): preserve compacted context and refine graph inspection

* fix(context): harden provenance, request usage, and drawer lifecycle

* fix(webui): align source skeleton and browser fixtures

* perf(context): reuse source analysis and capture request graphs once

* perf(webui): compact graph history and render graph motion on canvas

* fix(webui): remove redundant context sidebar header

* style(webui): clarify context replay icon

* perf(webui): pace context replay on an adaptive timeline

* feat(webui): briefly reveal labels for new context nodes

* fix(webui): reveal new labels only for loaded context files

* fix(webui): restart graph animation clock after idle

* fix(webui): reveal labels when replay reverses node exit

* refactor(context): project file-use facts without retention tracking

* refactor(context): observe file reads outside agent execution

* fix(webui): animate context sidebar closing

* refactor(context): remove unused graph and usage panel code

* refactor(context): isolate prompt observation from execution metadata

* fix(webui): clarify cache rate and show context token usage

* fix(webui): abbreviate context token counts in thousands

* fix(webui): omit token unit from context usage details

* fix(webui): restore large source preview highlighting and panel elevation

* fix(webui): distinguish modifier scrolling from keyboard focus

* fix(webui): align preview tab and panel corner radii

* fix(webui): attach file tabs to the header divider

* fix(webui): use one action to toggle file preview mode

* fix(webui): use hover hint for context replay

* fix(webui): share composer layout between graph and file sidebars

* fix(webui): align sidebar bottom with composer surface

* fix(webui): restore mobile graph drawing and touch file details

* test(webui): align legacy cache assertions with current label

* perf(context): retain source analysis and bound graph animation work

* style(webui): add light elevation to user messages

* test(webui): await lazy graph scene before replay assertions

* fix(webui): align preview skeleton and browser contracts
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-05 17:09:20 +08:00
1 parent 2b44088413
commit 519ed81132
132 files changed
+4673 -1159

No files matched your search

+57 -3
View File
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
changeAutomationChat,
parseWebuiThreadPayload,
cancelMcpOAuth,
configureChannel,
completeMcpOAuth,
@@ -110,7 +111,7 @@ describe("webui API helpers", () => {
await fetchWebuiThread("tok", "websocket:chat-1");
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -126,7 +127,7 @@ describe("webui API helpers", () => {
});
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1",
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -172,7 +173,7 @@ describe("webui API helpers", () => {
})).resolves.toBe(cached);
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({
headers: {
Authorization: "Bearer tok",
@@ -1423,3 +1424,56 @@ describe("webui API helpers", () => {
);
});
});
describe("context graph response dictionaries", () => {
const graph = { nodes: [{ path: "/guide.md", name: "guide.md", tokens: 10, state: "loaded" }], edges: [] };
const request = (id: string, fields: Record<string, unknown>) => ({
event: "model_request", chat_id: "chat", request_id: id, run_id: "run", sequence: 2,
phase: "completed", ...fields,
});
const payload = (events: unknown[], fields: Record<string, unknown> = {}) => ({ schemaVersion: 3, projection: "events", events, ...fields });
it("resolves repeated graphs and checkpoint graphs into shared domain objects", () => {
const result = parseWebuiThreadPayload(payload([
request("one", { context_graph_ref: "0", request_usage: { context_tokens: 20 } }),
request("two", { context_graph_ref: "0", request_usage: null }),
{ event: "context_compaction", chat_id: "chat", compaction_id: "compact", phase: "succeeded",
context_snapshot: { graph_ref: "0", estimated_tokens: 10, context_window_tokens: 100 } },
], { context_graphs: { "0": { nodes: [0], edges: [] } }, context_graph_nodes: graph.nodes, context_graph_edges: graph.edges }));
const requests = result.events.filter((event) => event.event === "model_request");
expect(requests[0].context_graph).toBe(requests[1].context_graph);
expect(requests[0].context_graph).toEqual(graph);
expect(requests[1].request_usage).toBeNull();
expect(result.events[2]).toMatchObject({ context_snapshot: { graph } });
});
it("preserves a growing timeline while sharing unchanged node and edge entities", () => {
const nodes = Array.from({ length: 300 }, (_, index) => ({ path: `/${index}.md`, name: `${index}.md`, tokens: 10, state: "loaded" }));
const edges = nodes.slice(1).map((node, index) => ({ source: nodes[index].path, target: node.path }));
const descriptors = Object.fromEntries(Array.from({ length: 50 }, (_, index) => [String(index), {
nodes: Array.from({ length: 251 + index }, (_, n) => n),
edges: Array.from({ length: 250 + index }, (_, n) => n),
}]));
const result = parseWebuiThreadPayload(payload(Array.from({ length: 50 }, (_, index) => request(String(index), { context_graph_ref: String(index) })), {
context_graphs: descriptors, context_graph_nodes: nodes, context_graph_edges: edges,
}));
const requests = result.events.filter((event) => event.event === "model_request");
for (let index = 0; index < requests.length; index += 1) {
expect(requests[index].context_graph?.nodes).toEqual(nodes.slice(0, 251 + index));
expect(requests[index].context_graph?.edges).toEqual(edges.slice(0, 250 + index));
}
expect(requests[0].context_graph).not.toBe(requests[1].context_graph);
expect(requests[0].context_graph?.nodes[0]).toBe(requests[49].context_graph?.nodes[0]);
expect(requests[0].context_graph?.edges[0]).toBe(requests[49].context_graph?.edges[0]);
});
it("continues to accept inline graphs from older hosts", () => {
const result = parseWebuiThreadPayload(payload([request("one", { context_graph: graph })]));
expect(result.events[0]).toMatchObject({ context_graph: graph });
});
it("rejects unknown references and invalid dictionary entries", () => {
expect(() => parseWebuiThreadPayload(payload([request("one", { context_graph_ref: "missing" })], { context_graphs: {}, context_graph_nodes: [], context_graph_edges: [] }))).toThrow("Unknown context graph reference");
expect(() => parseWebuiThreadPayload(payload([], { context_graphs: { "0": { nodes: [], edges: [0] } }, context_graph_nodes: [], context_graph_edges: [{ source: "missing", target: "missing" }] }))).toThrow("Invalid context graph entity table");
});
});
+7
View File
@@ -65,6 +65,13 @@ describe("CodeBlock", () => {
expect(container.querySelectorAll("*").length).toBeLessThan(10);
});
it("keeps a Python module beyond the preview budget available as complete plain text", () => {
const code = Array.from({ length: 2800 }, (_, index) => `def function_${index}(): return "a realistic source line"`).join("\n");
render(<CodeBlock code={code} language="python" chrome="none"
showLineNumbers wrapLongLines={false} viewportHighlight />);
expect(screen.getByTestId("plain-code-fallback").querySelector("code > span > span:last-child")?.textContent).toBe(code);
});
it("paints large preview text before enhancing it, and cancels enhancement on unmount", async () => {
const callbacks = new Map<number, FrameRequestCallback>();
let next = 0;
+75 -165
View File
@@ -1,181 +1,91 @@
import { createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";
import type { ContextSnapshot } from "@/lib/types";
function pointer(
target: HTMLElement,
type: "pointerDown" | "pointerMove" | "pointerUp" | "pointerCancel" | "lostPointerCapture",
{ y, x = 160, time = 1000, id = 1 }: { y: number; x?: number; time?: number; id?: number },
) {
const event = createEvent[type](target, {
pointerId: id, pointerType: "touch", isPrimary: true, button: 0, clientX: x, clientY: y,
});
Object.defineProperty(event, "timeStamp", { value: time });
fireEvent(target, event);
}
const first: ContextSnapshot = { id: "1", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 },
graph: { nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [] } };
async function openSheet() {
const user = userEvent.setup();
render(
<ComposerUsagePopover
bottomSheet
showLabel
context={{ contextTokens: 10000, contextWindowTokens: 200000 }}
rounds={[
{ id: "round", timestamp: 0, inputTokens: 10000, cachedTokens: 8000 },
{ id: "round-2", timestamp: 60000, inputTokens: 14000, outputTokens: 280 },
]}
/>,
);
const trigger = screen.getByTestId("composer-context-usage");
await user.click(trigger);
const sheet = screen.getByRole("dialog", { name: "Context usage" });
const handle = within(sheet).getByRole("button", { name: "Close" });
return { user, trigger, sheet, handle };
}
describe("Mobile context usage sheet", () => {
it("keeps tiny rounds tappable without exaggerating their visual token usage", async () => {
describe("Context sidebar", () => {
it("stays open while writing a message and updates the graph as new snapshots arrive", async () => {
const user = userEvent.setup();
render(<ComposerUsagePopover bottomSheet context={null} rounds={[
{ id: "small", timestamp: 0, inputTokens: 1000 },
{ id: "large", timestamp: 60000, inputTokens: 500000 },
]} />);
const content = (snapshots: ContextSnapshot[]) => <><textarea aria-label="Message" />
<ComposerUsagePopover context={null} rounds={[]} snapshots={snapshots} /></>;
const view = render(content([first]));
await user.click(screen.getByTestId("composer-context-usage"));
const [small, large] = screen.getAllByTestId("round-usage-bar");
for (const bar of [small, large]) {
expect(bar.parentElement).toHaveClass("relative", "h-full", "flex-1");
expect(bar).toHaveClass("before:absolute", "before:inset-0");
}
expect(small).toHaveStyle({ height: "0.216px" });
expect(large).toHaveStyle({ height: "108px" });
await user.pointer([{ keys: "[TouchA>]", target: small }, { keys: "[/TouchA]", target: small }]);
expect(within(screen.getByRole("dialog", { name: "Context usage" })).getByRole("dialog"))
.toHaveTextContent("1,000");
const sidebar = screen.getByRole("complementary", { name: "Context usage" });
await user.type(screen.getByRole("textbox"), "Continue reading");
expect(sidebar).toBeVisible();
expect(screen.getByRole("textbox")).toHaveValue("Continue reading");
view.rerender(content([first, { ...first, id: "2", usage: { prompt_tokens: 2000 }, graph: {
nodes: [...first.graph.nodes, { path: "/b.md", name: "b.md", state: "loaded", tokens: 200 }], edges: [],
} }]));
expect(await within(sidebar).findByRole("button", { name: "b.md" })).toBeInTheDocument();
expect(within(sidebar).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");
expect(screen.getByRole("textbox")).toHaveFocus();
await user.click(within(sidebar).getByRole("button", { name: "Expand context panel" }));
const expanded = await screen.findByRole("dialog", { name: "Context usage" });
expect(within(expanded).getByRole("button", { name: "b.md" })).toBeInTheDocument();
expect(within(expanded).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");
await user.click(within(expanded).getByRole("button", { name: "Collapse context panel" }));
expect(within(sidebar).getByRole("button", { name: "Expand context panel" })).toBeVisible();
await user.click(screen.getByTestId("composer-context-usage"));
await waitFor(() => expect(screen.getByTestId("composer-context-usage")).toHaveFocus());
});
it("replaces the X with a keyboard-accessible drag handle", async () => {
const { user, handle, sheet, trigger } = await openSheet();
expect(within(sheet).getAllByRole("button", { name: "Close" })).toEqual([handle]);
expect(handle.querySelector("svg")).toBeNull();
expect(handle).toHaveClass("touch-none", "h-11");
handle.focus();
await user.keyboard("{Enter}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(trigger).toHaveFocus();
});
it("keeps tapped round details open, switches rounds, and toggles the same bar closed", async () => {
const { user, sheet } = await openSheet();
const [first, second] = within(sheet).getAllByTestId("round-usage-bar");
const tap = (target: HTMLElement) => user.pointer([
{ keys: "[TouchA>]", target },
{ keys: "[/TouchA]", target },
]);
expect(first.tagName).toBe("BUTTON");
await tap(first);
const details = within(sheet).getByRole("dialog");
expect(details).toHaveTextContent("10,000");
expect(details).toHaveTextContent("80%");
expect(first).toHaveAttribute("aria-expanded", "true");
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
fireEvent.pointerLeave(first, { pointerType: "touch" });
expect(details).toBeVisible();
await tap(second);
await waitFor(() => expect(within(sheet).getAllByRole("dialog")).toHaveLength(1));
expect(within(sheet).getByRole("dialog")).toHaveTextContent("14,000");
expect(within(sheet).getByRole("dialog")).toHaveTextContent("280");
expect(first).toHaveAttribute("aria-expanded", "false");
expect(second).toHaveAttribute("aria-expanded", "true");
await tap(second);
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
expect(sheet).toBeVisible();
await tap(first);
await tap(within(sheet).getByRole("heading", { name: "Context usage" }));
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
expect(sheet).toBeVisible();
});
it("dismisses nested round details with Escape before the sheet, and supports dragging with details open", async () => {
const { user, sheet, handle, trigger } = await openSheet();
const first = within(sheet).getAllByTestId("round-usage-bar")[0];
first.focus();
await user.keyboard("{Enter}");
expect(within(sheet).getByRole("dialog")).toBeVisible();
it("mounts in the conversation's side slot and closes with Escape from its controls", async () => {
const user = userEvent.setup();
const host = document.createElement("section");
Object.defineProperty(host, "clientWidth", { value: 900 });
document.body.append(host);
const view = render(<ComposerUsagePopover sidebarHost={host} context={null} rounds={[]} snapshots={[first]} />);
await user.click(screen.getByTestId("composer-context-usage"));
const sidebar = within(host).getByRole("complementary");
act(() => within(sidebar).getByRole("button", { name: "Expand context panel" }).focus());
await user.keyboard("{Escape}");
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
expect(sheet).toBeVisible();
expect(first).toHaveFocus();
await user.click(first);
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y: 520, time: 1400 });
pointer(handle, "pointerUp", { y: 520, time: 1500 });
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
expect(trigger).toHaveFocus();
await waitFor(() => expect(screen.getByTestId("composer-context-usage")).toHaveFocus());
expect(screen.getByTestId("composer-context-usage")).toHaveAttribute("aria-expanded", "false");
view.unmount(); host.remove();
});
it("keeps the open sidebar and playback when its trigger moves between responsive slots", async () => {
const user = userEvent.setup();
const toolbar = document.createElement("span");
const footer = document.createElement("span");
document.body.append(toolbar, footer);
const content = (host: HTMLElement) => <ComposerUsagePopover triggerHost={host} context={null} rounds={[]}
snapshots={[first, { ...first, id: "2", usage: { prompt_tokens: 2000 } }]} />;
const view = render(content(toolbar));
await user.click(within(toolbar).getByTestId("composer-context-usage"));
const sidebar = screen.getByRole("complementary");
await user.click(within(sidebar).getByRole("button", { name: "Play context history" }));
view.rerender(content(footer));
expect(screen.getByRole("complementary")).toBe(sidebar);
expect(within(sidebar).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "10");
expect(within(footer).getByTestId("composer-context-usage")).toHaveAttribute("aria-expanded", "true");
await user.click(within(footer).getByTestId("composer-context-usage"));
expect(screen.getByRole("complementary")).toBe(sidebar);
expect(sidebar.style.getPropertyValue("--file-preview-slot-width")).toBe("0px");
// Reopening during exit retains the graph instead of remounting it.
await user.click(within(footer).getByTestId("composer-context-usage"));
expect(screen.getByRole("complementary")).toBe(sidebar);
await user.click(within(footer).getByTestId("composer-context-usage"));
await waitFor(() => expect(screen.queryByRole("complementary")).not.toBeInTheDocument());
view.unmount(); toolbar.remove(); footer.remove();
});
it.each([
[100, 500],
[32, 40],
])("dismisses after dragging %dpx in %dms and opens at the original position", async (distance, duration) => {
const { user, handle, sheet, trigger } = await openSheet();
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y: 400 + distance, time: 1000 + duration });
// happy-dom doesn't expose individual transforms through getComputedStyle.
expect(sheet.style.translate).toBe(`0 ${distance}px`);
expect(sheet).toHaveStyle({ transition: "none" });
pointer(handle, "pointerUp", { y: 400 + distance, time: 1000 + duration });
it("opens a pane-contained drawer with a visible close control on narrow panes", async () => {
const user = userEvent.setup();
const host = document.createElement("section");
Object.defineProperty(host, "clientWidth", { value: 600 });
document.body.append(host);
const view = render(<ComposerUsagePopover sidebarHost={host} context={null} rounds={[]} snapshots={[first]} />);
await user.click(screen.getByTestId("composer-context-usage"));
const drawer = within(host).getByRole("dialog", { name: "Context usage" });
await user.click(within(drawer).getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
expect(trigger).toHaveFocus();
await user.click(trigger);
expect(screen.getByRole("dialog").style.translate).toBe("0 0px");
expect(screen.getByTestId("composer-context-usage")).toHaveFocus();
view.unmount(); host.remove();
});
it.each([
{ end: "pointerUp" as const, y: 432, x: 160 },
{ end: "pointerUp" as const, y: 370, x: 160 },
{ end: "pointerUp" as const, y: 460, x: 260 },
{ end: "pointerCancel" as const, y: 500, x: 160 },
{ end: "lostPointerCapture" as const, y: 500, x: 160 },
])("snaps back without a click-through on $end at ($x, $y)", async ({ end, y, x }) => {
const { user, handle, sheet } = await openSheet();
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y, x, time: 1400 });
pointer(handle, end, { y, x, time: 1500 });
expect(sheet.style.translate).toBe("0 0px");
expect(sheet.style.transition).toBe("");
fireEvent.click(handle, { detail: 1 });
expect(screen.getByRole("dialog")).toBeVisible();
await user.click(handle);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
});
it("does not capture content scrolling or let another pointer finish the drag", async () => {
const { user, handle, sheet } = await openSheet();
const content = within(sheet).getByRole("group", { name: "Input tokens" });
pointer(content, "pointerDown", { y: 480 });
pointer(content, "pointerMove", { y: 580 });
pointer(content, "pointerUp", { y: 580, time: 1500 });
expect(sheet.style.translate).toBe("0 0px");
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y: 412 });
pointer(handle, "pointerDown", { y: 412, id: 2 });
pointer(handle, "pointerUp", { y: 600, id: 2 });
expect(sheet.style.translate).toBe("0 12px");
pointer(handle, "pointerUp", { y: 412, time: 1500 });
expect(sheet.style.translate).toBe("0 0px");
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
});
@@ -0,0 +1,11 @@
import { expect, it, vi } from "vitest";
import { fitGraphLabel } from "@/components/thread/graph-canvas";
it("fits long Unicode labels with bounded measurements and complete code points", () => {
const name = "😀".repeat(255);
const measure = vi.fn((text: string) => Array.from(text).length);
const fitted = fitGraphLabel(name, measure);
expect(fitted).toBe(`${"😀".repeat(127)}…`);
expect(measure.mock.calls.length).toBeLessThanOrEqual(10);
expect(fitGraphLabel("a.md", measure)).toBe("a.md");
});
@@ -0,0 +1,119 @@
import { describe, expect, it } from "vitest";
import { createGraphSimulation, updateGraphSimulation, advanceGraphSimulation, startGraphSettlement } from "@/lib/context-graph-layout";
import { createGraphPresentation } from "@/components/thread/graph-presentation";
import type { ContextGraph } from "@/lib/types";
const first: ContextGraph = { nodes: [{ path: "a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [] };
const next: ContextGraph = { nodes: [...first.nodes, { path: "b.md", name: "b.md", state: "discovered", tokens: 0 }],
edges: [{ source: "a.md", target: "b.md" }] };
describe("context graph continuity", () => {
it("reintroduces a loaded filename when fast replay reverses its unfinished exit", () => {
const presentation = createGraphPresentation();
const loaded: ContextGraph = { nodes: [{ path: "loop.py", name: "loop.py", state: "loaded", tokens: 200 }], edges: [] };
presentation.update(loaded, null);
presentation.advance(2000, true);
presentation.update({ nodes: [], edges: [] }, null);
presentation.advance(200, false);
const exiting = presentation.frame.nodes[0];
expect(exiting.presence).toBeGreaterThan(0);
expect(exiting.labelRemaining).toBe(0);
presentation.update(loaded, null);
expect(presentation.frame.nodes[0]).toBe(exiting);
expect(exiting.labelRemaining).toBe(1600);
presentation.advance(300, false);
presentation.update(loaded, "loop.py");
expect(exiting.labelRemaining).toBe(1300);
});
it("briefly introduces new labels without restarting existing labels on graph or focus updates", () => {
const presentation = createGraphPresentation();
presentation.update(first, null);
presentation.advance(1000, false);
expect(presentation.frame.nodes[0].labelRemaining).toBe(600);
presentation.update(next, "a.md");
presentation.advance(300, false);
expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([300, 0]);
const loaded: ContextGraph = { ...next, nodes: next.nodes.map((node) => ({ ...node, state: "loaded" })) };
presentation.update(loaded, null);
presentation.advance(300, false);
expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([0, 1300]);
presentation.update(loaded, "b.md");
presentation.advance(300, false);
expect(presentation.frame.nodes[1].labelRemaining).toBe(1000);
// Replaying an earlier, unloaded state ends the automatic label reveal.
presentation.update(next, null);
expect(presentation.advance(0, true).moving).toBe(false);
expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([0, 0]);
});
it("retains existing particles and grows a linked node near its neighbour", () => {
const sim = createGraphSimulation(first, new Map(), 600, 300).stop();
const original = sim.nodes()[0];
original.x = 100; original.y = 100; original.vx = 2;
updateGraphSimulation(sim, next, new Map(), 600, 300);
expect(sim.nodes()[0]).toBe(original);
expect(original.vx).toBe(2);
expect(Math.hypot(sim.nodes()[1].x - 100, sim.nodes()[1].y - 100)).toBeLessThan(20);
const cache = new Map(sim.nodes().map((node) => [node.path, { x: node.x, y: node.y }]));
updateGraphSimulation(sim, first, cache, 600, 300);
updateGraphSimulation(sim, next, cache, 600, 300);
expect(sim.nodes()[1].x).toBe(cache.get("b.md")!.x);
expect(sim.nodes()[1].y).toBe(cache.get("b.md")!.y);
sim.stop();
});
it("settles reduced motion in slices to the same finite layout", () => {
const previous = new Map([["a.md", { x: 50, y: 80 }], ["b.md", { x: 150, y: 130 }]]);
const reference = createGraphSimulation(next, previous, 600, 300).stop();
const sliced = createGraphSimulation(next, previous, 600, 300).stop();
reference.alpha(1).alphaTarget(0).tick(300);
const advance = startGraphSettlement(sliced);
expect(advance(0)).toBe(false);
let slices = 1;
while (!advance(0)) slices++;
expect(slices).toBe(299);
expect(sliced.nodes().map(({ x, y }) => ({ x, y }))).toEqual(reference.nodes().map(({ x, y }) => ({ x, y })));
expect(sliced.nodes().every((node) => node.vx === 0 && node.vy === 0)).toBe(true);
expect(sliced.alpha()).toBe(0);
});
it("reaches the same layout at slow and fast paint rates without stretching physical time", () => {
const previous = new Map([["a.md", { x: 50, y: 80 }], ["b.md", { x: 150, y: 130 }]]);
const simulate = (frameMs: number) => {
const sim = createGraphSimulation(next, previous, 600, 300).stop();
let elapsed = 0;
while (sim.alpha() > sim.alphaMin()) {
advanceGraphSimulation(sim, frameMs, Infinity);
elapsed += frameMs;
}
return { elapsed, positions: sim.nodes().map(({ x, y }) => ({ x, y })) };
};
const fast = simulate(1000 / 60), slow = simulate(50);
expect(slow.positions).toEqual(fast.positions);
expect(Math.abs(slow.elapsed - fast.elapsed)).toBeLessThan(51);
// A constrained frame still makes progress, rather than queuing an unbounded catch-up.
const bounded = createGraphSimulation(next, previous, 600, 300).stop();
const reference = createGraphSimulation(next, previous, 600, 300).stop().tick();
advanceGraphSimulation(bounded, 10_000, 0);
expect(bounded.nodes().map(({ x, y }) => ({ x, y }))).toEqual(reference.nodes().map(({ x, y }) => ({ x, y })));
});
it("reverses an in-flight exit from its current opacity when a graph returns", () => {
const presentation = createGraphPresentation();
presentation.update(next, null);
for (let index = 0; index < 20; index++) presentation.advance(1000 / 60, false);
const node = () => presentation.frame.nodes.find((item) => item.path === "b.md")!;
expect(node().presence).toBeGreaterThan(0.7);
presentation.update(first, null);
for (let index = 0; index < 8; index++) presentation.advance(1000 / 60, false);
const fading = node().presence;
expect(fading).toBeGreaterThan(0);
expect(fading).toBeLessThan(0.5);
presentation.update(next, null);
expect(node().presence).toBe(fading);
for (let index = 0; index < 20; index++) presentation.advance(1000 / 60, false);
expect(node().presence).toBeGreaterThan(0.9);
expect(presentation.frame.edges).toHaveLength(1);
});
});
@@ -0,0 +1,70 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { ContextInspector } from "@/components/thread/ContextInspector";
import type { ContextSnapshot } from "@/lib/types";
const snapshots: ContextSnapshot[] = [
{ id: "first", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 }, graph: {
nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [],
} },
{ id: "second", contextWindowTokens: 10000, usage: { prompt_tokens: 2000, cached_tokens: 800 }, graph: {
nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }, { path: "/b.md", name: "b.md", state: "discovered", tokens: 0 }],
edges: [{ source: "/a.md", target: "/b.md" }],
} },
];
describe("Context inspector", () => {
it("exposes every graph node as a named keyboard control", async () => {
const user = userEvent.setup();
render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
const node = await screen.findByRole("button", { name: "a.md" });
expect(screen.getByRole("button", { name: "b.md" })).toBeInTheDocument();
act(() => node.focus());
await user.keyboard("{Enter}");
expect(await screen.findByText("About 100 tokens")).toBeVisible();
expect(node).toHaveFocus();
});
it("opens the selected file through the supplied preview action without loading its context", async () => {
const open = vi.fn();
const user = userEvent.setup();
render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} onOpenFile={open} />);
const node = await screen.findByRole("button", { name: "a.md" });
await user.hover(node);
expect(screen.queryByText("About 100 tokens")).not.toBeInTheDocument();
await user.click(node);
expect(await screen.findByText("About 100 tokens")).toBeVisible();
expect(open).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Open file" }));
expect(open).toHaveBeenCalledWith("/a.md");
expect(snapshots[1].graph.nodes[1].state).toBe("discovered");
});
});
it("stops playback at compaction and shows the new baseline", async () => {
const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
fireEvent.click(screen.getByRole("button", { name: "Play context history" }));
const compacted: ContextSnapshot = { id: "compacted", graph: { nodes: [{ path: "/system.md", name: "system.md", state: "loaded", tokens: 300 }], edges: [] },
estimatedTokens: 1500, contextWindowTokens: 10000 };
rerender(<ContextInspector context={null} rounds={[]} snapshots={[compacted]} />);
expect(screen.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "15");
expect(screen.getByText("≈15%")).toBeVisible();
await waitFor(() => expect(screen.queryByRole("button", { name: "a.md" })).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "system.md" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();
});
it("shows token usage from the displayed snapshot, including estimates without cache data", () => {
const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
const meter = screen.getByRole("progressbar").parentElement!.parentElement!;
fireEvent.pointerEnter(meter);
expect(screen.getByText("2k / 10k")).toBeVisible();
expect(screen.getByText("40%")).toBeVisible();
rerender(<ContextInspector context={null} rounds={[]} snapshots={[{
id: "compacted", estimatedTokens: 1500, contextWindowTokens: 10000, graph: { nodes: [], edges: [] },
}]} />);
expect(screen.getByText("≈1.5k / 10k")).toBeVisible();
});
+62
View File
@@ -0,0 +1,62 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { ContextInspector } from "@/components/thread/ContextInspector";
import type { ContextGraph, ContextSnapshot } from "@/lib/types";
// Painting is explicit here so slow rendering can be exercised without a canvas.
vi.mock("@/components/thread/ContextGraphScene", () => ({
ContextGraphScene: ({ graph, onReady }: { graph: ContextGraph; onReady: (graph: ContextGraph) => void }) =>
<button onClick={() => onReady(graph)}>Paint snapshot</button>,
}));
afterEach(() => vi.useRealTimers());
async function start(count: number) {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
const snapshots: ContextSnapshot[] = Array.from({ length: count }, (_, index) => ({
id: String(index), contextWindowTokens: 10000,
usage: { prompt_tokens: (index + 1) * 100 }, graph: { nodes: [], edges: [] },
}));
await act(async () => {
render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
await vi.dynamicImportSettled();
});
const play = screen.getByRole("button", { name: "Play context history" });
fireEvent.click(play);
return play;
}
const paint = () => fireEvent.click(screen.getByRole("button", { name: "Paint snapshot" }));
const progress = () => screen.getByRole("progressbar").getAttribute("aria-valuenow");
it("replays short histories at five steps per second and can restart", async () => {
const play = await start(2);
expect(play).toBeDisabled();
expect(progress()).toBe("1");
paint();
act(() => vi.advanceTimersByTime(200));
expect(progress()).toBe("2");
paint();
act(() => vi.advanceTimersByTime(200));
expect(play).toBeEnabled();
fireEvent.click(play);
expect(progress()).toBe("1");
});
it("speeds up longer histories without dropping unpainted snapshots", async () => {
await start(400);
// A delayed first paint does not skip intermediate request states.
act(() => vi.advanceTimersByTime(350));
expect(progress()).toBe("1");
paint();
act(() => vi.advanceTimersByTime(1));
expect(progress()).toBe("2");
paint();
act(() => vi.advanceTimersByTime(1));
expect(progress()).toBe("3");
paint();
act(() => vi.advanceTimersByTime(1));
expect(progress()).toBe("4");
paint();
// The fourth deadline remains at 400ms, not 100ms after its late paint.
act(() => vi.advanceTimersByTime(47));
expect(progress()).toBe("5");
});
+61
View File
@@ -0,0 +1,61 @@
import { act, createEvent, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
const originalAnimate = Object.getOwnPropertyDescriptor(Element.prototype, "animate");
let finish: (() => void) | null = null;
beforeEach(() => {
// happy-dom has no WAAPI timeline; explicitly finish the browser-owned settlement.
Object.defineProperty(Element.prototype, "animate", { configurable: true, value: () => ({
cancel: vi.fn(),
set onfinish(callback: () => void) { finish = callback; },
}) });
});
afterEach(() => {
if (originalAnimate) Object.defineProperty(Element.prototype, "animate", originalAnimate);
else Reflect.deleteProperty(Element.prototype, "animate");
finish = null;
});
function pointer(target: HTMLElement, type: "pointerDown" | "pointerMove" | "pointerUp" | "pointerCancel" | "lostPointerCapture", y: number, id = 1) {
fireEvent(target, createEvent[type](target, { pointerId: id, pointerType: "touch", isPrimary: id === 1, button: 0, clientY: y }));
}
function openDrawer() {
render(<Dialog><DialogTrigger>Open drawer</DialogTrigger><DialogContent placement="bottom" aria-describedby={undefined}>
<DialogTitle>Details</DialogTitle>
</DialogContent></Dialog>);
fireEvent.click(screen.getByRole("button", { name: "Open drawer" }));
const drawer = screen.getByRole("dialog");
Object.defineProperty(drawer, "offsetHeight", { configurable: true, value: 500 });
return { drawer, handle: screen.getByRole("button", { name: "Close" }) };
}
describe("shared bottom dialog drag", () => {
it.each(["pointerUp", "pointerCancel", "lostPointerCapture"] as const)("rebounds without click-through after %s", (end) => {
const { drawer, handle } = openDrawer();
pointer(handle, "pointerDown", 100);
pointer(handle, "pointerMove", end === "pointerUp" ? 115 : 260);
pointer(handle, end, end === "pointerUp" ? 115 : 260);
fireEvent.click(handle, { detail: 1 });
expect(screen.getByRole("dialog")).toBe(drawer);
act(() => finish?.());
expect(drawer.style.translate).toBe("0 0px");
expect(screen.getByRole("dialog")).toBe(drawer);
fireEvent.click(handle);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("ignores another touch ending over the handle while the first touch drags", () => {
const { drawer, handle } = openDrawer();
pointer(handle, "pointerDown", 100);
pointer(handle, "pointerMove", 115);
pointer(handle, "pointerDown", 115, 2);
pointer(handle, "pointerUp", 200, 2);
expect(finish).toBeNull();
pointer(handle, "pointerMove", 120);
expect(drawer.style.translate).toBe("0 20px");
pointer(handle, "pointerCancel", 120);
act(() => finish?.());
expect(drawer.style.translate).toBe("0 0px");
});
});
+4 -3
View File
@@ -227,7 +227,7 @@ describe("FilePreviewPanel", () => {
await setAppLanguage("zh-CN");
});
expect(screen.getByRole("button", { name: "预览" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("heading", { name: "Notes" })).toBeVisible();
expect(screen.getByRole("button", { name: "原文" })).toBeInTheDocument();
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
});
@@ -246,7 +246,7 @@ describe("FilePreviewPanel", () => {
source.focus();
fireEvent.click(source);
expect(source).toHaveFocus();
expect(source).toHaveAttribute("aria-pressed", "true");
expect(source).toHaveAccessibleName("Preview");
expect(screen.getByTestId("mock-code-block").textContent).toBe(content);
expect(CodeBlock).toHaveBeenLastCalledWith(expect.objectContaining({
code: content, chrome: "none", showLineNumbers: true, wrapLongLines: false, viewportHighlight: true,
@@ -267,7 +267,8 @@ describe("FilePreviewPanel", () => {
await screen.findByRole("heading", { name: "Notes" });
fireEvent.click(screen.getByRole("button", { name: "Source" }));
rerender(view("notes.md", "a", "new"));
expect(screen.getByRole("button", { name: "Source" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("button", { name: "Preview" })).toBeVisible();
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("# Notes");
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
rerender(view("other.md"));
await screen.findByRole("heading", { name: "Notes" });
@@ -43,7 +43,7 @@ describe("shared latest thread requests", () => {
const surviving = fetchLatestWebuiThread(client, "token", KEY);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
"/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1",
"/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({ headers: { Authorization: "Bearer token", "If-None-Match": '"cached"' } }),
);
const rejected = expect(first).rejects.toMatchObject({ name: "AbortError" });
@@ -742,9 +742,9 @@ describe("MarkdownTextRenderer", () => {
expect(table).toHaveTextContent("nanobot");
expect(table).toHaveClass(
"[&_th]:whitespace-normal",
"[&_th]:[overflow-wrap:anywhere]",
"[&_th]:[overflow-wrap:normal]",
"[&_td]:whitespace-normal",
"[&_td]:[overflow-wrap:anywhere]",
"[&_td]:[overflow-wrap:normal]",
);
expect(container.firstElementChild).toHaveClass("space-y-4");
expect(container.firstElementChild).not.toHaveClass("space-y-0");
+2 -2
View File
@@ -372,7 +372,7 @@ describe("MessageBubble", () => {
rerender(<MessageBubble message={message} />);
expect(bubble).not.toHaveClass("border-dashed");
expect(bubble).toHaveClass("bg-secondary/70");
expect(bubble).toHaveClass("user-message-surface", "bg-secondary/70");
});
it("renders completed message branches with static wrapper classes", async () => {
@@ -538,7 +538,7 @@ describe("MessageBubble", () => {
expect(command.firstElementChild).toHaveClass("opacity-90");
expect(command.className).not.toMatch(/(?:^|\s)(?:bg-|border|ring|rounded)/);
expect(command.parentElement).toHaveTextContent("/model gpt-5");
expect(command.parentElement).toHaveClass("rounded-floating", "bg-secondary/70");
expect(command.parentElement).toHaveClass("rounded-floating", "user-message-surface", "bg-secondary/70");
});
it("keeps unknown and invalid slash commands as plain message text", () => {
+57 -3
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { parseWebuiThreadPayload } from "@/lib/api";
import { composerContextSnapshots } from "@/lib/context-graph";
import { composerUsageSnapshots } from "@/lib/model-request";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadTranscript } from "@/lib/thread-transcript";
@@ -18,6 +19,20 @@ function project(transcript: ThreadTranscript, event: ThreadProjectionEvent, per
}
describe("model request snapshots", () => {
it("replays each request's matching file graph and usage after reload", () => {
const transcript = new ThreadTranscript();
const first = { nodes: [{ path: "/a.md", name: "a.md", state: "loaded" as const, tokens: 100 }], edges: [] };
const second = { nodes: [...first.nodes, { path: "/b.md", name: "b.md", state: "discovered" as const, tokens: 0 }], edges: [{ source: "/a.md", target: "/b.md" }] };
for (const event of [
request(1, { request_id: "first", context_graph: first }),
request(2, { request_id: "first", phase: "completed", context_graph: first, round_usages: rounds(1) }),
request(3, { request_id: "second", context_graph: second }),
request(4, { request_id: "second", phase: "completed", context_graph: second, round_usages: rounds(2) }),
]) project(transcript, event, true);
expect(transcript.modelRequests.get("turn")?.contextSnapshots?.map((snapshot) => ({
graph: snapshot.graph, tokens: snapshot.usage?.prompt_tokens,
}))).toEqual([{ graph: first, tokens: 100 }, { graph: second, tokens: 101 }]);
});
it("validates request identity, phase, sequence, and usage at the history boundary", () => {
for (const invalid of [{ phase: "unknown" }, { sequence: -1 }, { run_id: null }, { usage: { context_tokens: "123" } }]) {
expect(() => parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...request(1), ...invalid }] })).toThrow();
@@ -60,10 +75,10 @@ describe("model request snapshots", () => {
expect(latest().compacted).toBe(false);
send({ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 3 });
expect(latest().compacted).toBe(true);
expect(latest().roundUsages).toEqual(rounds(1));
expect(latest().roundUsages).toBeUndefined();
send(request(4, { usage: usage(1), round_usages: rounds(1) }));
expect(latest().compacted).toBe(true);
expect(latest().roundUsages).toEqual(rounds(1));
expect(latest().roundUsages).toBeUndefined();
expect(projectWebuiThreadMessages(transcript.messages).map((row) => row.kind)).toEqual(["compaction"]);
const smaller = { ...usage(2), context_tokens: 50 };
send(request(5, { request_id: "request-4", phase: "completed", usage: smaller, round_usages: rounds(2) }));
@@ -86,7 +101,7 @@ describe("model request snapshots", () => {
] as ThreadProjectionEvent[]) project(transcript, event, persisted);
const snapshot = composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)!;
expect(snapshot.compacted).toBe(true);
expect(snapshot.roundUsages).toEqual(rounds(1));
expect(snapshot.roundUsages).toBeUndefined();
});
it("preserves legacy compaction invalidation and historical rounds without request events", () => {
@@ -203,3 +218,42 @@ describe("model request snapshots", () => {
expect(snapshot.roundUsages?.[0].prompt_tokens).toBe(102);
});
});
it.each([false, true])("starts a new graph history and estimated meter at compaction (persisted=%s)", (persisted) => {
const transcript = new ThreadTranscript();
const oldGraph = { nodes: [{ path: "/read.md", name: "read.md", state: "loaded" as const, tokens: 300 }], edges: [] };
const systemGraph = { nodes: [{ path: "/SOUL.md", name: "SOUL.md", state: "loaded" as const, tokens: 40 }], edges: [] };
project(transcript, request(1, { context_graph: oldGraph, phase: "completed", usage: usage(1) }), persisted);
const event = parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...envelope, event: "context_compaction", compaction_id: "boundary",
phase: "succeeded", turn_seq: 2, context_snapshot: { graph: systemGraph, estimated_tokens: 1200, context_window_tokens: 10000 } }] }).events[0];
expect(event).not.toBeNull();
if (!event) throw new Error("Compaction snapshot rejected");
project(transcript, event, persisted);
expect(composerContextSnapshots(transcript.messages, transcript.modelRequests)).toEqual([
{ id: "compaction-boundary", graph: systemGraph, estimatedTokens: 1200, contextWindowTokens: 10000 },
]);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({
compacted: true, estimatedContextTokens: 1200, contextWindowTokens: 10000,
});
const reloadedRequests = new Map(transcript.modelRequests);
reloadedRequests.set("older-turn", {
...transcript.modelRequests.get("turn")!, createdAt: 0,
contextSnapshots: [{ id: "older-request", graph: oldGraph, turnSeq: 1 }],
});
expect(composerContextSnapshots(transcript.messages, reloadedRequests).map((s) => s.id))
.toEqual(["compaction-boundary"]);
project(transcript, request(3, { context_graph: systemGraph, phase: "completed", usage: { context_tokens: 1300, request_count: 2 } }), persisted);
expect(composerContextSnapshots(transcript.messages, transcript.modelRequests).map((s) => s.id)).toEqual(["compaction-boundary", "request-3"]);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({ compacted: false, usage: { context_tokens: 1300 } });
});
it.each(["failed", "cancelled", "completed"] as const)("does not borrow previous usage for a %s request without measurement", (phase) => {
const transcript = new ThreadTranscript();
const graph = { nodes: [{ path: "/a.md", name: "a.md", state: "loaded" as const, tokens: 20 }], edges: [] };
project(transcript, request(1, { phase: "completed", context_graph: graph, request_usage: usage(1), round_usages: rounds(1) }));
project(transcript, request(2, { phase, context_graph: graph, request_usage: null, round_usages: rounds(1) }));
const frames = composerContextSnapshots(transcript.messages, transcript.modelRequests);
expect(frames[0].usage).toEqual(usage(1));
expect(frames[1].usage).toBeUndefined();
});
+16 -1
View File
@@ -1,4 +1,4 @@
import { render, screen, waitFor } from "@testing-library/react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
@@ -12,6 +12,21 @@ beforeEach(() => {
afterEach(() => restoreBrowserFocus());
it("opens Ctrl+F only in the active pane and selects a filtered message with Enter", async () => {
const user = userEvent.setup();
const jump = vi.fn();
const props = { messages: [{ id: "one", role: "user" as const, content: "alpha", createdAt: 1 }], onJumpToPrompt: jump };
const view = render(<PromptNavigator {...props} shortcutEnabled={false} />);
fireEvent.keyDown(window, { key: "f", ctrlKey: true });
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
view.rerender(<PromptNavigator {...props} shortcutEnabled />);
fireEvent.keyDown(window, { key: "f", ctrlKey: true });
const input = await screen.findByRole("textbox", { name: "Search messages" });
await waitFor(() => expect(input).toHaveFocus());
await user.keyboard("alpha{Enter}");
expect(jump).toHaveBeenCalledWith("one");
});
it("keeps a long searchable index windowed and keyboard-reachable", async () => {
const user = userEvent.setup();
const jump = vi.fn();
+49
View File
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { activateReloadCache, clearReloadCache, readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
import { parseWebuiThreadPayload } from "@/lib/api";
import { WebuiThreadCache } from "@/lib/webui-thread-cache";
import { canonicalThreadPayload } from "./thread-test-payload";
@@ -19,6 +20,54 @@ describe("tab reload cache", () => {
expect(new WebuiThreadCache().get("websocket:b")).toBeUndefined();
});
it.each(["inline", "references"])("restores all 50 growing graph frames from compact tab storage (%s)", (format) => {
activateReloadCache("ws://localhost:8765/?token=first");
const nodes = Array.from({ length: 300 }, (_, index) => ({
path: `/workspace/${index}.md`, name: `${index}.md`, tokens: 256, state: "loaded",
}));
const edges = nodes.flatMap((node, source) => [1, 2, 3].flatMap((offset) => source + offset < nodes.length
? [{ source: node.path, target: nodes[source + offset].path }] : []));
const graphs = Array.from({ length: 50 }, (_, index) => {
const count = 251 + index;
const paths = new Set(nodes.slice(0, count).map((node) => node.path));
return { nodes: nodes.slice(0, count), edges: edges.filter((edge) => paths.has(edge.source) && paths.has(edge.target)) };
});
const table = Object.fromEntries(graphs.map((graph, index) => [String(index), {
nodes: graph.nodes.map((node) => nodes.indexOf(node)), edges: graph.edges.map((edge) => edges.indexOf(edge)),
}]));
const events = graphs.map((graph, index) => ({
event: "model_request", chat_id: "growing", request_id: String(index), run_id: "run", sequence: index + 1,
phase: "completed", request_usage: { context_tokens: 10000 + index },
...(format === "inline" ? { context_graph: structuredClone(graph) } : { context_graph_ref: String(index) }),
}));
const body = parseWebuiThreadPayload({ schemaVersion: 3, sessionKey: "websocket:growing", revision: "growing-50",
projection: "events", active_turn_id: null, page: { before_cursor: "older", has_more_before: true },
events: [{ event: "context_compaction", chat_id: "growing", compaction_id: "checkpoint", phase: "succeeded",
context_snapshot: { estimated_tokens: 100, context_window_tokens: 100000,
...(format === "inline" ? { graph: structuredClone(graphs[0]) } : { graph_ref: "0" }) } }, ...events],
...(format === "references" ? { context_graphs: table, context_graph_nodes: nodes, context_graph_edges: edges } : {}),
});
const cache = new WebuiThreadCache();
cache.set("websocket:growing", body);
expect(cache.get("websocket:growing")).toBe(body);
const raw = sessionStorage.getItem("nanobot.reload.v1.thread");
expect(raw).not.toBeNull();
expect(raw!.length).toBeLessThanOrEqual(512 * 1024);
const restored = new WebuiThreadCache().get("websocket:growing");
expect(restored).toEqual(body);
expect(restored).not.toHaveProperty("context_graphs");
expect(restored).not.toHaveProperty("context_graph_nodes");
expect(restored).not.toHaveProperty("context_graph_edges");
const frames = restored!.events.filter((event) => event.event === "model_request");
expect(frames).toHaveLength(50);
for (let index = 0; index < frames.length; index += 1) {
expect(frames[index].context_graph).toEqual(graphs[index]);
expect(frames[index].request_usage?.context_tokens).toBe(10000 + index);
}
expect(frames[0].context_graph?.nodes[0]).toBe(frames[49].context_graph?.nodes[0]);
expect(frames[0].context_graph?.edges[0]).toBe(frames[49].context_graph?.edges[0]);
});
it("does not restore another gateway's data or data after logout", () => {
activateReloadCache("ws://localhost:8765/");
new WebuiThreadCache().set("websocket:a", thread);
@@ -26,8 +26,7 @@ async function loadView(fail = false) {
await initializeI18n();
await loadAllLocaleResources();
const { SessionInfoPopoverView } = await import("@/components/thread/SessionInfoPopoverView");
render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView
title="Release work" jobs={[job]} loading={false} loadFailed={false} now={Date.now()}
render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView jobs={[job]} loading={false} loadFailed={false} now={Date.now()}
onAction={async () => []} onEdit={async () => [job]}
/></>);
return loaded;
+3 -12
View File
@@ -58,7 +58,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -93,7 +92,7 @@ describe("SessionInfoPopover", () => {
let finish!: (response: Response) => void;
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const user = userEvent.setup();
const view = render(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" title="Release work" />);
const view = render(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" />);
await user.click(screen.getByRole("button", { name: "Session details" }));
expect(screen.getByRole("status", { name: "Loading automations..." })).toHaveAttribute("aria-busy", "true");
await act(async () => finish(automationsResponse([automationJob()])));
@@ -107,7 +106,7 @@ describe("SessionInfoPopover", () => {
await act(async () => fail(new Error("Refresh failed")));
expect(screen.getByRole("button", { name: /Morning check/ })).toBeVisible();
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
view.rerender(<SessionInfoPopover client={client} sessionKey="websocket:chat-2" token="tok" title="Other project" />);
view.rerender(<SessionInfoPopover client={client} sessionKey="websocket:chat-2" token="tok" />);
expect(screen.queryByRole("button", { name: /Morning check/ })).not.toBeInTheDocument();
expect(screen.getByRole("status", { name: "Loading automations..." })).toBeVisible();
await act(async () => finish(automationsResponse([])));
@@ -128,7 +127,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -165,7 +163,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -189,14 +186,12 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="@hyperframes 使用指南"
/>,
);
await user.click(screen.getByRole("button", { name: "会话详情" }));
expect(await screen.findByText("会话")).toBeInTheDocument();
expect(screen.getByText("自动任务")).toBeInTheDocument();
expect(await screen.findByText("自动任务")).toBeInTheDocument();
expect(screen.getByText("Morning check")).toBeInTheDocument();
expect(screen.getByText(/下次/)).toBeInTheDocument();
expect(screen.queryByText("Session")).not.toBeInTheDocument();
@@ -217,7 +212,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -255,7 +249,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -284,7 +277,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -314,7 +306,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
+54 -128
View File
@@ -672,130 +672,54 @@ describe("ThreadComposer", () => {
fireEvent.focus(context);
const tooltip = await screen.findByRole("tooltip");
expect(tooltip).toHaveTextContent("Context 7%");
expect(tooltip.parentElement).toHaveClass("rounded-full", "px-2.5", "py-1");
expect(tooltip.parentElement).not.toHaveTextContent("Available");
});
it("opens an input-token chart with one bar for each logical round", () => {
render(
<ThreadComposer
onSend={vi.fn()}
modelLabel="gpt-5.6-sol"
modelPreset="gpt-5-6-sol"
modelProvider="openai_codex"
contextUsage={{
contextTokens: 14_700,
contextWindowTokens: 200_000,
}}
recentRoundUsage={[
{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 3, 7, 20),
inputTokens: 18_000,
outputTokens: 280,
cachedTokens: 12_000,
generationMs: 12_000,
},
{
id: "turn-2",
timestamp: Date.UTC(2026, 8, 3, 8, 22),
inputTokens: 29_400,
outputTokens: 416,
cachedTokens: 26_180,
generationMs: 40_000,
},
]}
placeholder="Ask anything..."
/>,
);
it("opens the current graph and replays its request snapshots from the beginning", async () => {
// Happy DOM has no canvas renderer; supply the operations used by graph paint
// so replay can receive the same painted-frame acknowledgement as a browser.
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
setTransform: vi.fn(), clearRect: vi.fn(), setLineDash: vi.fn(), beginPath: vi.fn(),
moveTo: vi.fn(), lineTo: vi.fn(), stroke: vi.fn(), arc: vi.fn(), fill: vi.fn(),
roundRect: vi.fn(), fillText: vi.fn(), measureText: (text: string) => ({ width: text.length * 6 }),
} as unknown as CanvasRenderingContext2D);
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 200, contextWindowTokens: 1000 }}
contextSnapshots={[
{ id: "first", contextWindowTokens: 1000, usage: { prompt_tokens: 100 }, graph: { nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 40 }], edges: [] } },
{ id: "second", contextWindowTokens: 1000, usage: { prompt_tokens: 200 }, graph: { nodes: [{ path: "/b.md", name: "b.md", state: "loaded", tokens: 60 }], edges: [] } },
]} />);
fireEvent.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByText("Context")).toBeInTheDocument();
expect(screen.getByText("14.7K / 200K")).toBeInTheDocument();
expect(screen.getByText("Recent rounds")).toBeInTheDocument();
expect(screen.getByText("Input tokens")).toBeInTheDocument();
expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(2);
const [smallerBar, largerBar] = screen.getAllByTestId("round-usage-bar");
expect(
Number.parseFloat(smallerBar.style.height) / Number.parseFloat(largerBar.style.height),
).toBeCloseTo(18_000 / 29_400, 5);
expect(largerBar.querySelector(".kv-cache-reused")).toBeInTheDocument();
expect(largerBar.querySelector(".kv-cache-not-reused")).toBeInTheDocument();
expect(screen.queryByText("Reused")).not.toBeInTheDocument();
expect(screen.queryByText("Not reused")).not.toBeInTheDocument();
expect(screen.getByRole("img", {
name: /input tokens 29,400.*KV cache hit rate 89%.*output tokens 416.*generation time 40/i,
})).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "b.md" })).toBeInTheDocument();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");
const replay = screen.getByRole("button", { name: "Play context history" });
fireEvent.click(replay);
expect(replay).toBeDisabled();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "10");
expect(await screen.findByRole("button", { name: "a.md" })).toBeInTheDocument();
await waitFor(() => expect(replay).toBeEnabled(), { timeout: 2500 });
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");
});
it("uses each visible bar as its round detail trigger", async () => {
const user = userEvent.setup();
render(
<ThreadComposer
onSend={vi.fn()}
contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}
recentRoundUsage={[
{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 3, 7, 20),
inputTokens: 18_000,
outputTokens: 280,
cachedTokens: 12_000,
},
{
id: "turn-2",
timestamp: Date.UTC(2026, 8, 3, 8, 22),
inputTokens: 29_400,
outputTokens: 416,
cachedTokens: 26_180,
},
]}
placeholder="Ask anything..."
/>,
);
await user.click(screen.getByTestId("composer-context-usage"));
const firstBar = screen.getByRole("img", { name: /input tokens 18,000/i });
const secondBar = screen.getByRole("img", { name: /input tokens 29,400/i });
expect(firstBar).toHaveAttribute("data-testid", "round-usage-bar");
expect(secondBar).toHaveAttribute("data-testid", "round-usage-bar");
await user.hover(firstBar);
const firstTooltip = await screen.findByRole("tooltip");
expect(within(firstTooltip).getByText("Input tokens")).toBeInTheDocument();
expect(within(firstTooltip).getByText("18,000")).toBeInTheDocument();
await user.click(firstBar);
await user.unhover(firstBar);
await user.hover(secondBar);
const secondTooltip = await screen.findByRole("tooltip");
expect(within(secondTooltip).getByText("Input tokens")).toBeInTheDocument();
expect(within(secondTooltip).getByText("29,400")).toBeInTheDocument();
it("shows the latest round cache metrics when inspecting legacy history", () => {
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 14700, contextWindowTokens: 200000 }}
recentRoundUsage={[{ inputTokens: 18000, cachedTokens: 12000 },
{ inputTokens: 29400, cachedTokens: 26180 }]} />);
fireEvent.click(screen.getByTestId("composer-context-usage"));
const meter = screen.getByRole("progressbar", { name: "Context" });
fireEvent.pointerEnter(meter.parentElement!.parentElement!);
expect(screen.getByText("Cache hit rate")).toBeInTheDocument();
expect(screen.getByText("89%")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();
});
it("keeps context usage visible when the provider omits cache metrics", () => {
render(
<ThreadComposer
onSend={() => {}}
contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}
recentRoundUsage={[{
id: "turn-without-cache-metrics",
timestamp: new Date(2026, 8, 3, 16, 22).getTime(),
inputTokens: 29_400,
outputTokens: 416,
}]}
placeholder="Ask anything..."
/>,
);
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 14700, contextWindowTokens: 200000 }}
recentRoundUsage={[{ inputTokens: 29400 }]} />);
fireEvent.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByRole("progressbar", { name: "Context 7%" })).toHaveAttribute(
"aria-valuenow",
"7",
);
const [bar] = screen.getAllByTestId("round-usage-bar");
expect(bar.firstElementChild).toHaveClass("bg-muted-foreground/25");
expect(screen.queryByText("Reused")).not.toBeInTheDocument();
const meter = screen.getByRole("progressbar", { name: "Context" });
expect(meter).toHaveAttribute("aria-valuenow", "7");
fireEvent.pointerEnter(meter.parentElement!.parentElement!);
expect(screen.queryByText("Cache hit rate")).not.toBeInTheDocument();
});
it("keeps the thread composer compact while matching the hero style", () => {
@@ -1292,6 +1216,7 @@ describe("ThreadComposer", () => {
it.each(["thread", "hero"] as const)("keeps narrow %s permissions inline and usage below without losing the draft", async (variant) => {
let width = 390;
vi.stubGlobal("innerWidth", width);
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(
() => rect({ width, height: 160 }),
);
@@ -1323,6 +1248,7 @@ describe("ThreadComposer", () => {
// A narrow desktop panel uses the same layout; resizing must not replace the textarea.
width = 800;
vi.stubGlobal("innerWidth", width);
fireEvent(window, new Event("resize"));
expect(form).not.toHaveAttribute("data-compact-controls");
expect(primary).toContainElement(access);
@@ -1374,6 +1300,7 @@ describe("ThreadComposer", () => {
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue(
rect({ width: 390, height: 160 }),
);
vi.stubGlobal("innerWidth", 390);
const user = userEvent.setup();
const onSend = vi.fn();
render(
@@ -1381,10 +1308,7 @@ describe("ThreadComposer", () => {
onSend={onSend}
contextUsage={{ contextTokens: 10000, contextWindowTokens: 200000 }}
recentRoundUsage={[{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 13, 7, 20),
inputTokens: 10000,
outputTokens: 280,
cachedTokens: 8000,
}]}
/>,
@@ -1392,12 +1316,11 @@ describe("ThreadComposer", () => {
const trigger = screen.getByTestId("composer-context-usage");
await user.click(trigger);
const sheet = screen.getByRole("dialog", { name: "Context usage" });
expect(sheet).toHaveClass("bottom-0", "max-h-[60dvh]");
expect(sheet).toHaveFocus();
expect(within(sheet).getByRole("heading", { name: "Context usage" })).toBeVisible();
expect(within(sheet).getByText("10K / 200K")).toBeVisible();
expect(within(sheet).getByTestId("round-usage-bar")).toBeVisible();
expect(sheet).toContainElement(within(sheet).getByRole("group", { name: "Input tokens" }));
expect(sheet).toHaveClass("mt-auto", "h-[85%]");
expect(sheet.contains(document.activeElement)).toBe(true);
expect(within(sheet).getByRole("heading", { name: "Context usage" })).toBeInTheDocument();
expect(within(sheet).getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "5");
expect(within(sheet).getByRole("button", { name: "Play context history" })).toBeDisabled();
expect(document.body).toHaveStyle({ pointerEvents: "none" });
if (dismissal === "Escape") await user.keyboard("{Escape}");
@@ -1410,23 +1333,24 @@ describe("ThreadComposer", () => {
expect(onSend).toHaveBeenCalledWith("still works", undefined, undefined);
});
it("releases the mobile sheet when resizing to desktop and keeps the desktop popover", async () => {
it("releases the mobile modal lock when resizing and keeps the desktop sidebar open", async () => {
let width = 390;
vi.stubGlobal("innerWidth", width);
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(
() => rect({ width, height: 160 }),
);
const user = userEvent.setup();
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 500, contextWindowTokens: 1000 }} />);
await user.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByRole("dialog")).toHaveClass("bottom-0");
expect(screen.getByRole("dialog")).toHaveClass("mt-auto");
width = 800;
vi.stubGlobal("innerWidth", width);
fireEvent(window, new Event("resize"));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
await user.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByRole("dialog", { name: "Context usage" })).not.toHaveClass("bottom-0");
expect(screen.getByRole("progressbar", { name: "Context 50%" })).toBeVisible();
expect(screen.getByRole("complementary", { name: "Context usage" })).toBeInTheDocument();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "50");
});
it.each([
@@ -1640,6 +1564,7 @@ describe("ThreadComposer", () => {
it("keeps the inline permission menu and directory picker mounted across composer widths", () => {
let width = 390;
vi.stubGlobal("innerWidth", width);
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }));
const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };
const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope}
@@ -1652,6 +1577,7 @@ describe("ThreadComposer", () => {
expect(row.querySelector(".thread-composer-workspace-group")).toContainElement(trigger);
expect(container.querySelector(".thread-composer-footer-primary")).toContainElement(access);
width = 800;
vi.stubGlobal("innerWidth", width);
fireEvent(window, new Event("resize"));
expect(container.querySelector(".thread-composer-meta")).toBe(row);
expect(screen.getByRole("button", { name: "Switch directory" })).toBe(trigger);
+36 -11
View File
@@ -947,7 +947,7 @@ describe("ThreadShell", () => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("renders each logical round in a completed turn as its own usage bar", async () => {
it("shows legacy history usage and clears it after successful compaction", async () => {
const client = makeClient();
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
if (String(input).includes("websocket%3Ausage-chart/webui-thread")) {
@@ -1013,10 +1013,8 @@ describe("ThreadShell", () => {
const trigger = await screen.findByTestId("composer-context-usage");
fireEvent.click(trigger);
expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(4);
expect(screen.getByRole("img", {
name: /input tokens 16,400.*KV cache hit rate 99%.*output tokens 236/i,
})).toBeInTheDocument();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "22");
expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();
expect(screen.getByTestId("composer-context-meter")).toBeInTheDocument();
for (const phase of ["started", "failed"] as const) {
act(() => client._emitChat("usage-chart", {
@@ -1028,8 +1026,7 @@ describe("ThreadShell", () => {
event: "context_compaction", chat_id: "usage-chart",
compaction_id: "success", phase: "succeeded",
}));
expect(trigger).toHaveAccessibleName("Open context usage");
expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(4);
await waitFor(() => expect(screen.queryByTestId("composer-context-usage")).not.toBeInTheDocument());
});
it("updates composer usage from active model snapshots without changing the body", async () => {
@@ -1041,7 +1038,10 @@ describe("ThreadShell", () => {
events: [{ ...envelope, event: "user_message", text: "Waiting for answer", starts_turn: true, turn_seq: 0 }] })
: { ok: false, status: 404, json: async () => ({}) },
)));
render(wrap(client, <ThreadShell
const footer = document.createElement("div");
document.body.append(footer);
const view = render(wrap(client, <ThreadShell
composerPortalTarget={footer}
session={session("live-usage")} title="Live usage" onToggleSidebar={() => {}}
settingsSnapshot={modelSettings("test-model", "deepseek")}
/>));
@@ -1050,6 +1050,7 @@ describe("ThreadShell", () => {
phase: "completed", sequence: 1, turn_seq: 1, context_window_tokens: 1000,
usage: { prompt_tokens: 100, completion_tokens: 10, context_tokens: 100, request_count: 1 },
round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }],
context_graph: { nodes: [{ path: "/first.md", name: "first.md", state: "loaded", tokens: 40 }], edges: [] },
}));
const trigger = await screen.findByTestId("composer-context-usage");
expect(trigger).toHaveAccessibleName("Context 10%. Open context usage");
@@ -1057,11 +1058,34 @@ describe("ThreadShell", () => {
phase: "completed", sequence: 2, turn_seq: 2, context_window_tokens: 1000,
usage: { prompt_tokens: 300, completion_tokens: 20, context_tokens: 200, request_count: 2 },
round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }, { prompt_tokens: 200, completion_tokens: 10 }],
context_graph: { nodes: [{ path: "/second.md", name: "second.md", state: "loaded", tokens: 60 }], edges: [] },
}));
expect(trigger).toHaveAccessibleName("Context 20%. Open context usage");
const input = screen.getByRole("textbox");
expect(footer).toContainElement(input);
fireEvent.change(input, { target: { value: "Preserve this draft" } });
const host = document.querySelector(".thread-preview-layout")!;
Object.defineProperty(host, "clientWidth", { value: 1000 });
fireEvent(window, new Event("resize"));
act(() => input.focus());
fireEvent.click(trigger);
expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(2);
expect(host.querySelector(".thread-conversation")).toContainElement(input);
expect(footer).not.toContainElement(input);
expect(input).toHaveValue("Preserve this draft");
expect(input).toHaveFocus();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");
expect(await screen.findByRole("button", { name: "second.md" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Play context history" })).toBeEnabled();
expect(screen.getByText("Waiting for answer")).toBeInTheDocument();
const sidebar = screen.getByTestId("context-sidebar");
fireEvent.click(trigger);
expect(screen.getByTestId("context-sidebar")).toBe(sidebar);
expect(sidebar).toHaveAttribute("data-closing");
expect(footer).toContainElement(input);
expect(input).toHaveValue("Preserve this draft");
await waitFor(() => expect(screen.queryByTestId("context-sidebar")).not.toBeInTheDocument());
view.unmount();
footer.remove();
});
it.each([false, true])("restores context after compaction only with newer usage (%s)", async (newReply) => {
@@ -1090,11 +1114,12 @@ describe("ThreadShell", () => {
session={session("compact-usage")} title="Compact usage" onToggleSidebar={() => {}}
settingsSnapshot={modelSettings("test-model", "deepseek")}
/>));
const trigger = await screen.findByTestId("composer-context-usage");
await screen.findByText("Before compact");
if (newReply) {
const trigger = await screen.findByTestId("composer-context-usage");
expect(trigger).toHaveAccessibleName("Context 2%. Open context usage");
} else {
expect(trigger).toHaveAccessibleName("Open context usage");
expect(screen.queryByTestId("composer-context-usage")).not.toBeInTheDocument();
}
});
+2 -1
View File
@@ -30,7 +30,8 @@ describe("UI shape system", () => {
<DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription>
</DialogContent></Dialog>);
const dialog = screen.getByRole("dialog");
expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");
expect(dialog.parentElement).toHaveClass("items-start", placement === "bottom" ? "overflow-clip" : "overflow-y-auto");
if (placement === "bottom") expect(dialog).toHaveClass("overflow-y-auto");
// The scroll owner stays inside Radix's overlay/scroll-lock boundary.
expect(dialog.parentElement?.parentElement).toHaveAttribute("data-state", "open");
expect(dialog).toHaveClass(placement === "bottom" ? "mt-auto" : "my-auto");
+1 -1
View File
@@ -306,7 +306,7 @@ describe("durable run recovery", () => {
await reopen();
expect(fetchMock).toHaveBeenCalledWith(
"/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1",
"/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({ headers: { Authorization: "Bearer renewed-token" } }),
);
expect(client.getRunStartedAt("inactive")).toBeNull();