fix(webui): preserve live context usage between model requests

This commit is contained in:
chengyongru authored and chengyongru committed 2026-11-06 13:09:44 +08:00
1 parent 7ea2c9a830
commit 5b9a4ea530
3 files changed
+73 -8

No files matched your search

@@ -14,6 +14,13 @@ const ContextGraphScene = lazy(() => import("./ContextGraphScene").then(module =
const EMPTY_GRAPH: ContextGraph = { nodes: [], edges: [] };
const surface = "context-inspector-surface select-none rounded-[20px] bg-card";
function latestUsageSnapshot(snapshots: readonly ContextSnapshot[]) {
for (let index = snapshots.length - 1; index >= 0; index -= 1) {
const snapshot = snapshots[index];
if (snapshot.estimatedTokens !== undefined || snapshot.usage !== undefined) return snapshot;
}
}
export function ContextInspector({ context, rounds, snapshots, onOpenFile, sidebar = false, expandable = true }: {
context: ComposerContextUsage | null; rounds: readonly ComposerRoundUsage[];
snapshots: readonly ContextSnapshot[]; onOpenFile?: (path: string) => void; sidebar?: boolean; expandable?: boolean;
@@ -37,17 +44,19 @@ export function ContextInspector({ context, rounds, snapshots, onOpenFile, sideb
return () => window.clearTimeout(timer);
}, [replay, readyGraph]);
const snapshot = replay ? replay.frames[replay.index] : snapshots.at(-1);
// The live graph advances before usage arrives; replay stays frame-local.
const usageSnapshot = replay ? snapshot : latestUsageSnapshot(snapshots);
const latestRound = rounds.at(-1);
const tokens = snapshot ? snapshot.estimatedTokens ?? snapshot.usage?.context_tokens ?? snapshot.usage?.prompt_tokens : context?.contextTokens;
const estimated = snapshot?.estimatedTokens !== undefined || (!snapshot?.usage && context?.estimated);
const windowTokens = snapshot?.contextWindowTokens ?? context?.contextWindowTokens;
const tokens = usageSnapshot ? usageSnapshot.estimatedTokens ?? usageSnapshot.usage?.context_tokens ?? usageSnapshot.usage?.prompt_tokens : context?.contextTokens;
const estimated = usageSnapshot ? usageSnapshot.estimatedTokens !== undefined : context?.estimated;
const windowTokens = usageSnapshot ? usageSnapshot.contextWindowTokens : context?.contextWindowTokens ?? snapshot?.contextWindowTokens;
const tokenNumbers = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 1 });
const hasTokenUsage = tokens !== undefined || !!windowTokens;
const used = tokens !== undefined && windowTokens ? Math.min(100, tokens / windowTokens * 100) : null;
const cached = snapshot ? snapshot.usage?.cached_tokens : latestRound?.cachedTokens;
const input = snapshot ? snapshot.usage?.prompt_tokens : latestRound?.inputTokens;
const cached = usageSnapshot ? usageSnapshot.usage?.cached_tokens : latestRound?.cachedTokens;
const input = usageSnapshot ? usageSnapshot.usage?.prompt_tokens : latestRound?.inputTokens;
const cachedWidth = cached !== undefined && windowTokens ? Math.min(used ?? 0, cached / windowTokens * 100) : 0;
const duration = snapshot ? snapshot.usage?.generation_ms : latestRound?.generationMs;
const duration = usageSnapshot ? usageSnapshot.usage?.generation_ms : latestRound?.generationMs;
const toggleExpanded = useCallback(() => setExpanded((value) => !value), []);
const openFileCallback = useRef(onOpenFile);
openFileCallback.current = onOpenFile;
+29 -2
View File
@@ -54,17 +54,44 @@ it("stops playback at compaction and shows the new baseline", async () => {
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();
const pending: ContextSnapshot = { id: "after-compaction", graph: compacted.graph, contextWindowTokens: 10000 };
rerender(<ContextInspector context={null} rounds={[]} snapshots={[compacted, pending]} />);
expect(screen.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "15");
expect(screen.getByText("≈15%")).toBeVisible();
});
it("shows token usage from the displayed snapshot, including estimates without cache data", () => {
const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
it("keeps the latest measured usage while the live graph advances and updates on completion", async () => {
const measured = { ...snapshots[1], usage: { ...snapshots[1].usage, generation_ms: 2000 } };
const history = [snapshots[0], measured];
const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={history} />);
const meter = screen.getByRole("progressbar").parentElement!.parentElement!;
fireEvent.pointerEnter(meter);
expect(screen.getByText("2k / 10k")).toBeVisible();
expect(screen.getByText("40%")).toBeVisible();
const pending: ContextSnapshot = { id: "third", contextWindowTokens: 20000, graph: {
nodes: [{ path: "/c.md", name: "c.md", state: "loaded", tokens: 100 }], edges: [],
} };
rerender(<ContextInspector context={null} rounds={[]} snapshots={[...history, pending]} />);
expect(screen.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");
expect(screen.getByText("2k / 10k")).toBeVisible();
expect(screen.getByText("40%")).toBeVisible();
expect(screen.getByText("2s")).toBeVisible();
expect(await screen.findByRole("button", { name: "c.md" })).toBeInTheDocument();
rerender(<ContextInspector context={null} rounds={[]} snapshots={[...history, {
...pending, usage: { context_tokens: 3000, prompt_tokens: 3000, cached_tokens: 1500, generation_ms: 4000 },
}]} />);
expect(screen.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "15");
expect(screen.getByText("3k / 20k")).toBeVisible();
expect(screen.getByText("50%")).toBeVisible();
expect(screen.getByText("4s")).toBeVisible();
rerender(<ContextInspector context={null} rounds={[]} snapshots={[{
id: "compacted", estimatedTokens: 1500, contextWindowTokens: 10000, graph: { nodes: [], edges: [] },
}]} />);
expect(screen.getByText("≈1.5k / 10k")).toBeVisible();
expect(screen.queryByText("50%")).not.toBeInTheDocument();
expect(screen.queryByText("4s")).not.toBeInTheDocument();
rerender(<ContextInspector context={null} rounds={[]} snapshots={[pending]} />);
expect(screen.getByRole("progressbar")).not.toHaveAttribute("aria-valuenow");
expect(screen.getByText("— / 20k")).toBeVisible();
});
+29
View File
@@ -60,3 +60,32 @@ it("speeds up longer histories without dropping unpainted snapshots", async () =
act(() => vi.advanceTimersByTime(47));
expect(progress()).toBe("5");
});
it("keeps replay usage frame-local and restores the latest measurement when playback ends", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
const snapshots: ContextSnapshot[] = [
{ id: "measured", contextWindowTokens: 10000, usage: { prompt_tokens: 1000, cached_tokens: 500 }, graph: { nodes: [], edges: [] } },
{ id: "pending", contextWindowTokens: 20000, graph: { nodes: [], edges: [] } },
];
await act(async () => {
render(<ContextInspector context={{ contextTokens: 1000, contextWindowTokens: 10000 }}
rounds={[{ inputTokens: 1000, cachedTokens: 500 }]} snapshots={snapshots} />);
await vi.dynamicImportSettled();
});
expect(progress()).toBe("10");
const play = screen.getByRole("button", { name: "Play context history" });
fireEvent.click(play);
expect(progress()).toBe("10");
paint();
act(() => vi.advanceTimersByTime(200));
expect(progress()).toBeNull();
fireEvent.pointerEnter(screen.getByRole("progressbar").parentElement!.parentElement!);
expect(screen.getByText("— / 20k")).toBeVisible();
expect(screen.queryByText("50%")).not.toBeInTheDocument();
paint();
act(() => vi.advanceTimersByTime(200));
expect(play).toBeEnabled();
expect(progress()).toBe("10");
expect(screen.getByText("1k / 10k")).toBeVisible();
expect(screen.getByText("50%")).toBeVisible();
});