feat(dashboard): lazy routes, Needs-you strip, URL state, exact numbers

- Workspace, SettingsHub, SessionDetail and the Workflow sub-tab are lazy
  (main bundle 2,166 kB -> ~920 kB), wrapped in RouteErrorBoundary: a stale
  chunk after a self-update reloads once (vite:preloadError too), any other
  error shows a Reload panel instead of a blank page.
- Live refresh: lib/throttle.ts + hooks/useLiveRefresh.ts replace trailing
  debounces that froze under a steady event stream; refresh skips hidden
  tabs and refetches after a WebSocket reconnect. Monitor loads only while
  shown, with one batched GET /api/agents?session_ids= instead of N+1; a
  failing endpoint is an inline error, not a blank Dashboard.
- NeedsYouStrip on Monitor and above Analytics. Tabs, filters, page, sort
  and search live in the URL (Dashboard, Sessions, Activity, SessionDetail).
- Sessions: tool / workspace / date-range filters, CSV/JSON export
  (formula-neutralised), focusable row links, Open in workspace (the dead
  /run links are gone), stale responses dropped, error + Retry.
- Fixes: "NaNs" durations, 30/7-day charts skipping idle days, weekday
  labels west of UTC (now averages), cache hit rate denominator, billable
  tokens vs cache reads, exact tool-call counts, "To" date = end of day,
  invalid ?from= no longer throws, recent list no longer shrinks to 15,
  stable message keys, transcript switch races.
- Light-theme-unreadable bg-black code panels and dark-only DAG fills use
  tokens; status configs and chart colours use theme tokens; Health tab
  and other literals translated.
- Server (additive): GET /api/agents?session_ids=, GET /api/sessions
  awaiting=1&from=&to=, stats tool_call_count/distinct_tool_count, event
  rows carry session/agent labels.
This commit is contained in:
2026-10-05 13:22:04 +07:00
parent 8fb703c6db
commit 03f1673fce
63 changed files with 3879 additions and 1662 deletions
@@ -0,0 +1,121 @@
/**
* @file Sessions.urlState.test.tsx
* @description The Sessions list keeps its filters in the URL: one filter
* change is one load at page 0, "Waiting" asks the server (`awaiting`) instead
* of downloading every active session, and a stale response never overwrites
* a newer one.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";
import { MemoryRouter, useLocation, useNavigate } from "react-router-dom";
import { api } from "../../lib/api";
import { Sessions } from "../Sessions";
import type { Session } from "../../lib/types";
function GoPlain() {
const nav = useNavigate();
return <button onClick={() => nav("/sessions")}>go-plain</button>;
}
function Where() {
const loc = useLocation();
return <span data-testid="where">{loc.search}</span>;
}
const page = (sessions: Partial<Session>[], total = sessions.length) => ({
sessions: sessions as Session[],
total,
limit: 10,
offset: 0,
});
beforeEach(() => {
vi.restoreAllMocks();
vi.spyOn(api.sessions, "facets").mockResolvedValue({ cwds: [] } as never);
vi.spyOn(api.remoteSources, "list").mockResolvedValue({ sources: [] } as never);
vi.spyOn(api.run, "list").mockResolvedValue({ items: [] });
});
describe("Sessions URL state", () => {
it("one filter click = one load at page 0; Waiting asks the server", async () => {
const list = vi.spyOn(api.sessions, "list").mockResolvedValue(page([]));
render(
<MemoryRouter initialEntries={["/sessions?page=3"]}>
<Sessions />
<Where />
</MemoryRouter>
);
await waitFor(() => expect(list).toHaveBeenCalled());
expect(list.mock.calls[list.mock.calls.length - 1]![0]).toMatchObject({ offset: 30 });
list.mockClear();
fireEvent.click(screen.getByRole("button", { name: "Waiting" }));
await waitFor(() => expect(list).toHaveBeenCalledTimes(1));
expect(list.mock.calls[0]![0]).toMatchObject({
status: "active",
awaiting: true,
offset: 0,
limit: 10,
});
expect(screen.getByTestId("where").textContent).toBe("?status=waiting");
});
it("drops a response that arrives after a newer one", async () => {
let resolveOld!: (v: ReturnType<typeof page>) => void;
const list = vi
.spyOn(api.sessions, "list")
.mockImplementationOnce(() => new Promise((r) => (resolveOld = r)))
.mockResolvedValue(
page([
{ id: "new-1", name: "Fresh", status: "completed", started_at: "2026-01-01T00:00:00Z" },
])
);
render(
<MemoryRouter initialEntries={["/sessions"]}>
<Sessions />
</MemoryRouter>
);
await waitFor(() => expect(list).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByRole("button", { name: "Completed" }));
expect(await screen.findByText("Fresh")).toBeInTheDocument();
await act(async () => {
resolveOld(
page([
{ id: "old-1", name: "Stale", status: "completed", started_at: "2026-01-01T00:00:00Z" },
])
);
});
expect(screen.queryByText("Stale")).not.toBeInTheDocument();
});
it("an outside navigation that clears ?q= clears the box, and the old q is not written back", async () => {
vi.spyOn(api.sessions, "list").mockResolvedValue(page([]));
render(
<MemoryRouter initialEntries={["/sessions?q=abc"]}>
<Sessions />
<GoPlain />
<Where />
</MemoryRouter>
);
expect(screen.getByRole("textbox", { name: /search sessions/i })).toHaveValue("abc");
fireEvent.click(screen.getByText("go-plain"));
await waitFor(() =>
expect(screen.getByRole("textbox", { name: /search sessions/i })).toHaveValue("")
);
await act(() => new Promise((r) => setTimeout(r, 400)));
expect(screen.getByTestId("where").textContent).toBe("");
});
it("a page past the end goes back to page 1", async () => {
vi.spyOn(api.sessions, "list").mockResolvedValue(page([], 5));
render(
<MemoryRouter initialEntries={["/sessions?page=7"]}>
<Sessions />
<Where />
</MemoryRouter>
);
await waitFor(() => expect(screen.getByTestId("where").textContent).toBe(""));
});
});