The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(ui): inline Lens settings tab and investigation editor (#44479)
devin-ai-integration[bot]9a5e828310ef
diff --git a/ui/litellm-dashboard/package-lock.json b/ui/litellm-dashboard/package-lock.jsonindex b4c886752df..37027f215fe 100644--- a/ui/litellm-dashboard/package-lock.json+++ b/ui/litellm-dashboard/package-lock.json@@ -42,6 +42,7 @@"react-dom": "19.2.8","react-error-boundary": "6.1.6","react-hook-form": "7.82.0",+ "react-hotkeys-hook": "5.3.3","react-intersection-observer": "11.0.1","react-json-view-lite": "2.5.0","react-markdown": "9.1.0",@@ -10537,6 +10538,19 @@"react": "^16.8.0 || ^17 || ^18 || ^19"}},+ "node_modules/react-hotkeys-hook": {+ "version": "5.3.3",+ "resolved": "https://registry.npmjs.org/react-hotkeys-hook/-/react-hotkeys-hook-5.3.3.tgz",+ "integrity": "sha512-aswgyWUnE25hmhzHTfKDmKzsaSE5DJ4LKaU/o6rQSXkDd/1Bh9TfAFQbHkf6fLy11HvlYkp+cDDarGdhmCDhoQ==",+ "license": "MIT",+ "workspaces": [+ "packages/*"+ ],+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },"node_modules/react-intersection-observer": {"version": "11.0.1","resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-11.0.1.tgz",diff --git a/ui/litellm-dashboard/package.json b/ui/litellm-dashboard/package.jsonindex bba51e9aa2b..388b6c7eab9 100644--- a/ui/litellm-dashboard/package.json+++ b/ui/litellm-dashboard/package.json@@ -59,6 +59,7 @@"react-dom": "19.2.8","react-error-boundary": "6.1.6","react-hook-form": "7.82.0",+ "react-hotkeys-hook": "5.3.3","react-intersection-observer": "11.0.1","react-json-view-lite": "2.5.0","react-markdown": "9.1.0",diff --git a/ui/litellm-dashboard/src/app/layout.tsx b/ui/litellm-dashboard/src/app/layout.tsxindex 60db7104a03..7bb05ef11a7 100644--- a/ui/litellm-dashboard/src/app/layout.tsx+++ b/ui/litellm-dashboard/src/app/layout.tsx@@ -7,6 +7,7 @@ import { ThemeProvider } from "next-themes";import { AuthProvider } from "@/contexts/AuthContext";import ReactQueryProvider from "@/contexts/ReactQueryProvider";+import HotkeysProvider from "@/contexts/HotkeysProvider";import { Toaster } from "@/components/ui/sonner";const inter = Inter({ subsets: ["latin"] });@@ -30,7 +31,9 @@ export default function RootLayout({<ThemeProvider attribute="class" defaultTheme="light" enableSystem disableTransitionOnChange><NuqsAdapter><ReactQueryProvider>- <AuthProvider>{children}</AuthProvider>+ <HotkeysProvider>+ <AuthProvider>{children}</AuthProvider>+ </HotkeysProvider><Toaster /></ReactQueryProvider></NuqsAdapter>diff --git a/ui/litellm-dashboard/src/components/lens/HeaderActions.tsx b/ui/litellm-dashboard/src/components/lens/HeaderActions.tsxdeleted file mode 100644index 8df9307c990..00000000000--- a/ui/litellm-dashboard/src/components/lens/HeaderActions.tsx+++ /dev/null@@ -1,13 +0,0 @@-"use client";--import { useContext, type ReactNode } from "react";-import { createPortal } from "react-dom";--import { LensPreviewContext } from "./LensPreviewButton";--export function HeaderActions({ children }: { children: ReactNode }) {- const preview = useContext(LensPreviewContext);- const actions = <div className="flex flex-wrap items-center gap-3">{children}</div>;- if (preview === undefined) return actions;- return preview.target ? createPortal(actions, preview.target) : null;-}diff --git a/ui/litellm-dashboard/src/components/lens/LensModeSwitch.tsx b/ui/litellm-dashboard/src/components/lens/LensModeSwitch.tsxnew file mode 100644index 00000000000..11d02567799--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/LensModeSwitch.tsx@@ -0,0 +1,101 @@+"use client";++import { Tabs as TabsPrimitive } from "@base-ui/react/tabs";+import { Activity, ScanSearch, Settings } from "lucide-react";+import { StatusDot } from "@/components/shared/StatusDot";+import { cn } from "@/lib/cva.config";+import type { InvestigationActivity } from "./model/status";+import { useWorkerConnected } from "./hooks/useWorkerConnected";+import type { LensList } from "./model/types";+import { LENS_TABS, type LensTab } from "./route";+import { frameCorner, frameTab } from "./ui/frame";++const MODE_ICONS = { traces: Activity, investigations: ScanSearch, settings: Settings } as const;++const ACTIVITY_DOT: Record<Exclude<InvestigationActivity, "idle">, { className: string; label: string }> = {+ running: { className: "bg-info motion-safe:animate-pulse", label: "An investigation is running" },+ queued: { className: "bg-muted-foreground/60", label: "An investigation is queued" },+};++function ActivityDot({ activity }: { activity: InvestigationActivity }) {+ if (activity === "idle") return null;+ return (+ <span+ aria-hidden="true"+ className={cn(+ "size-1.5 rounded-full animate-in fade-in-0 zoom-in-50 duration-300",+ ACTIVITY_DOT[activity].className,+ )}+ />+ );+}++/** Inverted corner joining the tab's side border to the card's top border; plain CSS borders so both snap to the same pixels. */+function NotchCorner({ side, demo }: { side: "left" | "right"; demo: boolean }) {+ return (+ <span+ aria-hidden="true"+ className={cn(+ "pointer-events-none absolute bottom-0 size-3 overflow-hidden",+ side === "left" ? "-left-3" : "-right-3",+ )}+ >+ <span className={frameCorner({ session: demo ? "demo" : "live", side })} />+ </span>+ );+}++export function LensModeSwitch({+ activity,+ demo,+ workers,+ setup,+}: {+ activity: InvestigationActivity;+ demo: boolean;+ workers: LensList["workers"] | null;+ setup?: string;+}) {+ const connected = useWorkerConnected(workers);+ const settingsTitle = connected ? "Worker connected" : "Connect worker";+ const tabs = Object.entries(LENS_TABS).filter(([view]) => view !== "settings" || workers);+ return (+ <div className={frameTab({ session: demo ? "demo" : "live" })}>+ <NotchCorner side="left" demo={demo} />+ <NotchCorner side="right" demo={demo} />+ <TabsPrimitive.List aria-label="Lens" className="relative inline-flex h-9 items-center p-1">+ <TabsPrimitive.Indicator className="absolute top-1 bottom-1 left-(--active-tab-left) w-(--active-tab-width) rounded-full bg-muted transition-[left,width] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none" />+ {tabs.map(([view, label]) => {+ const Icon = MODE_ICONS[view as LensTab];+ const workerDisconnected = view === "settings" && workers !== null && !connected;+ return (+ <TabsPrimitive.Tab+ key={view}+ value={view}+ title={view === "settings" ? settingsTitle : undefined}+ aria-description={+ view === "investigations" && activity !== "idle" ? ACTIVITY_DOT[activity].label : undefined+ }+ className={cn(+ "relative z-raised inline-flex h-full items-center gap-2 rounded-full text-sm font-medium text-muted-foreground outline-none transition-colors duration-200 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 data-active:text-foreground",+ view === "settings" ? "px-2.5" : "px-4",+ )}+ >+ <span className="relative inline-flex">+ <Icon aria-hidden="true" className="size-4" />+ {workerDisconnected && <StatusDot state="error" className="absolute -top-0.5 -right-0.5 size-1.5" />}+ </span>+ <span className={cn(view === "settings" && "sr-only")}>{label}</span>+ {view === "investigations" && setup && (+ <span className="rounded-full bg-muted px-1.5 py-0.5 text-xs leading-none font-medium text-muted-foreground animate-in fade-in-0 duration-200">+ {setup}+ </span>+ )}+ {view === "investigations" && <ActivityDot activity={activity} />}+ </TabsPrimitive.Tab>+ );+ })}+ </TabsPrimitive.List>+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/LensNavigation.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/LensPage.integration.test.tsxsimilarity index 96%rename from ui/litellm-dashboard/src/components/lens/LensNavigation.integration.test.tsxrename to ui/litellm-dashboard/src/components/lens/LensPage.integration.test.tsxindex 769a77500e8..320dbef4142 100644--- a/ui/litellm-dashboard/src/components/lens/LensNavigation.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/lens/LensPage.integration.test.tsx@@ -2,6 +2,7 @@ import { screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { renderWithProviders, testQueryClient } from "@/../tests/test-utils";+import { dismissLensIntro } from "@/../tests/lens-test-utils";import LensPage from "@/app/(dashboard)/lens/page";const { auth } = vi.hoisted(() => ({ auth: vi.fn() }));@@ -18,6 +19,9 @@ vi.mock("./investigations/InvestigationsView", () => ({describe("Lens navigation", () => {beforeEach(() => {testQueryClient.clear();+ window.localStorage.clear();+ window.sessionStorage.clear();+ dismissLensIntro();auth.mockReturnValue({ accessToken: "test-token", userRole: "Admin", isViewOnly: false });vi.stubGlobal("fetch",diff --git a/ui/litellm-dashboard/src/components/lens/LensServicesProvider.tsx b/ui/litellm-dashboard/src/components/lens/LensServicesProvider.tsxdeleted file mode 100644index ab5ee61fa4e..00000000000--- a/ui/litellm-dashboard/src/components/lens/LensServicesProvider.tsx+++ /dev/null@@ -1,13 +0,0 @@-"use client";--import type { ReactNode } from "react";-import { TracesApiContext } from "@/components/view_logs/TraceView/tracesApi";-import { LensApiContext, type LensServices } from "./services";--export function LensServicesProvider({ services, children }: { services: LensServices; children: ReactNode }) {- return (- <LensApiContext.Provider value={services.lens}>- <TracesApiContext.Provider value={services.traces}>{children}</TracesApiContext.Provider>- </LensApiContext.Provider>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/LensSetup.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/LensSetup.integration.test.tsxindex 036b02f04c4..cfc9a7183d4 100644--- a/ui/litellm-dashboard/src/components/lens/LensSetup.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/lens/LensSetup.integration.test.tsx@@ -2,8 +2,11 @@ import { act, fireEvent, screen, within, waitFor } from "@testing-library/react"import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { renderWithProviders, testQueryClient } from "@/../tests/test-utils";+import { dismissLensIntro } from "@/../tests/lens-test-utils";+import { readStorage } from "@/lib/storage";+import { LENS_INTRO_DISMISSED, LENS_INTRO_SEEN } from "./storage";import { LensWorkspace } from "./LensWorkspace";-import { createLensDemoData } from "./demo/createLensDemo";+import { createLensDemoData } from "./data/demo/fixtures";import type { LensList } from "./model/types";const network = vi.fn<typeof fetch>();@@ -50,6 +53,8 @@ function serve({ enabled = false, traces = false, requests = false, connected =beforeEach(() => {testQueryClient.clear();+ window.localStorage.clear();+ window.sessionStorage.clear();network.mockReset();list.mockReset();vi.stubGlobal("fetch", network);@@ -57,10 +62,95 @@ beforeEach(() => {serve();});+const renderWorkspace = (options?: Parameters<typeof renderWithProviders>[1], userRole = "Admin") =>+ renderWithProviders(<LensWorkspace accessToken="setup-token" userRole={userRole} readOnly={false} />, options);++const setupParam = (onUrlUpdate: ReturnType<typeof vi.fn>) =>+ new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? "")).get("setup");++async function connectWorkerFromSettings(user: ReturnType<typeof userEvent.setup>) {+ const settings = within(await screen.findByRole("region", { name: "Settings" }));+ expect(settings.getByRole("heading", { name: "Connect a worker" })).toBeVisible();+ await user.click(settings.getByRole("combobox", { name: "Analysis model" }));+ await user.click(await screen.findByRole("option", { name: "analysis" }));+ await user.click(settings.getByRole("button", { name: "Get install command" }));+ expect(await settings.findByRole("heading", { name: "Worker connected" })).toBeVisible();+ await user.click(settings.getByRole("button", { name: "New investigation" }));+ expect(await screen.findByRole("region", { name: "New investigation" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+}++describe("Lens introduction", () => {+ it("opens on the first visit, rests for the session on close, and stays away after don't show again", async () => {+ const user = userEvent.setup();+ const onUrlUpdate = vi.fn();+ const first = renderWorkspace({ onUrlUpdate });+ const intro = within(await screen.findByRole("dialog"));+ expect(await intro.findByRole("heading", { name: "The gateway that helps your agents improve" })).toBeVisible();+ expect(intro.getByRole("heading", { name: "Before you start" })).toBeVisible();+ await user.click(intro.getByRole("button", { name: "Close" }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(readStorage(LENS_INTRO_SEEN)).toBe(true);+ expect(readStorage(LENS_INTRO_DISMISSED)).toBe(false);+ first.unmount();++ const second = renderWorkspace();+ expect(await screen.findByRole("tablist", { name: "Lens" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ second.unmount();++ window.sessionStorage.clear();+ const third = renderWorkspace();+ const reopened = within(await screen.findByRole("dialog"));+ await user.click(reopened.getByRole("checkbox", { name: "Don’t show this again" }));+ await user.click(reopened.getByRole("button", { name: "Close" }));+ expect(readStorage(LENS_INTRO_DISMISSED)).toBe(true);+ third.unmount();++ window.sessionStorage.clear();+ const fourth = renderWorkspace();+ expect(await screen.findByRole("tablist", { name: "Lens" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ fourth.unmount();++ renderWorkspace({ searchParams: "?setup=lens" });+ expect(await screen.findByRole("dialog")).toBeVisible();+ });++ it("lets settings bring back an introduction hidden with don't show again", async () => {+ const user = userEvent.setup();+ const first = renderWorkspace();+ const intro = within(await screen.findByRole("dialog"));+ await user.click(intro.getByRole("checkbox", { name: "Don’t show this again" }));+ await user.click(intro.getByRole("button", { name: "Close" }));+ first.unmount();++ const settings = renderWorkspace({ searchParams: "?tab=settings" });+ const toggle = within(await screen.findByRole("region", { name: "Introduction" })).getByRole("switch", {+ name: "Show the introduction on each new session",+ });+ expect(toggle).not.toBeChecked();+ await user.click(toggle);+ expect(toggle).toBeChecked();+ settings.unmount();++ window.sessionStorage.clear();+ renderWorkspace();+ expect(await screen.findByRole("dialog")).toBeVisible();+ });++ it("never opens on its own inside the sample session", async () => {+ renderWorkspace({ searchParams: "?demo=true" });+ expect(await screen.findByText("Where is order #1042?")).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+});+describe("Lens setup journey", () => {it.each(["/lens", "/lens/activity/available"])("keeps recorded traces visible while %s is pending",async (pendingPath) => {+ dismissLensIntro();serve({ enabled: true, traces: true });const normal = network.getMockImplementation()!;network.mockImplementation((input, init) =>@@ -68,7 +158,7 @@ describe("Lens setup journey", () => {? new Promise<Response>(() => {}): normal(input, init),);- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />);+ renderWorkspace();expect(await screen.findByRole("table", { name: "Agent runs" })).toBeVisible();},);@@ -76,6 +166,7 @@ describe("Lens setup journey", () => {it.each(["/v1/traces", "/lens/activity/available"])("opens a saved investigation while %s is pending",async (pendingPath) => {+ dismissLensIntro();serve();list.mockResolvedValue({ lenses: data.lenses, workers: [worker()], tracing_enabled: false });const normal = network.getMockImplementation()!;@@ -84,116 +175,97 @@ describe("Lens setup journey", () => {? new Promise<Response>(() => {}): normal(input, init),);- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />, {- searchParams: `?lens=${data.lenses[0].id}`,- });+ renderWorkspace({ searchParams: `?lens=${data.lenses[0].id}` });expect(await screen.findByRole("heading", { name: data.lenses[0].settings.name })).toBeVisible();},);- it("shares the introduction across tabs and stays in setup after the first trace", async () => {+ it("walks a first visit from the introduction through tracing into the Settings tab and the first investigation", async () => {const user = userEvent.setup();const onUrlUpdate = vi.fn();- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />, { onUrlUpdate });- expect(await screen.findByRole("heading", { name: "Before you start" })).toBeVisible();- await user.click(screen.getByRole("tab", { name: "Investigations" }));- expect(screen.getByRole("heading", { name: "Before you start" })).toBeVisible();- await user.click(screen.getByRole("button", { name: "Set up Lens" }));- await waitFor(() => expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get("setup")).toBe("lens"));+ renderWorkspace({ onUrlUpdate });+ const intro = within(await screen.findByRole("dialog"));+ await user.click(await intro.findByRole("button", { name: "Set up Lens" }));+ await waitFor(() => expect(setupParam(onUrlUpdate)).toBe("lens"));serve({ enabled: true });- await user.click(screen.getByRole("button", { name: "Check setup" }));- expect(await screen.findByText("Trace storage is connected")).toBeVisible();- await user.click(screen.getByRole("button", { name: "Continue to your agent" }));- expect(screen.getByRole("button", { name: "Check for traces" })).toBeVisible();+ await user.click(intro.getByRole("button", { name: "Check setup" }));+ expect(await intro.findByText("Trace storage is connected")).toBeVisible();+ await user.click(intro.getByRole("button", { name: "Continue to your agent" }));+ expect(intro.getByRole("button", { name: "Check for traces" })).toBeVisible();serve({ enabled: true, traces: true });- await user.click(screen.getByRole("button", { name: "Check for traces" }));- expect(await screen.findByText(/Your first trace is ready/)).toBeVisible();- expect(screen.queryByRole("table", { name: "Agent runs" })).not.toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Continue to worker" }));- const connection = within(await screen.findByRole("dialog", { name: "Connect a worker" }));- await user.click(connection.getByRole("combobox", { name: "Analysis model" }));- await user.click(await screen.findByRole("option", { name: "analysis" }));- await user.click(connection.getByRole("button", { name: "Get install command" }));- const connected = within(await screen.findByRole("dialog", { name: "Worker connected" }));- await user.click(connected.getByRole("button", { name: "New investigation" }));- expect(await screen.findByRole("dialog", { name: "Which activity should we investigate?" })).toBeVisible();- expect(screen.getByRole("heading", { name: "Get Lens running", hidden: true })).toBeInTheDocument();+ await user.click(intro.getByRole("button", { name: "Check for traces" }));+ expect(await intro.findByText(/Your first trace is ready/)).toBeVisible();+ expect(screen.getByRole("dialog")).toBeVisible();+ await user.click(intro.getByRole("button", { name: "Continue to worker" }));+ await waitFor(() => expect(setupParam(onUrlUpdate)).toBeNull());+ await connectWorkerFromSettings(user);});- it("resumes setup after a reload and leaves only when the user chooses traces", async () => {+ it("resumes setup from the URL and leaves only when the user chooses traces", async () => {serve({ enabled: true, traces: true });const user = userEvent.setup();- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />, {- searchParams: "?tab=investigations&setup=lens",- });- expect(await screen.findByRole("button", { name: "Connect worker" })).toBeVisible();- await user.click(screen.getByRole("tab", { name: "Traces" }));- expect(screen.getByRole("heading", { name: "Get Lens running" })).toBeVisible();- await user.click(screen.getByRole("button", { name: "View traces" }));+ const onUrlUpdate = vi.fn();+ renderWorkspace({ searchParams: "?tab=investigations&setup=lens", onUrlUpdate });+ const intro = within(await screen.findByRole("dialog"));+ expect(await intro.findByRole("button", { name: "Connect worker" })).toBeVisible();+ expect(intro.getByRole("heading", { name: "Get Lens running" })).toBeVisible();+ await user.click(intro.getByRole("button", { name: "View traces" }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();expect(await screen.findByRole("table", { name: "Agent runs" })).toBeVisible();+ await waitFor(() => expect(setupParam(onUrlUpdate)).toBeNull());await user.click(screen.getByRole("tab", { name: "Investigations" }));- expect(await screen.findByRole("heading", { name: "Run your first investigation" })).toBeVisible();- expect(screen.queryByRole("link", { name: "Set up traces" })).not.toBeInTheDocument();- expect(screen.queryByRole("heading", { name: "Get Lens running" })).not.toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Set up Lens" }));- expect(await screen.findByRole("heading", { name: "Get Lens running" })).toBeVisible();- expect(screen.getByRole("button", { name: "Connect worker" })).toBeVisible();+ const guide = within(await screen.findByRole("region", { name: "Get Lens running" }));+ expect(guide.getByRole("button", { name: /Connect a worker/ })).toHaveAttribute("aria-expanded", "true");+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();});it("allows request-only investigations without forcing agent instrumentation", async () => {+ dismissLensIntro();serve({ requests: true });const user = userEvent.setup();- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />, {- searchParams: "?tab=investigations",- });- expect(await screen.findByText("Request logs received")).toBeVisible();- expect(screen.getByRole("button", { name: "Connect worker" })).toBeEnabled();- expect(screen.queryByRole("heading", { name: "Before you start" })).not.toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Set up Lens" }));- expect(await screen.findByRole("heading", { name: "Before you start" })).toBeVisible();+ const welcome = renderWorkspace({ searchParams: "?tab=investigations" });+ expect(await screen.findByRole("region", { name: "Get Lens running" })).toBeVisible();expect(screen.getByRole("button", { name: "Connect worker" })).toBeEnabled();- await user.click(screen.getByRole("button", { name: /Enable tracing on the gateway/ }));- expect(screen.getByRole("button", { name: "Continue with request logs" })).toBeEnabled();- await user.click(screen.getByRole("button", { name: /Send your first trace/ }));- await user.click(screen.getByRole("button", { name: "Continue with request logs" }));- const connection = within(await screen.findByRole("dialog", { name: "Connect a worker" }));- await user.click(connection.getByRole("combobox", { name: "Analysis model" }));- await user.click(await screen.findByRole("option", { name: "analysis" }));- await user.click(connection.getByRole("button", { name: "Get install command" }));- const connected = within(await screen.findByRole("dialog", { name: "Worker connected" }));- await user.click(connected.getByRole("button", { name: "New investigation" }));- expect(await screen.findByRole("dialog", { name: "Which activity should we investigate?" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ welcome.unmount();+ renderWorkspace({ searchParams: "?tab=investigations&setup=lens" });+ const intro = within(await screen.findByRole("dialog"));+ expect(await intro.findByRole("heading", { name: "Before you start" })).toBeVisible();+ expect(intro.getByRole("button", { name: "Connect worker" })).toBeEnabled();+ await user.click(intro.getByRole("button", { name: /Enable tracing on the gateway/ }));+ expect(intro.getByRole("button", { name: "Continue with request logs" })).toBeEnabled();+ await user.click(intro.getByRole("button", { name: /Send your first trace/ }));+ await user.click(intro.getByRole("button", { name: "Continue with request logs" }));+ await connectWorkerFromSettings(user);});it("keeps setup recoverable when checking for a first trace fails", async () => {serve({ enabled: true });const user = userEvent.setup();- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />, {- searchParams: "?setup=lens",- });- await screen.findByRole("button", { name: "Check for traces" });+ renderWorkspace({ searchParams: "?setup=lens" });+ const intro = within(await screen.findByRole("dialog"));+ await intro.findByRole("button", { name: "Check for traces" });const normal = network.getMockImplementation()!;network.mockImplementation(async (input, init) => {const path = new URL(String(input), "http://localhost").pathname;if (path === "/v1/traces") return Response.json({ detail: "Trace storage unavailable" }, { status: 503 });return normal(input, init);});- await user.click(screen.getByRole("button", { name: "Check for traces" }));- expect(await screen.findByRole("alert")).toHaveTextContent("Could not check setup");- expect(screen.queryByRole("button", { name: "Continue to worker" })).not.toBeInTheDocument();+ await user.click(intro.getByRole("button", { name: "Check for traces" }));+ expect(await intro.findByRole("alert")).toHaveTextContent("Could not check setup");+ expect(intro.queryByRole("button", { name: "Continue to worker" })).not.toBeInTheDocument();serve({ enabled: true, traces: true });- await user.click(screen.getByRole("button", { name: "Retry" }));- expect(await screen.findByRole("button", { name: "Continue to worker" })).toBeEnabled();- expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ await user.click(intro.getByRole("button", { name: "Retry" }));+ expect(await intro.findByRole("button", { name: "Continue to worker" })).toBeEnabled();+ expect(intro.queryByRole("alert")).not.toBeInTheDocument();});it("keeps request-only users in investigations when an activity refresh fails", async () => {+ dismissLensIntro();serve({ requests: true, connected: true });const user = userEvent.setup();- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />, {- searchParams: "?tab=investigations",- });- expect(await screen.findByText("Request logs received")).toBeVisible();+ renderWorkspace({ searchParams: "?tab=investigations" });+ expect(await screen.findByRole("button", { name: "New investigation" })).toBeEnabled();const normal = network.getMockImplementation()!;network.mockImplementation((input, init) =>new URL(String(input), "http://localhost").pathname === "/lens/activity/available"@@ -201,25 +273,21 @@ describe("Lens setup journey", () => {: normal(input, init),);await act(() => testQueryClient.refetchQueries());- expect(await screen.findByRole("alert")).toHaveTextContent("Could not check recorded activity");- expect(screen.queryByRole("heading", { name: "Get Lens running" })).not.toBeInTheDocument();+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not check setup. Activity unavailable");+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();expect(screen.getByRole("button", { name: "New investigation" })).toBeDisabled();network.mockImplementation(normal);await user.click(screen.getByRole("button", { name: "Retry" }));- expect(await screen.findByText("Request logs received")).toBeVisible();- expect(screen.getByRole("button", { name: "New investigation" })).toBeEnabled();+ await waitFor(() => expect(screen.getByRole("button", { name: "New investigation" })).toBeEnabled());+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();});it("keeps administrator-only setup unavailable to trace viewers", async () => {serve({ enabled: true, traces: true });- const user = userEvent.setup();- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Internal User" readOnly={false} />, {- searchParams: "?setup=lens",- });- expect(await screen.findByText(/A gateway administrator can connect a worker/)).toBeVisible();- expect(screen.getByRole("button", { name: "Connect worker" })).toBeDisabled();- await user.click(screen.getByRole("tab", { name: "Investigations" }));- expect(screen.getByRole("button", { name: "Connect worker" })).toBeDisabled();+ renderWorkspace({ searchParams: "?setup=lens" }, "Internal User");+ const intro = within(await screen.findByRole("dialog"));+ expect(await intro.findByText(/A gateway administrator can connect a worker/)).toBeVisible();+ expect(intro.getByRole("button", { name: "Connect worker" })).toBeDisabled();expect(network.mock.calls.some(([input]) => new URL(String(input), "http://localhost").pathname === "/lens")).toBe(false,);@@ -243,25 +311,23 @@ describe("Lens setup journey", () => {});const user = userEvent.setup();const onUrlUpdate = vi.fn();- renderWithProviders(<LensWorkspace accessToken="setup-token" userRole="Admin" readOnly={false} />, {- searchParams: "?setup=lens",- onUrlUpdate,- });- await user.click(await screen.findByRole("button", { name: "New investigation" }));- const dialog = within(screen.getByRole("dialog"));- fireEvent.change(dialog.getByRole("textbox", { name: "Investigation name" }), {+ renderWorkspace({ searchParams: "?setup=lens", onUrlUpdate });+ const intro = within(await screen.findByRole("dialog"));+ await user.click(await intro.findByRole("button", { name: "New investigation" }));+ const editor = within(await screen.findByRole("region", { name: "New investigation" }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ fireEvent.change(editor.getByRole("textbox", { name: "Investigation name" }), {target: { value: "My first review" },});- await user.click(dialog.getByRole("button", { name: "Continue" }));- await user.click(dialog.getByRole("button", { name: "Continue" }));- await waitFor(() => expect(dialog.getByRole("button", { name: "Run and monitor" })).toBeEnabled());- await user.click(dialog.getByRole("button", { name: "Run and monitor" }));+ await user.click(editor.getByRole("button", { name: "Continue" }));+ await user.click(editor.getByRole("button", { name: "Continue" }));+ await waitFor(() => expect(editor.getByRole("button", { name: "Run and monitor" })).toBeEnabled());+ await user.click(editor.getByRole("button", { name: "Run and monitor" }));expect(await screen.findByRole("heading", { name: "My first review" })).toBeVisible();- expect(screen.queryByRole("heading", { name: "Get Lens running" })).not.toBeInTheDocument();expect(within(screen.getByRole("tablist", { name: "Lens" })).getByRole("tab", { name: "Investigations" }),).toHaveAttribute("aria-selected", "true");- await waitFor(() => expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get("setup")).toBeNull());+ await waitFor(() => expect(setupParam(onUrlUpdate)).toBeNull());const create = network.mock.calls.find(([input, init]) => new URL(String(input), "http://localhost").pathname === "/lens" && init?.method === "POST",);diff --git a/ui/litellm-dashboard/src/components/lens/LensWorkspace.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/LensWorkspace.integration.test.tsxindex 41ce6ed77c6..9e7ece7cf7c 100644--- a/ui/litellm-dashboard/src/components/lens/LensWorkspace.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/lens/LensWorkspace.integration.test.tsx@@ -2,8 +2,10 @@ import { screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { renderWithProviders, testQueryClient } from "@/../tests/test-utils";+import { dismissLensIntro } from "@/../tests/lens-test-utils";import { LensWorkspace } from "./LensWorkspace";-import { createLensDemoData } from "./demo/createLensDemo";+import { lensKeys } from "./data/queries";+import { createLensDemoData } from "./data/demo/fixtures";const lastUrl = (onUrlUpdate: ReturnType<typeof vi.fn>) =>new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? ""));@@ -13,6 +15,9 @@ const expectUrl = (onUrlUpdate: ReturnType<typeof vi.fn>, check: (params: URLSeaconst network = vi.fn<typeof fetch>();beforeEach(() => {testQueryClient.clear();+ window.localStorage.clear();+ window.sessionStorage.clear();+ dismissLensIntro();vi.stubGlobal("fetch", network);network.mockReset();network.mockImplementation(async (input) => {@@ -27,6 +32,7 @@ describe("Lens interactive demo", () => {it("opens without tracing, keeps the sample session in the URL, and restores the live view without mixing data", async () => {const user = userEvent.setup();const onUrlUpdate = vi.fn();+ window.localStorage.clear();renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Internal User" readOnly={false} />, {onUrlUpdate,});@@ -38,7 +44,6 @@ describe("Lens interactive demo", () => {await expectUrl(onUrlUpdate, (url) => expect(url.get("demo")).toBe("true"));expect(screen.queryByRole("button", { name: "Set up tracing" })).not.toBeInTheDocument();network.mockClear();- await user.click(screen.getByRole("button", { name: "Refresh" }));expect(screen.getByText("Where is order #1042?")).toBeVisible();const search = screen.getByRole("combobox", { name: "Search runs" });await user.type(search, "headphones");@@ -85,7 +90,8 @@ describe("Lens interactive demo", () => {await expectUrl(onUrlUpdate, (url) => expect(url.get("view")).toBe("conversation"));expect(network).not.toHaveBeenCalled();await user.click(screen.getByRole("switch", { name: "Demo data" }));- expect(await screen.findByRole("heading", { name: "The gateway that helps your agents improve" })).toBeVisible();+ expect(await screen.findByRole("heading", { name: "Enable tracing" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();await expectUrl(onUrlUpdate, (url) => expect([...url.keys()]).toEqual([]));});@@ -97,7 +103,7 @@ describe("Lens interactive demo", () => {searchParams: "?tab=traces&setup=lens&trace=live-trace&span=live-span&lens=live-lens",onUrlUpdate,});- await user.click(await screen.findByRole("switch", { name: "Demo data" }));+ await user.click(await screen.findByRole("button", { name: "Explore with sample data" }));expect(await screen.findByText("Where is order #1042?")).toBeVisible();await expectUrl(onUrlUpdate, (url) =>expect([...url.entries()]).toEqual([@@ -126,6 +132,7 @@ describe("Lens interactive demo", () => {it("connects findings and history to their original trace without live requests", async () => {const user = userEvent.setup();const onUrlUpdate = vi.fn();+ window.localStorage.clear();renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />, {searchParams: "?tab=investigations",onUrlUpdate,@@ -133,7 +140,7 @@ describe("Lens interactive demo", () => {await user.click(await screen.findByRole("button", { name: "Explore with sample data" }));network.mockClear();await user.click(await screen.findByRole("row", { name: /Repeated lookups leave customers without an answer/ }));- const finding = screen.getByRole("dialog");+ const finding = screen.getByRole("complementary", { name: "Finding details" });expect(within(finding).getByText(/The support agent retries/)).toBeVisible();const summaries = within(finding).getAllByText("support_agent", { exact: true });await user.click(summaries[0]);@@ -146,16 +153,19 @@ describe("Lens interactive demo", () => {expect(await navigator.clipboard.readText()).not.toContain("Authorization");await user.click(screen.getByRole("tab", { name: "Attributes" }));expect(await screen.findByText("gen_ai.agent.name")).toBeVisible();- await user.click(- within(screen.getByRole("dialog", { name: "Original run" })).getByRole("button", { name: "Close" }),- );- await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close" }));+ expect(within(finding).getByRole("button", { name: "Back to finding" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ await user.click(within(finding).getByRole("button", { name: "Back to finding" }));+ expect(within(finding).getByText(/The support agent retries/)).toBeVisible();+ await user.click(within(finding).getByRole("button", { name: "Close finding (Esc)" }));expect(await screen.findByRole("table", { name: "Investigations" })).toBeVisible();expect(network).not.toHaveBeenCalled();await expectUrl(onUrlUpdate, (url) => expect(url.get("demo")).toBe("true"));await expectUrl(onUrlUpdate, (url) => expect(url.has("span")).toBe(false));await user.click(screen.getByRole("switch", { name: "Demo data" }));- expect(await screen.findByRole("heading", { name: "The gateway that helps your agents improve" })).toBeVisible();+ await expectUrl(onUrlUpdate, (url) => expect(url.get("demo")).toBeNull());+ expect(screen.getByRole("switch", { name: "Demo data" })).not.toBeChecked();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();});it("has no demo entry for existing investigations, populated traces, or connecting another agent", async () => {@@ -180,7 +190,7 @@ describe("Lens interactive demo", () => {expect(screen.queryByRole("button", { name: "Set up tracing" })).not.toBeInTheDocument();});- it("offers sample data in the main panel only for the active tab that needs setup", async () => {+ it("shows the header preview only for the active tab that still needs setup", async () => {const user = userEvent.setup();const saved = createLensDemoData().lenses[0];network.mockImplementation(async (input) => {@@ -191,14 +201,13 @@ describe("Lens interactive demo", () => {return Response.json({ data: [], traces: false, requests: false });});renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />);- expect(await screen.findByRole("button", { name: "Explore with sample data" })).toBeVisible();+ expect(await screen.findByRole("button", { name: "Preview sample" })).toBeVisible();const tabs = within(screen.getByRole("tablist", { name: "Lens" }));await user.click(tabs.getByRole("tab", { name: "Investigations" }));expect(await screen.findByRole("row", { name: new RegExp(saved.settings.name) })).toBeVisible();expect(screen.queryByRole("button", { name: "Preview sample" })).not.toBeInTheDocument();- expect(screen.queryByRole("button", { name: "Explore with sample data" })).not.toBeInTheDocument();await user.click(tabs.getByRole("tab", { name: "Traces" }));- await user.click(await screen.findByRole("button", { name: "Explore with sample data" }));+ await user.click(await screen.findByRole("button", { name: "Preview sample" }));expect(await screen.findByRole("table", { name: "Agent runs" })).toBeVisible();expect(screen.queryByRole("button", { name: "Preview sample" })).not.toBeInTheDocument();});@@ -220,7 +229,235 @@ describe("Lens interactive demo", () => {const tab = within(screen.getByRole("tablist", { name: "Lens" })).getByRole("tab", { name: "Investigations" });await waitFor(() => expect(tab).toHaveAccessibleDescription("An investigation is running"));lenses.mockReturnValue([withJob("completed")]);- await testQueryClient.refetchQueries({ queryKey: ["lens", "list"] });+ await testQueryClient.refetchQueries({ queryKey: lensKeys.lists() });await waitFor(() => expect(tab).toHaveAccessibleDescription(""));});++ it("marks the Investigations tab while the inline editor is open and clears it on back", async () => {+ const user = userEvent.setup();+ const saved = createLensDemoData().lenses[0];+ network.mockImplementation(async (input) => {+ const path = new URL(String(input), "http://localhost").pathname;+ if (path === "/lens") return Response.json({ lenses: [saved], workers: [], tracing_enabled: true });+ if (path.endsWith("/runs")) return Response.json(saved.jobs);+ if (path === "/lens/agents") return Response.json([]);+ if (path.startsWith("/lens/preview")) return Response.json({ eligible: 0, selected: 0, executions: [] });+ if (path === "/v1/traces") return Response.json({ detail: "Tracing is not enabled" }, { status: 501 });+ return Response.json({ data: [], traces: true, requests: false });+ });+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />, {+ searchParams: "?tab=investigations&dialog=new",+ });+ const tabs = within(screen.getByRole("tablist", { name: "Lens" }));+ expect(await screen.findByRole("region", { name: "New investigation" })).toBeVisible();+ const tab = tabs.getByRole("tab", { name: /^Investigations/ });+ expect(tab).toHaveAttribute("aria-selected", "true");+ expect(within(tab).getByText("New")).toBeVisible();+ await user.click(screen.getByRole("button", { name: "Back to investigations" }));+ expect(await screen.findByRole("row", { name: new RegExp(saved.settings.name) })).toBeVisible();+ expect(within(tab).queryByText("New")).not.toBeInTheDocument();+ });++ it("adds a quiet Settings tab that manages the worker inline and reflects its health", async () => {+ const user = userEvent.setup();+ const onUrlUpdate = vi.fn();+ const saved = createLensDemoData().lenses[0];+ const worker = {+ id: "worker",+ name: "Worker",+ revoked: false,+ analysis_key_id: "a".repeat(64),+ scope: saved.scope,+ last_seen: new Date().toISOString(),+ };+ const workers = vi.fn(() => [worker]);+ network.mockImplementation(async (input) => {+ const path = new URL(String(input), "http://localhost").pathname;+ if (path === "/lens") return Response.json({ lenses: [saved], workers: workers(), tracing_enabled: true });+ if (path.endsWith("/runs")) return Response.json(saved.jobs);+ if (path === "/v1/traces") return Response.json({ detail: "Tracing is not enabled" }, { status: 501 });+ return Response.json({ data: [], traces: true, requests: false });+ });+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />, { onUrlUpdate });+ const tabs = within(screen.getByRole("tablist", { name: "Lens" }));+ const settings = await tabs.findByRole("tab", { name: "Settings" });+ expect(settings).toHaveAttribute("title", "Worker connected");+ await user.click(settings);+ await expectUrl(onUrlUpdate, (url) => expect(url.get("tab")).toBe("settings"));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ const panel = within(screen.getByRole("region", { name: "Settings" }));+ expect(panel.getByRole("status")).toHaveTextContent("Tracing enabled");+ expect(panel.getByRole("heading", { name: "Analysis worker" })).toBeVisible();+ expect(panel.getByRole("heading", { name: worker.name })).toBeVisible();+ expect(panel.getByText("Connected")).toBeVisible();+ await user.click(panel.getByRole("button", { name: "Edit access" }));+ expect(panel.getByRole("heading", { name: "Analysis access" })).toBeVisible();+ await user.click(panel.getByRole("button", { name: "Cancel" }));+ expect(panel.getByRole("heading", { name: "Analysis worker" })).toBeVisible();+ workers.mockReturnValue([{ ...worker, revoked: true }]);+ await testQueryClient.refetchQueries({ queryKey: lensKeys.lists() });+ await waitFor(() => expect(settings).toHaveAttribute("title", "Connect worker"));+ expect(panel.getByRole("heading", { name: "Connect a worker" })).toBeVisible();+ expect(panel.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();+ await user.click(panel.getByRole("button", { name: "Connect an agent" }));+ await expectUrl(onUrlUpdate, (url) => expect(url.get("tab")).toBe("traces"));+ expect(tabs.getByRole("tab", { name: "Traces" })).toHaveAttribute("aria-selected", "true");+ });++ it("sends the first-time guide's Connect worker into the Settings tab", async () => {+ const user = userEvent.setup();+ const onUrlUpdate = vi.fn();+ network.mockImplementation(async (input) => {+ const path = new URL(String(input), "http://localhost").pathname;+ if (path === "/lens") return Response.json({ lenses: [], workers: [], tracing_enabled: true });+ if (path === "/v1/traces") return Response.json({ data: [{}] });+ return Response.json({ data: [], traces: true, requests: false });+ });+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />, {+ searchParams: "?tab=investigations",+ onUrlUpdate,+ });+ const guide = within(await screen.findByRole("region", { name: "Get Lens running" }));+ await user.click(await guide.findByRole("button", { name: "Connect worker" }));+ await expectUrl(onUrlUpdate, (url) => expect(url.get("tab")).toBe("settings"));+ const panel = within(await screen.findByRole("region", { name: "Settings" }));+ expect(panel.getByRole("heading", { name: "Connect a worker" })).toBeVisible();+ expect(panel.getByRole("button", { name: "Get install command" })).toBeVisible();+ });++ it("keeps a pending worker install across tab switches and offers the first investigation once it connects", async () => {+ const user = userEvent.setup();+ const onUrlUpdate = vi.fn();+ const token = "b".repeat(64);+ const worker = {+ id: "worker",+ name: "Lens worker",+ revoked: false,+ analysis_key_id: token,+ scope: { all_teams: true, api_key_hash: "", team_id: "" },+ last_seen: "1970-01-01T00:00:00Z",+ };+ const workers = vi.fn((): (typeof worker)[] => []);+ network.mockImplementation(async (input, init) => {+ const path = new URL(String(input), "http://localhost").pathname;+ if (path === "/lens") return Response.json({ lenses: [], workers: workers(), tracing_enabled: true });+ if (path === "/lens/workers/register" && init?.method === "POST") {+ workers.mockReturnValue([worker]);+ return Response.json({ token: "lens-test-token", image: "lens-worker:v1", worker });+ }+ if (path === "/key/list") return Response.json({ keys: [{ token, key_alias: "Analysis" }], total_pages: 1 });+ if (path === "/key/info") return Response.json({ info: { models: [], max_budget: null } });+ if (path === "/lens/agents") return Response.json([]);+ if (path.startsWith("/lens/preview")) return Response.json({ eligible: 0, selected: 0, executions: [] });+ if (path === "/v1/traces") return Response.json({ data: [createLensDemoData().runs[0].trace.summary] });+ return Response.json({ data: [], traces: true, requests: false });+ });+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />, {+ searchParams: "?tab=settings",+ onUrlUpdate,+ });+ const panel = within(await screen.findByRole("region", { name: "Settings" }));+ await user.click(panel.getByText("Advanced options"));+ await user.click(panel.getByRole("switch", { name: "Use an existing virtual key" }));+ await user.click(panel.getByRole("combobox", { name: "Charge analysis to" }));+ await user.click(await screen.findByRole("option", { name: "Analysis" }));+ await user.click(panel.getByRole("button", { name: "Get install command" }));+ expect(await panel.findByText("Waiting for your worker to connect…")).toBeInTheDocument();+ const tabs = within(screen.getByRole("tablist", { name: "Lens" }));+ await user.click(tabs.getByRole("tab", { name: "Traces" }));+ await waitFor(() => expect(panel.getByText("Waiting for your worker to connect…")).not.toBeVisible());+ await user.click(tabs.getByRole("tab", { name: "Settings" }));+ expect(panel.getByText("Waiting for your worker to connect…")).toBeVisible();+ expect(panel.getByLabelText("Docker command preview")).toHaveTextContent("LENS_WORKER_TOKEN=lens-test-token");+ workers.mockReturnValue([{ ...worker, last_seen: new Date().toISOString() }]);+ await testQueryClient.refetchQueries({ queryKey: lensKeys.lists() });+ expect(await panel.findByRole("heading", { name: "Worker connected" })).toBeVisible();+ await user.click(panel.getByRole("button", { name: "New investigation" }));+ await expectUrl(onUrlUpdate, (url) => expect(url.get("tab")).toBe("investigations"));+ expect(lastUrl(onUrlUpdate).get("dialog")).toBe("new");+ expect(await screen.findByRole("region", { name: "New investigation" })).toBeVisible();+ });++ it("hides the Settings tab for read-only sessions", async () => {+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly />);+ expect(await screen.findByRole("tablist", { name: "Lens" })).toBeVisible();+ await waitFor(() => expect(network).toHaveBeenCalled());+ expect(screen.queryByRole("tab", { name: "Settings" })).not.toBeInTheDocument();+ });++ it("sends read-only sessions following a Settings link to the default tab", async () => {+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly />, {+ searchParams: "?tab=settings",+ });+ expect(await screen.findByRole("tab", { name: "Traces", selected: true })).toBeVisible();+ });++ it("turns the worker health dot off once heartbeats expire even when polling returns unchanged data", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ const saved = createLensDemoData().lenses[0];+ const worker = {+ id: "worker",+ name: "Worker",+ revoked: false,+ analysis_key_id: "a".repeat(64),+ scope: saved.scope,+ last_seen: new Date().toISOString(),+ };+ network.mockImplementation(async (input) => {+ const path = new URL(String(input), "http://localhost").pathname;+ if (path === "/lens") return Response.json({ lenses: [saved], workers: [worker], tracing_enabled: true });+ if (path === "/v1/traces") return Response.json({ detail: "Tracing is not enabled" }, { status: 501 });+ return Response.json({ data: [], traces: true, requests: false });+ });+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />);+ const tabs = within(screen.getByRole("tablist", { name: "Lens" }));+ const settings = await tabs.findByRole("tab", { name: "Settings" });+ expect(settings).toHaveAttribute("title", "Worker connected");+ await vi.advanceTimersByTimeAsync(130000);+ await waitFor(() => expect(settings).toHaveAttribute("title", "Connect worker"));+ } finally {+ vi.useRealTimers();+ }+ });++ it("polls /lens every 2s while Settings waits for a worker, then drops to the 10s cadence once it connects", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ const saved = createLensDemoData().lenses[0];+ const worker = {+ id: "worker",+ name: "Worker",+ revoked: false,+ analysis_key_id: "a".repeat(64),+ scope: saved.scope,+ last_seen: new Date(Date.now() - 600_000).toISOString(),+ };+ const workers = vi.fn(() => [worker]);+ const listCalls = () =>+ network.mock.calls.filter(([input]) => new URL(String(input), "http://localhost").pathname === "/lens").length;+ network.mockImplementation(async (input) => {+ const path = new URL(String(input), "http://localhost").pathname;+ if (path === "/lens") return Response.json({ lenses: [saved], workers: workers(), tracing_enabled: true });+ if (path === "/v1/traces") return Response.json({ detail: "Tracing is not enabled" }, { status: 501 });+ return Response.json({ data: [], traces: true, requests: false });+ });+ renderWithProviders(<LensWorkspace accessToken="live-token" userRole="Admin" readOnly={false} />, {+ searchParams: "?tab=settings",+ });+ expect(await screen.findByRole("region", { name: "Settings" })).toBeVisible();+ const initial = listCalls();+ await vi.advanceTimersByTimeAsync(2000);+ await waitFor(() => expect(listCalls()).toBe(initial + 1));+ workers.mockReturnValue([{ ...worker, last_seen: new Date().toISOString() }]);+ await vi.advanceTimersByTimeAsync(2000);+ await waitFor(() => expect(listCalls()).toBe(initial + 2));+ await vi.advanceTimersByTimeAsync(2000);+ expect(listCalls()).toBe(initial + 2);+ await vi.advanceTimersByTimeAsync(8000);+ await waitFor(() => expect(listCalls()).toBe(initial + 3));+ } finally {+ vi.useRealTimers();+ }+ });});diff --git a/ui/litellm-dashboard/src/components/lens/LensWorkspace.tsx b/ui/litellm-dashboard/src/components/lens/LensWorkspace.tsxindex 63bef720211..caa8576bdd7 100644--- a/ui/litellm-dashboard/src/components/lens/LensWorkspace.tsx+++ b/ui/litellm-dashboard/src/components/lens/LensWorkspace.tsx@@ -2,37 +2,49 @@import { useId, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { Tabs as TabsPrimitive } from "@base-ui/react/tabs";-import { Activity, Aperture, ArrowUpRight, Loader2, ScanSearch } from "lucide-react";+import { Aperture, ArrowUpRight } from "lucide-react";import AgentTracesPage from "@/components/view_logs/TraceView/AgentTracesPage";+import { Button } from "@/components/ui/button";+import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";import { Switch } from "@/components/ui/switch";import { Tabs, TabsContent } from "@/components/ui/tabs";-import { LensServicesProvider } from "./LensServicesProvider";-import { LensPreviewContext } from "./LensPreviewButton";+import { LensServicesProvider, useLensAccessToken, useLensApi, useLiveLensServices } from "./data/LensServices";+import { LensPreviewContext } from "@/components/view_logs/TraceView/LensPreviewButton";import { isProxyAdminRole, isProxyAdminTierRole } from "@/utils/roles";import { InvestigationsView } from "./investigations/InvestigationsView";-import { createLensDemo } from "./demo/createLensDemo";-import { lensQueries } from "./api/queries";-import { useLensApi } from "./services";-import { investigationActivity, type InvestigationActivity } from "./model/status";+import { LensSettings } from "./settings/LensSettings";+import { createLensDemo } from "./data/demo/createLensDemo";+import { lensQueries } from "./data/queries";+import { LensModeSwitch } from "./LensModeSwitch";+import { frameCard } from "./ui/frame";+import { investigationActivity, listPollInterval } from "./model/status";import { cn } from "@/lib/cva.config";-import { LENS_TABS, useLensRoute, type LensTab } from "./route";-import { Button } from "@/components/ui/button";-import { LensGettingStarted } from "./setup/LensGettingStarted";-import { useLensSetup, type LensSetupState } from "./setup/useLensSetup";+import { useDialogRoute, useLensRoute, type LensDialog, type LensTab } from "./route";+import { LensIntroDialog, useLensIntro } from "./onboarding/LensIntroDialog";+import { OnboardingProvider, type Onboarding } from "./onboarding/OnboardingContext";+import { traceRefOf, useOpenTraceRouting } from "@/components/view_logs/TraceView/traceRouting";type WorkspaceProps = { accessToken: string; userRole: string; readOnly: boolean };export function LensWorkspace(props: WorkspaceProps) {const { demo } = useLensRoute();- return demo ? <SampleSession /> : <LensContent {...props} />;+ return demo ? <SampleSession /> : <LiveSession {...props} />;+}++function LiveSession(props: WorkspaceProps) {+ const services = useLiveLensServices(props.accessToken);+ return (+ <LensServicesProvider services={services}>+ <LensContent userRole={props.userRole} readOnly={props.readOnly} />+ </LensServicesProvider>+ );}function SampleSession() {const [services] = useState(() => createLensDemo());return (<LensServicesProvider services={services}>- <LensContent accessToken="lens-demo" userRole="proxy_admin_viewer" readOnly />+ <LensContent userRole="proxy_admin_viewer" readOnly /></LensServicesProvider>);}@@ -47,234 +59,164 @@ function DemoToggle({ demo, onChange }: { demo: boolean; onChange: (demo: boolea);}-const MODE_ICONS = { traces: Activity, investigations: ScanSearch } as const;--const ACTIVITY_DOT: Record<Exclude<InvestigationActivity, "idle">, { className: string; label: string }> = {- running: { className: "bg-info motion-safe:animate-pulse", label: "An investigation is running" },- queued: { className: "bg-muted-foreground/60", label: "An investigation is queued" },-};--function ActivityDot({ activity }: { activity: InvestigationActivity }) {- if (activity === "idle") return null;- return (- <span- aria-hidden="true"- className={cn(- "size-1.5 rounded-full animate-in fade-in-0 zoom-in-50 duration-300",- ACTIVITY_DOT[activity].className,- )}- />- );-}--const FRAME = {- live: {- card: "border border-foreground/15",- tab: "-mb-px border-x border-t border-foreground/15",- corner: { left: "border-r border-b", right: "border-l border-b", tone: "border-foreground/15" },- },- demo: {- card: "border-2 border-info",- tab: "-mb-0.5 border-x-2 border-t-2 border-info",- corner: { left: "border-r-2 border-b-2", right: "border-l-2 border-b-2", tone: "border-info" },- },-} as const;--const frameOf = (demo: boolean) => FRAME[demo ? "demo" : "live"];--/** Inverted corner joining the tab's side border to the card's top border; plain CSS borders so both snap to the same pixels. */-function NotchCorner({ side, demo }: { side: "left" | "right"; demo: boolean }) {- const { corner } = frameOf(demo);- return (- <span- aria-hidden="true"- className={cn(- "pointer-events-none absolute bottom-0 size-3 overflow-hidden",- side === "left" ? "-left-3" : "-right-3",- )}- >- <span- className={cn(- "block size-full shadow-[0_0_0_12px_var(--card)]",- side === "left" ? "rounded-br-xl" : "rounded-bl-xl",- corner[side],- corner.tone,- )}- />- </span>- );-}--function LensModeSwitch({ activity, demo }: { activity: InvestigationActivity; demo: boolean }) {- return (- <div className={cn("relative z-raised rounded-t-2xl bg-card px-1.5 pt-1.5 pb-[7px]", frameOf(demo).tab)}>- <NotchCorner side="left" demo={demo} />- <NotchCorner side="right" demo={demo} />- <TabsPrimitive.List- aria-label="Lens"- className="relative inline-flex h-9 items-center rounded-full bg-muted/70 p-1"- >- <TabsPrimitive.Indicator className="absolute top-1 bottom-1 left-(--active-tab-left) w-(--active-tab-width) rounded-full bg-background shadow-sm ring-1 ring-border transition-[left,width] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none" />- {Object.entries(LENS_TABS).map(([view, label]) => {- const Icon = MODE_ICONS[view as LensTab];- return (- <TabsPrimitive.Tab- key={view}- value={view}- aria-description={- view === "investigations" && activity !== "idle" ? ACTIVITY_DOT[activity].label : undefined- }- className="relative z-raised inline-flex h-full items-center gap-2 rounded-full px-4 text-sm font-medium text-muted-foreground outline-none transition-colors duration-200 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 data-active:text-foreground"- >- <Icon aria-hidden="true" className="size-4" />- {label}- {view === "investigations" && <ActivityDot activity={activity} />}- </TabsPrimitive.Tab>- );- })}- </TabsPrimitive.List>- </div>- );-}+/** The inline investigation editor marks the tab so the notch says where you are, not just which tab is open. */+const SETUP_LABELS: Partial<Record<LensDialog, string>> = { new: "New", edit: "Editing", duplicate: "Duplicate" };-function useInvestigationActivity(accessToken: string, enabled: boolean): InvestigationActivity {- const api = useLensApi(accessToken);- const { data } = useQuery({ ...lensQueries.list(api, false), enabled });- return investigationActivity(data?.lenses ?? []);+/** The one always-mounted `/lens` observer; every other reader is a plain cache subscriber. */+function useLensOverview(enabled: boolean, settingsOpen: boolean) {+ const api = useLensApi();+ const { data } = useQuery({+ ...lensQueries.list(api),+ enabled,+ refetchInterval: (query) => listPollInterval(query.state.data, settingsOpen, Date.now()),+ });+ return { activity: investigationActivity(data?.lenses ?? []), list: data };}const PANEL ="flex min-h-0 flex-1 flex-col overflow-y-auto animate-in fade-in-0 duration-300 motion-reduce:animate-none";-function LensContent({ accessToken, userRole, readOnly }: WorkspaceProps) {- const { tab, lensId, demo, settingUp, setTab, setLensId, setDemo, setSetup } = useLensRoute();+function LensContent({ userRole, readOnly }: Omit<WorkspaceProps, "accessToken">) {+ const accessToken = useLensAccessToken();+ const { tab, lensId, demo, settingUp, setTab, setDemo, setSetup } = useLensRoute();+ const { dialog, openDialog } = useDialogRoute();+ const { openTrace } = useOpenTraceRouting();const [previewTarget, setPreviewTarget] = useState<HTMLDivElement | null>(null);- const activeTab = tab ?? (lensId ? "investigations" : "traces");- const canInvestigate = isProxyAdminTierRole(userRole);- const setupState = useLensSetup(accessToken, !demo, canInvestigate, settingUp);- const setupLocation = { tab: activeTab, canInvestigate, selected: !!lensId, requested: settingUp };- const showSetup = !demo && needsSetup(setupState, setupLocation);- const showSetupButton = !demo && !showSetup && isProxyAdminRole(userRole);+ const canViewInvestigations = isProxyAdminTierRole(userRole);+ const isAdmin = isProxyAdminRole(userRole);+ const canConfigure = canViewInvestigations && !readOnly;+ const defaultTab = lensId ? "investigations" : "traces";+ const activeTab = tab === "settings" && !canConfigure ? defaultTab : tab ?? defaultTab;+ const intro = useLensIntro({ demo, settingUp });+ const { activity, list } = useLensOverview(+ canViewInvestigations,+ (canConfigure && activeTab === "settings") || intro.open,+ );+ const workers = canConfigure && list ? list.workers : null;+ const leaveIntro = (forever = false) => {+ if (!intro.open) return;+ intro.close(forever);+ setSetup(false);+ };const startSetup = () => {if (!settingUp) setSetup(true);};- const showTraces = () => {- setSetup(false);- setTab(setupState.tracesReady ? "traces" : "investigations");+ const exitIntro = (to: LensTab) => {+ leaveIntro();+ setTab(to);};- const showCreated = (id: string) => {- setSetup(false);- setLensId(id);+ const showSettings = () => {+ leaveIntro();+ setTab("settings");+ };+ const startFirstInvestigation = () => {+ leaveIntro();setTab("investigations");+ openDialog("new");+ };+ const showSentTrace = (trace: TraceSummary) => {+ leaveIntro();+ setTab("traces");+ openTrace(traceRefOf(trace));+ };+ const enterDemo = () => {+ leaveIntro();+ setDemo(true);+ };+ const onboarding: Onboarding = {+ readOnly,+ canViewInvestigations,+ canInvestigate: isAdmin,+ canMintTracingKey: isAdmin,+ connect: showSettings,+ create: startFirstInvestigation,+ openTrace: showSentTrace,};- const activity = useInvestigationActivity(accessToken, canInvestigate);const preview = (view: LensTab) => ({target: previewTarget,- open: !demo && activeTab === view ? () => setDemo(true) : undefined,+ open: !demo && !intro.open && activeTab === view ? enterDemo : undefined,});- const setupContent = setupState.loading ? (- <p role="status" className="flex items-center gap-2 py-8 text-sm text-muted-foreground">- <Loader2 aria-hidden="true" className="size-4 animate-spin" />- Checking Lens setup…- </p>- ) : (- <TabsContent value={activeTab} keepMounted className={cn(PANEL, "p-4")}>- <LensGettingStarted- accessToken={accessToken}- state={setupState}- readOnly={readOnly}- canInvestigate={isProxyAdminRole(userRole)}- canMintTracingKey={isProxyAdminRole(userRole)}- onStart={startSetup}- onExit={showTraces}- onCreated={showCreated}- onDemo={() => setDemo(true)}- />- </TabsContent>- );return (- <main className="flex h-full w-full min-w-0 flex-1 flex-col px-4 pt-3 pb-4">- <Tabs value={activeTab} onValueChange={(value) => setTab(value as LensTab)} className="min-h-0 flex-1 gap-0">- <div className="grid grid-cols-[1fr_auto_1fr] items-end gap-3">- <div className="flex min-w-0 flex-col gap-1 pb-3">- <h1 className="flex items-center gap-2 text-lg font-semibold tracking-tight">- <Aperture aria-hidden="true" className="size-5" strokeWidth={2} />- Lens- </h1>- <p className="truncate text-xs text-muted-foreground">- Trace your agents and investigate what goes wrong.{" "}- <a- href="https://docs.litellm.ai/docs/proxy/lens"- target="_blank"- rel="noopener noreferrer"- className="inline-flex items-center gap-0.5 font-medium text-foreground/80 underline-offset-2 hover:text-foreground hover:underline"- >- Docs- <ArrowUpRight aria-hidden="true" className="size-3" />- </a>- </p>+ <OnboardingProvider value={onboarding}>+ <main className="flex h-full w-full min-w-0 flex-1 flex-col px-4 pt-3 pb-4">+ <Tabs value={activeTab} onValueChange={(value) => setTab(value as LensTab)} className="min-h-0 flex-1 gap-0">+ <div className="grid grid-cols-[1fr_auto_1fr] items-end gap-3">+ <div className="flex min-w-0 flex-col gap-1 pb-3">+ <h1 className="flex items-center gap-2 text-lg font-semibold tracking-tight">+ <Aperture aria-hidden="true" className="size-5" strokeWidth={2} />+ Lens+ </h1>+ <p className="truncate text-xs text-muted-foreground">+ Trace your agents and investigate what goes wrong.{" "}+ <a+ href="https://docs.litellm.ai/docs/proxy/lens"+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-0.5 font-medium text-foreground/80 underline-offset-2 hover:text-foreground hover:underline"+ >+ Docs+ <ArrowUpRight aria-hidden="true" className="size-3" />+ </a>+ </p>+ </div>+ <LensModeSwitch+ activity={activity}+ demo={demo}+ workers={workers}+ setup={activeTab === "investigations" && dialog ? SETUP_LABELS[dialog] : undefined}+ />+ <div className="flex min-w-0 flex-wrap items-center justify-end gap-3 pb-3">+ <div ref={setPreviewTarget} />+ <DemoToggle demo={demo} onChange={(next) => (next ? enterDemo() : setDemo(false))} />+ </div></div>- <LensModeSwitch activity={activity} demo={demo} />- <div className="flex min-w-0 flex-wrap items-center justify-end gap-3 pb-3">- {showSetupButton && (- <Button variant="outline" size="sm" onClick={startSetup}>- Set up Lens- </Button>+ <div className={frameCard({ session: demo ? "demo" : "live" })}>+ <TabsContent value="traces" keepMounted className={PANEL}>+ <LensPreviewContext.Provider value={preview("traces")}>+ <AgentTracesPage+ accessToken={accessToken}+ isActive={activeTab === "traces"}+ readOnly={readOnly}+ canMintTracingKey={isAdmin}+ />+ </LensPreviewContext.Provider>+ </TabsContent>+ <TabsContent value="investigations" className={PANEL}>+ <LensPreviewContext.Provider value={preview("investigations")}>+ {canViewInvestigations ? (+ <InvestigationsView readOnly={readOnly || !isAdmin} />+ ) : (+ <p className="py-6 text-sm text-muted-foreground">+ Investigations require proxy administrator access. You can still view your traces.+ </p>+ )}+ </LensPreviewContext.Provider>+ </TabsContent>+ {workers && list && (+ <TabsContent value="settings" keepMounted className={cn(PANEL, "p-6")}>+ <LensSettings+ list={list}+ workerReadyAction={+ list.lenses.length === 0 ? (+ <Button className="w-full" onClick={startFirstInvestigation}>+ New investigation+ </Button>+ ) : undefined+ }+ onOpenTraces={() => setTab("traces")}+ />+ </TabsContent>)}- <div ref={setPreviewTarget} />- <DemoToggle demo={demo} onChange={setDemo} /></div>- </div>- <div className={cn("flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl bg-card", frameOf(demo).card)}>- {showSetup ? (- setupContent- ) : (- <>- <TabsContent value="traces" keepMounted className={PANEL}>- <LensPreviewContext.Provider value={preview("traces")}>- <AgentTracesPage- accessToken={accessToken}- isActive={activeTab === "traces"}- readOnly={readOnly}- canMintTracingKey={isProxyAdminRole(userRole)}- />- </LensPreviewContext.Provider>- </TabsContent>- <TabsContent value="investigations" className={cn(PANEL, "p-4")}>- <LensPreviewContext.Provider value={preview("investigations")}>- {canInvestigate ? (- <InvestigationsView- active={activeTab === "investigations"}- accessToken={accessToken}- readOnly={readOnly || !isProxyAdminRole(userRole)}- />- ) : (- <p className="py-6 text-sm text-muted-foreground">- Investigations require proxy administrator access. You can still view your traces.- </p>- )}- </LensPreviewContext.Provider>- </TabsContent>- </>- )}- </div>- </Tabs>- </main>+ </Tabs>+ <LensIntroDialog+ open={intro.open}+ onClose={leaveIntro}+ onStart={startSetup}+ onExit={exitIntro}+ onDemo={enterDemo}+ />+ </main>+ </OnboardingProvider>);}--function needsSetup(- state: LensSetupState,- {- tab,- canInvestigate,- selected,- requested,- }: { tab: LensTab; canInvestigate: boolean; selected: boolean; requested: boolean },-) {- if (requested) return true;- if (!state.missingTraces) return false;- if (tab === "traces") return true;- const hasActivity = state.hasInvestigations || state.hasRequests || selected;- return canInvestigate && !hasActivity;-}diff --git a/ui/litellm-dashboard/src/components/lens/api/mutations.ts b/ui/litellm-dashboard/src/components/lens/api/mutations.tsdeleted file mode 100644index 0bc9109b1bb..00000000000--- a/ui/litellm-dashboard/src/components/lens/api/mutations.ts+++ /dev/null@@ -1,93 +0,0 @@-"use client";--import { validateWorkerAddress, analysisAccessSchema, type AnalysisAccess } from "../setup/worker/workerSchema";--import { useMutation } from "@tanstack/react-query";-import type { Lens, Settings, WorkerCreated } from "../model/types";--import type { LensApi } from "./service";-import { useLensApi } from "../services";--export type LensWrite = (api: LensApi) => Promise<unknown>;--export function useLensUpdate(accessToken: string) {- const api = useLensApi(accessToken);- return useMutation({ retry: false, mutationFn: (write: LensWrite) => write(api) });-}--export function useSaveLens(accessToken: string) {- const api = useLensApi(accessToken);- return useMutation({- retry: false,- mutationFn: ({ id, settings }: { id?: string; settings: Settings }): Promise<Lens> => api.saveLens(id, settings),- });-}--export function useRevokeWorker(accessToken: string) {- const api = useLensApi(accessToken);- return useMutation({ retry: false, mutationFn: (id: string) => api.revokeWorker(id) });-}--export async function createAnalysisKey(api: LensApi, access: AnalysisAccess): Promise<string> {- const parsed = analysisAccessSchema.safeParse(access);- if (!parsed.success) throw new Error(parsed.error.issues[0].message);- const result = await api.generateAnalysisKey(parsed.data);- if (!result.token_id) throw new Error("The proxy did not return the new key's ID");- return result.token_id;-}--export function usePrepareWorker(- accessToken: string,- { onChanged, onPrepared }: { onChanged: () => void; onPrepared: (created: WorkerCreated | null) => void },-) {- const api = useLensApi(accessToken);- return useMutation({- retry: false,- mutationFn: async ({- address,- useExisting,- analysisKey,- access,- editingWorker,- }: {- address: string;- useExisting: boolean;- analysisKey: string | null;- access: AnalysisAccess;- editingWorker: string | null;- }) => {- let newKey: string | null = null;- try {- validateWorkerAddress(address);- const keyId = useExisting ? analysisKey : await createAnalysisKey(api, access);- if (!useExisting) newKey = keyId;- if (editingWorker) {- await api.setWorkerBillingKey(editingWorker, keyId);- onPrepared(null);- onChanged();- return null;- }- const created = await api.registerWorker(keyId);- onPrepared(created);- onChanged();- return created;- } catch (e) {- const message = e instanceof Error ? e.message : "Could not create credential";- if (newKey) {- try {- const current = await api.lenses();- if (!current.workers.some((worker) => !worker.revoked && worker.analysis_key_id === newKey)) {- await api.deleteKeys([newKey]);- }- onChanged();- } catch {- throw new Error(- `${message}. Could not confirm cleanup. Check the Lens analysis key in Virtual Keys before retrying.`,- );- }- }- throw new Error(message);- }- },- });-}diff --git a/ui/litellm-dashboard/src/components/lens/data/LensServices.tsx b/ui/litellm-dashboard/src/components/lens/data/LensServices.tsxnew file mode 100644index 00000000000..8abeab16a78--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/data/LensServices.tsx@@ -0,0 +1,40 @@+"use client";++import { createContext, useContext, useMemo, type ReactNode } from "react";+import { apiClient } from "@/components/networking";+import { liveTracesApi, TracesApiContext, type TracesApi } from "@/components/view_logs/TraceView/tracesApi";+import { liveLensApi, type LensApi } from "./service";++export interface LensServices {+ readonly accessToken: string;+ readonly lens: LensApi;+ readonly traces: TracesApi;+}++const LensServicesContext = createContext<LensServices | null>(null);++export function liveLensServices(accessToken: string): LensServices {+ return { accessToken, lens: liveLensApi(apiClient, accessToken), traces: liveTracesApi(accessToken) };+}++function useLensServices(): LensServices {+ const provided = useContext(LensServicesContext);+ if (!provided) throw new Error("Lens services need a LensServicesProvider above them");+ return provided;+}++export const useLensApi = (): LensApi => useLensServices().lens;++export const useLensAccessToken = (): string => useLensServices().accessToken;++export function useLiveLensServices(accessToken: string): LensServices {+ return useMemo(() => liveLensServices(accessToken), [accessToken]);+}++export function LensServicesProvider({ services, children }: { services: LensServices; children: ReactNode }) {+ return (+ <LensServicesContext.Provider value={services}>+ <TracesApiContext.Provider value={services.traces}>{children}</TracesApiContext.Provider>+ </LensServicesContext.Provider>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/demo/createLensDemo.test.ts b/ui/litellm-dashboard/src/components/lens/data/demo/createLensDemo.test.tssimilarity index 95%rename from ui/litellm-dashboard/src/components/lens/demo/createLensDemo.test.tsrename to ui/litellm-dashboard/src/components/lens/data/demo/createLensDemo.test.tsindex 61879a10365..be7b39607f7 100644--- a/ui/litellm-dashboard/src/components/lens/demo/createLensDemo.test.ts+++ b/ui/litellm-dashboard/src/components/lens/data/demo/createLensDemo.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from "vitest";-import { createLensDemo, createLensDemoData } from "./createLensDemo";-import { evidenceTarget } from "../model/findings";+import { createLensDemo } from "./createLensDemo";+import { createLensDemoData } from "./fixtures";+import { evidenceTarget } from "../../model/findings";describe("Lens demo data", () => {it("links every finding to the quoted original step and assessed run", () => {diff --git a/ui/litellm-dashboard/src/components/lens/data/demo/createLensDemo.ts b/ui/litellm-dashboard/src/components/lens/data/demo/createLensDemo.tsnew file mode 100644index 00000000000..97ab6c84e91--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/data/demo/createLensDemo.ts@@ -0,0 +1,76 @@+import { ApiError } from "@/lib/http/client";+import type { TracesApi } from "@/components/view_logs/TraceView/tracesApi";+import type { LensServices } from "../LensServices";+import type { LensApi } from "../service";+import { createLensDemoData, type LensDemoData } from "./fixtures";++const notInDemo = (): Promise<never> =>+ Promise.reject(new ApiError("This item is not in the demo", 404, { detail: "This item is not in the demo" }));+const readOnly = (): Promise<never> =>+ Promise.reject(new ApiError("Demo data is read-only", 403, { detail: "Demo data is read-only" }));+const found = <T>(value: T | undefined): Promise<T> => (value === undefined ? notInDemo() : Promise.resolve(value));++function demoLensApi(data: LensDemoData): LensApi {+ const jobs = (lensId: string) => data.lenses.find((lens) => lens.id === lensId)?.jobs;+ return {+ scope: "demo",+ lenses: async () => ({ lenses: data.lenses, workers: [], tracing_enabled: true }),+ activity: async () => ({ traces: true, requests: false }),+ runs: (lensId, offset) => found(jobs(lensId)?.slice(offset)),+ run: (lensId, jobId) => found(jobs(lensId)?.find((job) => job.id === jobId)),+ execution: notInDemo,+ sample: notInDemo,+ agents: notInDemo,+ models: async () => ({ data: [] }),+ modelDetails: async () => ({ data: [] }),+ keys: notInDemo,+ keyInfo: notInDemo,+ saveLens: readOnly,+ startRun: readOnly,+ watchAll: async () => ({ watching: [], skipped: [] }),+ cancelRun: readOnly,+ reviewFinding: readOnly,+ registerWorker: readOnly,+ setWorkerBillingKey: readOnly,+ revokeWorker: readOnly,+ generateAnalysisKey: readOnly,+ deleteKeys: readOnly,+ };+}++function demoTracesApi(data: LensDemoData): TracesApi {+ const run = (traceId: string) => data.runs.find(({ trace }) => trace.summary.trace_id === traceId);+ return {+ live: false,+ handoff: (traceId, spanId) => {+ const found = run(traceId);+ const step = spanId ? found?.details.find((span) => span.span_id === spanId) : found;+ return { text: JSON.stringify(step, null, 2), copied: spanId ? "Step copied" : "Trace copied" };+ },+ list: async ({ startMs, endMs }) => ({+ data: data.runs+ .map((item) => item.trace.summary)+ .filter((trace) => Date.parse(trace.start_time) >= startMs && Date.parse(trace.start_time) <= endMs),+ next_cursor: null,+ }),+ anyRecorded: async () => data.runs.length > 0,+ trace: (traceId) => found(run(traceId)?.trace),+ span: (traceId, spanId) => found(run(traceId)?.details.find((span) => span.span_id === spanId)),+ spanError: async (traceId, spanId) => {+ const span = run(traceId)?.trace.spans.find((item) => item.span_id === spanId);+ return found(+ span && {+ span_id: span.span_id,+ message: span.error ?? "",+ total_chars: span.error?.length ?? 0,+ next_cursor: null,+ },+ );+ },+ };+}++export function createLensDemo(now = Date.now()): LensServices {+ const data = createLensDemoData(now);+ return { accessToken: "lens-demo", lens: demoLensApi(data), traces: demoTracesApi(data) };+}diff --git a/ui/litellm-dashboard/src/components/lens/demo/createLensDemo.ts b/ui/litellm-dashboard/src/components/lens/data/demo/fixtures.tssimilarity index 77%rename from ui/litellm-dashboard/src/components/lens/demo/createLensDemo.tsrename to ui/litellm-dashboard/src/components/lens/data/demo/fixtures.tsindex b5071aaa9fe..51dc89e6fa6 100644--- a/ui/litellm-dashboard/src/components/lens/demo/createLensDemo.ts+++ b/ui/litellm-dashboard/src/components/lens/data/demo/fixtures.ts@@ -1,11 +1,6 @@-import { ApiError } from "@/lib/http/client";-import type { TracesApi } from "@/components/view_logs/TraceView/tracesApi";-import type { LensServices } from "../services";-import type { LensApi } from "../api/service";import type { Trace, Span, SpanDetail } from "@/components/view_logs/TraceView/traceTypes";-import type { Lens, Finding, Job, Settings } from "../model/types";+import type { Lens, Finding, Job, Settings } from "../../model/types";import { withReleaseCases } from "./lensDemoLongTrace";-import { scenarios, type Scenario } from "./scenarios";const executionId = (traceId: string) => btoa(JSON.stringify(["traces", "", traceId]));@@ -336,74 +331,3 @@ export function createLensDemoData(now = Date.now()) {});return { runs, lenses };}--const notInDemo = (): Promise<never> =>- Promise.reject(new ApiError("This item is not in the demo", 404, { detail: "This item is not in the demo" }));-const readOnly = (): Promise<never> =>- Promise.reject(new ApiError("Demo data is read-only", 403, { detail: "Demo data is read-only" }));-const found = <T>(value: T | undefined): Promise<T> => (value === undefined ? notInDemo() : Promise.resolve(value));--function demoLensApi(data: LensDemoData): LensApi {- const jobs = (lensId: string) => data.lenses.find((lens) => lens.id === lensId)?.jobs;- return {- scope: "demo",- lenses: async () => ({ lenses: data.lenses, workers: [], tracing_enabled: true }),- activity: async () => ({ traces: true, requests: false }),- runs: (lensId, offset) => found(jobs(lensId)?.slice(offset)),- run: (lensId, jobId) => found(jobs(lensId)?.find((job) => job.id === jobId)),- execution: notInDemo,- sample: notInDemo,- agents: notInDemo,- models: async () => ({ data: [] }),- modelDetails: async () => ({ data: [] }),- keys: notInDemo,- keyInfo: notInDemo,- saveLens: readOnly,- startRun: readOnly,- watchAll: async () => ({ watching: [], skipped: [] }),- cancelRun: readOnly,- reviewFinding: readOnly,- registerWorker: readOnly,- setWorkerBillingKey: readOnly,- revokeWorker: readOnly,- generateAnalysisKey: readOnly,- deleteKeys: readOnly,- };-}--function demoTracesApi(data: LensDemoData): TracesApi {- const run = (traceId: string) => data.runs.find(({ trace }) => trace.summary.trace_id === traceId);- return {- live: false,- handoff: (traceId, spanId) => {- const found = run(traceId);- const step = spanId ? found?.details.find((span) => span.span_id === spanId) : found;- return { text: JSON.stringify(step, null, 2), copied: spanId ? "Step copied" : "Trace copied" };- },- list: async ({ startMs, endMs }) => ({- data: data.runs- .map((item) => item.trace.summary)- .filter((trace) => Date.parse(trace.start_time) >= startMs && Date.parse(trace.start_time) <= endMs),- next_cursor: null,- }),- anyRecorded: async () => data.runs.length > 0,- trace: (traceId) => found(run(traceId)?.trace),- span: (traceId, spanId) => found(run(traceId)?.details.find((span) => span.span_id === spanId)),- spanError: async (traceId, spanId) => {- const span = run(traceId)?.trace.spans.find((item) => item.span_id === spanId);- return found(- span && {- span_id: span.span_id,- message: span.error ?? "",- total_chars: span.error?.length ?? 0,- next_cursor: null,- },- );- },- };-}--export function createLensDemo(now = Date.now()): LensServices {- const data = createLensDemoData(now);- return { lens: demoLensApi(data), traces: demoTracesApi(data) };-}diff --git a/ui/litellm-dashboard/src/components/lens/demo/lensDemoLongTrace.ts b/ui/litellm-dashboard/src/components/lens/data/demo/lensDemoLongTrace.tssimilarity index 100%rename from ui/litellm-dashboard/src/components/lens/demo/lensDemoLongTrace.tsrename to ui/litellm-dashboard/src/components/lens/data/demo/lensDemoLongTrace.tsdiff --git a/ui/litellm-dashboard/src/components/lens/demo/scenarios.ts b/ui/litellm-dashboard/src/components/lens/data/demo/scenarios.tssimilarity index 100%rename from ui/litellm-dashboard/src/components/lens/demo/scenarios.tsrename to ui/litellm-dashboard/src/components/lens/data/demo/scenarios.tsdiff --git a/ui/litellm-dashboard/src/components/lens/data/mutations.ts b/ui/litellm-dashboard/src/components/lens/data/mutations.tsnew file mode 100644index 00000000000..1a4a5ffca8a--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/data/mutations.ts@@ -0,0 +1,56 @@+"use client";++import { useMutation, useQueryClient } from "@tanstack/react-query";+import type { Lens, LensList, Settings } from "../model/types";++import type { LensApi } from "./service";+import { lensKeys } from "./queries";+import { useLensApi } from "./LensServices";++export type LensWrite = (api: LensApi) => Promise<unknown>;++export function useInvalidateLenses() {+ const api = useLensApi();+ const client = useQueryClient();+ return () =>+ Promise.all([+ client.invalidateQueries({ queryKey: lensKeys.list(api.scope) }),+ client.invalidateQueries({ queryKey: lensKeys.histories() }),+ ]);+}++export function useLensUpdate() {+ const api = useLensApi();+ const invalidate = useInvalidateLenses();+ return useMutation({ retry: false, mutationFn: (write: LensWrite) => write(api), onSettled: invalidate });+}++function upsertLens(list: LensList | undefined, saved: Lens): LensList | undefined {+ if (!list) return list;+ const known = list.lenses.some((lens) => lens.id === saved.id);+ const lenses = known ? list.lenses.map((lens) => (lens.id === saved.id ? saved : lens)) : [...list.lenses, saved];+ return { ...list, lenses };+}++export function useSaveLens() {+ const api = useLensApi();+ const client = useQueryClient();+ return useMutation({+ retry: false,+ mutationFn: ({ id, settings }: { id?: string; settings: Settings }): Promise<Lens> => api.saveLens(id, settings),+ onSuccess: (saved) => {+ client.setQueryData<LensList>(lensKeys.list(api.scope), (current) => upsertLens(current, saved));+ return client.invalidateQueries({ queryKey: lensKeys.list(api.scope) });+ },+ });+}++export function useRevokeWorker() {+ const api = useLensApi();+ const client = useQueryClient();+ return useMutation({+ retry: false,+ mutationFn: (id: string) => api.revokeWorker(id),+ onSettled: () => client.invalidateQueries({ queryKey: lensKeys.list(api.scope) }),+ });+}diff --git a/ui/litellm-dashboard/src/components/lens/api/queries.ts b/ui/litellm-dashboard/src/components/lens/data/queries.tssimilarity index 70%rename from ui/litellm-dashboard/src/components/lens/api/queries.tsrename to ui/litellm-dashboard/src/components/lens/data/queries.tsindex b6ddf402a16..05cb98fdb2b 100644--- a/ui/litellm-dashboard/src/components/lens/api/queries.ts+++ b/ui/litellm-dashboard/src/components/lens/data/queries.ts@@ -1,9 +1,12 @@-import { infiniteQueryOptions, queryOptions, type Query } from "@tanstack/react-query";-import type { LensList, Settings, ActivitySelection } from "../model/types";+import { infiniteQueryOptions, keepPreviousData, queryOptions } from "@tanstack/react-query";+import { hasActiveJob } from "../model/status";+import type { Sample, Settings, ActivitySelection, Job } from "../model/types";import type { KeyPage, LensApi } from "./service";export type { Key } from "./service";+type Activity = Awaited<ReturnType<LensApi["activity"]>>;+export const lensKeys = {all: ["lens"] as const,lists: () => [...lensKeys.all, "list"] as const,@@ -19,29 +22,20 @@ export const lensKeys = {models: (scope: string) => [...lensKeys.all, "models", { scope }] as const,modelDetails: (scope: string) => [...lensKeys.all, "model-details", { scope }] as const,activity: (scope: string) => [...lensKeys.all, "activity-available", { scope }] as const,- discovery: (scope: string, source: Settings["source"], hours: number | undefined, asOf: string) =>- [...lensKeys.all, "discovery", { scope, source, hours, asOf }] as const,- preview: (scope: string, selection: ActivitySelection, offset: number, asOf: string) =>- [...lensKeys.all, "preview", { scope, selection, offset, asOf }] as const,- agents: (scope: string, asOf: string) => [...lensKeys.all, "agents", { scope, asOf }] as const,+ discoveries: () => [...lensKeys.all, "discovery"] as const,+ discovery: (scope: string, source: Settings["source"], hours: number | undefined) =>+ [...lensKeys.discoveries(), { scope, source, hours }] as const,+ preview: (scope: string, selection: ActivitySelection, asOf: string) =>+ [...lensKeys.all, "preview", { scope, selection, asOf }] as const,+ agents: (scope: string) => [...lensKeys.all, "agents", { scope }] as const,analysisKeys: (scope: string, query: string) => [...lensKeys.all, "analysis-keys", { scope, query }] as const,analysisKeyInfo: (scope: string, keyId: string | undefined) =>[...lensKeys.all, "analysis-key-info", { scope, keyId }] as const,};export const lensQueries = {- list(api: LensApi, workerSetup: boolean) {- const options = {- queryKey: lensKeys.list(api.scope),- queryFn: () => api.lenses(),- refetchInterval: (current: Query<LensList>): number | false => {- const running = current.state.data?.lenses.some((item) =>- item.jobs.some((job) => ["queued", "running"].includes(job.status)),- );- return workerSetup || running ? 2000 : 10000;- },- };- return queryOptions(options);+ list(api: LensApi) {+ return queryOptions({ queryKey: lensKeys.list(api.scope), queryFn: () => api.lenses(), staleTime: 5000 });},models(api: LensApi) {return queryOptions({ queryKey: lensKeys.models(api.scope), queryFn: () => api.models() });@@ -54,7 +48,8 @@ export const lensQueries = {queryKey: lensKeys.activity(api.scope),queryFn: () => api.activity(),enabled: loaded,- refetchInterval: 5000,+ refetchInterval: ({ state }: { state: { data?: Activity } }) =>+ state.data?.traces && state.data.requests ? false : 5000,};return queryOptions(options);},@@ -63,7 +58,8 @@ export const lensQueries = {queryKey: lensKeys.history(api.scope, lensId, historyOffset),enabled: !!lensId,queryFn: () => api.runs(lensId as string, historyOffset),- refetchInterval: 10000,+ refetchInterval: ({ state }: { state: { data?: Job[] } }) =>+ state.data && hasActiveJob(state.data) ? 10000 : false,};return queryOptions(options);},@@ -96,31 +92,32 @@ export const lensQueries = {};return queryOptions(options);},- discovery(api: LensApi, { value, asOf, enabled }: { value: ActivitySelection; asOf: string; enabled: boolean }) {+ discovery(api: LensApi, { value, enabled }: { value: ActivitySelection; enabled: boolean }) {const unfiltered = { source: value.source, service: "", filters: [], lookback_hours: value.lookback_hours };const options = {- queryKey: lensKeys.discovery(api.scope, value.source, value.lookback_hours, asOf),- queryFn: () => api.sample(unfiltered, 0, asOf),+ queryKey: lensKeys.discovery(api.scope, value.source, value.lookback_hours),+ queryFn: () => api.sample(unfiltered, 0, new Date().toISOString()),staleTime: 60000,enabled,};return queryOptions(options);},- preview(- api: LensApi,- { scope, offset, asOf, enabled }: { scope: ActivitySelection; offset: number; asOf: string; enabled: boolean },- ) {+ preview(api: LensApi, { scope, asOf, enabled }: { scope: ActivitySelection; asOf: string; enabled: boolean }) {const options = {- queryKey: lensKeys.preview(api.scope, scope, offset, asOf),- queryFn: () => api.sample(scope, offset, asOf),+ queryKey: lensKeys.preview(api.scope, scope, asOf),+ initialPageParam: 0,+ queryFn: ({ pageParam }: { pageParam: number }) => api.sample(scope, pageParam, asOf),+ getNextPageParam: (lastPage: Sample) => lastPage.next_offset ?? undefined,enabled,staleTime: 30000,+ gcTime: 60_000,+ placeholderData: keepPreviousData,};- return queryOptions(options);+ return infiniteQueryOptions(options);},- agents(api: LensApi, asOf: string, source: Settings["source"]) {+ agents(api: LensApi, source: Settings["source"]) {const options = {- queryKey: lensKeys.agents(api.scope, asOf),+ queryKey: lensKeys.agents(api.scope),queryFn: () => api.agents(),enabled: source !== "requests",staleTime: 60000,diff --git a/ui/litellm-dashboard/src/components/lens/api/service.ts b/ui/litellm-dashboard/src/components/lens/data/service.tssimilarity index 96%rename from ui/litellm-dashboard/src/components/lens/api/service.tsrename to ui/litellm-dashboard/src/components/lens/data/service.tsindex 0383efa3e20..6f23aa0dda7 100644--- a/ui/litellm-dashboard/src/components/lens/api/service.ts+++ b/ui/litellm-dashboard/src/components/lens/data/service.ts@@ -1,9 +1,17 @@import { z } from "zod";-import type { RunWindow } from "../investigations/detail/RunNowDialog";import type { ApiClient } from "@/lib/http/client";import type { components } from "@/lib/http/schema";-import type { ActivitySelection, Job, Lens, LensList, Sample, Settings, WorkerCreated } from "../model/types";-import type { AnalysisModelInfo } from "../setup/fields/analysisModels";+import type {+ ActivitySelection,+ AnalysisModelInfo,+ Job,+ Lens,+ LensList,+ RunWindow,+ Sample,+ Settings,+ WorkerCreated,+} from "../model/types";export type ExecutionContent = components["schemas"]["ExecutionContent"];export type FindingStatus = components["schemas"]["FindingUpdate"]["status"];diff --git a/ui/litellm-dashboard/src/components/lens/hooks/useLensReadiness.ts b/ui/litellm-dashboard/src/components/lens/hooks/useLensReadiness.tsnew file mode 100644index 00000000000..a41c9b909c3--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/hooks/useLensReadiness.ts@@ -0,0 +1,58 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { isTracingNotEnabled, useTraceAvailability } from "@/components/view_logs/TraceView/useAgentTraces";+import { useLensAccessToken, useLensApi } from "../data/LensServices";+import { lensQueries } from "../data/queries";+import { readiness, type Readiness, type ReadinessInput } from "../model/readiness";+import { useWorkerConnected } from "./useWorkerConnected";++export interface LensReadiness extends Readiness {+ readonly loading: boolean;+ readonly checking: boolean;+ readonly error: string | undefined;+ refresh(): void;+}++export function useLensReadiness(canInvestigate: boolean): LensReadiness {+ const api = useLensApi();+ const accessToken = useLensAccessToken();+ const traces = useTraceAvailability(accessToken, true);+ const list = useQuery({ ...lensQueries.list(api), enabled: canInvestigate });+ const activity = useQuery(lensQueries.activity(api, canInvestigate && list.isSuccess));+ const connected = useWorkerConnected(list.data?.workers);+ const tracesDisabled = isTracingNotEnabled(traces.error);+ const input: ReadinessInput = {+ traces: {+ recorded: traces.data,+ failed: traces.isError,+ disabled: tracesDisabled,+ checked: traces.isSuccess,+ },+ tracingConfigured: list.data?.tracing_enabled ?? false,+ activity: activity.data,+ activityError: activity.error,+ connected,+ listError: list.error,+ investigations: list.data?.lenses.length ?? 0,+ };+ const state = readiness(input);+ const activityError = state.activityReady ? null : (tracesDisabled ? null : traces.error) || activity.error;+ const error = list.error || activityError;+ const loadingTraces = !state.activityReady && traces.isPending;+ const loadingActivity = !state.activityReady && list.isSuccess && activity.isPending;+ const loadingInvestigations = canInvestigate && (list.isPending || loadingActivity);+ const refresh = () => {+ void traces.refetch();+ if (!canInvestigate) return;+ void list.refetch();+ void activity.refetch();+ };+ return {+ ...state,+ loading: loadingTraces || loadingInvestigations,+ checking: traces.isFetching || list.isFetching || activity.isFetching,+ error: error?.message,+ refresh,+ };+}diff --git a/ui/litellm-dashboard/src/components/lens/hooks/useWorkerConnected.ts b/ui/litellm-dashboard/src/components/lens/hooks/useWorkerConnected.tsnew file mode 100644index 00000000000..19c38a98144--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/hooks/useWorkerConnected.ts@@ -0,0 +1,12 @@+"use client";++import { useNow } from "@/hooks/useNow";+import { workerConnected } from "../model/status";+import type { LensList } from "../model/types";++const HEARTBEAT_TICK_MS = 5000;++export function useWorkerConnected(workers: LensList["workers"] | null | undefined): boolean {+ const now = useNow(HEARTBEAT_TICK_MS);+ return workers?.some((worker) => workerConnected(worker, now)) ?? false;+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/Evidence.tsx b/ui/litellm-dashboard/src/components/lens/investigations/Evidence.tsxnew file mode 100644index 00000000000..1023e636537--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/Evidence.tsx@@ -0,0 +1,131 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";++import { Inspector } from "@/components/shared/Inspector";+import { Button } from "@/components/ui/button";+import { RunView } from "@/components/view_logs/TraceView/TraceDrawer";+import { useLocalRunSelection } from "@/components/view_logs/TraceView/traceRouting";++import { lensQueries } from "../data/queries";+import { useLensAccessToken, useLensApi } from "../data/LensServices";+import { evidenceTarget, type EvidenceTarget } from "../model/findings";+import type { EvidenceRef } from "../route";++const SECTION = 8000;++export interface EvidenceViewProps {+ readonly lensId: string;+ readonly evidence: EvidenceRef;+ /** Shown as a back link above the evidence when it is stacked over something else. */+ readonly backLabel?: string;+ readonly onBack?: () => void;+}++/** The original trace step or logged request a piece of evidence points at, filling the panel. */+export function EvidenceView({ lensId, evidence, backLabel, onBack }: EvidenceViewProps) {+ const target = evidenceTarget(evidence.id);+ return (+ <div className="flex min-h-0 flex-1 flex-col" data-testid="evidence-view">+ {onBack && backLabel && (+ <div className="flex h-9 shrink-0 items-center border-b px-3">+ <Inspector.BackLink label={backLabel} onClick={onBack} />+ </div>+ )}+ <EvidenceBody+ key={`${evidence.id}:${evidence.span}`}+ lensId={lensId}+ target={target}+ evidence={evidence}+ onBack={onBack}+ />+ </div>+ );+}++function EvidenceBody({+ lensId,+ target,+ evidence,+ onBack = () => {},+}: {+ lensId: string;+ target: EvidenceTarget | null;+ evidence: EvidenceRef;+ onBack?: () => void;+}) {+ if (target?.source === "traces")+ return (+ <TraceEvidence+ traceId={target.id}+ traceRef={target.traceRef}+ initialSpanId={evidence.span || null}+ onBack={onBack}+ />+ );+ if (target?.source === "requests") return <RequestEvidence lensId={lensId} evidenceId={evidence.id} />;+ return <p className="p-4 text-sm text-muted-foreground">This evidence is no longer available.</p>;+}++export function TraceEvidence({+ traceId,+ traceRef,+ initialSpanId,+ onBack,+}: {+ traceId: string;+ traceRef?: string;+ initialSpanId: string | null;+ onBack: () => void;+}) {+ const selection = useLocalRunSelection(initialSpanId);+ const accessToken = useLensAccessToken();+ return (+ <RunView+ traceId={traceId}+ traceRef={traceRef}+ selection={selection}+ accessToken={accessToken}+ onBack={onBack}+ embedded+ />+ );+}++function RequestEvidence({ lensId, evidenceId }: { lensId: string; evidenceId: string }) {+ const api = useLensApi();+ const [offset, setOffset] = useState(0);+ const request = { lensId, evidenceId, requestOffset: offset, source: "requests" };+ const evidence = useQuery(lensQueries.evidence(api, request));+ return (+ <div className="min-h-0 flex-1 overflow-y-auto">+ <header className="border-b px-4 py-4">+ <h2 className="text-sm font-semibold">Request evidence</h2>+ <p className="text-xs text-muted-foreground">Original logged input and output</p>+ </header>+ <div className="space-y-3 p-4">+ {evidence.isLoading && <p role="status">Loading request…</p>}+ {evidence.error && <p role="alert">{evidence.error.message}</p>}+ {evidence.data?.parts.map((p) => (+ <pre className="text-xs break-words whitespace-pre-wrap" key={p.span_id}>+ {p.content}+ </pre>+ ))}+ {evidence.data?.parts.length === 0 && <p>Request was not found or is past retention</p>}+ <div className="flex flex-wrap gap-2">+ {offset > 0 && (+ <Button variant="outline" onClick={() => setOffset(Math.max(0, offset - SECTION))}>+ Previous section+ </Button>+ )}+ {evidence.data?.parts.some((p) => p.truncated) && (+ <Button variant="outline" onClick={() => setOffset(offset === 0 ? 1 : offset + SECTION)}>+ Next section+ </Button>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/FindingDetails.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/investigations/FindingDetails.integration.test.tsxnew file mode 100644index 00000000000..a8abcf9bc25--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/FindingDetails.integration.test.tsx@@ -0,0 +1,135 @@+import { fireEvent, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, expect, it, vi } from "vitest";++import type { RunSelection } from "@/components/view_logs/TraceView/traceRouting";++import { renderWithLens } from "@/../tests/lens-test-utils";+import { Inspector } from "@/components/shared/Inspector";++import type { OwnedFinding } from "../model/inbox";+import type { Finding, Lens } from "../model/types";+import { FindingPanel, ownedFindingKey } from "./FindingDetails";++vi.mock("@/components/view_logs/TraceView/TraceDrawer", () => ({+ RunView: ({ traceId, selection }: { traceId: string; selection: RunSelection }) => (+ <div data-testid="run-view">+ {traceId} at {selection.spanId}+ </div>+ ),+}));++const lens = {+ id: "lens",+ settings: { name: "Support reviews", agent_name: "support_agent" },+ jobs: [],+ findings: [],+} as unknown as Lens;++const finding: Finding = {+ id: "finding",+ check_id: "check",+ title: "Repeated retries",+ description: "The tool kept failing",+ kind: "issue",+ priority: "high",+ status: "open",+ revision: 1,+ first_seen: "2026-09-30T10:00:00Z",+ last_seen: "2026-09-30T10:00:00Z",+ reason: "Saved feedback",+ suggestion: "",+ limitation: "",+ occurrences: [],+ evidence: [],+};++const owned = (current: Finding | null): OwnedFinding | null => (current ? { lens, finding: current } : null);++function Harness({ current, onReview }: { current: Finding | null; onReview: FindingPanelReview }) {+ return (+ <Inspector.Root+ items={[]}+ itemKey={ownedFindingKey}+ selected={owned(current)}+ onSelectedChange={vi.fn()}+ noun="finding"+ storageKey="test.finding"+ >+ <FindingPanel readOnly={false} busy={false} onReview={onReview} />+ </Inspector.Root>+ );+}+type FindingPanelReview = Parameters<typeof FindingPanel>[0]["onReview"];++afterEach(() => vi.restoreAllMocks());++it("keeps a feedback draft during refreshes, sends it with status changes, and restores saved feedback on reopening", async () => {+ vi.spyOn(window, "matchMedia").mockImplementation(+ (query: string) =>+ ({+ matches: query.includes("reduce"),+ media: query,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }) as unknown as MediaQueryList,+ );+ const user = userEvent.setup();+ const onReview = vi.fn();+ const view = renderWithLens(<Harness current={finding} onReview={onReview} />);+ const reason = () => screen.getByRole("textbox", { name: "What should Lens remember?" });+ expect(screen.getByRole("complementary", { name: "Finding details" })).toHaveTextContent("support_agent");+ expect(reason()).toHaveValue("Saved feedback");+ fireEvent.change(reason(), { target: { value: "Draft feedback" } });+ await user.click(screen.getByRole("button", { name: "Mark resolved" }));+ expect(onReview).toHaveBeenLastCalledWith({ lens, finding }, "resolved", "Draft feedback");++ const refreshed: Finding = { ...finding, reason: "Server feedback", status: "resolved" };+ view.rerender(<Harness current={refreshed} onReview={onReview} />);+ expect(reason()).toHaveValue("Draft feedback");+ await user.click(screen.getByRole("button", { name: "Reopen" }));+ expect(onReview).toHaveBeenLastCalledWith({ lens, finding: refreshed }, "open", "Draft feedback");+ await user.click(screen.getByRole("button", { name: "This is expected" }));+ expect(onReview).toHaveBeenLastCalledWith({ lens, finding: refreshed }, "dismissed", "Draft feedback");++ view.rerender(<Harness current={null} onReview={onReview} />);+ expect(screen.queryByRole("complementary")).not.toBeInTheDocument();+ view.rerender(<Harness current={refreshed} onReview={onReview} />);+ expect(reason()).toHaveValue("Server feedback");+ const other: Finding = { ...finding, id: "other", reason: "Other feedback" };+ view.rerender(<Harness current={other} onReview={onReview} />);+ expect(reason()).toHaveValue("Other feedback");+});++it("stacks a quote's original step over the finding and keeps the feedback draft on the way back", async () => {+ const user = userEvent.setup();+ const traceOf = (id: string) => btoa(JSON.stringify(["traces", "", id]));+ const quoted: Finding = {+ ...finding,+ evidence: [+ { execution_id: traceOf("trace-1"), span_id: "step-a", quote: "first quote", role: "support" },+ { execution_id: traceOf("trace-2"), span_id: "step-b", quote: "second quote", role: "support" },+ ],+ };+ const onUrlUpdate = vi.fn();+ renderWithLens(<Harness current={quoted} onReview={vi.fn()} />, { onUrlUpdate });+ const panel = screen.getByRole("complementary", { name: "Finding details" });+ const reason = () => within(panel).getByRole("textbox", { name: "What should Lens remember?", hidden: true });+ fireEvent.change(reason(), { target: { value: "Draft feedback" } });+ for (const summary of within(panel).getAllByText(/quote$/)) await user.click(summary);+ await user.click(within(panel).getAllByRole("button", { name: "Open original step" })[0]);+ expect(await within(panel).findByTestId("run-view")).toHaveTextContent("trace-1 at step-a");+ expect(reason()).not.toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();++ await user.click(within(panel).getByRole("button", { name: "Back to finding" }));+ expect(within(panel).queryByTestId("run-view")).not.toBeInTheDocument();+ expect(reason()).toBeVisible();+ expect(reason()).toHaveValue("Draft feedback");++ await user.click(within(panel).getAllByRole("button", { name: "Open original step" })[1]);+ expect(await within(panel).findByTestId("run-view")).toHaveTextContent("trace-2 at step-b");+ const url = new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? ""));+ expect(url.get("evidence")).toBe(traceOf("trace-2"));+ expect(url.get("evidence_span")).toBe("step-b");+});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/FindingDetails.tsx b/ui/litellm-dashboard/src/components/lens/investigations/FindingDetails.tsxnew file mode 100644index 00000000000..2c9ec48b13b--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/FindingDetails.tsx@@ -0,0 +1,200 @@+"use client";++import { useState } from "react";+import { ArrowUpRight } from "lucide-react";++import { Inspector } from "@/components/shared/Inspector";+import { Button } from "@/components/ui/button";+import { Textarea } from "@/components/ui/textarea";++import { evidenceTarget } from "../model/findings";+import { runTime } from "../model/format";+import { findingAgents, findingKey, type OwnedFinding, sampledExecutions } from "../model/inbox";+import type { Finding, Sample } from "../model/types";+import { EvidenceView } from "./Evidence";+import { IssueBrief } from "./IssueBrief";+import { type EvidenceRef, useEvidenceRoute } from "../route";++export const ownedFindingKey = (owned: OwnedFinding): string => findingKey(owned.lens, owned.finding);++export interface FindingDetailsProps {+ readonly finding: Finding;+ readonly agents?: readonly string[];+ readonly sampledRuns: Sample["executions"];+ readonly readOnly: boolean;+ readonly busy: boolean;+ readonly onOpenEvidence: (evidence: EvidenceRef) => void;+ readonly onReview: (status: Finding["status"], reason: string) => void;+}++export function FindingDetails({+ finding,+ agents = [],+ sampledRuns,+ readOnly,+ busy,+ onOpenEvidence,+ onReview,+}: FindingDetailsProps) {+ const [reason, setReason] = useState(finding.reason ?? "");+ const evidenceGroups = [...new Set(finding.evidence.map((e) => e.execution_id))].map((id) => ({+ id,+ run: sampledRuns.find((r) => r.id === id),+ quotes: finding.evidence.filter((e) => e.execution_id === id),+ }));+ return (+ <div className="min-h-0 flex-1 overflow-y-auto">+ <header className="flex flex-col gap-1.5 border-b px-4 py-4">+ <h2 className="text-xl leading-snug font-semibold">{finding.title}</h2>+ <p className="text-sm text-muted-foreground">+ {agents.length > 0 && <span className="font-medium text-foreground">{agents.join(", ")} · </span>}+ {finding.kind === "issue" ? `${finding.priority} priority` : "Pattern"} · {finding.occurrences?.length ?? 0}{" "}+ linked {finding.occurrences?.length === 1 ? "run" : "runs"}+ </p>+ </header>+ <div className="space-y-6 p-4">+ {finding.brief ? (+ <IssueBrief title={finding.title} brief={finding.brief} />+ ) : (+ <>+ <div>+ <p className="mb-2 text-sm font-medium">What happened</p>+ <p className="text-sm leading-6 whitespace-pre-wrap">{finding.description}</p>+ </div>+ {finding.suggestion && (+ <div className="border-y py-4">+ <p className="text-sm font-medium">What to do next</p>+ <p className="mt-2 text-sm leading-6">{finding.suggestion}</p>+ </div>+ )}+ </>+ )}+ {finding.limitation && (+ <details className="text-sm">+ <summary className="cursor-pointer font-medium">Evidence limits</summary>+ <p className="mt-3 leading-6 text-muted-foreground">{finding.limitation}</p>+ </details>+ )}+ <div>+ <p className="text-sm font-medium">Evidence by run</p>+ <p className="mt-1 mb-3 text-xs text-muted-foreground">+ Exact quotes from the recorded activity. Counterexamples are labeled separately from supporting evidence.+ </p>+ <div className="space-y-2">+ {evidenceGroups.map((group) => (+ <details key={group.id} className="rounded-lg border p-3">+ <summary className="cursor-pointer text-sm font-medium">+ {group.run?.name ?? evidenceTarget(group.id)?.id.slice(0, 12) ?? "Recorded run"}+ <span className="ml-2 text-xs font-normal text-muted-foreground">+ {group.quotes.length} {group.quotes.length === 1 ? "quote" : "quotes"}+ {group.run ? ` · ${runTime(group.run.start_time)}` : ""}+ </span>+ </summary>+ <div className="mt-3 space-y-3">+ {group.quotes.map((e, i) => (+ <div key={`${e.span_id}-${i}`} className="rounded-md bg-muted/40 p-3">+ {e.role === "counterexample" && (+ <p className="mb-1 text-xs font-medium text-muted-foreground">Counterexample</p>+ )}+ <blockquote className="text-xs leading-5 whitespace-pre-wrap break-words">{e.quote}</blockquote>+ <Button+ variant="ghost"+ size="sm"+ className="mt-2"+ onClick={() => onOpenEvidence({ id: e.execution_id, span: e.span_id })}+ >+ {evidenceTarget(e.execution_id)?.source === "traces" ? "Open original step" : "Open request"}+ <ArrowUpRight className="size-3" />+ </Button>+ </div>+ ))}+ </div>+ </details>+ ))}+ </div>+ </div>+ {!readOnly && (+ <div className="space-y-3 border-t pt-4">+ <label className="grid gap-2 text-sm">+ What should Lens remember?+ <Textarea+ value={reason}+ onChange={(e) => setReason(e.target.value)}+ placeholder="What should Lens know about this finding?"+ />+ </label>+ <p className="text-xs text-muted-foreground">Your explanation informs future scans of this Lens.</p>+ <div className="flex flex-wrap gap-2">+ {finding.kind === "issue" && (+ <Button+ disabled={busy}+ onClick={() => onReview(finding.status === "resolved" ? "open" : "resolved", reason)}+ >+ {finding.status === "resolved" ? "Reopen" : "Mark resolved"}+ </Button>+ )}+ <Button disabled={busy} variant="outline" onClick={() => onReview("dismissed", reason)}>+ This is expected+ </Button>+ </div>+ </div>+ )}+ </div>+ </div>+ );+}++export interface FindingPanelProps {+ readonly readOnly: boolean;+ readonly busy: boolean;+ /** Runs to name evidence by; defaults to every run the owning investigation has sampled. */+ readonly sampledRuns?: Sample["executions"];+ readonly onReview: (owned: OwnedFinding, status: Finding["status"], reason: string) => void;+}++/**+ * A finding in the side panel. Opening a quote's original step or request stacks it over the finding, which+ * stays mounted so a feedback draft survives the round trip.+ */+export function FindingPanelBody({+ owned,+ readOnly,+ busy,+ sampledRuns,+ onReview,+}: FindingPanelProps & { readonly owned: OwnedFinding }) {+ const { evidence, setEvidence } = useEvidenceRoute();+ return (+ <>+ <div hidden={evidence !== null} className={evidence ? undefined : "flex min-h-0 flex-1 flex-col"}>+ <FindingDetails+ key={ownedFindingKey(owned)}+ finding={owned.finding}+ agents={findingAgents(owned.lens, owned.finding)}+ sampledRuns={sampledRuns ?? sampledExecutions(owned.lens)}+ readOnly={readOnly}+ busy={busy}+ onOpenEvidence={setEvidence}+ onReview={(status, reason) => onReview(owned, status, reason)}+ />+ </div>+ {evidence && (+ <EvidenceView+ lensId={owned.lens.id}+ evidence={evidence}+ backLabel="Back to finding"+ onBack={() => setEvidence(null)}+ />+ )}+ </>+ );+}++/** The side panel for whichever finding the surrounding Inspector has open. */+export function FindingPanel(props: FindingPanelProps) {+ return (+ <Inspector.Panel label="Finding details" testId="finding-panel">+ {(owned: OwnedFinding) => <FindingPanelBody {...props} owned={owned} />}+ </Inspector.Panel>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/FindingSheet.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/investigations/FindingSheet.integration.test.tsxdeleted file mode 100644index 51a33212953..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/FindingSheet.integration.test.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { fireEvent, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { expect, it, vi } from "vitest";-import { renderWithProviders } from "@/../tests/test-utils";-import type { Finding } from "../model/types";-import { FindingSheet } from "./FindingSheet";--const finding: Finding = {- id: "finding",- check_id: "check",- title: "Repeated retries",- description: "The tool kept failing",- kind: "issue",- priority: "high",- status: "open",- revision: 1,- first_seen: "2026-09-30T10:00:00Z",- last_seen: "2026-09-30T10:00:00Z",- reason: "Saved feedback",- suggestion: "",- limitation: "",- occurrences: [],- evidence: [],-};--it("keeps a feedback draft during refreshes, sends it with status changes, and restores saved feedback on reopening", async () => {- const user = userEvent.setup();- const changeFinding = vi.fn().mockResolvedValue(undefined);- const props = { sampledRuns: [], readOnly: false, busy: false, onClose: vi.fn(), onEvidence: vi.fn(), changeFinding };- const view = renderWithProviders(<FindingSheet {...props} finding={finding} />);- const reason = () => screen.getByRole("textbox", { name: "What should Lens remember?" });- expect(reason()).toHaveValue("Saved feedback");- fireEvent.change(reason(), { target: { value: "Draft feedback" } });- await user.click(screen.getByRole("button", { name: "Mark resolved" }));- expect(changeFinding).toHaveBeenLastCalledWith("resolved", "Draft feedback");-- const refreshed: Finding = { ...finding, reason: "Server feedback", status: "resolved" };- view.rerender(<FindingSheet {...props} finding={refreshed} />);- expect(reason()).toHaveValue("Draft feedback");- await user.click(screen.getByRole("button", { name: "Reopen" }));- expect(changeFinding).toHaveBeenLastCalledWith("open", "Draft feedback");- await user.click(screen.getByRole("button", { name: "This is expected" }));- expect(changeFinding).toHaveBeenLastCalledWith("dismissed", "Draft feedback");-- view.rerender(<FindingSheet {...props} />);- view.rerender(<FindingSheet {...props} finding={refreshed} />);- expect(reason()).toHaveValue("Server feedback");- const other: Finding = { ...finding, id: "other", reason: "Other feedback" };- view.rerender(<FindingSheet {...props} finding={other} />);- expect(reason()).toHaveValue("Other feedback");-});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/FindingSheet.tsx b/ui/litellm-dashboard/src/components/lens/investigations/FindingSheet.tsxdeleted file mode 100644index c3f8b2b3a7e..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/FindingSheet.tsx+++ /dev/null@@ -1,164 +0,0 @@-import { useState } from "react";-import { ArrowUpRight } from "lucide-react";-import { Button } from "@/components/ui/button";-import { Textarea } from "@/components/ui/textarea";-import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from "@/components/ui/sheet";-import { IssueBrief } from "./IssueBrief";-import { evidenceTarget } from "../model/findings";-import { runTime } from "../model/format";-import { type Finding, type Sample } from "../model/types";--export function FindingSheet({- finding,- agents = [],- sampledRuns,- readOnly,- busy,- onClose,- onEvidence,- changeFinding,-}: {- finding?: Finding;- agents?: readonly string[];- sampledRuns: Sample["executions"];- readOnly: boolean;- busy: boolean;- onClose: () => void;- onEvidence: (evidence: { id: string; span: string }) => void;- changeFinding: (status: Finding["status"], reason: string) => Promise<void>;-}) {- const [reason, setReason] = useFindingReason(finding);- const evidenceGroups = finding- ? [...new Set(finding.evidence.map((e) => e.execution_id))].map((id) => ({- id,- run: sampledRuns.find((r) => r.id === id),- quotes: finding.evidence.filter((e) => e.execution_id === id),- }))- : [];- return (- <Sheet- open={!!finding}- onOpenChange={(open) => {- if (!open) onClose();- }}- >- <SheetContent className="overflow-y-auto data-[side=right]:sm:max-w-2xl">- {finding && (- <>- <SheetHeader>- <SheetTitle className="pr-8 text-xl leading-snug">{finding.title}</SheetTitle>- <SheetDescription>- {agents.length > 0 && <span className="font-medium text-foreground">{agents.join(", ")} · </span>}- {finding.kind === "issue" ? `${finding.priority} priority` : "Pattern"} ·{" "}- {finding.occurrences?.length ?? 0} linked {finding.occurrences?.length === 1 ? "run" : "runs"}- </SheetDescription>- </SheetHeader>- <div className="space-y-6 p-4">- {finding.brief ? (- <IssueBrief title={finding.title} brief={finding.brief} />- ) : (- <>- <div>- <p className="mb-2 text-sm font-medium">What happened</p>- <p className="text-sm leading-6 whitespace-pre-wrap">{finding.description}</p>- </div>- {finding.suggestion && (- <div className="border-y py-4">- <p className="text-sm font-medium">What to do next</p>- <p className="mt-2 text-sm leading-6">{finding.suggestion}</p>- </div>- )}- </>- )}- {finding.limitation && (- <details className="text-sm">- <summary className="cursor-pointer font-medium">Evidence limits</summary>- <p className="mt-3 leading-6 text-muted-foreground">{finding.limitation}</p>- </details>- )}- <div>- <p className="text-sm font-medium">Evidence by run</p>- <p className="mt-1 mb-3 text-xs text-muted-foreground">- Exact quotes from the recorded activity. Counterexamples are labeled separately from supporting- evidence.- </p>- <div className="space-y-2">- {evidenceGroups.map((group) => (- <details key={group.id} className="rounded-lg border p-3">- <summary className="cursor-pointer text-sm font-medium">- {group.run?.name ?? evidenceTarget(group.id)?.id.slice(0, 12) ?? "Recorded run"}- <span className="ml-2 text-xs font-normal text-muted-foreground">- {group.quotes.length} {group.quotes.length === 1 ? "quote" : "quotes"}- {group.run ? ` · ${runTime(group.run.start_time)}` : ""}- </span>- </summary>- <div className="mt-3 space-y-3">- {group.quotes.map((e, i) => (- <div key={`${e.span_id}-${i}`} className="rounded-md bg-muted/40 p-3">- {e.role === "counterexample" && (- <p className="mb-1 text-xs font-medium text-muted-foreground">Counterexample</p>- )}- <blockquote className="text-xs leading-5 whitespace-pre-wrap break-words">- {e.quote}- </blockquote>- <Button- variant="ghost"- size="sm"- className="mt-2"- onClick={() => {- onEvidence({ id: e.execution_id, span: e.span_id });- }}- >- {evidenceTarget(e.execution_id)?.source === "traces"- ? "Open original step"- : "Open request"}- <ArrowUpRight className="size-3" />- </Button>- </div>- ))}- </div>- </details>- ))}- </div>- </div>- {!readOnly && (- <div className="space-y-3 border-t pt-4">- <label className="grid gap-2 text-sm">- What should Lens remember?- <Textarea- value={reason}- onChange={(e) => setReason(e.target.value)}- placeholder="What should Lens know about this finding?"- />- </label>- <p className="text-xs text-muted-foreground">Your explanation informs future scans of this Lens.</p>- <div className="flex flex-wrap gap-2">- {finding.kind === "issue" && (- <Button- disabled={busy}- onClick={() => changeFinding(finding.status === "resolved" ? "open" : "resolved", reason)}- >- {finding.status === "resolved" ? "Reopen" : "Mark resolved"}- </Button>- )}- <Button disabled={busy} variant="outline" onClick={() => changeFinding("dismissed", reason)}>- This is expected- </Button>- </div>- </div>- )}- </div>- </>- )}- </SheetContent>- </Sheet>- );-}--function useFindingReason(finding: Finding | undefined) {- const [draft, setDraft] = useState({ id: finding?.id, reason: finding?.reason ?? "" });- if (draft.id !== finding?.id) setDraft({ id: finding?.id, reason: finding?.reason ?? "" });- const reason = draft.reason;- const setReason = (reason: string) => setDraft({ ...draft, reason });- return [reason, setReason] as const;-}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationList.tsx b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationList.tsxindex 10a70999232..1c14b0bbc71 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationList.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationList.tsx@@ -1,6 +1,14 @@"use client";-import { Fragment, useState, type KeyboardEvent, type ReactNode } from "react";+import {+ getCoreRowModel,+ getExpandedRowModel,+ useReactTable,+ type CellContext,+ type ColumnDef,+ type TableOptions,+} from "@tanstack/react-table";+import { createContext, useContext, type ReactNode } from "react";import {ChevronRight,Circle,@@ -11,32 +19,64 @@ import {CircleX,Pencil,Play,- Search,} from "lucide-react";import { useNow } from "@/hooks/useNow";-import { Input } from "@/components/ui/input";+import { Inspector } from "@/components/shared/Inspector";+import { InspectorTable } from "@/components/shared/InspectorTable";import { formatActivityTimestamp } from "@/utils/activityTimestamp";import { cn } from "@/lib/cva.config";-import { agoLabel } from "@/components/view_logs/TraceView/lensField";+import { agoLabel, scopeLabel } from "../model/format";-import { findingAgents, openFindings, scheduleLabel } from "../model/inbox";+import { findingAgents, findingKey, openFindings, scheduleLabel } from "../model/inbox";import { lensStatus } from "../model/status";-import { scopeLabel } from "../model/format";+import { SearchBox } from "@/components/shared/search/SearchBox";+import { itemValues } from "@/components/shared/search/valueSource";import { type Finding, type Lens } from "../model/types";import { useListSearchRoute } from "../route";+import { FINDING_PANEL_WIDTH_KEY } from "../storage";+import { filterInvestigations, INVESTIGATION_INDEX, INVESTIGATION_QUERY } from "./investigationQuery";-const PRIORITY_COLOR = { high: "text-destructive", medium: "text-amber-500", low: "text-muted-foreground" } as const;-const ROW =- "border-b border-border/60 transition-colors duration-150 hover:bg-trace-row-hover motion-reduce:transition-none";+const PRIORITY_COLOR = { high: "text-destructive", medium: "text-warning", low: "text-muted-foreground" } as const;const META = "truncate text-xs text-muted-foreground";+const ACTION =+ "inline-flex size-7 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground";+const INVESTIGATION_HEIGHT = 56;+const FINDING_HEIGHT = 48;++/** One row of the list: an investigation, or an open finding shown under the investigation that owns it. */+export type InvestigationRow =+ | { readonly kind: "investigation"; readonly lens: Lens }+ | { readonly kind: "finding"; readonly lens: Lens; readonly finding: Finding };++export const investigationRowKey = (row: InvestigationRow): string =>+ row.kind === "investigation" ? `investigation:${row.lens.id}` : `finding:${findingKey(row.lens, row.finding)}`;++const findingRows = (row: InvestigationRow): InvestigationRow[] | undefined =>+ row.kind === "investigation"+ ? openFindings(row.lens).map((finding) => ({ kind: "finding", lens: row.lens, finding }))+ : undefined;++interface ListContextValue {+ readonly now: number;+ readonly connected: boolean;+ readonly readOnly: boolean;+ readonly onEdit: (id: string) => void;+ readonly onRunNow: (id: string) => void;+}++const ListContext = createContext<ListContextValue | null>(null);-function openOnRowKeyDown(event: KeyboardEvent<HTMLTableRowElement>, open: () => void) {- if (event.target !== event.currentTarget || (event.key !== "Enter" && event.key !== " ")) return;- event.preventDefault();- open();+function useList(): ListContextValue {+ const value = useContext(ListContext);+ if (value === null) throw new Error("Investigation cells must be rendered inside InvestigationList");+ return value;}+type Cell = CellContext<InvestigationRow, unknown>;++const ROW_LABEL = { investigation: "Investigation details", finding: "Finding details" } as const;+function JobIcon({ lens }: { lens: Lens }) {const status = lens.jobs[0]?.status;const className = "size-4 shrink-0";@@ -45,7 +85,7 @@ function JobIcon({ lens }: { lens: Lens }) {if (status === "failed") return <CircleX aria-hidden="true" className={cn(className, "text-destructive")} />;if (status === "cancelled")return <CircleSlash aria-hidden="true" className={cn(className, "text-muted-foreground")} />;- if (status === "completed") return <CircleCheck aria-hidden="true" className={cn(className, "text-emerald-600")} />;+ if (status === "completed") return <CircleCheck aria-hidden="true" className={cn(className, "text-success")} />;return <Circle aria-hidden="true" className={cn(className, "text-muted-foreground")} />;}@@ -58,222 +98,237 @@ function TwoLine({ meta, title, className }: { meta: ReactNode; title: ReactNode);}+function NameCell({ row }: Cell) {+ const { now } = useList();+ const item = row.original;+ if (item.kind === "investigation")+ return (+ <span className="flex min-w-0 items-center gap-2">+ <InspectorTable.Indent+ row={row}+ toggleLabel={(expanded) => `${expanded ? "Hide" : "Show"} findings for ${item.lens.settings.name}`}+ />+ <JobIcon lens={item.lens} />+ <TwoLine+ meta={`${scopeLabel(item.lens.settings)} · ${scheduleLabel(item.lens, now)}`}+ title={item.lens.settings.name}+ className="font-semibold"+ />+ </span>+ );+ const priority = item.finding.priority ?? "medium";+ return (+ <span+ className="flex min-w-0 items-center gap-2"+ title={item.finding.suggestion ? `Fix: ${item.finding.suggestion}` : undefined}+ >+ <InspectorTable.Indent row={row} className="h-12" />+ <span aria-hidden="true" className="w-4 shrink-0" />+ <CircleDot aria-hidden="true" className={cn("size-4 shrink-0", PRIORITY_COLOR[priority])} />+ <TwoLine+ meta={`${priority} priority · ${findingAgents(item.lens, item.finding).join(", ")}`}+ title={item.finding.title}+ />+ </span>+ );+}++function StatusCell({ row: { original: item } }: Cell) {+ const { connected } = useList();+ if (item.kind === "finding") {+ const runs = item.finding.occurrences.length;+ return (+ <span className="text-muted-foreground">+ {runs} {runs === 1 ? "run" : "runs"}+ </span>+ );+ }+ const failed = item.lens.jobs[0]?.status === "failed";+ return (+ <span className={cn("block truncate", failed ? "text-destructive" : "text-muted-foreground")}>+ {lensStatus(item.lens, connected)}+ </span>+ );+}++function FindingCount({ row: { original: item } }: Cell) {+ if (item.kind === "finding") return null;+ const count = openFindings(item.lens).length;+ if (count === 0) return null;+ return (+ <span+ title={`${count} open ${count === 1 ? "finding" : "findings"}`}+ className="inline-flex min-w-5 justify-center rounded-full bg-muted px-1.5 font-mono text-xs tabular-nums text-foreground"+ >+ {count}+ </span>+ );+}++function ActivityCell({ row: { original: item } }: Cell) {+ const { now } = useList();+ if (item.kind === "finding")+ return (+ <span title={formatActivityTimestamp(item.finding.last_seen)}>+ {agoLabel(Date.parse(item.finding.last_seen), now)}+ </span>+ );+ const latest = item.lens.jobs[0];+ return (+ <span title={latest ? formatActivityTimestamp(latest.created_at) : undefined}>+ {latest ? agoLabel(Date.parse(latest.created_at), now) : "never run"}+ </span>+ );+}++function ActionsCell({ row: { original: item } }: Cell) {+ const { readOnly, onEdit, onRunNow } = useList();+ if (item.kind === "finding")+ return <ChevronRight aria-hidden="true" className="mr-2 ml-auto size-3.5 text-muted-foreground/60" />;+ if (readOnly) return null;+ const { id, settings } = item.lens;+ return (+ <span className="flex items-center justify-end gap-0.5">+ <button+ type="button"+ aria-label={`Run ${settings.name} now`}+ title="Run now"+ onClick={(event) => {+ event.stopPropagation();+ onRunNow(id);+ }}+ className={ACTION}+ >+ <Play className="size-3.5" />+ </button>+ <button+ type="button"+ aria-label={`Edit ${settings.name}`}+ title="Edit"+ onClick={(event) => {+ event.stopPropagation();+ onEdit(id);+ }}+ className={cn(ACTION, "text-muted-foreground/60 group-hover:text-muted-foreground")}+ >+ <Pencil className="size-3.5" />+ </button>+ </span>+ );+}++const COLUMNS: ColumnDef<InvestigationRow>[] = [+ { id: "name", header: "Investigation", cell: NameCell, meta: { className: "pl-2 pr-0" } },+ { id: "status", size: 180, header: "Status", cell: StatusCell, meta: { className: "text-right text-xs" } },+ { id: "findings", size: 72, header: "Open findings", cell: FindingCount, meta: { className: "text-right" } },+ {+ id: "activity",+ size: 120,+ header: "Last activity",+ cell: ActivityCell,+ meta: { className: "text-right text-xs text-muted-foreground" },+ },+ { id: "actions", size: 76, header: "Actions", cell: ActionsCell, meta: { className: "pl-0 pr-3" } },+];++export interface InvestigationListProps {+ readonly lenses: readonly Lens[];+ readonly connected: boolean;+ readonly readOnly?: boolean;+ readonly selected: InvestigationRow | null;+ readonly onSelect: (row: InvestigationRow | null) => void;+ readonly onEdit: (id: string) => void;+ readonly onRunNow: (id: string) => void;+ readonly actions?: ReactNode;+ /** Body of the side panel for the selected row. */+ readonly children: (row: InvestigationRow) => ReactNode;+}++/** Investigations with their open findings; any row opens in the side panel and J/K walk the visible rows. */export function InvestigationList({lenses,connected,readOnly = false,- onOpen,+ selected,+ onSelect,onEdit,onRunNow,- onOpenFinding,-}: {- lenses: Lens[];- connected: boolean;- readOnly?: boolean;- onOpen: (id: string) => void;- onEdit: (id: string) => void;- onRunNow: (id: string) => void;- onOpenFinding: (lens: Lens, finding: Finding) => void;-}) {+ actions,+ children,+}: InvestigationListProps) {const [search, setSearch] = useListSearchRoute();const now = useNow(15000);- const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());- const toggle = (id: string) =>- setCollapsed((current) => {- const next = new Set(current);- if (!next.delete(id)) next.add(id);- return next;- });- const shown = lenses.filter((lens) =>- `${lens.settings.name} ${scopeLabel(lens.settings)}`.toLowerCase().includes(search.toLowerCase()),- );+ const shown = filterInvestigations([...lenses], search);+ const tableOptions: TableOptions<InvestigationRow> = {+ data: shown.map((lens): InvestigationRow => ({ kind: "investigation", lens })),+ columns: COLUMNS,+ getRowId: investigationRowKey,+ getSubRows: findingRows,+ initialState: { expanded: true },+ autoResetAll: false,+ getCoreRowModel: getCoreRowModel(),+ getExpandedRowModel: getExpandedRowModel(),+ };+ const table = useReactTable(tableOptions);+ const rows = table.getRowModel().rows.map((row) => row.original);+ const noun = selected?.kind ?? "investigation";return (- <div className="flex min-h-[420px] flex-1 flex-col overflow-hidden rounded-lg border border-border bg-card">- <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-border bg-muted/40 px-3 py-2">- <div className="relative w-full max-w-[380px]">- <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />- <Input- aria-label="Search investigations"- placeholder="Search investigations"- className="h-7 bg-background pl-8 text-xs"+ <Inspector.Root+ items={rows}+ itemKey={investigationRowKey}+ selected={selected}+ onSelectedChange={onSelect}+ noun={noun}+ storageKey={FINDING_PANEL_WIDTH_KEY}+ >+ <div className="flex min-h-[420px] flex-1 flex-col overflow-hidden bg-card">+ <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-border bg-card p-2">+ <SearchBox.Root+ language={INVESTIGATION_QUERY}+ values={itemValues(INVESTIGATION_INDEX, lenses)}value={search}- onChange={(e) => setSearch(e.target.value)}- />+ onValueChange={setSearch}+ label="Search investigations"+ >+ <SearchBox.Input+ className="rounded-lg"+ placeholder="Search investigations, or filter like status:failed schedule:watching"+ />+ <SearchBox.Suggestions />+ </SearchBox.Root>+ {actions && <div className="ml-auto flex items-center gap-2">{actions}</div>}</div>- </div>- <div className="min-h-0 flex-1 overflow-auto">- <table aria-label="Investigations" className="w-full min-w-[720px] table-fixed border-collapse text-left">- <thead className="sr-only">- <tr>- <th>Investigation</th>- <th>Status</th>- <th>Open findings</th>- <th>Last activity</th>- <th>Actions</th>- </tr>- </thead>- <tbody>- {shown.map((lens) => {- const latest = lens.jobs[0];- const findings = openFindings(lens);- const expanded = findings.length > 0 && !collapsed.has(lens.id);- return (- <Fragment key={lens.id}>- <tr- onClick={() => onOpen(lens.id)}- onKeyDown={(event) => openOnRowKeyDown(event, () => onOpen(lens.id))}+ <ListContext.Provider value={{ now, connected, readOnly, onEdit, onRunNow }}>+ <InspectorTable.Root table={table}>+ <InspectorTable.Grid aria-label="Investigations" className="min-w-[720px]">+ <InspectorTable.Header hidden />+ <InspectorTable.Body<InvestigationRow>+ rowHeight={(row) => (row.depth ? FINDING_HEIGHT : INVESTIGATION_HEIGHT)}+ >+ {(row) => (+ <InspectorTable.Row+ row={row}+ item={row.original}tabIndex={0}- aria-label={lens.settings.name}- className={cn(ROW, "group h-14 cursor-pointer focus-visible:outline-2 focus-visible:outline-ring")}- >- <td className="pl-2">- <span className="flex min-w-0 items-center gap-2">- {findings.length > 0 ? (- <button- type="button"- aria-expanded={expanded}- aria-label={`${expanded ? "Hide" : "Show"} findings for ${lens.settings.name}`}- onClick={(event) => {- event.stopPropagation();- toggle(lens.id);- }}- className="inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"- >- <ChevronRight- className={cn(- "size-3.5 transition-transform duration-150 motion-reduce:transition-none",- expanded && "rotate-90",- )}- />- </button>- ) : (- <span aria-hidden="true" className="size-6 shrink-0" />- )}- <JobIcon lens={lens} />- <TwoLine- meta={`${scopeLabel(lens.settings)} · ${scheduleLabel(lens, now)}`}- title={lens.settings.name}- className="font-semibold"- />- </span>- </td>- <td- className={cn(- "w-[180px] truncate px-3 text-right text-xs",- latest?.status === "failed" ? "text-destructive" : "text-muted-foreground",- )}- >- {lensStatus(lens, connected)}- </td>- <td className="w-[72px] px-3 text-right">- {findings.length > 0 && (- <span- title={`${findings.length} open ${findings.length === 1 ? "finding" : "findings"}`}- className="inline-flex min-w-5 justify-center rounded-full bg-muted px-1.5 font-mono text-xs tabular-nums text-foreground"- >- {findings.length}- </span>- )}- </td>- <td- className="w-[120px] px-3 text-right text-xs text-muted-foreground"- title={latest ? formatActivityTimestamp(latest.created_at) : undefined}- >- {latest ? agoLabel(Date.parse(latest.created_at), now) : "never run"}- </td>- <td className="w-[76px] pr-3">- {!readOnly && (- <span className="flex items-center justify-end gap-0.5">- <button- type="button"- aria-label={`Run ${lens.settings.name} now`}- title="Run now"- onClick={(event) => {- event.stopPropagation();- onRunNow(lens.id);- }}- className="inline-flex size-7 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"- >- <Play className="size-3.5" />- </button>- <button- type="button"- aria-label={`Edit ${lens.settings.name}`}- title="Edit"- onClick={(event) => {- event.stopPropagation();- onEdit(lens.id);- }}- className="inline-flex size-7 items-center justify-center rounded text-muted-foreground/60 hover:bg-muted hover:text-foreground group-hover:text-muted-foreground"- >- <Pencil className="size-3.5" />- </button>- </span>- )}- </td>- </tr>- {expanded &&- findings.map((finding, index) => {- const priority = finding.priority ?? "medium";- const last = index === findings.length - 1;- const runs = finding.occurrences.length;- return (- <tr- key={finding.id}- onClick={() => onOpenFinding(lens, finding)}- onKeyDown={(event) => openOnRowKeyDown(event, () => onOpenFinding(lens, finding))}- tabIndex={0}- aria-label={finding.title}- className={cn(ROW, "h-12 cursor-pointer focus-visible:outline-2 focus-visible:outline-ring")}- >- <td className="pl-2" title={finding.suggestion ? `Fix: ${finding.suggestion}` : undefined}>- <span className="flex min-w-0 items-center gap-2">- <span aria-hidden="true" className="relative h-12 w-6 shrink-0">- <span- className={cn("absolute left-3 top-0 w-px bg-border", last ? "h-1/2" : "h-full")}- />- <span className="absolute top-1/2 left-3 h-px w-3 bg-border" />- </span>- <span aria-hidden="true" className="w-4 shrink-0" />- <CircleDot- aria-hidden="true"- className={cn("size-4 shrink-0", PRIORITY_COLOR[priority])}- />- <TwoLine- meta={`${priority} priority · ${findingAgents(lens, finding).join(", ")}`}- title={finding.title}- />- </span>- </td>- <td className="px-3 text-right text-xs text-muted-foreground">- {runs} {runs === 1 ? "run" : "runs"}- </td>- <td />- <td- className="px-3 text-right text-xs text-muted-foreground"- title={formatActivityTimestamp(finding.last_seen)}- >- {agoLabel(Date.parse(finding.last_seen), now)}- </td>- <td className="pr-5">- <ChevronRight aria-hidden="true" className="ml-auto size-3.5 text-muted-foreground/60" />- </td>- </tr>- );- })}- </Fragment>- );- })}- </tbody>- </table>- {!shown.length && (- <div className="py-16 text-center text-xs text-muted-foreground">No investigations match your search.</div>- )}+ aria-label={+ row.original.kind === "finding" ? row.original.finding.title : row.original.lens.settings.name+ }+ className={row.depth ? "h-12" : "group h-14"}+ />+ )}+ </InspectorTable.Body>+ </InspectorTable.Grid>+ {!shown.length && (+ <div className="py-16 text-center text-xs text-muted-foreground">+ No investigations match your search.+ </div>+ )}+ </InspectorTable.Root>+ </ListContext.Provider></div>- <footer className="flex h-8 shrink-0 items-center border-t border-border bg-muted/40 px-3 font-mono text-xs text-muted-foreground">- {shown.length} {shown.length === 1 ? "investigation" : "investigations"} ·{" "}- {lenses.filter((l) => l.settings.enabled).length} watching- </footer>- </div>+ <Inspector.Panel label={ROW_LABEL[noun]} testId="investigation-panel">+ {children}+ </Inspector.Panel>+ </Inspector.Root>);}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationNavigation.tsx b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationNavigation.tsxdeleted file mode 100644index 022ae820ef8..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationNavigation.tsx+++ /dev/null@@ -1,54 +0,0 @@-"use client";-import { StatusDot } from "@/components/shared/StatusDot";--import { ArrowLeft, Plus } from "lucide-react";-import { Button } from "@/components/ui/button";-import type { Lens } from "../model/types";--export function InvestigationNavigation({- lens,- showActions,- activityReady,- connected,- ready,- selectLens,- setWorkerSetup,- setEditing,-}: {- lens: Lens | undefined;- showActions: boolean;- activityReady: boolean;- connected: boolean;- ready: boolean;- selectLens: (id: string | null) => void;- setWorkerSetup: (open: boolean) => void;- setEditing: (mode: "new") => void;-}) {- return (- <header className={lens ? "flex flex-wrap items-center justify-between gap-2" : "flex items-center gap-2"}>- {lens ? (- <Button variant="ghost" size="sm" className="-ml-3" onClick={() => selectLens(null)}>- <ArrowLeft className="size-4" /> Back- </Button>- ) : null}- {showActions && (- <div className="flex flex-wrap gap-2">- <Button- variant="ghost"- size="sm"- disabled={!activityReady}- onClick={() => setWorkerSetup(true)}- title={connected ? "Worker connected" : "Connect worker"}- className="text-muted-foreground"- >- <StatusDot state={connected ? "ok" : "warn"} />- {connected ? "Worker" : "Connect worker"}- </Button>- <Button size="sm" variant={lens ? "outline" : "default"} disabled={!ready} onClick={() => setEditing("new")}>- <Plus className="size-4" /> New investigation- </Button>- </div>- )}- </header>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationProgress.tsx b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationProgress.tsxindex 5d14a10f238..5ce600c0b64 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationProgress.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationProgress.tsx@@ -2,7 +2,6 @@import { useNow } from "@/hooks/useNow";-import { useState } from "react";import { Button } from "@/components/ui/button";import {analysisElapsed,@@ -12,11 +11,10 @@ import {analysisStages,remainingLabel,stageDurations,- type ProgressSample,} from "../model/progress";+import { useProgressSamples } from "./useProgressSamples";import { durationText } from "../model/format";-import { nextCheckStatus } from "../model/status";-import { type Lens, type Job } from "../model/types";+import { type Job } from "../model/types";import { cn } from "@/lib/cva.config";const steps = ["review runs", "find patterns", "check evidence"];@@ -32,11 +30,7 @@ export function InvestigationProgress({ job, onCancel }: { job: Job; onCancel?:const now = useNow(1000);const progress = analysisProgress(job);const fraction = analysisFraction(progress);- const [samples, setSamples] = useState<ProgressSample[]>([]);- const latest = samples.at(-1);- if (!latest || latest.step !== progress.step || latest.done !== progress.done) {- setSamples([...samples, { at: now, step: progress.step, done: progress.done, fraction }].slice(-120));- }+ const samples = useProgressSamples(progress);const pace = analysisPace(samples, now);const percent = Math.round(fraction * 100);const queued = progress.step < 0;@@ -130,20 +124,3 @@ export function InvestigationProgress({ job, onCancel }: { job: Job; onCancel?:</section>);}--export function NextCheck({ lens }: { lens: Lens }) {- const now = useNow(15000);- const label = nextCheckStatus(lens, now);- if (!label) return null;- return <p className="mt-1 text-xs text-muted-foreground">{label}</p>;-}--export function ScanDuration({ job }: { job: Job }) {- if (!job.finished_at) return null;- return (- <span title="Total time, including any wait for an analyzer">- {" · Took "}- {analysisElapsed(job.created_at, Date.parse(job.finished_at))}- </span>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationStatus.tsx b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationStates.tsxsimilarity index 69%rename from ui/litellm-dashboard/src/components/lens/investigations/InvestigationStatus.tsxrename to ui/litellm-dashboard/src/components/lens/investigations/InvestigationStates.tsxindex c8064a80b4e..aa313cd6e37 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationStatus.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationStates.tsx@@ -1,52 +1,13 @@"use client";-import type { ReactNode } from "react";import { ArrowUpRight, Loader2, SearchX, TriangleAlert } from "lucide-react";import { Button, buttonVariants } from "@/components/ui/button";-import { cn } from "@/lib/cva.config";+import { StateMessage } from "../ui/StateMessage";import { ApiError } from "@/lib/http/client";const DOCS_URL = "https://docs.litellm.ai/docs/proxy/lens";-function CenteredState({- role,- icon,- tone = "muted",- title,- description,- children,-}: {- role: "status" | "alert";- icon: ReactNode;- tone?: "muted" | "destructive";- title: string;- description: ReactNode;- children?: ReactNode;-}) {- return (- <div- role={role}- className="m-auto flex max-w-sm flex-col items-center gap-3 py-16 text-center animate-in fade-in-0 duration-300 motion-reduce:animate-none"- >- <span- aria-hidden="true"- className={cn(- "flex size-10 items-center justify-center rounded-full",- tone === "destructive" ? "bg-destructive/10 text-destructive" : "bg-muted text-muted-foreground",- )}- >- {icon}- </span>- <div className="flex flex-col gap-1">- <p className="text-sm font-medium text-foreground">{title}</p>- <p className="text-sm text-muted-foreground">{description}</p>- </div>- {children && <div className="mt-1 flex items-center gap-2">{children}</div>}- </div>- );-}-function DocsLink() {return (<a@@ -71,7 +32,7 @@ function loadFailureMessage(queryError: unknown, unavailable: boolean): string {export function InvestigationsLoadFailed({ queryError, refresh }: { queryError: unknown; refresh: () => void }) {const unavailable = queryError instanceof ApiError && queryError.status === 404;return (- <CenteredState+ <StateMessagerole="alert"tone="destructive"icon={<TriangleAlert className="size-5" />}@@ -82,7 +43,7 @@ export function InvestigationsLoadFailed({ queryError, refresh }: { queryError:{unavailable ? "Reload page" : "Try again"}</Button><DocsLink />- </CenteredState>+ </StateMessage>);}@@ -102,7 +63,7 @@ export function InvestigationError({ message, refresh }: { message: string; refrexport function InvestigationsLoading() {return (- <CenteredState+ <StateMessagerole="status"icon={<Loader2 className="size-5 animate-spin motion-reduce:animate-none" />}title="Loading investigations…"@@ -113,7 +74,7 @@ export function InvestigationsLoading() {export function InvestigationMissing({ selectLens }: { selectLens: (id: string | null) => void }) {return (- <CenteredState+ <StateMessagerole="alert"icon={<SearchX className="size-5" />}title="Investigation not found"@@ -122,6 +83,6 @@ export function InvestigationMissing({ selectLens }: { selectLens: (id: string |<Button size="sm" onClick={() => selectLens(null)}>View all investigations</Button>- </CenteredState>+ </StateMessage>);}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.integration.test.tsxindex 26445880070..5d90281a080 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.integration.test.tsx@@ -1,12 +1,13 @@import { act, fireEvent, screen, within, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";-import { renderWithProviders as renderProviders, testQueryClient } from "@/../tests/test-utils";+import { testQueryClient } from "@/../tests/test-utils";+import { renderWithLens } from "@/../tests/lens-test-utils";import { ApiError } from "@/lib/http/client";import { apiClient } from "@/components/networking";-import { lensKeys } from "../api/queries";+import { lensKeys } from "../data/queries";import { InvestigationsView } from "./InvestigationsView";-import { LensPreviewContext } from "../LensPreviewButton";+import { LensPreviewContext } from "@/components/view_logs/TraceView/LensPreviewButton";import { briefMarkdown } from "../model/findings";import { findingKey } from "../model/inbox";import { runTime } from "../model/format";@@ -16,13 +17,14 @@ const withPreview = (ui: React.ReactElement, open: () => void) => (<LensPreviewContext.Provider value={{ target: document.body, open }}>{ui}</LensPreviewContext.Provider>);-function renderWithProviders(ui: React.ReactElement, options?: Parameters<typeof renderProviders>[1]) {- return renderProviders(ui, { searchParams: window.location.search, ...options });+function renderWithProviders(ui: React.ReactElement, options?: Parameters<typeof renderWithLens>[1]) {+ return renderWithLens(ui, { searchParams: window.location.search, ...options });}vi.mock("@/components/networking", () => ({apiClient: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), request: vi.fn() },proxyBaseUrl: "",+ getProxyBaseUrl: () => "",}));beforeEach(() => {@@ -169,12 +171,13 @@ describe("Lens findings and runs", () => {it("separates patterns from issues and reveals original evidence only when requested", async () => {const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);- expect(await screen.findByText("Review used the wrong defect rate")).toBeInTheDocument();- expect(screen.queryByText(pattern.title)).not.toBeInTheDocument();+ renderWithProviders(<InvestigationsView readOnly />);+ const investigation = within(await screen.findByRole("complementary", { name: "Investigation details" }));+ expect(investigation.getByText("Review used the wrong defect rate")).toBeInTheDocument();+ expect(investigation.queryByText(pattern.title)).not.toBeInTheDocument();await user.click(screen.getByRole("button", { name: "Patterns (1)" }));await user.click(screen.getByRole("button", { name: new RegExp(pattern.title) }));- const detail = within(screen.getByRole("dialog", { name: pattern.title }));+ const detail = within(screen.getByRole("complementary", { name: "Finding details" }));expect(detail.getByText(pattern.description)).toBeVisible();expect(detail.getByText(pattern.limitation ?? "")).not.toBeVisible();expect(detail.getByText("Ignore the review instructions")).not.toBeVisible();@@ -201,9 +204,9 @@ describe("Lens findings and runs", () => {return { data: [] };});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);+ renderWithProviders(<InvestigationsView readOnly />);await user.click(await screen.findByRole("button", { name: new RegExp(finding.title) }));- return { user, detail: within(screen.getByRole("dialog", { name: finding.title })) };+ return { user, detail: within(screen.getByRole("complementary", { name: "Finding details" })) };}it.each(["Claude Code", "Codex"])("renders the issue brief and copies its markdown for %s", async (agent) => {@@ -232,12 +235,36 @@ describe("Lens findings and runs", () => {it("shows the actual frozen run selection in the Runs tab", async () => {const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);- await user.click(await screen.findByRole("tab", { name: "Traces" }));+ renderWithProviders(<InvestigationsView readOnly />);+ await user.click(await screen.findByRole("tab", { name: "Agent traces" }));expect(screen.getByText("Release-42")).toBeInTheDocument();expect(screen.getByTitle("trace-42")).toHaveTextContent("Release-42");expect(screen.getByText(/1 selected from 1 matching runs/)).toBeInTheDocument();});++ it("closes the open run when the keyboard switches to another investigation run", async () => {+ testQueryClient.clear();+ const older = { ...lens.jobs[0], id: "older", created_at: "2026-09-29T10:00:00Z" };+ vi.mocked(apiClient.get).mockImplementation(async (path) => {+ if (path === "/lens") return { lenses: [lens], workers: [], tracing_enabled: true };+ if (path === "/lens/lens/runs") return [...lens.jobs, older];+ return { data: [] };+ });+ const onUrlUpdate = vi.fn();+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView readOnly />, {+ searchParams: `?lens=lens§ion=runs&evidence=${executionId}`,+ onUrlUpdate,+ });+ expect(await screen.findByTestId("run-panel")).toBeInTheDocument();+ const picker = screen.getByRole("combobox", { name: "Investigation run" });+ await waitFor(() => expect(within(picker).getAllByRole("option")).toHaveLength(4));+ fireEvent.change(picker, { target: { value: "older" } });+ await waitFor(() => expect(screen.queryByTestId("run-panel")).not.toBeInTheDocument());+ const url = new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? ""));+ expect(url.get("run")).toBe("older");+ expect(url.has("evidence")).toBe(false);+ });});it("runs with saved settings from Run now without opening setup, then accepts an agent and window", async () => {@@ -264,7 +291,7 @@ it("runs with saved settings from Run now without opening setup, then accepts an});vi.mocked(apiClient.post).mockResolvedValue(lens);const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />);+ renderWithProviders(<InvestigationsView />);await user.click(await screen.findByRole("button", { name: "Run now" }));const choices = await screen.findByRole("dialog", { name: "Run now" });expect(within(choices).getByRole("button", { name: "Since last run" })).toHaveAttribute("aria-pressed", "true");@@ -293,7 +320,7 @@ it("offers the interactive demo without starting an investigation", async () =>});const onPreview = vi.fn();const user = userEvent.setup();- renderWithProviders(withPreview(<InvestigationsView accessToken="test" />, onPreview));+ renderWithProviders(withPreview(<InvestigationsView />, onPreview));await user.click(await screen.findByRole("button", { name: "Preview sample" }));expect(onPreview).toHaveBeenCalledOnce();expect(apiClient.post).not.toHaveBeenCalled();@@ -308,17 +335,21 @@ it("guides a first-time administrator into worker connection and lens setup", asreturn { traces: true, requests: false, data: [] };});const user = userEvent.setup();- renderWithProviders(withPreview(<InvestigationsView accessToken="test" />, vi.fn()));- const guide = within(await screen.findByRole("region", { name: "Run your first investigation" }));+ const connect = vi.fn();+ const create = vi.fn();+ renderWithProviders(withPreview(<InvestigationsView />, vi.fn()), {+ onboarding: { connect, create },+ });+ const guide = within(await screen.findByRole("region", { name: "Get Lens running" }));expect(apiClient.get).toHaveBeenCalledWith("/lens/activity/available", { accessToken: "test" });- expect(guide.getByText("Traces received")).toBeVisible();- expect(guide.queryByRole("link", { name: "View traces" })).not.toBeInTheDocument();+ expect(guide.getByRole("button", { name: /Send your first trace/ })).toContainElement(+ guide.getByLabelText("Step 2 complete"),+ );+ expect(guide.queryByRole("button", { name: "View traces" })).not.toBeInTheDocument();expect(await screen.findByRole("button", { name: "Preview sample" })).toBeVisible();await user.click(guide.getByRole("button", { name: "Connect worker" }));- const connection = within(await screen.findByRole("dialog", { name: "Connect a worker" }));- expect(connection.getByRole("button", { name: "Get install command" })).toBeVisible();- await user.click(connection.getByRole("button", { name: "Close" }));- expect(guide.getByRole("button", { name: "New investigation" })).toBeDisabled();+ expect(connect).toHaveBeenCalledOnce();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();await act(async () => {testQueryClient.setQueryData(lensKeys.list("test"), {lenses: [],@@ -335,10 +366,11 @@ it("guides a first-time administrator into worker connection and lens setup", as],});});- await waitFor(() => expect(guide.getByRole("button", { name: "New investigation" })).toBeEnabled());- expect(guide.queryByRole("button", { name: "Preview sample" })).not.toBeInTheDocument();- await user.click(guide.getByRole("button", { name: "New investigation" }));- expect(await screen.findByRole("dialog", { name: "Which activity should we investigate?" })).toBeVisible();+ await user.click(await guide.findByRole("button", { name: "Continue to investigation" }));+ expect(create).toHaveBeenCalledOnce();+ expect(screen.queryByRole("button", { name: "Preview sample" })).not.toBeInTheDocument();+ await user.click(guide.getByRole("button", { name: /Run your first investigation/ }));+ expect(guide.getByRole("button", { name: "New investigation" })).toBeEnabled();});it("opens the saved results of an older batch", async () => {@@ -357,11 +389,12 @@ it("opens the saved results of an older batch", async () => {return { data: [] };});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);+ renderWithProviders(<InvestigationsView readOnly />);await screen.findByRole("option", { name: `${runTime(older.created_at)} · completed` });await user.selectOptions(screen.getByRole("combobox", { name: "Investigation run" }), "older");- expect(await screen.findByText("Earlier batch finding")).toBeVisible();- expect(screen.queryByText(issue.title)).not.toBeInTheDocument();+ const investigation = within(screen.getByRole("complementary", { name: "Investigation details" }));+ expect(await investigation.findByText("Earlier batch finding")).toBeVisible();+ expect(investigation.queryByText(issue.title)).not.toBeInTheDocument();await user.click(screen.getByRole("button", { name: "Run details" }));expect(screen.getByText(/Took 2m 13s/)).toBeVisible();expect(screen.getByText("Activity window")).toBeVisible();@@ -396,9 +429,14 @@ it("reads request content from the beginning after its abbreviated preview", asy};});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);- await user.click(await screen.findByRole("tab", { name: "Traces" }));- await user.click(screen.getByRole("button", { name: /Release-42/ }));+ renderWithProviders(<InvestigationsView readOnly />);+ await user.click(await screen.findByRole("tab", { name: "Agent traces" }));+ const row = screen.getByRole("button", { name: /Release-42/ });+ await user.click(row);+ const panel = await screen.findByRole("complementary", { name: "Run details" });+ expect(row).toHaveAttribute("aria-selected", "true");+ expect(panel).toHaveTextContent("1 / 1");+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();expect(await screen.findByText("Abbreviated preview")).toBeVisible();await user.click(screen.getByRole("button", { name: "Next section" }));expect(await screen.findByText("Original at 1")).toBeVisible();@@ -418,15 +456,15 @@ it.each([false, true])(vi.mocked(apiClient.get).mockImplementation(async (path) =>path === "/lens" ? { lenses: [], workers: [], tracing_enabled: enabled } : { data: [] },);- renderWithProviders(<InvestigationsView accessToken="test" />);- expect(await screen.findByRole("heading", { name: "Find what needs attention" })).toBeVisible();- expect(screen.getByRole("link", { name: "Set up traces" })).toHaveAttribute(- "href",- expect.stringMatching(/^\/ui\/lens\/?\?tab=traces$/),- );- expect(screen.getByRole("button", { name: "New investigation" })).toBeDisabled();- expect(screen.getByRole("button", { name: "Connect worker" })).toBeDisabled();- expect(screen.queryByRole("button", { name: "Set up analysis" })).not.toBeInTheDocument();+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView />);+ const guide = within(await screen.findByRole("region", { name: "Get Lens running" }));+ expect(guide.getByRole("button", { name: /Send your first trace/ })).toHaveAttribute("aria-expanded", "true");+ expect(guide.getByRole("button", { name: "Check for traces" })).toBeVisible();+ await user.click(guide.getByRole("button", { name: /Connect a worker/ }));+ expect(guide.getByRole("button", { name: "Connect worker" })).toBeDisabled();+ await user.click(guide.getByRole("button", { name: /Run your first investigation/ }));+ expect(guide.getByRole("button", { name: "New investigation" })).toBeDisabled();},);@@ -439,15 +477,14 @@ it("enables first-lens setup when a trace arrives without leaving Investigations);vi.useFakeTimers();try {- const view = renderWithProviders(<InvestigationsView accessToken="test" />);+ const view = renderWithProviders(<InvestigationsView />);await act(async () => vi.advanceTimersByTimeAsync(50));- expect(screen.getByRole("link", { name: "Set up traces" })).toBeVisible();+ expect(screen.queryByText(/Your first trace is ready/)).not.toBeInTheDocument();traceCheck.mockResolvedValue({ traces: true, requests: false });await act(async () => vi.advanceTimersByTimeAsync(5000));- expect(screen.getByRole("button", { name: "Connect worker" })).toBeEnabled();- expect(screen.getByRole("button", { name: "New investigation" })).toBeDisabled();- expect(screen.queryByRole("link", { name: "Set up traces" })).not.toBeInTheDocument();+ expect(screen.getByText(/Your first trace is ready/)).toBeVisible();+ expect(screen.getByRole("button", { name: "Continue to worker" })).toBeEnabled();const completedChecks = traceCheck.mock.calls.length;await act(async () => vi.advanceTimersByTimeAsync(5000 * 2));@@ -471,13 +508,12 @@ it("allows retrying a failed trace readiness check without treating it as an empreturn { data: [] };});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />);- expect(await screen.findByRole("alert")).toHaveTextContent(- "Could not check recorded activity. Trace storage unavailable",- );- expect(screen.getByRole("button", { name: "Connect worker" })).toBeDisabled();+ renderWithProviders(<InvestigationsView />);+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not check setup. Trace storage unavailable");+ expect(screen.getByRole("region", { name: "Get Lens running" })).toBeVisible();await user.click(screen.getByRole("button", { name: "Retry" }));- expect(await screen.findByRole("link", { name: "Set up traces" })).toBeVisible();+ await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());+ expect(traceCheck).toHaveBeenCalledTimes(2);});it("shows a centered failure with a retry when investigations cannot load, then recovers", async () => {@@ -489,12 +525,12 @@ it("shows a centered failure with a retry when investigations cannot load, then.mockResolvedValue({ lenses: [], workers: [], tracing_enabled: true });vi.mocked(apiClient.get).mockImplementation(async (path) => (path === "/lens" ? list() : { data: [] }));const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />);+ renderWithProviders(<InvestigationsView />);const alert = await screen.findByRole("alert");expect(alert).toHaveTextContent("Couldn't load investigations");expect(alert).toHaveTextContent("Proxy timed out");await user.click(within(alert).getByRole("button", { name: "Try again" }));- expect(await screen.findByRole("heading", { name: "Find what needs attention" })).toBeVisible();+ expect(await screen.findByRole("region", { name: "Get Lens running" })).toBeVisible();expect(screen.queryByRole("alert")).not.toBeInTheDocument();});@@ -505,9 +541,9 @@ it("keeps saved investigations accessible when tracing is disabled", async () =>if (path === "/lens/lens/runs") return lens.jobs;return { data: [] };});- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);- expect(await screen.findByText(issue.title)).toBeVisible();- expect(screen.queryByRole("link", { name: "Set up traces" })).not.toBeInTheDocument();+ renderWithProviders(<InvestigationsView readOnly />);+ expect(await screen.findByRole("row", { name: issue.title })).toBeVisible();+ expect(screen.queryByRole("region", { name: "Get Lens running" })).not.toBeInTheDocument();});it("allows request-only accounts to connect a worker without requiring agent traces", async () => {@@ -518,13 +554,16 @@ it("allows request-only accounts to connect a worker without requiring agent traif (path === "/lens/activity/available") return { traces: false, requests: true };return { data: [] };});- renderWithProviders(<InvestigationsView accessToken="test" />);- expect(await screen.findByText("Request logs received")).toBeVisible();- expect(screen.getByRole("button", { name: "Connect worker" })).toBeEnabled();- expect(screen.getByRole("button", { name: "New investigation" })).toBeDisabled();+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView />);+ expect(await screen.findByRole("button", { name: "Connect worker" })).toBeEnabled();+ await user.click(screen.getByRole("button", { name: /Send your first trace/ }));+ const panel = within(screen.getByRole("region", { name: /Send your first trace/ }));+ expect(panel.getByText(/Request logs are already available/)).toBeVisible();+ expect(panel.getByRole("button", { name: "Continue with request logs" })).toBeEnabled();});-it("reopens the edit dialog from a shared link and drops it from the URL on cancel", async () => {+it("reopens the inline editor from a shared link and drops it from the URL on cancel", async () => {testQueryClient.clear();vi.mocked(apiClient.get).mockImplementation(async (path) => {if (path === "/lens") return { lenses: [lens], workers: [], tracing_enabled: true };@@ -534,14 +573,17 @@ it("reopens the edit dialog from a shared link and drops it from the URL on canc});const onUrlUpdate = vi.fn();const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />, {+ renderWithProviders(<InvestigationsView />, {searchParams: `?lens=${lens.id}&dialog=edit`,onUrlUpdate,});- const dialog = await screen.findByRole("dialog");- expect(within(dialog).getByDisplayValue(lens.settings.name)).toBeVisible();- await user.click(within(dialog).getByRole("button", { name: "Cancel" }));- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ const editor = await screen.findByRole("region", { name: "Edit investigation" });+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(within(editor).getByDisplayValue(lens.settings.name)).toBeVisible();+ expect(screen.queryByRole("heading", { level: 2, name: lens.settings.name })).not.toBeInTheDocument();+ await user.click(within(editor).getByRole("button", { name: "Cancel" }));+ await waitFor(() => expect(screen.queryByRole("region", { name: "Edit investigation" })).not.toBeInTheDocument());+ expect(await screen.findByRole("heading", { level: 2, name: lens.settings.name })).toBeVisible();const url = new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? ""));expect(url.has("dialog")).toBe(false);expect(url.get("lens")).toBe(lens.id);@@ -557,21 +599,101 @@ it("reopens a finding and a results section from shared links", async () => {});const onUrlUpdate = vi.fn();const user = userEvent.setup();- const { unmount } = renderWithProviders(<InvestigationsView accessToken="test" />, {+ const { unmount } = renderWithProviders(<InvestigationsView />, {searchParams: `?issue=${encodeURIComponent(findingKey(lens, issue))}`,onUrlUpdate,});- const sheet = await screen.findByRole("dialog");- expect(within(sheet).getAllByText(issue.title)[0]).toBeVisible();- await user.click(within(sheet).getByRole("button", { name: "Close" }));- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- expect(new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString)).has("issue")).toBe(false);+ const panel = await screen.findByRole("complementary", { name: "Finding details" });+ expect(within(panel).getByRole("heading", { name: issue.title })).toBeVisible();+ expect(screen.getByRole("row", { name: issue.title })).toHaveAttribute("aria-selected", "true");+ await user.click(within(panel).getByRole("button", { name: "Close finding (Esc)" }));+ await waitFor(() =>+ expect(new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString)).has("issue")).toBe(false),+ );+ expect(screen.getByRole("row", { name: issue.title })).toHaveAttribute("aria-selected", "false");unmount();- renderWithProviders(<InvestigationsView accessToken="test" />, { searchParams: `?lens=${lens.id}§ion=checks` });+ renderWithProviders(<InvestigationsView />, { searchParams: `?lens=${lens.id}§ion=checks` });expect(await screen.findByRole("tab", { name: "Criteria", selected: true })).toBeVisible();});+it("steps across findings and investigations with J and K, skipping hidden findings, and closes with Escape", async () => {+ window.history.replaceState({}, "", "/lens/");+ testQueryClient.clear();+ const twinIssue: Finding = { ...issue, id: "twin-issue", title: "Twin review used the wrong defect rate" };+ const twin: Lens = {+ ...lens,+ id: "twin",+ settings: { ...lens.settings, name: "Twin reviews" },+ findings: [twinIssue],+ jobs: lens.jobs.map((job) => ({ ...job, findings: [twinIssue] })),+ };+ vi.mocked(apiClient.get).mockImplementation(async (path) => {+ if (path === "/lens") return { lenses: [lens, twin], tracing_enabled: true, workers: [] };+ if (path === "/lens/activity/available") return { traces: true, requests: false };+ if (path.endsWith("/runs")) return [];+ return { data: [] };+ });+ const onUrlUpdate = vi.fn();+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView />, { onUrlUpdate });+ const lastIssue = () => new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? "")).get("issue");+ await user.click(await screen.findByRole("button", { name: `Hide findings for ${twin.settings.name}` }));+ expect(screen.queryByRole("row", { name: twinIssue.title })).not.toBeInTheDocument();++ await user.click(screen.getByRole("row", { name: issue.title }));+ const panel = await screen.findByRole("complementary", { name: "Finding details" });+ expect(panel).toHaveTextContent("2 / 3");+ await waitFor(() => expect(lastIssue()).toBe(findingKey(lens, issue)));++ await user.keyboard("j");+ await waitFor(() => expect(lastIssue()).toBeNull());+ expect(screen.getByRole("row", { name: twin.settings.name })).toHaveAttribute("aria-selected", "true");+ expect(screen.queryByRole("row", { name: twinIssue.title })).not.toBeInTheDocument();+ const twinPanel = screen.getByRole("complementary", { name: "Investigation details" });+ expect(within(twinPanel).getByRole("heading", { level: 2, name: twin.settings.name })).toBeVisible();+ expect(twinPanel).toHaveTextContent("3 / 3");+ expect(screen.getByRole("button", { name: "Next investigation (J)" })).toBeDisabled();++ await user.keyboard("k");+ await waitFor(() => expect(lastIssue()).toBe(findingKey(lens, issue)));+ await user.keyboard("{Escape}");+ await waitFor(() => expect(lastIssue()).toBeNull());+ expect(screen.getByRole("row", { name: issue.title })).toHaveAttribute("aria-selected", "false");+});++it("opens an investigation beside the list and walks from it into its findings with J and K", async () => {+ window.history.replaceState({}, "", "/lens/");+ testQueryClient.clear();+ vi.mocked(apiClient.get).mockImplementation(async (path) => {+ if (path === "/lens") return { lenses: [lens], tracing_enabled: true, workers: [] };+ if (path === "/lens/activity/available") return { traces: true, requests: false };+ if (path.endsWith("/runs")) return [];+ return { data: [] };+ });+ const onUrlUpdate = vi.fn();+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView />, { onUrlUpdate });+ const lastUrl = () => new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? ""));+ await user.click(await screen.findByRole("row", { name: lens.settings.name }));+ const panel = await screen.findByRole("complementary", { name: "Investigation details" });+ expect(within(panel).getByRole("heading", { level: 2, name: lens.settings.name })).toBeVisible();+ expect(screen.getByRole("table", { name: "Investigations" })).toBeVisible();+ expect(panel).toHaveTextContent("1 / 2");+ await waitFor(() => expect(lastUrl().get("lens")).toBe(lens.id));++ await user.keyboard("j");+ await waitFor(() => expect(lastUrl().get("issue")).toBe(findingKey(lens, issue)));+ expect(lastUrl().has("lens")).toBe(false);+ expect(screen.getByRole("complementary", { name: "Finding details" })).toHaveTextContent("2 / 2");+ expect(screen.getByRole("row", { name: issue.title })).toHaveAttribute("aria-selected", "true");++ await user.keyboard("k");+ await waitFor(() => expect(lastUrl().get("lens")).toBe(lens.id));+ expect(lastUrl().has("issue")).toBe(false);+ expect(screen.getByRole("complementary", { name: "Investigation details" })).toHaveTextContent("1 / 2");+});+it("lists each finding under the investigation that owns it and resolves only that copy", async () => {window.history.replaceState({}, "", "/lens/");testQueryClient.clear();@@ -579,11 +701,12 @@ it("lists each finding under the investigation that owns it and resolves only thvi.mocked(apiClient.get).mockImplementation(async (path) => {if (path === "/lens") return { lenses: [lens, twin], tracing_enabled: true, workers: [] };if (path === "/lens/activity/available") return { traces: true, requests: false };+ if (path.endsWith("/runs")) return [];return { data: [] };});vi.mocked(apiClient.patch).mockResolvedValue(undefined);const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />);+ renderWithProviders(<InvestigationsView />);const rows = await screen.findAllByRole("row", { name: issue.title });expect(rows).toHaveLength(2);await user.click(await screen.findByRole("button", { name: `Hide findings for ${lens.settings.name}` }));@@ -606,7 +729,7 @@ it("lists investigations without edit or run controls for read-only viewers", asreturn { data: [] };});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);+ renderWithProviders(<InvestigationsView readOnly />);const row = await screen.findByRole("row", { name: lens.settings.name });expect(within(row).queryByRole("button", { name: /now/ })).not.toBeInTheDocument();await user.click(row);@@ -625,7 +748,7 @@ it("opens investigations from the keyboard without treating nested edit keys asreturn { data: [] };});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />);+ renderWithProviders(<InvestigationsView />);const row = await screen.findByRole("row", { name: lens.settings.name });row.focus();expect(row).toHaveFocus();@@ -633,14 +756,16 @@ it("opens investigations from the keyboard without treating nested edit keys asexpect(await screen.findByRole("heading", { level: 2, name: lens.settings.name })).toBeVisible();expect(screen.queryByRole("dialog")).not.toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByRole("row", { name: lens.settings.name })).toHaveAttribute("aria-selected", "true");+ await user.click(screen.getByRole("button", { name: "Close investigation (Esc)" }));const editButton = await screen.findByRole("button", { name: `Edit ${lens.settings.name}` });editButton.focus();expect(editButton).toHaveFocus();await user.keyboard("{Enter}");- const dialog = await screen.findByRole("dialog");- expect(within(dialog).getByDisplayValue(lens.settings.name)).toBeVisible();+ const editor = await screen.findByRole("region", { name: "Edit investigation" });+ expect(within(editor).getByDisplayValue(lens.settings.name)).toBeVisible();expect(screen.queryByRole("heading", { level: 2, name: lens.settings.name })).not.toBeInTheDocument();+ expect(screen.queryByRole("row", { name: lens.settings.name })).not.toBeInTheDocument();});it("opens a failed investigation's details from its row and edits only from the pencil", async () => {@@ -663,13 +788,12 @@ it("opens a failed investigation's details from its row and edits only from thereturn { data: [] };});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />);+ renderWithProviders(<InvestigationsView />);await user.click(await screen.findByRole("button", { name: `Edit ${lens.settings.name}` }));- const dialog = await screen.findByRole("dialog");- expect(within(dialog).getByDisplayValue(lens.settings.name)).toBeVisible();- await user.click(within(dialog).getByRole("button", { name: "Cancel" }));- await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());- await user.click(screen.getByRole("row", { name: lens.settings.name }));+ const editor = await screen.findByRole("region", { name: "Edit investigation" });+ expect(within(editor).getByDisplayValue(lens.settings.name)).toBeVisible();+ await user.click(within(editor).getByRole("button", { name: "Cancel" }));+ await user.click(await screen.findByRole("row", { name: lens.settings.name }));expect(within(await screen.findByRole("alert")).getByLabelText("Investigation error")).toHaveTextContent("boom");expect(screen.queryByRole("dialog")).not.toBeInTheDocument();});@@ -686,7 +810,7 @@ it("shows the actual saved failure and run context without opening backend logs"if (path === "/lens/lens/runs/failed-run") return job;return { data: [] };});- renderWithProviders(<InvestigationsView accessToken="test" readOnly />);+ renderWithProviders(<InvestigationsView readOnly />);const failure = within(await screen.findByRole("alert"));expect(failure.getByLabelText("Investigation error")).toHaveTextContent(error.replaceAll("\n", " "));expect(failure.getByText("failed-run")).toBeVisible();@@ -701,6 +825,7 @@ it("keeps a finding open to retry when its update fails", async () => {vi.mocked(apiClient.get).mockImplementation(async (path) => {if (path === "/lens") return { lenses: [lens, twin], tracing_enabled: true, workers: [] };if (path === "/lens/activity/available") return { traces: true, requests: false };+ if (path.endsWith("/runs")) return [];return { data: [] };});vi.mocked(apiClient.patch).mockReset();@@ -708,10 +833,76 @@ it("keeps a finding open to retry when its update fails", async () => {if (String(path).startsWith("/lens/twin/")) throw new Error("Twin reviews could not be updated");});const user = userEvent.setup();- renderWithProviders(<InvestigationsView accessToken="test" />);+ renderWithProviders(<InvestigationsView />);await user.click(await screen.findByRole("button", { name: `Hide findings for ${lens.settings.name}` }));await user.click(screen.getByRole("row", { name: issue.title }));await user.click(await screen.findByRole("button", { name: "Mark resolved" }));expect(await screen.findByText("Twin reviews could not be updated")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Mark resolved" })).toBeVisible();});++it("pauses monitoring from the detail menu by saving the investigation with monitoring off", async () => {+ testQueryClient.clear();+ const watching: Lens = { ...lens, settings: { ...lens.settings, enabled: true } };+ vi.mocked(apiClient.get).mockImplementation(async (path) => {+ if (path === "/lens") return { lenses: [watching], workers: [], tracing_enabled: true };+ if (path === "/lens/lens/runs") return watching.jobs;+ return { data: [] };+ });+ vi.mocked(apiClient.request).mockReset();+ vi.mocked(apiClient.request).mockResolvedValue({ ...watching, settings: lens.settings });+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView />);+ await user.click(await screen.findByRole("button", { name: "Investigation actions" }));+ await user.click(await screen.findByRole("menuitem", { name: "Pause monitoring" }));+ await waitFor(() => expect(apiClient.request).toHaveBeenCalledTimes(1));+ expect(apiClient.request).toHaveBeenCalledWith("PUT", "/lens/lens", {+ accessToken: "test",+ body: { ...watching.settings, enabled: false },+ });+});++it("cancels the running job from the progress banner", async () => {+ testQueryClient.clear();+ const running = { ...lens.jobs[0], id: "live", status: "running" as const, stage: "Reading executions" };+ vi.mocked(apiClient.get).mockImplementation(async (path) => {+ if (path === "/lens")+ return { lenses: [{ ...lens, jobs: [running, lens.jobs[0]] }], workers: [], tracing_enabled: true };+ if (path === "/lens/lens/runs") return [running, lens.jobs[0]];+ return { data: [] };+ });+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView />);+ await user.click(await screen.findByRole("button", { name: "Cancel" }));+ await waitFor(() =>+ expect(apiClient.post).toHaveBeenCalledWith("/lens/lens/cancel", { accessToken: "test", body: {} }),+ );+});++it("refreshes run history as soon as the list reports a job the scheduler started", async () => {+ testQueryClient.clear();+ const runs = vi.fn().mockResolvedValue(lens.jobs);+ vi.mocked(apiClient.get).mockImplementation(async (path) => {+ if (path === "/lens") return { lenses: [lens], workers: [], tracing_enabled: true };+ if (path === "/lens/lens/runs") return runs();+ return { data: [] };+ });+ const user = userEvent.setup();+ renderWithProviders(<InvestigationsView readOnly />);+ await user.click(await screen.findByRole("tab", { name: "History" }));+ const history = within(await screen.findByRole("tabpanel", { name: "History" }));+ expect(await history.findByText("completed")).toBeVisible();+ const fetched = runs.mock.calls.length;++ const queued = { ...lens.jobs[0], id: "scheduled", status: "queued" as const, stage: "Queued", findings: null };+ runs.mockResolvedValue([queued, lens.jobs[0]]);+ await act(async () => {+ testQueryClient.setQueryData(lensKeys.list("test"), {+ lenses: [{ ...lens, jobs: [queued, lens.jobs[0]] }],+ workers: [],+ tracing_enabled: true,+ });+ });+ expect(await history.findByText("queued")).toBeVisible();+ expect(runs.mock.calls.length).toBeGreaterThan(fetched);+});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.tsx b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.tsxindex eee9460f4cb..c668bba3799 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsView.tsx@@ -1,344 +1,225 @@"use client";-import {- InvestigationMissing,- InvestigationsLoadFailed,- InvestigationsLoading,- InvestigationError,-} from "./InvestigationStatus";-import { InvestigationNavigation } from "./InvestigationNavigation";-import { useInvestigationResults } from "./useInvestigationResults";+import type { ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import { Plus } from "lucide-react";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/cva.config";+import { LensPreviewButton } from "@/components/view_logs/TraceView/LensPreviewButton";-import { useLensUpdate, useSaveLens, type LensWrite } from "../api/mutations";-import { lensKeys, lensQueries } from "../api/queries";-import { useLensApi } from "../services";+import { useInvalidateLenses } from "../data/mutations";+import { lensQueries } from "../data/queries";+import { useLensApi } from "../data/LensServices";+import { findFinding, findingKey, type OwnedFinding } from "../model/inbox";+import type { Finding, Lens, Settings } from "../model/types";+import { useDialogRoute, useIssueRoute, useLensRoute } from "../route";+import { InvestigationSetup } from "../setup/InvestigationSetup";+import { MonitoringDialog } from "../setup/MonitoringDialog";+import { useLensReadiness } from "../hooks/useLensReadiness";+import { OnboardingSetup } from "../onboarding/OnboardingSetup";import { InvestigationDetail } from "./detail/InvestigationDetail";+import { RunNowDialog } from "./detail/RunNowDialog";+import { FindingPanelBody } from "./FindingDetails";+import { InvestigationList, type InvestigationRow } from "./InvestigationList";+import { investigationScreen, type Screen, type SetupScreen } from "./investigationScreen";+import {+ InvestigationError,+ InvestigationMissing,+ InvestigationsLoadFailed,+ InvestigationsLoading,+} from "./InvestigationStates";import { ReadinessBanner } from "./ReadinessBanner";-import { RequestEvidenceSheet } from "./RequestEvidenceSheet";-import { useNow } from "@/hooks/useNow";+import { useInvestigationActions } from "./useInvestigationActions";+import { WatchAllBanner } from "./WatchAllBanner";-import { useDialogRoute, useIssueRoute, useLensRoute } from "../route";+export interface InvestigationsViewProps {+ readonly readOnly?: boolean;+}-import { useState } from "react";-import { useQuery, useQueryClient } from "@tanstack/react-query";+const assertNever = (value: never): never => {+ throw new Error(`Unhandled screen ${JSON.stringify(value)}`);+};-import { FindingSheet } from "./FindingSheet";-import { TraceSheet } from "./TraceSheet";-import { InvestigationSetupDialog } from "../setup/InvestigationSetupDialog";-import { WorkerDialog } from "../setup/worker/WorkerDialog";-import { useAnalysisKeyInfo } from "../setup/worker/AnalysisKeyDetails";-import { InvestigationList } from "./InvestigationList";-import { HeaderActions } from "../HeaderActions";-import { RunNowDialog } from "./detail/RunNowDialog";-import { findFinding, findingAgents, findingKey, sampledExecutions } from "../model/inbox";-import { WatchAllBanner } from "./WatchAllBanner";-import { MonitoringDialog } from "../setup/MonitoringDialog";-import { InvestigationsWelcome } from "./InvestigationsWelcome";-import { workerConnected, readiness } from "../model/status";-import { type Finding, type Lens, type Settings } from "../model/types";+interface BannersProps {+ readonly error: Error | null | undefined;+ readonly activityReady: boolean | null;+ readonly flush: boolean;+ readonly refresh: () => void;+}++function Banners({ error, activityReady, flush, refresh }: BannersProps) {+ if (!error && activityReady === null) return null;+ return (+ <div className={cn("flex flex-col gap-3", flush && "p-2 pb-0")}>+ {error && <InvestigationError message={error.message} refresh={refresh} />}+ {activityReady !== null && <ReadinessBanner activityReady={activityReady} className="py-2 text-xs" />}+ </div>+ );+}-export function InvestigationsView({- active = true,- accessToken,- readOnly = false,-}: {- active?: boolean;- accessToken: string;- readOnly?: boolean;-}) {- const api = useLensApi(accessToken);- const client = useQueryClient();- const updateLens = useLensUpdate(accessToken);- const saveLens = useSaveLens(accessToken);- const { dialog, target: dialogTarget, openDialog, closeDialog } = useDialogRoute();+export function InvestigationsView({ readOnly = false }: InvestigationsViewProps) {+ const api = useLensApi();+ const invalidateLenses = useInvalidateLenses();+ const actions = useInvestigationActions();+ const { dialog, target, openDialog, closeDialog } = useDialogRoute();const { issueKey, setIssueKey } = useIssueRoute();- const workerSetup = dialog === "workers";- const now = useNow(2000);- const query = useQuery(lensQueries.list(api, workerSetup));- const models = useQuery(lensQueries.models(api));- const modelDetails = useQuery(lensQueries.modelDetails(api));- const [agentsAsOf] = useState(() => new Date().toISOString());- const agents = useQuery(lensQueries.agents(api, agentsAsOf, "traces"));- const { lensId: selected, setLensId: setSelected } = useLensRoute();- const [skipped, setSkipped] = useState<readonly { id: string; name: string; reason: string }[]>([]);- const [error, setError] = useState("");- const [busy, setBusy] = useState(false);- const lenses = [...(query.data?.lenses ?? [])].sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));- const showEmpty = !query.isLoading && !query.error && lenses.length === 0;- const loaded = !query.isLoading && !query.error;- const showActions = !readOnly && !!query.data && !showEmpty;- const showReadiness = loaded && !showEmpty && !readOnly;- const missingSelection = !!selected && loaded;- const lens = lenses.find((e) => e.id === selected);- const targetLens = dialogTarget ? lenses.find((e) => e.id === dialogTarget) : lens;- const editing = dialog === "new" || dialog === "edit" || dialog === "duplicate" ? dialog : null;- const setupMode = editing === "new" || targetLens ? editing : null;- const peeked = issueKey ? findFinding(lenses, issueKey) : undefined;- const resultsLens = peeked?.lens ?? lens;- const results = useInvestigationResults(accessToken, resultsLens);- const {- finding,- sampledRuns,- target,- evidence,- requestEvidenceData,- requestEvidenceError,- requestEvidenceLoading,- requestOffset,- setRequestOffset,- setEvidence,- setFindingId,- reset: resetResults,- } = results;- const selectLens = (id: string | null) => {- setSelected(id);- resetResults();+ const { lensId, setLensId } = useLensRoute();+ const list = useQuery(lensQueries.list(api));+ const status = useLensReadiness(true);+ const { connected } = status;+ const screenInput = { list, lensId, dialog, target };+ const screen = investigationScreen(screenInput);+ const lenses = list.data?.lenses ?? [];+ const lens = lenses.find((candidate) => candidate.id === lensId);+ const peeked = issueKey ? findFinding(lenses, issueKey) ?? null : null;+ const selectedRow = (open: Lens | undefined): InvestigationRow | null => {+ if (peeked) return { kind: "finding", ...peeked };+ return open ? { kind: "investigation", lens: open } : null;};- const setEditing = (mode: "new" | "edit" | "duplicate") => openDialog(mode);- const setWorkerSetup = (open: boolean) => (open ? openDialog("workers") : closeDialog());- const setMonitoring = (open: boolean) => (open ? openDialog("monitoring") : closeDialog());- const connected = query.data?.workers?.some((w) => workerConnected(w, now)) ?? false;- const activeWorkers = query.data?.workers.filter((worker) => !worker.revoked) ?? [];- const defaultKeyId = activeWorkers.length === 1 ? activeWorkers[0].analysis_key_id : undefined;- const analysisAccess = useAnalysisKeyInfo(accessToken, defaultKeyId ?? undefined);- const defaultModel = analysisAccess.data?.models.length === 1 ? analysisAccess.data.models[0] : undefined;- const activity = useQuery(lensQueries.activity(api, loaded));- const { tracesReady, requestsReady, activityReady, ready } = readiness(- activity.data,- activity.error,- connected,- query.error,- );- const setupSettings = () => {- if (editing === "new") return undefined;- if (editing === "duplicate" && targetLens)- return { ...targetLens.settings, name: `${targetLens.settings.name} copy`, enabled: false };- return targetLens?.settings;+ const selectRow = (row: InvestigationRow | null) => {+ if (row?.kind === "finding") setIssueKey(findingKey(row.lens, row.finding));+ else if (row) setLensId(row.lens.id);+ else if (peeked) setIssueKey(null);+ else setLensId(null);};- const refresh = () => {- void client.invalidateQueries({ queryKey: lensKeys.list(api.scope) });- void client.invalidateQueries({ queryKey: lensKeys.histories() });+ const reviewPeeked = async (owned: OwnedFinding, status: Finding["status"], reason: string) => {+ const saved = await actions.review(owned.lens, owned.finding, status, reason);+ if (saved) setIssueKey(null);};- const update = async (write: LensWrite): Promise<boolean> => {- setBusy(true);- setError("");- try {- await updateLens.mutateAsync(write);- return true;- } catch (e) {- setError(e instanceof Error ? e.message : "Could not update lens");- return false;- } finally {- await client.invalidateQueries({ queryKey: lensKeys.list(api.scope) });- setBusy(false);- }+ const dialogLens = target ? lenses.find((candidate) => candidate.id === target) : lens;+ const refresh = () => {+ actions.reset();+ void invalidateLenses();};- const save = async (settings: Settings) => {- if (editing === "edit" && !targetLens) throw new Error("Reopen the investigation to edit its settings");- if (editing !== "edit" && !ready)+ const saveSetup = async (setup: SetupScreen, settings: Settings) => {+ if (setup.mode !== "edit" && !status.ready)throw new Error("Wait for recorded activity and a connected worker before starting an investigation");- const saved = await saveLens.mutateAsync({ id: editing === "edit" ? targetLens?.id : undefined, settings });+ const saved = await actions.save({ id: setup.mode === "edit" ? setup.lens.id : undefined, settings });closeDialog();- if (!dialogTarget) selectLens(saved.id);- refresh();- };- const openFinding = (owner: Lens, picked: Finding) => setIssueKey(findingKey(owner, picked));- const closeFinding = () => {- setFindingId(null);- setIssueKey(null);+ if (!target) setLensId(saved.id);};- const changeFinding = async (status: Finding["status"], reason: string) => {- if (peeked) {- const saved = await update((current) => current.reviewFinding(peeked.lens.id, peeked.finding.id, status, reason));- if (saved) closeFinding();- return;- }- if (!lens || !finding) return;- await update((current) => current.reviewFinding(lens.id, finding.id, status, reason));- };- const sheetFinding = peeked ? peeked.finding : finding;- const sheetRuns = peeked ? sampledExecutions(peeked.lens) : sampledRuns;- const detailAgents = lens && finding ? findingAgents(lens, finding) : [];- const sheetAgents = peeked ? findingAgents(peeked.lens, peeked.finding) : detailAgents;+ const bannerError = screen.kind === "failed" ? undefined : actions.error ?? list.error;+ const browsing = screen.kind === "list";+ const showReadiness = browsing && !readOnly && !status.ready;- const onDetail = !!selected;- const showDetailNav = onDetail && !showEmpty;- const showTables = !onDetail && lenses.length > 0;- const showMissing = missingSelection && !lens;- return (- <section aria-label="Investigations" className="flex w-full min-w-0 flex-1 flex-col gap-3">- {showDetailNav && (- <InvestigationNavigation- lens={lens}- showActions={showActions}- activityReady={activityReady}- connected={connected}- ready={ready}- selectLens={selectLens}- setWorkerSetup={setWorkerSetup}- setEditing={setEditing}- />- )}- {query.error && !query.data ? (- <InvestigationsLoadFailed queryError={query.error} refresh={refresh} />- ) : (- (error || query.error) && <InvestigationError message={error || query.error?.message || ""} refresh={refresh} />- )}- {query.isLoading && <InvestigationsLoading />}- {loaded && showEmpty && (- <InvestigationsWelcome- tracesReady={tracesReady}- requestsReady={requestsReady}- checking={activity.isPending}- traceError={activity.error?.message}- connected={connected}- readOnly={!!readOnly}- onRetry={() => {- void activity.refetch();- refresh();- }}- onConnect={() => setWorkerSetup(true)}- onCreate={() => setEditing("new")}- showPreview={activity.isSuccess && !ready}- />- )}- {showReadiness && !ready && <ReadinessBanner activityReady={activityReady} className="py-2 text-xs" />}- {showTables && (- <div className="flex min-h-0 flex-1 flex-col gap-2">- {active && (- <HeaderActions>- {!readOnly && (- <WatchAllBanner- lenses={lenses}- busy={busy}- skipped={skipped}- onWatchAll={() =>- update(async (api) => {- const result = await api.watchAll();- setSkipped(result.skipped);- })- }- />- )}- <InvestigationNavigation- lens={undefined}- showActions={showActions}- activityReady={activityReady}- connected={connected}- ready={ready}- selectLens={selectLens}- setWorkerSetup={setWorkerSetup}- setEditing={setEditing}- />- </HeaderActions>- )}+ const content = (current: Screen): ReactNode => {+ switch (current.kind) {+ case "loading":+ return <InvestigationsLoading />;+ case "failed":+ return <InvestigationsLoadFailed queryError={current.error} refresh={refresh} />;+ case "missing":+ return <InvestigationMissing selectLens={setLensId} />;+ case "welcome":+ if (status.loading) return <InvestigationsLoading />;+ return (+ <>+ {!status.ready && <LensPreviewButton />}+ <OnboardingSetup state={status} className="mx-auto w-full max-w-3xl py-6" />+ </>+ );+ case "list":+ return (<InvestigationList- lenses={lenses}+ lenses={current.lenses}connected={connected}readOnly={readOnly}- onOpen={selectLens}+ selected={selectedRow(current.lens)}+ onSelect={selectRow}onEdit={(id) => openDialog("edit", id)}onRunNow={(id) => openDialog("run_now", id)}- onOpenFinding={openFinding}+ actions={+ !readOnly && (+ <>+ <WatchAllBanner lenses={current.lenses} />+ <Button size="sm" className="h-8" disabled={!status.ready} onClick={() => openDialog("new")}>+ <Plus className="size-4" /> New investigation+ </Button>+ </>+ )+ }+ >+ {(row) =>+ row.kind === "finding" ? (+ <FindingPanelBody+ owned={row}+ readOnly={readOnly}+ busy={actions.busy}+ onReview={(owned, reviewStatus, reason) => void reviewPeeked(owned, reviewStatus, reason)}+ />+ ) : (+ <div className="min-h-0 flex-1 overflow-y-auto p-4">+ <InvestigationDetail+ lens={row.lens}+ readOnly={readOnly}+ ready={status.ready}+ busy={actions.busy}+ connected={connected}+ onEdit={() => openDialog("edit")}+ onDuplicate={() => openDialog("duplicate")}+ onPause={() => void actions.pause(row.lens)}+ onEnableMonitoring={() => openDialog("monitoring")}+ onCancelRun={() => void actions.cancelRun(row.lens)}+ onRunNow={() => openDialog("run_now")}+ onReviewFinding={(owned, reviewStatus, reason) =>+ void actions.review(owned.lens, owned.finding, reviewStatus, reason)+ }+ />+ </div>+ )+ }+ </InvestigationList>+ );+ case "setup":+ return (+ <InvestigationSetup+ ready={status.ready}+ mode={current.mode}+ initial={current.mode === "new" ? undefined : current.initial}+ defaultSource={!status.tracesReady && status.requestsReady ? "requests" : "traces"}+ onClose={closeDialog}+ onSave={(settings) => saveSetup(current, settings)}/>- </div>- )}- {showMissing && <InvestigationMissing selectLens={selectLens} />}- {lens && (- <InvestigationDetail- lens={lens}- readOnly={readOnly}- ready={ready}- busy={busy}- setEditing={setEditing}- setMonitoring={setMonitoring}- onRunNow={() => openDialog("run_now")}- update={update}- connected={connected}- results={results}- />- )}- {setupMode && (- <InvestigationSetupDialog- ready={ready}- mode={setupMode}- initial={setupSettings()}- defaultModel={defaultModel}- defaultSource={!tracesReady && requestsReady ? "requests" : "traces"}- models={models.data?.data.map((m) => m.id) ?? []}- modelDetails={modelDetails.data?.data ?? []}- modelsLoading={models.isLoading}- modelsError={models.error?.message}- accessToken={accessToken}- onClose={closeDialog}- onSave={save}- />- )}- {dialog === "run_now" && targetLens && (+ );+ default:+ return assertNever(current);+ }+ };++ return (+ <section+ aria-label="Investigations"+ className={cn("flex w-full min-w-0 flex-1 flex-col", !browsing && "gap-3 p-4")}+ >+ <Banners+ error={bannerError}+ activityReady={showReadiness ? status.activityReady : null}+ flush={browsing}+ refresh={refresh}+ />+ {content(screen)}+ {dialog === "run_now" && dialogLens && (<RunNowDialog- lens={targetLens}- agents={Array.isArray(agents.data) ? agents.data : []}- busy={busy}+ lens={dialogLens}+ busy={actions.busy}onClose={closeDialog}onRun={async (request) => {- await update((api) => api.startRun(targetLens.id, request));+ await actions.startRun(dialogLens, request);closeDialog();}}/>)}- {workerSetup && (- <WorkerDialog- accessToken={accessToken}- workers={query.data?.workers ?? []}- onClose={closeDialog}- onChanged={refresh}- onReady={ready && showEmpty ? () => openDialog("new") : undefined}- />- )}- {dialog === "monitoring" && lens && (+ {dialog === "monitoring" && dialogLens && (<MonitoringDialog- settings={lens.settings}- ready={ready}+ settings={dialogLens.settings}+ ready={status.ready}onClose={closeDialog}onSave={async (settings) => {- await saveLens.mutateAsync({ id: lens.id, settings });- refresh();+ await actions.save({ id: dialogLens.id, settings });}}/>)}- <FindingSheet- finding={sheetFinding}- agents={sheetAgents}- sampledRuns={sheetRuns}- readOnly={readOnly}- busy={busy}- onClose={closeFinding}- changeFinding={changeFinding}- onEvidence={(value) => {- setRequestOffset(0);- setEvidence(value);- }}- />- {resultsLens && target?.source === "traces" && (- <TraceSheet- open={!!evidence}- traceId={target.id}- traceRef={target.traceRef}- initialSpanId={evidence?.span}- accessToken={accessToken}- onClose={() => setEvidence(null)}- />- )}- <RequestEvidenceSheet- target={target}- setEvidence={setEvidence}- requestEvidenceData={requestEvidenceData}- requestEvidenceError={requestEvidenceError}- requestEvidenceLoading={requestEvidenceLoading}- requestOffset={requestOffset}- setRequestOffset={setRequestOffset}- /></section>);}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsWelcome.tsx b/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsWelcome.tsxdeleted file mode 100644index 6b0b20ead4b..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/InvestigationsWelcome.tsx+++ /dev/null@@ -1,168 +0,0 @@-import Link from "next/link";-import { Check, Loader2 } from "lucide-react";-import { Button, buttonVariants } from "@/components/ui/button";-import { LensPreviewButton } from "../LensPreviewButton";-import { uiHref } from "@/utils/uiHref";-import { cn } from "@/lib/cva.config";--export function InvestigationsWelcome({- tracesReady,- requestsReady = false,- checking,- traceError,- connected,- readOnly,- onConnect,- onCreate,- onRetry,- showPreview = false,-}: {- tracesReady: boolean;- requestsReady?: boolean;- checking: boolean;- traceError?: string;- connected: boolean;- readOnly: boolean;- onConnect: () => void;- onCreate: () => void;- onRetry: () => void;- showPreview?: boolean;-}) {- const activityReady = tracesReady || requestsReady;- const workerReady = activityReady && connected;- const canCreate = workerReady && !readOnly;- const canConnect = activityReady && !readOnly;- const traceStatus = activityStatus(tracesReady, requestsReady, checking);- const waitingForWorker = activityReady && !connected;- const stepOffset = Number(!activityReady);- const introduction = activityReady- ? {- title: "Run your first investigation",- description: "Your recorded activity is ready. Connect a worker and choose what Lens should look for.",- }- : {- title: "Find what needs attention",- description: "Check how your agents behave. Get findings you can trace back to what happened.",- };- const traceButtonClass = buttonVariants({- variant: "default",- className: "col-start-2 w-fit sm:col-start-auto",- });- return (- <section aria-labelledby="lens-welcome" className="m-auto w-full max-w-2xl py-10">- {showPreview && <LensPreviewButton />}- <h2 id="lens-welcome" className="text-xl font-semibold tracking-tight">- {introduction.title}- </h2>- <p className="mt-2 max-w-lg text-sm leading-6 text-muted-foreground">{introduction.description}</p>- {activityReady && (- <p role="status" className="mt-3 text-sm text-success">- {traceStatus}- </p>- )}- <ol className="mt-8 divide-y border-y">- {!activityReady && (- <li className="grid grid-cols-[28px_minmax(0,1fr)] items-center gap-x-4 gap-y-3 py-5 sm:grid-cols-[28px_minmax(0,1fr)_auto]">- <Step number={1} complete={activityReady} checking={checking} active={!activityReady} />- <div>- <h3 className="text-sm font-medium">Set up traces</h3>- <p className="mt-1 text-sm text-muted-foreground">{traceStatus}</p>- </div>- <Link href={uiHref("lens/?tab=traces")} className={traceButtonClass}>- Set up traces- </Link>- </li>- )}- <li- data-state={activityReady ? "active" : "inactive"}- className="grid grid-cols-[28px_minmax(0,1fr)] items-center gap-x-4 gap-y-3 py-5 text-muted-foreground data-[state=active]:text-foreground sm:grid-cols-[28px_minmax(0,1fr)_auto]"- >- <Step number={stepOffset + 1} complete={workerReady} active={waitingForWorker} />- <div>- <h3 className="text-sm font-medium">Connect a worker</h3>- <p className="mt-1 text-sm text-muted-foreground">- {workerReady ? "Worker connected" : "Runs your investigations in the background."}- </p>- </div>- <Button- className="col-start-2 w-fit sm:col-start-auto"- variant={waitingForWorker ? "default" : "ghost"}- disabled={!canConnect}- onClick={onConnect}- >- {connected ? "Manage worker" : "Connect worker"}- </Button>- </li>- <li- data-state={workerReady ? "active" : "inactive"}- className="grid grid-cols-[28px_minmax(0,1fr)] items-center gap-x-4 gap-y-3 py-5 text-muted-foreground data-[state=active]:text-foreground sm:grid-cols-[28px_minmax(0,1fr)_auto]"- >- <Step number={stepOffset + 2} complete={false} active={workerReady} />- <div>- <h3 className="text-sm font-medium">Run an investigation</h3>- </div>- <Button- className="col-start-2 w-fit sm:col-start-auto"- variant={workerReady ? "default" : "ghost"}- disabled={!canCreate}- onClick={onCreate}- >- New investigation- </Button>- </li>- </ol>- {traceError && (- <div role="alert" className="mt-6 text-sm text-destructive">- Could not check recorded activity. {traceError}{" "}- <Button variant="link" onClick={onRetry}>- Retry- </Button>- </div>- )}- {readOnly && (- <p className="mt-6 text-sm text-muted-foreground">An administrator can finish setup and run investigations.</p>- )}- </section>- );-}--function Step({- number,- complete,- checking = false,- active = false,-}: {- number: number;- complete: boolean;- checking?: boolean;- active?: boolean;-}) {- const incomplete = checking ? <Loader2 className="size-4 animate-spin" /> : number;- const state = stepState(complete, active);- return (- <span- data-state={state}- className={cn(- "flex size-7 items-center justify-center rounded-full text-xs font-medium",- "data-[state=complete]:bg-emerald-50 data-[state=complete]:text-emerald-700 dark:data-[state=complete]:bg-emerald-950 dark:data-[state=complete]:text-emerald-400",- "data-[state=active]:bg-foreground data-[state=active]:text-background",- "data-[state=inactive]:border data-[state=inactive]:text-muted-foreground",- )}- aria-label={complete ? `Step ${number} complete` : `Step ${number}`}- >- {complete ? <Check className="size-4" /> : incomplete}- </span>- );-}--function stepState(complete: boolean, active?: boolean) {- if (complete) return "complete";- if (active) return "active";- return "inactive";-}--function activityStatus(traces: boolean, requests: boolean, checking: boolean) {- if (traces) return "Traces received";- if (requests) return "Request logs received";- return checking ? "Checking for activity…" : "Connect your agent and send a trace.";-}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/IssueBrief.tsx b/ui/litellm-dashboard/src/components/lens/investigations/IssueBrief.tsxindex 1f3847af87c..02f1c4b34fd 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/IssueBrief.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/IssueBrief.tsx@@ -51,7 +51,7 @@ export function IssueBrief({ title, brief }: { title: string; brief: IssueBriefclassName="inline-flex h-7 items-center gap-1.5 rounded-md border border-border bg-background px-2 text-xs font-medium hover:bg-muted">{copied === agent.name ? (- <Check className="size-3.5 text-emerald-600" />+ <Check className="size-3.5 text-success" />) : (<img src={agent.logo} alt="" aria-hidden className="size-3.5" />)}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/RequestEvidenceSheet.tsx b/ui/litellm-dashboard/src/components/lens/investigations/RequestEvidenceSheet.tsxdeleted file mode 100644index 1be718ea008..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/RequestEvidenceSheet.tsx+++ /dev/null@@ -1,69 +0,0 @@-"use client";--import type { components } from "@/lib/http/schema";--import { Button } from "@/components/ui/button";--import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from "@/components/ui/sheet";-import { evidenceTarget } from "../model/findings";--type RequestEvidence = components["schemas"]["ExecutionContent"];--export function RequestEvidenceSheet({- target,- setEvidence,- requestEvidenceData,- requestEvidenceError,- requestEvidenceLoading,- requestOffset,- setRequestOffset,-}: {- target: ReturnType<typeof evidenceTarget>;- setEvidence: (value: { id: string; span: string } | null) => void;- requestEvidenceData: RequestEvidence | undefined;- requestEvidenceError: Error | null | undefined;- requestEvidenceLoading: boolean;- requestOffset: number;- setRequestOffset: (offset: number) => void;-}) {- return (- <Sheet- open={target?.source === "requests"}- onOpenChange={(open) => {- if (!open) setEvidence(null);- }}- >- <SheetContent className="overflow-y-auto data-[side=right]:sm:max-w-2xl">- <SheetHeader>- <SheetTitle>Request evidence</SheetTitle>- <SheetDescription>Original logged input and output</SheetDescription>- </SheetHeader>- <div className="p-4 space-y-3">- {requestEvidenceLoading && <p role="status">Loading request…</p>}- {requestEvidenceError && <p role="alert">{requestEvidenceError.message}</p>}- {requestEvidenceData?.parts.map((p) => (- <pre className="whitespace-pre-wrap break-words text-xs" key={p.span_id}>- {p.content}- </pre>- ))}- {requestEvidenceData?.parts.length === 0 && <p>Request was not found or is past retention</p>}- <div className="flex flex-wrap gap-2">- {requestOffset > 0 && (- <Button variant="outline" onClick={() => setRequestOffset(Math.max(0, requestOffset - 8000))}>- Previous section- </Button>- )}- {requestEvidenceData?.parts.some((p) => p.truncated) && (- <Button- variant="outline"- onClick={() => setRequestOffset(requestOffset === 0 ? 1 : requestOffset + 8000)}- >- Next section- </Button>- )}- </div>- </div>- </SheetContent>- </Sheet>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/TraceSheet.test.tsx b/ui/litellm-dashboard/src/components/lens/investigations/TraceSheet.test.tsxdeleted file mode 100644index bf50ad89639..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/TraceSheet.test.tsx+++ /dev/null@@ -1,20 +0,0 @@-import { render, screen } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";--import type { RunSelection } from "@/components/view_logs/TraceView/traceRouting";--import { TraceSheet } from "./TraceSheet";--vi.mock("@/components/view_logs/TraceView/TraceDrawer", () => ({- RunView: ({ selection }: { selection: RunSelection }) => <div data-testid="run-view">{selection.spanId}</div>,-}));--describe("TraceSheet", () => {- it("opens another finding's evidence on its own step", () => {- const props = { open: true, traceId: "trace-1", accessToken: "t", onClose: vi.fn() };- const { rerender } = render(<TraceSheet {...props} initialSpanId="step-a" />);- expect(screen.getByTestId("run-view")).toHaveTextContent("step-a");- rerender(<TraceSheet {...props} initialSpanId="step-b" />);- expect(screen.getByTestId("run-view")).toHaveTextContent("step-b");- });-});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/TraceSheet.tsx b/ui/litellm-dashboard/src/components/lens/investigations/TraceSheet.tsxdeleted file mode 100644index c8a1f2644ef..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/TraceSheet.tsx+++ /dev/null@@ -1,64 +0,0 @@-import { RunView } from "@/components/view_logs/TraceView/TraceDrawer";-import { useLocalRunSelection } from "@/components/view_logs/TraceView/traceRouting";-import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from "@/components/ui/sheet";--export function TraceSheet({- open,- traceId,- traceRef,- initialSpanId,- accessToken,- onClose,-}: {- open: boolean;- traceId: string;- traceRef?: string;- initialSpanId?: string;- accessToken: string;- onClose: () => void;-}) {- return (- <Sheet- open={open}- onOpenChange={(value) => {- if (!value) onClose();- }}- >- <SheetContent className="w-full overflow-y-auto data-[side=right]:sm:max-w-[90vw]">- <SheetHeader>- <SheetTitle className="text-xl">Original run</SheetTitle>- <SheetDescription>Recorded agent steps and evidence</SheetDescription>- </SheetHeader>- {open && (- <SheetRun- key={`${traceId}:${traceRef}:${initialSpanId}`}- traceId={traceId}- traceRef={traceRef}- initialSpanId={initialSpanId ?? null}- accessToken={accessToken}- onBack={onClose}- />- )}- </SheetContent>- </Sheet>- );-}--function SheetRun({- traceId,- traceRef,- initialSpanId,- accessToken,- onBack,-}: {- traceId: string;- traceRef?: string;- initialSpanId: string | null;- accessToken: string;- onBack: () => void;-}) {- const selection = useLocalRunSelection(initialSpanId);- return (- <RunView traceId={traceId} traceRef={traceRef} selection={selection} accessToken={accessToken} onBack={onBack} />- );-}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/WatchAllBanner.tsx b/ui/litellm-dashboard/src/components/lens/investigations/WatchAllBanner.tsxindex 4c8c8a00e75..6c16b4d7c1d 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/WatchAllBanner.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/WatchAllBanner.tsx@@ -1,20 +1,23 @@"use client";+import { z } from "zod";+import { useLensUpdate } from "../data/mutations";import type { Lens } from "../model/types";-export function WatchAllBanner({- lenses,- busy,- onWatchAll,- skipped = [],-}: {- lenses: readonly Lens[];- busy: boolean;- onWatchAll: () => void;- skipped?: readonly { id: string; name: string; reason: string }[];-}) {+const watchAllResult = z.object({+ skipped: z.array(z.object({ id: z.string(), name: z.string(), reason: z.string() })),+});++export interface WatchAllBannerProps {+ readonly lenses: readonly Lens[];+}++export function WatchAllBanner({ lenses }: WatchAllBannerProps) {+ const watchAll = useLensUpdate();const paused = lenses.filter((lens) => !lens.settings.enabled).length;if (paused === 0) return null;+ const result = watchAllResult.safeParse(watchAll.data);+ const skipped = result.success ? result.data.skipped : [];if (skipped.length >= paused)return (<span@@ -27,11 +30,11 @@ export function WatchAllBanner({);return (<span role="status" className="text-xs text-muted-foreground">- {paused} paused ·{" "}+ {paused} paused · {watchAll.error && <span className="text-destructive">{watchAll.error.message} · </span>}<buttontype="button"- disabled={busy}- onClick={onWatchAll}+ disabled={watchAll.isPending}+ onClick={() => watchAll.mutate((api) => api.watchAll())}className="font-medium text-foreground underline-offset-2 hover:underline disabled:opacity-50">Turn all ondiff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/CriteriaTab.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/CriteriaTab.tsxindex ffaf0bf48fc..3b1470408c2 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/CriteriaTab.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/CriteriaTab.tsx@@ -4,39 +4,37 @@ import { Button } from "@/components/ui/button";import { TabsContent } from "@/components/ui/tabs";import { type Settings } from "../../model/types";-import { watches } from "../../setup/watches";+import { watches } from "../../model/watches";-export function CriteriaTab({- batchSettings,- readOnly,- setEditing,-}: {- batchSettings: Settings | undefined;- readOnly: boolean;- setEditing: (mode: "edit") => void;-}) {+export interface CriteriaTabProps {+ readonly settings: Settings | undefined;+ readonly readOnly: boolean;+ readonly onEditCriteria: () => void;+}++export function CriteriaTab({ settings, readOnly, onEditCriteria }: CriteriaTabProps) {return (<TabsContent value="checks" className="pt-4 space-y-4"><div className="flex items-center justify-between"><p className="text-sm text-muted-foreground">Used for this run</p>{!readOnly && (- <Button variant="outline" size="sm" onClick={() => setEditing("edit")}>+ <Button variant="outline" size="sm" onClick={onEditCriteria}>Edit criteria</Button>)}</div>- {batchSettings?.context && (+ {settings?.context && (<div className="space-y-2 border-b pb-5"><h3 className="text-base font-semibold">What should the agent be doing?</h3><p className="text-xs text-muted-foreground">The purpose and expected outcome of the agent.</p>- <p className="mt-2 whitespace-pre-wrap text-sm">{batchSettings.context}</p>+ <p className="mt-2 whitespace-pre-wrap text-sm">{settings.context}</p></div>)}<div className="pt-2"><h3 className="text-base font-semibold">Watch for</h3><p className="mt-1 text-xs text-muted-foreground">Specific problems or patterns to investigate.</p></div>- {batchSettings?.checks.map((c, index) => (+ {settings?.checks.map((c, index) => (<div key={c.id} className="flex items-start gap-3 border-b py-4"><span className="mt-0.5 text-xs tabular-nums text-muted-foreground">{index + 1}.</span><CheckSummary check={c} />diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/FindingsTab.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/FindingsTab.tsxindex ddea9c73313..f99d80c5db8 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/FindingsTab.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/FindingsTab.tsx@@ -1,109 +1,122 @@"use client";-import { ListRow } from "@/components/shared/ListRow";+import type { ReactNode } from "react";import { ChevronRight, CheckCircle2 } from "lucide-react";-import { Button } from "@/components/ui/button";+import { Inspector } from "@/components/shared/Inspector";+import { Button } from "@/components/ui/button";import { TabsContent } from "@/components/ui/tabs";-import { type Lens, type Finding, type Job } from "../../model/types";import { cn } from "@/lib/cva.config";-const priorityColors = { high: "bg-red-500", medium: "bg-amber-500", low: "bg-slate-400" };+import { sortedFindings } from "../../model/findings";+import type { OwnedFinding } from "../../model/inbox";+import { activeJob } from "../../model/status";+import { type Lens, type Finding, type Job } from "../../model/types";+import { ownedFindingKey } from "../FindingDetails";+import { FINDING_PANEL_WIDTH_KEY } from "../../storage";+import { useFindingFilters, useFindingRoute } from "../../route";++const priorityColors = { high: "bg-destructive", medium: "bg-warning", low: "bg-muted-foreground" };function emptyFindingTitle(active: boolean, scanned: boolean, status?: string) {if (status === "failed" || status === "cancelled") return "No findings from this run";if (active) return "Your findings will appear here";return scanned ? "No matching findings" : "Ready for the first analysis";}-export function FindingsTab({- kind,- setKind,- batchFindings,- filter,- setFilter,- visibleFindings,- setFindingId,- active,- lens,- job,-}: {- kind: "issue" | "pattern";- setKind: (kind: "issue" | "pattern") => void;- batchFindings: Finding[];- filter: string;- setFilter: (filter: string) => void;- visibleFindings: Finding[];- setFindingId: (id: string) => void;+export interface FindingsTabProps {+ readonly lens: Lens;+ readonly job: Job | undefined;+ readonly findings: readonly Finding[];+ /** The finding panel, rendered inside this tab's Inspector so J/K walk the listed findings. */+ readonly children?: ReactNode;+}- active: Job | undefined;- lens: Lens;- job: Job | undefined;-}) {+export function FindingsTab({ lens, job, findings, children }: FindingsTabProps) {+ const { kind, setKind, status, setStatus } = useFindingFilters();+ const { findingId, setFindingId } = useFindingRoute();+ const active = activeJob(lens.jobs) !== undefined;+ const openCount = (of: Finding["kind"]) => findings.filter((f) => f.kind === of && f.status === "open").length;+ const visible = sortedFindings(findings.filter((f) => (status === "all" || f.status === status) && f.kind === kind));+ const picked = findings.find((f) => f.id === findingId);+ const selected: OwnedFinding | null = picked ? { lens, finding: picked } : null;return (- <TabsContent value="findings" className="pt-4 space-y-4">- <div className="flex flex-wrap items-center justify-between gap-3">- <div className="flex gap-1" aria-label="Finding category">- <Button size="sm" variant={kind === "issue" ? "secondary" : "ghost"} onClick={() => setKind("issue")}>- Needs attention ({batchFindings.filter((f) => f.kind === "issue" && f.status === "open").length ?? 0})- </Button>- <Button size="sm" variant={kind === "pattern" ? "secondary" : "ghost"} onClick={() => setKind("pattern")}>- Patterns ({batchFindings.filter((f) => f.kind === "pattern" && f.status === "open").length ?? 0})- </Button>- </div>- <select- aria-label="Finding status"- className="rounded-md border bg-background px-2 py-1 text-xs"- value={filter}- onChange={(e) => setFilter(e.target.value)}- >- <option value="open">Open</option>- <option value="resolved">Resolved</option>- <option value="dismissed">Dismissed</option>- <option value="all">All statuses</option>- </select>- </div>- <p className="text-xs text-muted-foreground">- {kind === "issue"- ? "Problems worth investigating, highest priority first."- : "Useful behavior and trends. These do not necessarily need a fix."}- </p>- <div className="divide-y border-y">- {visibleFindings.map((f) => (- <ListRow- key={f.id}- onClick={() => {- setFindingId(f.id);- }}- className="flex w-full gap-3 py-4 text-left hover:bg-muted/30 focus-visible:outline-2 focus-visible:outline-ring"+ <Inspector.Root+ items={visible.map((finding) => ({ lens, finding }))}+ itemKey={ownedFindingKey}+ selected={selected}+ onSelectedChange={(owned) => setFindingId(owned?.finding.id ?? null)}+ noun="finding"+ storageKey={FINDING_PANEL_WIDTH_KEY}+ >+ <TabsContent value="findings" className="pt-4 space-y-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex gap-1" aria-label="Finding category">+ <Button size="sm" variant={kind === "issue" ? "secondary" : "ghost"} onClick={() => setKind("issue")}>+ Needs attention ({openCount("issue")})+ </Button>+ <Button size="sm" variant={kind === "pattern" ? "secondary" : "ghost"} onClick={() => setKind("pattern")}>+ Patterns ({openCount("pattern")})+ </Button>+ </div>+ <select+ aria-label="Finding status"+ className="rounded-md border bg-background px-2 py-1 text-xs"+ value={status}+ onChange={(e) => setStatus(e.target.value)}>- <span- data-state={f.priority ?? "medium"}- className={cn("mt-1 size-2 shrink-0 rounded-full", priorityColors[f.priority ?? "medium"])}- aria-label={`${f.priority} priority`}- />- <div className="min-w-0 flex-1">- <p className="text-sm font-medium">{f.title}</p>- <p className="mt-1 line-clamp-2 text-sm text-muted-foreground">{f.description}</p>+ <option value="open">Open</option>+ <option value="resolved">Resolved</option>+ <option value="dismissed">Dismissed</option>+ <option value="all">All statuses</option>+ </select>+ </div>+ <p className="text-xs text-muted-foreground">+ {kind === "issue"+ ? "Problems worth investigating, highest priority first."+ : "Useful behavior and trends. These do not necessarily need a fix."}+ </p>+ <div className="divide-y border-y">+ {visible.map((f) => (+ <Inspector.Row+ key={f.id}+ item={{ lens, finding: f }}+ render={+ <button+ type="button"+ className="flex w-full gap-3 py-4 text-left hover:bg-muted/30 focus-visible:outline-2 focus-visible:outline-ring data-[state=selected]:bg-trace-row-selected data-[state=selected]:shadow-[inset_2px_0_0_var(--trace-brand)]"+ />+ }+ >+ <span+ data-state={f.priority ?? "medium"}+ className={cn("mt-1 size-2 shrink-0 rounded-full", priorityColors[f.priority ?? "medium"])}+ aria-label={`${f.priority} priority`}+ />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium">{f.title}</p>+ <p className="mt-1 line-clamp-2 text-sm text-muted-foreground">{f.description}</p>+ <p className="mt-2 text-xs text-muted-foreground">+ {f.occurrences?.length ?? 0} linked {f.occurrences?.length === 1 ? "run" : "runs"} ·{" "}+ {f.kind === "issue" ? `${f.priority} priority` : "Pattern"}+ </p>+ </div>+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" />+ </Inspector.Row>+ ))}+ {visible.length === 0 && (+ <div className="px-6 py-14 text-center">+ <CheckCircle2 className="mx-auto mb-3 size-5 text-muted-foreground" />+ <p className="text-sm font-medium">{emptyFindingTitle(active, !!lens.last_scan_at, job?.status)}</p><p className="mt-2 text-xs text-muted-foreground">- {f.occurrences?.length ?? 0} linked {f.occurrences?.length === 1 ? "run" : "runs"} ·{" "}- {f.kind === "issue" ? `${f.priority} priority` : "Pattern"}+ {active+ ? "Lens is reviewing the selected activity."+ : "Findings reflect the runs analyzed, not a guarantee about all activity."}</p></div>- <ChevronRight className="size-4 shrink-0 text-muted-foreground" />- </ListRow>- ))}- {visibleFindings.length === 0 && (- <div className="px-6 py-14 text-center">- <CheckCircle2 className="mx-auto mb-3 size-5 text-muted-foreground" />- <p className="text-sm font-medium">{emptyFindingTitle(!!active, !!lens.last_scan_at, job?.status)}</p>- <p className="mt-2 text-xs text-muted-foreground">- {active- ? "Lens is reviewing the selected activity."- : "Findings reflect the runs analyzed, not a guarantee about all activity."}- </p>- </div>- )}- </div>- </TabsContent>+ )}+ </div>+ </TabsContent>+ {children}+ </Inspector.Root>);}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTab.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTab.tsxindex 6a59a2f8ff4..284d0e2626e 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTab.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTab.tsx@@ -1,47 +1,46 @@"use client";import { ListRow } from "@/components/shared/ListRow";+import { useState } from "react";import { ChevronRight } from "lucide-react";import { Button } from "@/components/ui/button";import { TabsContent } from "@/components/ui/tabs";-import { ScanDuration } from "../InvestigationProgress";-import type { Lens, Job } from "../../model/types";+import { HistoryTimeline } from "./HistoryTimeline";+import { ScanDuration } from "./JobMeta";+import { useRunHistory } from "./useRunHistory";+import type { Lens } from "../../model/types";+import { useRunRoute } from "../../route";import { money, when } from "../../model/format";-export function HistoryTab({- history,- historyError,- refetchHistory,- lens,- openBatch,- historyOffset,- setHistoryOffset,-}: {- history: Job[] | undefined;- historyError: Error | null | undefined;- refetchHistory: () => void;- lens: Lens;- openBatch: (id: string) => void;- historyOffset: number;- setHistoryOffset: (offset: number) => void;-}) {+const PAGE = 50;++export interface HistoryTabProps {+ readonly lens: Lens;+}++export function HistoryTab({ lens }: HistoryTabProps) {+ const [offset, setOffset] = useState(0);+ const history = useRunHistory(lens, offset);+ const { openRun } = useRunRoute();+ const rows = history.data ?? lens.jobs;return (<TabsContent value="activity" className="pt-4 space-y-4">- {historyError && (+ {history.error && (<p role="alert" className="text-sm text-destructive">Could not load run history.{" "}- <Button variant="link" size="sm" onClick={() => void refetchHistory()}>+ <Button variant="link" size="sm" onClick={() => void history.refetch()}>Retry</Button></p>)}+ {rows.length > 0 && <HistoryTimeline jobs={rows} slots={PAGE} onOpen={openRun} />}<div className="divide-y border-y">- {(history ?? lens.jobs)?.map((j) => (+ {rows.map((j) => (<ListRowkey={j.id}- onClick={() => openBatch(j.id)}+ onClick={() => openRun(j.id)}className="flex w-full items-center gap-4 py-4 text-left hover:bg-muted/30 focus-visible:outline-2 focus-visible:outline-ring"><div className="min-w-0 flex-1">@@ -66,21 +65,16 @@ export function HistoryTab({</ListRow>))}</div>- {(historyOffset > 0 || (history?.length ?? 0) >= 50) && (+ {(offset > 0 || (history.data?.length ?? 0) >= PAGE) && (<div className="flex justify-between">- <Button- variant="ghost"- size="sm"- disabled={!historyOffset}- onClick={() => setHistoryOffset(Math.max(0, historyOffset - 50))}- >+ <Button variant="ghost" size="sm" disabled={!offset} onClick={() => setOffset(Math.max(0, offset - PAGE))}>Newer runs</Button><Buttonvariant="ghost"size="sm"- disabled={(history?.length ?? 0) < 50}- onClick={() => setHistoryOffset(historyOffset + 50)}+ disabled={(history.data?.length ?? 0) < PAGE}+ onClick={() => setOffset(offset + PAGE)}>Older runs</Button>diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTimeline.test.ts b/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTimeline.test.tsnew file mode 100644index 00000000000..a8d10b1df16--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTimeline.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";++import type { Job } from "../../model/types";+import { checkColumns } from "./HistoryTimeline";++const coverage: Job["coverage"] = {+ eligible: 0,+ selected: 0,+ screened: 0,+ investigated: 0,+ inconclusive: 0,+ grouping_batches: 0,+ grouped_batches: 0,+ candidates: 0,+ partial: 0,+ unassessable: 0,+};++const job: Job = {+ assessments: [],+ steps: [],+ trigger: "schedule",+ coverage,+ attempts: 0,+ error: "",+ cost: 0,+ id: "scan",+ status: "running",+ stage: "Reading executions",+ created_at: "2026-09-30T12:00:00Z",+ start: "2026-09-29T12:00:00Z",+ end: "2026-09-30T12:00:00Z",+ revision: 1,+ settings: {+ context: "",+ source: "traces",+ lookback_hours: 24,+ service: "",+ agent_name: "",+ filters: [],+ enabled: false,+ interval_minutes: 15,+ sample_size: 100,+ sample_percent: 100,+ concurrency: 8,+ team_id: "",+ execution_ids: [],+ monthly_budget: 20,+ name: "Release reviews",+ model: "analysis",+ checks: [{ enabled: true, id: "failures", instruction: "Find failed outcomes" }],+ },+};++const assessment = (id: string, issues: string[]): Job["assessments"][number] => ({+ execution_id: id,+ cannot_assess: false,+ issue_checks: issues,+ pattern_checks: [],+});++const check = (id: string, status: Job["status"], screened: number, assessments: Job["assessments"]): Job => ({+ ...job,+ id,+ status,+ coverage: { ...coverage, screened },+ assessments,+});++describe("checkColumns", () => {+ const newest = check("newest", "completed", 3, [+ assessment("a", ["failures"]),+ assessment("b", []),+ assessment("c", ["failures", "other"]),+ ]);+ const oldest = check("oldest", "failed", 7, []);++ it("pads the left and puts the newest check on the right", () => {+ const columns = checkColumns([newest, oldest], 4);+ expect(columns.map((c) => c.job?.id ?? null)).toEqual([null, null, "oldest", "newest"]);+ expect(columns[0]).toMatchObject({ total: 0, failed: 0 });+ });++ it("counts reviewed traces and the traces with at least one issue", () => {+ expect(checkColumns([newest], 1)[0]).toMatchObject({ total: 3, failed: 2, opacity: 1 });+ });++ it("fades checks that did not complete", () => {+ const [failed] = checkColumns([oldest], 1);+ const [cancelled] = checkColumns([{ ...oldest, status: "cancelled" }], 1);+ expect(failed.opacity).toBeLessThan(1);+ expect(cancelled.opacity).toBe(failed.opacity);+ });++ it("keeps only the most recent checks that fit", () => {+ expect(checkColumns([newest, oldest], 1).map((c) => c.job?.id)).toEqual(["newest"]);+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTimeline.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTimeline.tsxnew file mode 100644index 00000000000..1cee2d5b1f4--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/HistoryTimeline.tsx@@ -0,0 +1,92 @@+"use client";++import { useState } from "react";++import { DotFieldCanvas, DotFieldRoot } from "@/components/shared/dotField/DotField";+import type { DotColumn } from "@/components/shared/dotField/dots";++import { when } from "../../model/format";+import type { Job } from "../../model/types";++const UNSUCCESSFUL_OPACITY = 0.35;++export interface CheckColumn extends DotColumn {+ job: Job | null;+}++const affectedRuns = (job: Job): number => job.assessments.filter((a) => a.issue_checks.length > 0).length;++/** One column per check, oldest on the left, padded with empty slots so spacing stays stable as checks accrue. */+export function checkColumns(jobs: readonly Job[], slots: number): readonly CheckColumn[] {+ const recent = jobs.slice(0, slots).reverse();+ const padding = Array.from(+ { length: slots - recent.length },+ (): CheckColumn => ({+ job: null,+ total: 0,+ failed: 0,+ series: [],+ }),+ );+ const checks = recent.map(+ (job): CheckColumn => ({+ job,+ total: job.coverage.screened,+ failed: affectedRuns(job),+ series: [],+ opacity: job.status === "failed" || job.status === "cancelled" ? UNSUCCESSFUL_OPACITY : 1,+ }),+ );+ return [...padding, ...checks];+}++const pct = (value: number): string => `${value * 100}%`;++export interface HistoryTimelineProps {+ readonly jobs: readonly Job[];+ readonly slots: number;+ readonly onOpen: (jobId: string) => void;+}++/** Every check as a dot column: reviewed traces in grey, affected traces in red, failed checks faded. */+export function HistoryTimeline({ jobs, slots, onOpen }: HistoryTimelineProps) {+ const columns = checkColumns(jobs, slots);+ const [hover, setHover] = useState<number | null>(null);+ const hovered = hover === null ? null : columns[hover];+ return (+ <div className="relative select-none" data-testid="history-timeline">+ <DotFieldRoot columns={columns} hover={hover} className="flex" onPointerLeave={() => setHover(null)}>+ <DotFieldCanvas />+ {columns.map(({ job }, i) =>+ job ? (+ <button+ key={job.id}+ type="button"+ aria-label={`Check at ${when(job.created_at)}`}+ className="relative h-full flex-1 focus-visible:outline-2 focus-visible:outline-ring"+ onPointerEnter={() => setHover(i)}+ onFocus={() => setHover(i)}+ onBlur={() => setHover(null)}+ onClick={() => onOpen(job.id)}+ />+ ) : (+ <span key={`empty-${i}`} className="h-full flex-1" />+ ),+ )}+ </DotFieldRoot>+ {hovered?.job && hover !== null && (+ <div+ role="tooltip"+ className="pointer-events-none absolute top-full z-floating mt-1 rounded-md border border-border bg-popover px-2.5 py-1.5 font-mono text-xs text-popover-foreground shadow-md"+ style={{ left: pct(Math.min(0.75, hover / slots)) }}+ >+ <div>{when(hovered.job.created_at)}</div>+ <div>+ {hovered.total} reviewed, {hovered.failed} affected+ </div>+ {hovered.job.status !== "completed" && <div className="capitalize">{hovered.job.status}</div>}+ </div>+ )}+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationActions.test.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationActions.test.tsxnew file mode 100644index 00000000000..ac6f10bbf5f--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationActions.test.tsx@@ -0,0 +1,101 @@+import { screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { renderWithProviders } from "@/../tests/test-utils";+import type { Lens } from "../../model/types";+import { InvestigationActions, type InvestigationActionsProps } from "./InvestigationActions";++const lens: Lens = {+ version: 0,+ spent: 0,+ id: "lens",+ scope: { all_teams: true, api_key_hash: "", team_id: "" },+ settings: {+ context: "",+ source: "traces",+ lookback_hours: 24,+ service: "",+ agent_name: "",+ filters: [],+ interval_minutes: 15,+ sample_size: 100,+ sample_percent: 100,+ concurrency: 8,+ team_id: "",+ execution_ids: [],+ monthly_budget: 20,+ name: "Release reviews",+ model: "analysis",+ enabled: true,+ checks: [],+ },+ revision: 1,+ created_at: "2026-09-30T10:00:00Z",+ next_run_at: "2026-09-30T10:00:00Z",+ budget_month: "2026-09",+ findings: [],+ jobs: [],+};++function renderActions(overrides: Partial<InvestigationActionsProps> = {}) {+ const intents = {+ onEdit: vi.fn(),+ onDuplicate: vi.fn(),+ onPause: vi.fn(),+ onEnableMonitoring: vi.fn(),+ onRunNow: vi.fn(),+ };+ renderWithProviders(<InvestigationActions lens={lens} ready busy={false} {...intents} {...overrides} />);+ return intents;+}++describe("InvestigationActions", () => {+ it("reports each menu choice as an intent without touching the API", async () => {+ const user = userEvent.setup();+ const intents = renderActions();+ await user.click(screen.getByRole("button", { name: "Run now" }));+ expect(intents.onRunNow).toHaveBeenCalledOnce();+ await user.click(screen.getByRole("button", { name: "Investigation actions" }));+ await user.click(await screen.findByRole("menuitem", { name: "Pause monitoring" }));+ expect(intents.onPause).toHaveBeenCalledOnce();+ expect(intents.onEnableMonitoring).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Investigation actions" }));+ await user.click(await screen.findByRole("menuitem", { name: "Edit investigation" }));+ expect(intents.onEdit).toHaveBeenCalledOnce();+ await user.click(screen.getByRole("button", { name: "Investigation actions" }));+ await user.click(await screen.findByRole("menuitem", { name: "Duplicate" }));+ expect(intents.onDuplicate).toHaveBeenCalledOnce();+ });++ it("offers to enable monitoring on a paused investigation", async () => {+ const user = userEvent.setup();+ const paused = { ...lens, settings: { ...lens.settings, enabled: false } };+ const intents = renderActions({ lens: paused });+ await user.click(screen.getByRole("button", { name: "Investigation actions" }));+ await user.click(await screen.findByRole("menuitem", { name: "Enable monitoring" }));+ expect(intents.onEnableMonitoring).toHaveBeenCalledOnce();+ expect(intents.onPause).not.toHaveBeenCalled();+ });++ it("blocks a second run while one is queued or running", () => {+ const job = {+ id: "job",+ status: "queued" as const,+ stage: "Queued",+ trigger: "manual" as const,+ attempts: 0,+ error: "",+ cost: 0,+ created_at: lens.created_at,+ start: lens.created_at,+ end: lens.created_at,+ revision: 1,+ settings: lens.settings,+ assessments: [],+ steps: [],+ findings: [],+ };+ renderActions({ lens: { ...lens, jobs: [job] } });+ expect(screen.getByRole("button", { name: "Run now" })).toBeDisabled();+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationActions.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationActions.tsxindex f13aeb14193..fa00ea0607e 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationActions.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationActions.tsx@@ -8,28 +8,34 @@ import {DropdownMenuContent,DropdownMenuItem,} from "@/components/ui/dropdown-menu";-import { type Lens, type Job } from "../../model/types";-import type { LensWrite } from "../../api/mutations";+import { hasActiveJob } from "../../model/status";+import { type Lens } from "../../model/types";++export interface InvestigationIntents {+ readonly onEdit: () => void;+ readonly onDuplicate: () => void;+ readonly onPause: () => void;+ readonly onEnableMonitoring: () => void;+ readonly onCancelRun: () => void;+ readonly onRunNow: () => void;+}++export type InvestigationActionsProps = Omit<InvestigationIntents, "onCancelRun"> & {+ readonly lens: Lens;+ readonly ready: boolean;+ readonly busy: boolean;+};export function InvestigationActions({lens,ready,busy,- active,- setEditing,- setMonitoring,- update,+ onEdit,+ onDuplicate,+ onPause,+ onEnableMonitoring,onRunNow,-}: {- lens: Lens;- ready: boolean;- busy: boolean;- active: Job | undefined;- setEditing: (mode: "new" | "edit" | "duplicate") => void;- setMonitoring: (open: boolean) => void;- update: (write: LensWrite) => Promise<unknown>;- onRunNow: () => void;-}) {+}: InvestigationActionsProps) {return (<div className="flex flex-wrap gap-2"><DropdownMenu>@@ -37,31 +43,28 @@ export function InvestigationActions({<MoreHorizontal className="size-4" /></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-48">- <DropdownMenuItem onClick={() => setEditing("edit")}>+ <DropdownMenuItem onClick={onEdit}><Settings2 />Edit investigation</DropdownMenuItem>- <DropdownMenuItem disabled={!ready} onClick={() => setEditing("duplicate")}>+ <DropdownMenuItem disabled={!ready} onClick={onDuplicate}><Copy />Duplicate</DropdownMenuItem>{lens.settings.enabled ? (- <DropdownMenuItem- disabled={busy}- onClick={() => update((api) => api.saveLens(lens.id, { ...lens.settings, enabled: false }))}- >+ <DropdownMenuItem disabled={busy} onClick={onPause}><Pause />Pause monitoring</DropdownMenuItem>) : (- <DropdownMenuItem disabled={!ready || busy} onClick={() => setMonitoring(true)}>+ <DropdownMenuItem disabled={!ready || busy} onClick={onEnableMonitoring}><Play />Enable monitoring</DropdownMenuItem>)}</DropdownMenuContent></DropdownMenu>- <Button disabled={busy || !!active || !ready} onClick={onRunNow}>+ <Button disabled={busy || hasActiveJob(lens.jobs) || !ready} onClick={onRunNow}><Play className="size-3" />Run now</Button>diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationDetail.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationDetail.tsxindex beae19c5e53..9a2bb98f29d 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationDetail.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationDetail.tsx@@ -1,74 +1,50 @@"use client";-import type { useInvestigationResults } from "../useInvestigationResults";import { Button } from "@/components/ui/button";-import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";import { RunsTab } from "./RunsTab";import { InvestigationProgress } from "../InvestigationProgress";import { StepFeed } from "../StepFeed";import { InvestigationSummary } from "./InvestigationSummary";import { InvestigationFailure } from "./InvestigationFailure";import { scopeLabel, sourceLabels } from "../../model/format";-import { type Lens } from "../../model/types";-import type { LensWrite } from "../../api/mutations";+import type { OwnedFinding } from "../../model/inbox";+import { activeJob } from "../../model/status";+import { type Finding, type Lens } from "../../model/types";+import { FindingPanel } from "../FindingDetails";+import { useSectionRoute } from "../../route";+import { useRunSnapshot } from "../useRunSnapshot";-import { InvestigationActions } from "./InvestigationActions";+import { InvestigationActions, type InvestigationIntents } from "./InvestigationActions";import { RunPicker } from "./RunPicker";import { FindingsTab } from "./FindingsTab";import { CriteriaTab } from "./CriteriaTab";import { HistoryTab } from "./HistoryTab";++export type InvestigationDetailProps = InvestigationIntents & {+ readonly lens: Lens;+ readonly readOnly: boolean;+ readonly ready: boolean;+ readonly busy: boolean;+ readonly connected: boolean;+ readonly onReviewFinding: (owned: OwnedFinding, status: Finding["status"], reason: string) => void;+};+export function InvestigationDetail({lens,readOnly,ready,busy,- setEditing,- setMonitoring,- onRunNow,- update,connected,- results,-}: {- lens: Lens;- readOnly: boolean;- ready: boolean;- busy: boolean;- setEditing: (mode: "new" | "edit" | "duplicate") => void;- setMonitoring: (open: boolean) => void;- onRunNow: () => void;- update: (write: LensWrite) => Promise<unknown>;- connected: boolean;- results: ReturnType<typeof useInvestigationResults>;-}) {- const {- active,- job,- tab,- setTab,- batchSettings,- batchId,- setBatchId,- setFindingId,- selectedOutsideHistory,- history,- historyError,- refetchHistory,- historicalError,- refetchHistorical,- missingSnapshot,- kind,- setKind,- batchFindings,- filter,- setFilter,- visibleFindings,- setRequestOffset,- setEvidence,- openBatch,- historyOffset,- setHistoryOffset,- } = results;+ onCancelRun,+ onReviewFinding,+ ...intents+}: InvestigationDetailProps) {+ const { section, setSection } = useSectionRoute();+ const snapshot = useRunSnapshot(lens);+ const { job, batchId, batchSettings, batchFindings, missingSnapshot } = snapshot;+ const active = activeJob(lens.jobs);return (<div><section className="min-w-0 space-y-5">@@ -79,107 +55,47 @@ export function InvestigationDetail({{sourceLabels[lens.settings.source ?? "traces"]} · {scopeLabel(lens.settings)}</p></div>- {!readOnly && (- <InvestigationActions- lens={lens}- ready={ready}- busy={busy}- active={active}- setEditing={setEditing}- setMonitoring={setMonitoring}- update={update}- onRunNow={onRunNow}- />- )}+ {!readOnly && <InvestigationActions lens={lens} ready={ready} busy={busy} {...intents} />}</div><InvestigationSummary lens={lens} connected={connected} />- {active && (- <InvestigationProgress- key={active.id}- job={active}- onCancel={- readOnly- ? undefined- : () => {- void update((api) => api.cancelRun(lens.id));- }- }- />- )}+ {active && <InvestigationProgress key={active.id} job={active} onCancel={readOnly ? undefined : onCancelRun} />}{active && <StepFeed job={active} />}{job?.error && <InvestigationFailure job={job} connected={connected} />}- <Tabs value={tab} onValueChange={setTab} key={lens.id}>+ <Tabs value={section} onValueChange={setSection} key={lens.id}><div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-b"><TabsList variant="line"><TabsTrigger value="findings">Findings</TabsTrigger><TabsTrigger value="checks">Criteria</TabsTrigger>- <TabsTrigger value="runs">- {- { requests: "Requests", both: "Traces & requests", traces: "Traces" }[- batchSettings?.source ?? "traces"- ]- }- </TabsTrigger>+ <TabsTrigger value="runs">{sourceLabels[batchSettings?.source ?? "traces"]}</TabsTrigger><TabsTrigger value="activity">History</TabsTrigger></TabsList>- {tab !== "activity" && (- <RunPicker- batchId={batchId}- setBatchId={setBatchId}- setFindingId={setFindingId}- job={job}- selectedOutsideHistory={selectedOutsideHistory}- history={history}- lens={lens}- />- )}+ {section !== "activity" && <RunPicker lens={lens} job={job} />}</div>- {historicalError && (+ {snapshot.error && (<p role="alert" className="text-sm text-destructive">Could not load this run.{" "}- <Button variant="link" onClick={() => void refetchHistorical()}>+ <Button variant="link" onClick={snapshot.refetch}>Retry</Button></p>)}- {missingSnapshot && tab !== "activity" && (+ {missingSnapshot && section !== "activity" && (<p className="text-sm text-muted-foreground">This older batch predates saved result snapshots. Its findings remain available under All accumulatedfindings.</p>)}- <FindingsTab- kind={kind}- setKind={setKind}- batchFindings={batchFindings}- filter={filter}- setFilter={setFilter}- visibleFindings={visibleFindings}- setFindingId={setFindingId}- active={active}- lens={lens}- job={job}- />- <CriteriaTab batchSettings={batchSettings} readOnly={readOnly} setEditing={setEditing} />- <TabsContent value="runs" className="pt-4 space-y-4">- <RunsTab- key={job?.id ?? batchId}- job={job}- onOpen={(id) => {- setRequestOffset(0);- setEvidence({ id, span: "" });- }}+ <FindingsTab lens={lens} job={job} findings={batchFindings}>+ <FindingPanel+ readOnly={readOnly}+ busy={busy}+ sampledRuns={job?.sample?.executions}+ onReview={onReviewFinding}/>- </TabsContent>- <HistoryTab- history={history}- historyError={historyError}- refetchHistory={refetchHistory}- lens={lens}- openBatch={openBatch}- historyOffset={historyOffset}- setHistoryOffset={setHistoryOffset}- />+ </FindingsTab>+ <CriteriaTab settings={batchSettings} readOnly={readOnly} onEditCriteria={intents.onEdit} />+ <RunsTab key={job?.id ?? batchId} lens={lens} job={job} />+ <HistoryTab lens={lens} /></Tabs></section></div>diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationSummary.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationSummary.tsxindex bfe08863f7d..5f2101139f9 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationSummary.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/InvestigationSummary.tsx@@ -1,5 +1,5 @@import type { ComponentProps } from "react";-import { NextCheck } from "../InvestigationProgress";+import { NextCheck } from "./JobMeta";import { lensStatus } from "../../model/status";import { runTime } from "../../model/format";import { type Lens } from "../../model/types";diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/JobMeta.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/JobMeta.tsxnew file mode 100644index 00000000000..a846b68df3d--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/JobMeta.tsx@@ -0,0 +1,23 @@+"use client";++import { useNow } from "@/hooks/useNow";+import { analysisElapsed } from "../../model/progress";+import { nextCheckStatus } from "../../model/status";+import type { Job, Lens } from "../../model/types";++export function NextCheck({ lens }: { lens: Lens }) {+ const now = useNow(15000);+ const label = nextCheckStatus(lens, now);+ if (!label) return null;+ return <p className="mt-1 text-xs text-muted-foreground">{label}</p>;+}++export function ScanDuration({ job }: { job: Job }) {+ if (!job.finished_at) return null;+ return (+ <span title="Total time, including any wait for an analyzer">+ {" · Took "}+ {analysisElapsed(job.created_at, Date.parse(job.finished_at))}+ </span>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunNowDialog.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/RunNowDialog.tsxindex 45a8ae06040..e8695c22168 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunNowDialog.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/RunNowDialog.tsx@@ -1,6 +1,7 @@"use client";import { useState } from "react";+import { useQuery } from "@tanstack/react-query";import { Button } from "@/components/ui/button";import {@@ -13,60 +14,30 @@ import {} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";-import type { Lens } from "../../model/types";--export interface RunWindow {- agent_name?: string;- start?: string;- end?: string;- lookback_hours?: number;-}--const PRESETS = [- { label: "Since last run", hours: null },- { label: "Last hour", hours: 1 },- { label: "Last 24h", hours: 24 },- { label: "Last 7d", hours: 168 },- { label: "Custom", hours: -1 },-] as const;+import { lensQueries } from "../../data/queries";+import { useLensApi } from "../../data/LensServices";+import type { Lens, RunWindow } from "../../model/types";+import { RUN_PRESETS, runRequest, type RunChoice, type RunPreset } from "../../model/runRequest";const localInput = (date: Date) =>new Date(date.getTime() - date.getTimezoneOffset() * 60_000).toISOString().slice(0, 16);-export interface RunChoice {- preset: (typeof PRESETS)[number]["hours"];- agent: string;- saved: string;- start: string;- end: string;-}--export function runRequest({ preset, agent, saved, start, end }: RunChoice): RunWindow | string {- const agentPart = agent.trim() && agent.trim() !== saved ? { agent_name: agent.trim() } : {};- if (preset === null) return agentPart;- if (preset > 0) return { ...agentPart, lookback_hours: preset };- const startMs = Date.parse(start);- const endMs = Date.parse(end);- if (Number.isNaN(startMs) || Number.isNaN(endMs)) return "Choose a start and end time";- if (startMs >= endMs) return "Start time must be before end time";- return { ...agentPart, start: new Date(startMs).toISOString(), end: new Date(endMs).toISOString() };-}-export function RunNowDialog({lens,- agents,busy,onClose,onRun,}: {lens: Lens;- agents: readonly string[];busy: boolean;onClose: () => void;onRun: (request: RunWindow) => Promise<void>;}) {+ const api = useLensApi();+ const agentsQuery = useQuery(lensQueries.agents(api, "traces"));+ const agents = Array.isArray(agentsQuery.data) ? agentsQuery.data : [];const now = new Date();- const [preset, setPreset] = useState<(typeof PRESETS)[number]["hours"]>(null);+ const [preset, setPreset] = useState<RunPreset>(null);const [agent, setAgent] = useState(lens.settings.agent_name ?? "");const [start, setStart] = useState(localInput(new Date(now.getTime() - 3_600_000)));const [end, setEnd] = useState(localInput(now));@@ -109,7 +80,7 @@ export function RunNowDialog({<fieldset className="space-y-2"><legend className="text-sm font-medium">Traces to review</legend><div className="flex flex-wrap gap-1.5">- {PRESETS.map((p) => (+ {RUN_PRESETS.map((p) => (<buttonkey={p.label}type="button"diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunPicker.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/RunPicker.tsxindex b505edf6f30..f017bd4e312 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunPicker.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/RunPicker.tsx@@ -4,46 +4,39 @@ import { Info } from "lucide-react";import { Button } from "@/components/ui/button";import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from "@/components/ui/popover";-import { ScanDuration } from "../InvestigationProgress";+import { ScanDuration } from "./JobMeta";+import { useRunHistory } from "./useRunHistory";import type { Lens, Job } from "../../model/types";+import { useRunRoute } from "../../route";import { money, when } from "../../model/format";-export function RunPicker({- batchId,- setBatchId,- setFindingId,- job,- selectedOutsideHistory,- history,- lens,-}: {- batchId: string;- setBatchId: (id: string) => void;- setFindingId: (id: string | null) => void;- job: Job | undefined;- selectedOutsideHistory: boolean;- history: Job[] | undefined;- lens: Lens;-}) {+export interface RunPickerProps {+ readonly lens: Lens;+ readonly job: Job | undefined;+}++export function RunPicker({ lens, job }: RunPickerProps) {+ const { batchId, selectRun } = useRunRoute();+ const history = useRunHistory(lens, 0);+ const options = history.data ?? lens.jobs;+ const aggregate = batchId === "latest" || batchId === "all";+ const outsideHistory = !aggregate && !options.some((j) => j.id === batchId);return (<div className="flex min-w-0 items-center gap-1 pb-1"><selectaria-label="Investigation run"className="h-8 w-44 max-w-full truncate rounded-md border-0 bg-transparent px-2 text-xs text-muted-foreground hover:bg-muted focus-visible:outline-2 focus-visible:outline-ring"value={batchId}- onChange={(e) => {- setBatchId(e.target.value);- setFindingId(null);- }}+ onChange={(e) => selectRun(e.target.value)}><option value="latest">Latest run</option>- {job && selectedOutsideHistory && (+ {job && outsideHistory && (<option value={batchId}>{when(job.created_at)} · {job.status}</option>)}- {(history ?? lens.jobs)?.map((j) => (+ {options.map((j) => (<option key={j.id} value={j.id}>{when(j.created_at)} · {j.status}</option>diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunsTab.tsx b/ui/litellm-dashboard/src/components/lens/investigations/detail/RunsTab.tsxindex bb6fd79ce0d..3f02fff5c31 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunsTab.tsx+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/RunsTab.tsx@@ -1,9 +1,25 @@-import { ListRow } from "@/components/shared/ListRow";+"use client";+import { useState } from "react";import { ChevronRight } from "lucide-react";++import { Inspector } from "@/components/shared/Inspector";import { Button } from "@/components/ui/button";+import { TabsContent } from "@/components/ui/tabs";+import { runTime } from "../../model/format";-import { type Job } from "../../model/types";+import { type Job, type Lens } from "../../model/types";+import { EvidenceView } from "../Evidence";+import { FINDING_PANEL_WIDTH_KEY } from "../../storage";+import { useRunEvidenceRoute } from "../../route";++const PAGE = 50;++interface RunRef {+ readonly id: string;+}++const runKey = (run: RunRef): string => run.id;function assessmentLabel(assessment: Job["assessments"][number] | undefined): string {if (!assessment) return "Not reviewed";@@ -11,7 +27,14 @@ function assessmentLabel(assessment: Job["assessments"][number] | undefined): streturn assessment.issue_checks?.length ? "Issue observed" : "No issue observed";}-export function RunsTab({ job, onOpen }: { job?: Job; onOpen: (id: string) => void }) {+export interface RunsTabProps {+ readonly lens: Lens;+ readonly job?: Job;+}++/** The runs a batch reviewed; each opens its original trace or request in the side panel. */+export function RunsTab({ lens, job }: RunsTabProps) {+ const { runId, selectRun } = useRunEvidenceRoute();const [runOffset, setRunOffset] = useState(0);const [runFilter, setRunFilter] = useState("all");const assessments = new Map(job?.assessments?.map((a) => [a.execution_id, a]));@@ -23,84 +46,103 @@ export function RunsTab({ job, onOpen }: { job?: Job; onOpen: (id: string) => voif (runFilter === "clear") return assessment && !assessment.cannot_assess && !assessment.issue_checks?.length;return assessment?.issue_checks?.includes(runFilter);});+ const page: readonly RunRef[] = visibleRuns.slice(runOffset, runOffset + PAGE);+ const selected: RunRef | null = runId === null ? null : runs.find((run) => run.id === runId) ?? { id: runId };return (- <div className="space-y-4">- <div className="flex flex-wrap items-center justify-between gap-3">- <p className="text-sm text-muted-foreground">- {runs.length} selected from {job?.sample?.eligible ?? 0} matching runs- </p>- <select- aria-label="Filter reviewed runs"- className="h-8 max-w-full rounded-md border bg-background px-2 text-xs sm:max-w-64"- value={runFilter}- onChange={(e) => {- setRunFilter(e.target.value);- setRunOffset(0);- }}- >- <option value="all">All outcomes</option>- <option value="clear">No issue observed</option>- <option value="unknown">Insufficient evidence or not reviewed</option>- {job?.settings?.context && <option value="expected_behavior">Expected behavior deviation</option>}- {job?.settings?.checks.map((check) => (- <option key={check.id} value={check.id}>- {check.instruction}- </option>- ))}- </select>- </div>- <div className="divide-y border-y">- {visibleRuns.slice(runOffset, runOffset + 50).map((run) => (- <ListRow- key={run.id}- title={run.trace_id}- onClick={() => onOpen(run.id)}- className="group grid w-full grid-cols-[minmax(0,1fr)_16px] items-center gap-x-4 gap-y-1 py-4 text-left hover:bg-muted/40 focus-visible:outline-2 focus-visible:outline-ring sm:grid-cols-[minmax(0,1fr)_180px_130px_16px]"- >- <span className="col-start-1 row-start-1 min-w-0 truncate text-sm font-medium">{run.name}</span>- <span className="col-start-1 row-start-2 text-xs text-muted-foreground sm:col-start-2 sm:row-start-1">- {runTime(run.start_time)}- </span>- <span className="col-start-1 row-start-3 text-xs text-muted-foreground sm:col-start-3 sm:row-start-1">- {assessmentLabel(assessments.get(run.id))}- </span>- <ChevronRight- aria-hidden="true"- className="col-start-2 row-start-1 size-4 text-muted-foreground group-hover:text-foreground sm:col-start-4"- />- </ListRow>- ))}- {!visibleRuns.length && (- <p className="py-10 text-center text-sm text-muted-foreground">- {runs.length- ? "No runs match this outcome."- : "Selected activity appears here when the worker starts reviewing it."}+ <Inspector.Root+ items={page}+ itemKey={runKey}+ selected={selected}+ onSelectedChange={(run) => selectRun(run?.id ?? null)}+ noun="run"+ storageKey={FINDING_PANEL_WIDTH_KEY}+ >+ <TabsContent value="runs" className="space-y-4 pt-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="text-sm text-muted-foreground">+ {runs.length} selected from {job?.sample?.eligible ?? 0} matching runs</p>- )}- </div>- {(runOffset > 0 || visibleRuns.length > 50) && (- <div className="flex items-center justify-between text-xs text-muted-foreground">- <Button- size="sm"- variant="ghost"- disabled={!runOffset}- onClick={() => setRunOffset(Math.max(0, runOffset - 50))}- >- Previous runs- </Button>- <span>- {runOffset + 1}–{Math.min(runOffset + 50, visibleRuns.length)} of {visibleRuns.length}- </span>- <Button- size="sm"- variant="ghost"- disabled={runOffset + 50 >= visibleRuns.length}- onClick={() => setRunOffset(runOffset + 50)}+ <select+ aria-label="Filter reviewed runs"+ className="h-8 max-w-full rounded-md border bg-background px-2 text-xs sm:max-w-64"+ value={runFilter}+ onChange={(e) => {+ setRunFilter(e.target.value);+ setRunOffset(0);+ }}>- Next runs- </Button>+ <option value="all">All outcomes</option>+ <option value="clear">No issue observed</option>+ <option value="unknown">Insufficient evidence or not reviewed</option>+ {job?.settings?.context && <option value="expected_behavior">Expected behavior deviation</option>}+ {job?.settings?.checks.map((check) => (+ <option key={check.id} value={check.id}>+ {check.instruction}+ </option>+ ))}+ </select></div>- )}- </div>+ <div className="divide-y border-y">+ {visibleRuns.slice(runOffset, runOffset + PAGE).map((run) => (+ <Inspector.Row+ key={run.id}+ item={run}+ render={+ <button+ type="button"+ title={run.trace_id}+ className="group grid w-full grid-cols-[minmax(0,1fr)_16px] items-center gap-x-4 gap-y-1 py-4 text-left hover:bg-muted/40 focus-visible:outline-2 focus-visible:outline-ring data-[state=selected]:bg-trace-row-selected data-[state=selected]:shadow-[inset_2px_0_0_var(--trace-brand)] sm:grid-cols-[minmax(0,1fr)_180px_130px_16px]"+ />+ }+ >+ <span className="col-start-1 row-start-1 min-w-0 truncate text-sm font-medium">{run.name}</span>+ <span className="col-start-1 row-start-2 text-xs text-muted-foreground sm:col-start-2 sm:row-start-1">+ {runTime(run.start_time)}+ </span>+ <span className="col-start-1 row-start-3 text-xs text-muted-foreground sm:col-start-3 sm:row-start-1">+ {assessmentLabel(assessments.get(run.id))}+ </span>+ <ChevronRight+ aria-hidden="true"+ className="col-start-2 row-start-1 size-4 text-muted-foreground group-hover:text-foreground sm:col-start-4"+ />+ </Inspector.Row>+ ))}+ {!visibleRuns.length && (+ <p className="py-10 text-center text-sm text-muted-foreground">+ {runs.length+ ? "No runs match this outcome."+ : "Selected activity appears here when the worker starts reviewing it."}+ </p>+ )}+ </div>+ {(runOffset > 0 || visibleRuns.length > PAGE) && (+ <div className="flex items-center justify-between text-xs text-muted-foreground">+ <Button+ size="sm"+ variant="ghost"+ disabled={!runOffset}+ onClick={() => setRunOffset(Math.max(0, runOffset - PAGE))}+ >+ Previous runs+ </Button>+ <span>+ {runOffset + 1}–{Math.min(runOffset + PAGE, visibleRuns.length)} of {visibleRuns.length}+ </span>+ <Button+ size="sm"+ variant="ghost"+ disabled={runOffset + PAGE >= visibleRuns.length}+ onClick={() => setRunOffset(runOffset + PAGE)}+ >+ Next runs+ </Button>+ </div>+ )}+ </TabsContent>+ <Inspector.Panel label="Run details" testId="run-panel">+ {(run: RunRef) => <EvidenceView lensId={lens.id} evidence={{ id: run.id, span: "" }} />}+ </Inspector.Panel>+ </Inspector.Root>);}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/useRunHistory.ts b/ui/litellm-dashboard/src/components/lens/investigations/detail/useRunHistory.tsnew file mode 100644index 00000000000..94d1519ddc2--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/detail/useRunHistory.ts@@ -0,0 +1,20 @@+"use client";++import { useEffect } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useLensApi } from "../../data/LensServices";+import { lensKeys, lensQueries } from "../../data/queries";+import { activeJob } from "../../model/status";+import type { Lens } from "../../model/types";++/** Run history polls off its own rows, so a job the list poll discovers has to push it to refetch. */+export function useRunHistory(lens: Lens, historyOffset: number) {+ const api = useLensApi();+ const client = useQueryClient();+ const activeId = activeJob(lens.jobs)?.id;+ useEffect(() => {+ if (!activeId) return;+ void client.invalidateQueries({ queryKey: lensKeys.histories() }, { cancelRefetch: false });+ }, [activeId, client]);+ return useQuery(lensQueries.history(api, { lensId: lens.id, historyOffset }));+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/investigationQuery.test.ts b/ui/litellm-dashboard/src/components/lens/investigations/investigationQuery.test.tsnew file mode 100644index 00000000000..96167b14b8f--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/investigationQuery.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";++import { fieldValues } from "@/components/shared/search/evaluate";+import type { Job, Lens } from "../model/types";+import { filterInvestigations, INVESTIGATION_INDEX } from "./investigationQuery";++function makeLens(id: string, settings: Partial<Lens["settings"]>, jobs: readonly Pick<Job, "status">[] = []): Lens {+ return {+ version: 0,+ spent: 0,+ id,+ scope: { all_teams: true, api_key_hash: "", team_id: "" },+ settings: {+ context: "",+ source: "traces",+ lookback_hours: 24,+ service: "",+ agent_name: "",+ filters: [],+ interval_minutes: 15,+ sample_size: 100,+ sample_percent: 100,+ concurrency: 8,+ team_id: "",+ execution_ids: [],+ monthly_budget: 20,+ name: id,+ model: "analysis",+ enabled: true,+ checks: [],+ ...settings,+ },+ revision: 1,+ created_at: "2026-09-30T10:00:00Z",+ next_run_at: "2026-09-30T10:00:00Z",+ budget_month: "2026-09",+ findings: [],+ jobs: jobs as Job[],+ };+}++const lenses = [+ makeLens("Refund audit", { agent_name: "billing-agent" }, [{ status: "failed" }, { status: "completed" }]),+ makeLens("Release reviews", { service: "reviewer", enabled: false }, [{ status: "completed" }]),+ makeLens("Lead scoring", { filters: [{ key: "team", value: "sales" }] }),+];++const names = (query: string) => filterInvestigations(lenses, query).map((lens) => lens.settings.name);++describe("filterInvestigations", () => {+ it("matches free text against the name and the scope", () => {+ expect(names("REFUND")).toEqual(["Refund audit"]);+ expect(names("sales")).toEqual(["Lead scoring"]);+ expect(names("reviewer")).toEqual(["Release reviews"]);+ });++ it("filters by the latest run's status, treating no runs as never", () => {+ expect(names("status:failed")).toEqual(["Refund audit"]);+ expect(names("status:completed")).toEqual(["Release reviews"]);+ expect(names("status:never")).toEqual(["Lead scoring"]);+ });++ it("filters by schedule and by agent, falling back to the service", () => {+ expect(names("schedule:paused")).toEqual(["Release reviews"]);+ expect(names("-schedule:paused")).toEqual(["Refund audit", "Lead scoring"]);+ expect(names("agent:billing-agent")).toEqual(["Refund audit"]);+ expect(names("agent:reviewer")).toEqual(["Release reviews"]);+ });+});++describe("INVESTIGATION_INDEX values", () => {+ it("offers only the agents and statuses present", () => {+ expect(fieldValues(INVESTIGATION_INDEX, lenses, "agent")).toEqual(["billing-agent", "reviewer"]);+ expect(fieldValues(INVESTIGATION_INDEX, lenses, "status")).toEqual(["completed", "failed", "never"]);+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/investigationQuery.ts b/ui/litellm-dashboard/src/components/lens/investigations/investigationQuery.tsnew file mode 100644index 00000000000..8f37a862baf--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/investigationQuery.ts@@ -0,0 +1,30 @@+import { Bot, CalendarClock, CircleDashed, SquareChevronRight } from "lucide-react";++import { type ClientIndex, filterItems } from "@/components/shared/search/evaluate";+import type { FieldSpec, QueryLanguage } from "@/components/shared/search/language";+import { scopeLabel } from "../model/format";+import type { Lens } from "../model/types";++const INVESTIGATION_FIELDS = {+ name: { group: "Investigation", icon: SquareChevronRight, suggestValues: true },+ agent: { group: "Investigation", icon: Bot, suggestValues: true },+ status: { group: "Latest run", icon: CircleDashed, suggestValues: true },+ schedule: { group: "Investigation", icon: CalendarClock, suggestValues: true },+} as const satisfies Record<string, FieldSpec>;++export type InvestigationField = keyof typeof INVESTIGATION_FIELDS;++export const INVESTIGATION_QUERY: QueryLanguage<InvestigationField> = { fields: INVESTIGATION_FIELDS };++export const INVESTIGATION_INDEX: ClientIndex<Lens, InvestigationField> = {+ read: {+ name: (lens) => [lens.settings.name],+ agent: (lens) => [lens.settings.agent_name, lens.settings.service].filter(Boolean),+ status: (lens) => [lens.jobs[0]?.status ?? "never"],+ schedule: (lens) => [lens.settings.enabled ? "watching" : "paused"],+ },+ freeText: (lens) => [lens.settings.name, scopeLabel(lens.settings)],+};++export const filterInvestigations = (lenses: Lens[], query: string): Lens[] =>+ filterItems(INVESTIGATION_QUERY, INVESTIGATION_INDEX, lenses, query);diff --git a/ui/litellm-dashboard/src/components/lens/investigations/investigationScreen.test.ts b/ui/litellm-dashboard/src/components/lens/investigations/investigationScreen.test.tsnew file mode 100644index 00000000000..6303e9e7802--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/investigationScreen.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from "vitest";+import { investigationScreen, type ScreenInput } from "./investigationScreen";+import type { Lens, LensList } from "../model/types";++function makeLens(id: string, created_at: string): Lens {+ return {+ version: 0,+ spent: 0,+ id,+ scope: { all_teams: true, api_key_hash: "", team_id: "" },+ settings: {+ context: "",+ source: "traces",+ lookback_hours: 24,+ service: "",+ agent_name: "",+ filters: [],+ interval_minutes: 15,+ sample_size: 100,+ sample_percent: 100,+ concurrency: 8,+ team_id: "",+ execution_ids: [],+ monthly_budget: 20,+ name: `Lens ${id}`,+ model: "analysis",+ enabled: true,+ checks: [],+ },+ revision: 1,+ created_at,+ next_run_at: created_at,+ budget_month: "2026-09",+ findings: [],+ jobs: [],+ };+}++const older = makeLens("older", "2026-09-01T10:00:00Z");+const newer = makeLens("newer", "2026-09-30T10:00:00Z");+const list = (lenses: Lens[]): LensList => ({ lenses, workers: [], tracing_enabled: true });+const ready = (lenses: Lens[]): ScreenInput["list"] => ({ data: list(lenses), error: null });+const route = { lensId: null, dialog: null, target: null } as const;++describe("investigationScreen", () => {+ it("loads, then fails only while there is nothing cached to show", () => {+ expect(investigationScreen({ ...route, list: { data: undefined, error: null } })).toEqual({ kind: "loading" });+ const error = new Error("down");+ expect(investigationScreen({ ...route, list: { data: undefined, error } })).toEqual({ kind: "failed", error });+ expect(investigationScreen({ ...route, list: { data: list([newer]), error } })).toMatchObject({ kind: "list" });+ });++ it("welcomes an empty account and lists newest investigations first otherwise", () => {+ expect(investigationScreen({ ...route, list: ready([]) })).toEqual({ kind: "welcome" });+ expect(investigationScreen({ ...route, list: ready([older, newer]) })).toEqual({+ kind: "list",+ lenses: [newer, older],+ });+ });++ it("keeps the list on screen with the selected investigation, or reports it missing", () => {+ expect(investigationScreen({ ...route, list: ready([older, newer]), lensId: "older" })).toEqual({+ kind: "list",+ lenses: [newer, older],+ lens: older,+ });+ expect(investigationScreen({ ...route, list: ready([older]), lensId: "gone" })).toEqual({ kind: "missing" });+ expect(investigationScreen({ ...route, list: { data: undefined, error: null }, lensId: "older" })).toEqual({+ kind: "loading",+ });+ });++ it("enters setup for new, edit and duplicate, prefilled from the targeted investigation", () => {+ expect(investigationScreen({ ...route, list: ready([older]), dialog: "new" })).toEqual({+ kind: "setup",+ mode: "new",+ });+ const edit: ScreenInput = { ...route, list: ready([older]), lensId: "older", dialog: "edit" };+ const editing = { kind: "setup", mode: "edit", lens: older, initial: older.settings };+ expect(investigationScreen(edit)).toEqual(editing);+ const duplicate: ScreenInput = {+ ...route,+ list: ready([older, newer]),+ lensId: "older",+ dialog: "duplicate",+ target: "newer",+ };+ const duplicating = {+ kind: "setup",+ mode: "duplicate",+ lens: newer,+ initial: { ...newer.settings, name: "Lens newer copy", enabled: false },+ };+ expect(investigationScreen(duplicate)).toEqual(duplicating);+ });++ it("falls back to the plain screen when an edit names an investigation that is not loaded", () => {+ const editGone: ScreenInput = { ...route, list: ready([older]), lensId: "gone", dialog: "edit" };+ expect(investigationScreen(editGone)).toEqual({ kind: "missing" });+ const runNow: ScreenInput = { ...route, list: ready([older]), dialog: "run_now", target: "older" };+ expect(investigationScreen(runNow)).toMatchObject({ kind: "list" });+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/investigations/investigationScreen.ts b/ui/litellm-dashboard/src/components/lens/investigations/investigationScreen.tsnew file mode 100644index 00000000000..ab65413a541--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/investigationScreen.ts@@ -0,0 +1,51 @@+import type { Lens, LensList, Settings } from "../model/types";+import type { LensDialog } from "../route";++export type SetupMode = "new" | "edit" | "duplicate";++export interface ScreenInput {+ readonly list: { readonly data: LensList | undefined; readonly error: Error | null };+ readonly lensId: string | null;+ readonly dialog: LensDialog | null;+ readonly target: string | null;+}++export type SetupScreen =+ | { readonly kind: "setup"; readonly mode: "new" }+ | { readonly kind: "setup"; readonly mode: "edit" | "duplicate"; readonly lens: Lens; readonly initial: Settings };++export type Screen =+ | { readonly kind: "loading" }+ | { readonly kind: "failed"; readonly error: Error }+ | { readonly kind: "welcome" }+ | { readonly kind: "list"; readonly lenses: readonly Lens[]; readonly lens?: Lens }+ | { readonly kind: "missing" }+ | SetupScreen;++const isSetupMode = (dialog: LensDialog | null): dialog is SetupMode =>+ dialog === "new" || dialog === "edit" || dialog === "duplicate";++function setupScreen(mode: SetupMode, lens: Lens | undefined): SetupScreen | undefined {+ if (mode === "new") return { kind: "setup", mode };+ if (!lens) return undefined;+ const initial =+ mode === "duplicate" ? { ...lens.settings, name: `${lens.settings.name} copy`, enabled: false } : lens.settings;+ return { kind: "setup", mode, lens, initial };+}++export function investigationScreen({ list, lensId, dialog, target }: ScreenInput): Screen {+ const lenses = list.data?.lenses ?? [];+ const selected = lenses.find((lens) => lens.id === lensId);+ const setup = isSetupMode(dialog)+ ? setupScreen(dialog, target ? lenses.find((lens) => lens.id === target) : selected)+ : undefined;+ if (setup) return setup;+ if (!list.data) return list.error ? { kind: "failed", error: list.error } : { kind: "loading" };+ if (lensId && !selected) return { kind: "missing" };+ if (lenses.length === 0) return { kind: "welcome" };+ return {+ kind: "list",+ lenses: [...lenses].sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)),+ ...(selected ? { lens: selected } : {}),+ };+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/useInvestigationActions.ts b/ui/litellm-dashboard/src/components/lens/investigations/useInvestigationActions.tsnew file mode 100644index 00000000000..7d974a47614--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/useInvestigationActions.ts@@ -0,0 +1,26 @@+"use client";++import { useLensUpdate, useSaveLens, type LensWrite } from "../data/mutations";+import type { Finding, Lens, RunWindow, Settings } from "../model/types";++/** Every write the Investigations screens can ask for, so leaves only ever express intent. */+export function useInvestigationActions() {+ const update = useLensUpdate();+ const save = useSaveLens();+ const attempt = (write: LensWrite): Promise<boolean> =>+ update.mutateAsync(write).then(+ () => true,+ () => false,+ );+ return {+ busy: update.isPending,+ error: update.error,+ reset: update.reset,+ save: (input: { id?: string; settings: Settings }): Promise<Lens> => save.mutateAsync(input),+ pause: (lens: Lens) => attempt((api) => api.saveLens(lens.id, { ...lens.settings, enabled: false })),+ cancelRun: (lens: Lens) => attempt((api) => api.cancelRun(lens.id)),+ startRun: (lens: Lens, request: RunWindow) => attempt((api) => api.startRun(lens.id, request)),+ review: (lens: Lens, finding: Finding, status: Finding["status"], reason: string) =>+ attempt((api) => api.reviewFinding(lens.id, finding.id, status, reason)),+ };+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/useInvestigationResults.ts b/ui/litellm-dashboard/src/components/lens/investigations/useInvestigationResults.tsdeleted file mode 100644index c1505d2235a..00000000000--- a/ui/litellm-dashboard/src/components/lens/investigations/useInvestigationResults.ts+++ /dev/null@@ -1,107 +0,0 @@-"use client";--import { useQueryStates } from "nuqs";-import { useCallback, useState } from "react";-import { useQuery } from "@tanstack/react-query";-import { useLensApi } from "../services";-import { lensQueries } from "../api/queries";-import { evidenceTarget, mergeFeedback, sortedFindings } from "../model/findings";-import type { Job, Lens } from "../model/types";-import { RESULT_PARSERS, RESULT_TABS, type ResultTab } from "../route";--const isResultTab = (tab: string): tab is ResultTab => (RESULT_TABS as readonly string[]).includes(tab);--export function useInvestigationResults(accessToken: string, lens: Lens | undefined) {- const api = useLensApi(accessToken);- const [params, setParams] = useQueryStates(RESULT_PARSERS);- const { run: batchId, section: tab, finding: findingId, finding_status: filter, kind } = params;- const [historyOffset, setHistoryOffset] = useState(0);- const setBatchId = useCallback((run: string) => void setParams({ run }), [setParams]);- const setTab = useCallback((section: string) => void (isResultTab(section) && setParams({ section })), [setParams]);- const setFindingId = useCallback(- (finding: string | null) => void setParams({ finding }, { history: "push" }),- [setParams],- );- const setFilter = useCallback((finding_status: string) => void setParams({ finding_status }), [setParams]);- const setKind = useCallback((next: typeof kind) => void setParams({ kind: next }), [setParams]);- const evidence = params.evidence === null ? null : { id: params.evidence, span: params.evidence_span ?? "" };- const setEvidence = useCallback(- (next: { id: string; span: string } | null) =>- void setParams({ evidence: next?.id ?? null, evidence_span: next?.span || null }, { history: "push" }),- [setParams],- );- const history = useQuery(lensQueries.history(api, { lensId: lens?.id, historyOffset }));- const historical = useQuery(lensQueries.run(api, lens?.id, batchId));- const { job, missingSnapshot, selectedOutsideHistory, batchSettings, batchFindings } = runSnapshot(- lens,- batchId,- historical.data,- history.data,- );- const finding = batchFindings.find((f) => f.id === findingId);- const openBatch = (id: string) => void setParams({ run: id, section: null, finding: null });- const active = lens?.jobs?.find((j) => j.status === "queued" || j.status === "running");- const visibleFindings = sortedFindings(- batchFindings.filter((f) => (filter === "all" || f.status === filter) && f.kind === kind),- );- const sampledRuns = job?.sample?.executions ?? [];- const target = evidence ? evidenceTarget(evidence.id) : null;- const [requestOffset, setRequestOffset] = useState(0);- const evidenceInput = { lensId: lens?.id, evidenceId: evidence?.id, requestOffset, source: target?.source };- const requestEvidence = useQuery(lensQueries.evidence(api, evidenceInput));- const reset = useCallback(() => {- setHistoryOffset(0);- void setParams({ run: null, finding: null, section: null });- }, [setParams]);-- return {- batchId,- setBatchId,- historyOffset,- setHistoryOffset,- tab,- setTab,- findingId,- setFindingId,- filter,- setFilter,- kind,- setKind,- evidence,- setEvidence,- history: history.data,- historyError: history.error,- refetchHistory: history.refetch,- historicalError: historical.error,- refetchHistorical: historical.refetch,- job,- missingSnapshot,- selectedOutsideHistory,- batchSettings,- batchFindings,- finding,- openBatch,- active,- visibleFindings,- sampledRuns,- target,- requestOffset,- setRequestOffset,- requestEvidenceData: requestEvidence.data,- requestEvidenceError: requestEvidence.error,- requestEvidenceLoading: requestEvidence.isLoading,- reset,- };-}--function runSnapshot(lens: Lens | undefined, batchId: string, historical: Job | undefined, history: Job[] | undefined) {- const job = ["latest", "all"].includes(batchId) ? lens?.jobs?.[0] : historical;- const missingSnapshot = job?.status === "completed" && job.findings == null && batchId !== "all";- const selectedOutsideHistory = !["latest", "all"].includes(batchId) && !history?.some((j) => j.id === batchId);- const batchSettings = job?.settings ?? lens?.settings;- const batchFindings = mergeFeedback(- batchId === "all" ? lens?.findings ?? [] : job?.findings ?? [],- lens?.findings ?? [],- );- return { job, missingSnapshot, selectedOutsideHistory, batchSettings, batchFindings };-}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/useProgressSamples.ts b/ui/litellm-dashboard/src/components/lens/investigations/useProgressSamples.tsnew file mode 100644index 00000000000..66cf9a134c8--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/useProgressSamples.ts@@ -0,0 +1,32 @@+"use client";++import { useEffect, useState, useSyncExternalStore } from "react";+import { analysisFraction, type ProgressSample } from "../model/progress";++const KEEP = 120;++type Progress = Pick<ProgressSample, "step" | "done"> & { readonly total: number };++/** A wall-clock log of progress changes; the clock is the external system, so it lives outside render. */+function createSampleLog() {+ const listeners = new Set<() => void>();+ const state = { samples: [] as readonly ProgressSample[] };+ return {+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => void listeners.delete(listener);+ },+ snapshot: () => state.samples,+ record: (progress: Progress) => {+ const sample = { at: Date.now(), ...progress, fraction: analysisFraction(progress) };+ state.samples = [...state.samples, sample].slice(-KEEP);+ listeners.forEach((listener) => listener());+ },+ };+}++export function useProgressSamples({ step, done, total }: Progress): readonly ProgressSample[] {+ const [log] = useState(createSampleLog);+ useEffect(() => log.record({ step, done, total }), [log, step, done, total]);+ return useSyncExternalStore(log.subscribe, log.snapshot, log.snapshot);+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/useRunSnapshot.ts b/ui/litellm-dashboard/src/components/lens/investigations/useRunSnapshot.tsnew file mode 100644index 00000000000..38656b719b3--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/investigations/useRunSnapshot.ts@@ -0,0 +1,38 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { useLensApi } from "../data/LensServices";+import { lensQueries } from "../data/queries";+import { mergeFeedback } from "../model/findings";+import type { Finding, Job, Lens, Settings } from "../model/types";+import { useRunRoute } from "../route";++export interface RunSnapshot {+ readonly batchId: string;+ readonly job: Job | undefined;+ readonly missingSnapshot: boolean;+ readonly batchSettings: Settings | undefined;+ readonly batchFindings: readonly Finding[];+ readonly error: Error | null;+ readonly refetch: () => void;+}++const isAggregate = (batchId: string) => batchId === "latest" || batchId === "all";++/** The run a detail view is looking at: the latest job from the list, or one older job fetched on its own. */+export function useRunSnapshot(lens: Lens | undefined): RunSnapshot {+ const api = useLensApi();+ const { batchId } = useRunRoute();+ const historical = useQuery(lensQueries.run(api, lens?.id, batchId));+ const job = isAggregate(batchId) ? lens?.jobs[0] : historical.data;+ const current = lens?.findings ?? [];+ return {+ batchId,+ job,+ missingSnapshot: job?.status === "completed" && job.findings == null && batchId !== "all",+ batchSettings: job?.settings ?? lens?.settings,+ batchFindings: mergeFeedback(batchId === "all" ? current : job?.findings ?? [], current),+ error: historical.error,+ refetch: () => void historical.refetch(),+ };+}diff --git a/ui/litellm-dashboard/src/components/lens/model/findings.ts b/ui/litellm-dashboard/src/components/lens/model/findings.tsindex 2c2c61e57a6..2ef6929e7de 100644--- a/ui/litellm-dashboard/src/components/lens/model/findings.ts+++ b/ui/litellm-dashboard/src/components/lens/model/findings.ts@@ -8,7 +8,14 @@ export function sortedFindings(findings: Finding[]): Finding[] {);}-export function evidenceTarget(id: string): { source: string; team: string; id: string; traceRef?: string } | null {+export interface EvidenceTarget {+ readonly source: string;+ readonly team: string;+ readonly id: string;+ readonly traceRef?: string;+}++export function evidenceTarget(id: string): EvidenceTarget | null {try {const parsed: unknown = JSON.parse(atob(id.replace(/-/g, "+").replace(/_/g, "/")));if (!Array.isArray(parsed) || ![3, 4].includes(parsed.length) || !parsed.every((item) => typeof item === "string"))diff --git a/ui/litellm-dashboard/src/components/lens/model/format.test.ts b/ui/litellm-dashboard/src/components/lens/model/format.test.tsindex f7d3da278a0..6bea67c2bbe 100644--- a/ui/litellm-dashboard/src/components/lens/model/format.test.ts+++ b/ui/litellm-dashboard/src/components/lens/model/format.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { durationLabel, durationText, money, scopeLabel, when } from "./format";+import { agoLabel, durationLabel, durationText, money, scopeLabel, when } from "./format";describe("Lens labels", () => {it("formats an empty scope and joins recorded scope constraints in their original order", () => {@@ -30,3 +30,19 @@ describe("Lens labels", () => {expect(when(null)).toBe("Not yet");});});++describe("agoLabel", () => {+ const now = Date.UTC(2026, 9, 3, 12, 0, 0);++ it("rounds down to the largest whole unit", () => {+ expect(agoLabel(now - 2_000, now)).toBe("just now");+ expect(agoLabel(now - 45_000, now)).toBe("45s ago");+ expect(agoLabel(now - 12 * 60_000 - 59_000, now)).toBe("12m ago");+ expect(agoLabel(now - 3 * 3_600_000, now)).toBe("3h ago");+ expect(agoLabel(now - 2 * 86_400_000, now)).toBe("2d ago");+ });++ it("treats a timestamp slightly in the future as just now instead of negative", () => {+ expect(agoLabel(now + 10_000, now)).toBe("just now");+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/model/format.ts b/ui/litellm-dashboard/src/components/lens/model/format.tsindex b25cad3cf74..cd09f470dcc 100644--- a/ui/litellm-dashboard/src/components/lens/model/format.ts+++ b/ui/litellm-dashboard/src/components/lens/model/format.ts@@ -1,6 +1,7 @@import { formatActivityTimestamp as runTime } from "@/utils/activityTimestamp";import type { Settings } from "./types";-export { formatActivityTimestamp as runTime } from "@/utils/activityTimestamp";++export { runTime };export function scopeLabel(settings: Partial<Pick<Settings, "service" | "agent_name" | "filters">>): string {return (@@ -27,6 +28,15 @@ export function durationLabel(value: number, base: "minutes" | "hours" = "minutereturn `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;}+export function agoLabel(thenMs: number, nowMs: number): string {+ const seconds = Math.max(0, Math.floor((nowMs - thenMs) / 1000));+ if (seconds < 5) return "just now";+ if (seconds < 60) return `${seconds}s ago`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;+ return `${Math.floor(seconds / 86400)}d ago`;+}+export const money = (n: number) =>new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 3 }).format(n);export const when = (value?: string | null) => (value ? runTime(value) : "Not yet");diff --git a/ui/litellm-dashboard/src/components/lens/model/inbox.ts b/ui/litellm-dashboard/src/components/lens/model/inbox.tsindex 6fd23b35e28..f2a4d386a33 100644--- a/ui/litellm-dashboard/src/components/lens/model/inbox.ts+++ b/ui/litellm-dashboard/src/components/lens/model/inbox.ts@@ -38,7 +38,12 @@ export function openFindings(lens: Lens): Finding[] {export const findingKey = (lens: Lens, finding: Finding) => `${lens.id}:${finding.id}`;-export function findFinding(lenses: readonly Lens[], key: string) {+export interface OwnedFinding {+ readonly lens: Lens;+ readonly finding: Finding;+}++export function findFinding(lenses: readonly Lens[], key: string): OwnedFinding | undefined {return lenses.flatMap((lens) => lens.findings.map((finding) => ({ lens, finding }))).find(({ lens, finding }) => findingKey(lens, finding) === key);diff --git a/ui/litellm-dashboard/src/components/lens/model/progress.ts b/ui/litellm-dashboard/src/components/lens/model/progress.tsindex f63fefb4cd8..d1a22431701 100644--- a/ui/litellm-dashboard/src/components/lens/model/progress.ts+++ b/ui/litellm-dashboard/src/components/lens/model/progress.ts@@ -82,7 +82,7 @@ export interface ProgressSample {fraction: number;}-export const stageWeights = [0.6, 0.2, 0.2];+const stageWeights = [0.6, 0.2, 0.2];export function analysisFraction({step,diff --git a/ui/litellm-dashboard/src/components/lens/model/readiness.test.ts b/ui/litellm-dashboard/src/components/lens/model/readiness.test.tsnew file mode 100644index 00000000000..ce560520bfd--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/model/readiness.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vitest";+import { initialSetupStep, readiness, type ReadinessInput } from "./readiness";++const base: ReadinessInput = {+ traces: { recorded: undefined, failed: false, disabled: false, checked: false },+ tracingConfigured: false,+ activity: undefined,+ activityError: null,+ connected: true,+ listError: null,+ investigations: 0,+};++describe("readiness", () => {+ it("counts traces confirmed from storage as recorded activity even when the activity check fails", () => {+ const failing = { ...base, activityError: new Error("Activity unavailable") };+ expect(readiness(failing).ready).toBe(false);+ const seen = { ...failing, traces: { ...base.traces, recorded: true } };+ expect(readiness(seen)).toMatchObject({ tracesReady: true, ready: true });+ expect(readiness({ ...seen, traces: { ...seen.traces, failed: true } }).tracesReady).toBe(false);+ });++ it("needs a connected worker and a healthy list on top of recorded activity", () => {+ const active = { ...base, activity: { traces: false, requests: true } };+ expect(readiness(active)).toMatchObject({ requestsReady: true, activityReady: true, ready: true });+ expect(readiness({ ...active, connected: false }).ready).toBe(false);+ expect(readiness({ ...active, listError: new Error("down") }).ready).toBe(false);+ });++ it("treats tracing as enabled once storage answers or the gateway reports it configured, unless storage says it is off", () => {+ expect(readiness(base).tracingEnabled).toBe(false);+ expect(readiness({ ...base, tracingConfigured: true }).tracingEnabled).toBe(true);+ expect(readiness({ ...base, traces: { ...base.traces, checked: true } }).tracingEnabled).toBe(true);+ const disabled = { ...base, tracingConfigured: true, traces: { ...base.traces, checked: true, disabled: true } };+ expect(readiness(disabled).tracingEnabled).toBe(false);+ });++ it("knows whether any investigation exists", () => {+ expect(readiness(base).hasInvestigations).toBe(false);+ expect(readiness({ ...base, investigations: 2 }).hasInvestigations).toBe(true);+ });+});++describe("initialSetupStep", () => {+ it("opens the first step that still needs work", () => {+ const offline = { ...base, connected: false };+ expect(initialSetupStep(readiness(offline))).toBe(0);+ expect(initialSetupStep(readiness({ ...offline, tracingConfigured: true }))).toBe(1);+ const recorded = { ...offline, activity: { traces: false, requests: true } };+ expect(initialSetupStep(readiness(recorded))).toBe(2);+ expect(initialSetupStep(readiness({ ...recorded, connected: true }))).toBe(3);+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/model/readiness.ts b/ui/litellm-dashboard/src/components/lens/model/readiness.tsnew file mode 100644index 00000000000..d62f9c8bed3--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/model/readiness.ts@@ -0,0 +1,47 @@+export interface Readiness {+ readonly tracingEnabled: boolean;+ readonly tracesReady: boolean;+ readonly requestsReady: boolean;+ readonly activityReady: boolean;+ readonly connected: boolean;+ readonly hasInvestigations: boolean;+ readonly ready: boolean;+}++export interface ReadinessInput {+ readonly traces: {+ readonly recorded: boolean | undefined;+ readonly failed: boolean;+ readonly disabled: boolean;+ readonly checked: boolean;+ };+ readonly tracingConfigured: boolean;+ readonly activity: { readonly traces: boolean; readonly requests: boolean } | undefined;+ readonly activityError: unknown;+ readonly connected: boolean;+ readonly listError: unknown;+ readonly investigations: number;+}++export function readiness(input: ReadinessInput): Readiness {+ const { traces, activity, activityError, connected, listError } = input;+ /** Traces confirmed straight from trace storage count as recorded activity even if the activity check fails. */+ const tracesSeen = traces.recorded === true && !traces.failed;+ const tracesReady = tracesSeen || (activity?.traces === true && !activityError);+ const requestsReady = activity?.requests === true && !activityError;+ const activityReady = tracesReady || requestsReady;+ return {+ tracingEnabled: !traces.disabled && (traces.checked || input.tracingConfigured),+ tracesReady,+ requestsReady,+ activityReady,+ connected,+ hasInvestigations: input.investigations > 0,+ ready: activityReady && connected && !listError,+ };+}++export function initialSetupStep(state: Readiness): number {+ if (state.activityReady) return state.connected ? 3 : 2;+ return state.tracingEnabled ? 1 : 0;+}diff --git a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunNowDialog.test.ts b/ui/litellm-dashboard/src/components/lens/model/runRequest.test.tssimilarity index 97%rename from ui/litellm-dashboard/src/components/lens/investigations/detail/RunNowDialog.test.tsrename to ui/litellm-dashboard/src/components/lens/model/runRequest.test.tsindex 617685d80e2..d7edc732bfb 100644--- a/ui/litellm-dashboard/src/components/lens/investigations/detail/RunNowDialog.test.ts+++ b/ui/litellm-dashboard/src/components/lens/model/runRequest.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { runRequest } from "./RunNowDialog";+import { runRequest } from "./runRequest";const base = { agent: "support", saved: "support", start: "", end: "" };diff --git a/ui/litellm-dashboard/src/components/lens/model/runRequest.ts b/ui/litellm-dashboard/src/components/lens/model/runRequest.tsnew file mode 100644index 00000000000..ffb9a88f089--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/model/runRequest.ts@@ -0,0 +1,30 @@+import type { RunWindow } from "./types";++export const RUN_PRESETS = [+ { label: "Since last run", hours: null },+ { label: "Last hour", hours: 1 },+ { label: "Last 24h", hours: 24 },+ { label: "Last 7d", hours: 168 },+ { label: "Custom", hours: -1 },+] as const;++export type RunPreset = (typeof RUN_PRESETS)[number]["hours"];++export interface RunChoice {+ preset: RunPreset;+ agent: string;+ saved: string;+ start: string;+ end: string;+}++export function runRequest({ preset, agent, saved, start, end }: RunChoice): RunWindow | string {+ const agentPart = agent.trim() && agent.trim() !== saved ? { agent_name: agent.trim() } : {};+ if (preset === null) return agentPart;+ if (preset > 0) return { ...agentPart, lookback_hours: preset };+ const startMs = Date.parse(start);+ const endMs = Date.parse(end);+ if (Number.isNaN(startMs) || Number.isNaN(endMs)) return "Choose a start and end time";+ if (startMs >= endMs) return "Start time must be before end time";+ return { ...agentPart, start: new Date(startMs).toISOString(), end: new Date(endMs).toISOString() };+}diff --git a/ui/litellm-dashboard/src/components/lens/model/status.test.ts b/ui/litellm-dashboard/src/components/lens/model/status.test.tsindex c6b9eabf70e..2c9a2e362d1 100644--- a/ui/litellm-dashboard/src/components/lens/model/status.test.ts+++ b/ui/litellm-dashboard/src/components/lens/model/status.test.ts@@ -1,4 +1,4 @@-import { investigationActivity, nextCheckStatus, workerConnected } from "./status";+import { activeJob, investigationActivity, listPollInterval, nextCheckStatus, workerConnected } from "./status";import { describe, expect, it } from "vitest";import type { Job, Lens, LensList } from "./types";@@ -111,3 +111,49 @@ it("summarizes activity across investigations, preferring a running scan over aexpect(investigationActivity([withStatus("queued"), withStatus("running")])).toBe("running");expect(investigationActivity([{ ...lens, jobs: [lens.jobs[0], { ...job, status: "running" }] }])).toBe("running");});++describe("List polling cadence", () => {+ const now = Date.parse("2026-10-01T12:00:00Z");+ const connectedWorker: LensList["workers"][number] = {+ id: "worker",+ name: "Worker",+ revoked: false,+ analysis_key_id: "key",+ last_seen: "2026-10-01T11:59:59Z",+ scope: { all_teams: true, api_key_hash: "", team_id: "" },+ };+ const staleWorker = { ...connectedWorker, last_seen: "2026-10-01T11:00:00Z" };+ const list = (workers: LensList["workers"], lenses: Lens[] = [lens]): LensList => ({+ lenses,+ workers,+ tracing_enabled: true,+ });++ it("polls slowly when nothing is running and Settings is closed", () => {+ expect(listPollInterval(list([staleWorker]), false, now)).toBe(10000);+ expect(listPollInterval(undefined, false, now)).toBe(10000);+ });++ it("polls fast while Settings waits for a worker and slows down once one connects", () => {+ expect(listPollInterval(undefined, true, now)).toBe(2000);+ expect(listPollInterval(list([staleWorker]), true, now)).toBe(2000);+ expect(listPollInterval(list([connectedWorker]), true, now)).toBe(10000);+ });++ it("speeds up as soon as any investigation is queued or running, whatever tab is open", () => {+ const queued: Lens = { ...lens, jobs: [{ ...job, status: "queued" }] };+ const running: Lens = { ...lens, jobs: [lens.jobs[0], { ...job, status: "running" }] };+ expect(listPollInterval(list([connectedWorker], [lens, queued]), false, now)).toBe(2000);+ expect(listPollInterval(list([connectedWorker], [running]), false, now)).toBe(2000);+ expect(listPollInterval(list([connectedWorker], [lens]), false, now)).toBe(10000);+ });+});++describe("activeJob", () => {+ it("picks the queued or running job and ignores finished ones", () => {+ const done = { ...job, id: "done", status: "completed" as const };+ expect(activeJob([done, job])).toBe(job);+ expect(activeJob([done, { ...job, status: "queued" }])?.status).toBe("queued");+ expect(activeJob([done])).toBeUndefined();+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/model/status.ts b/ui/litellm-dashboard/src/components/lens/model/status.tsindex 75a345c6ea5..64e7579a38f 100644--- a/ui/litellm-dashboard/src/components/lens/model/status.ts+++ b/ui/litellm-dashboard/src/components/lens/model/status.ts@@ -1,10 +1,25 @@import { formatActivityTimestamp } from "@/utils/activityTimestamp";-import type { Lens, LensList } from "./types";+import type { Job, Lens, LensList } from "./types";export function workerConnected(worker: LensList["workers"][number], now = Date.now()): boolean {return !worker.revoked && !!worker.analysis_key_id && now - Date.parse(worker.last_seen) < 120000;}+export function activeJob(jobs: readonly Job[]): Job | undefined {+ return jobs.find((job) => job.status === "queued" || job.status === "running");+}++export function hasActiveJob(jobs: readonly Job[]): boolean {+ return activeJob(jobs) !== undefined;+}++/** One observer polls `/lens`: fast while work is in flight or a worker is being connected, slow otherwise. */+export function listPollInterval(list: LensList | undefined, settingsOpen: boolean, now: number): number {+ const running = list?.lenses.some((lens) => hasActiveJob(lens.jobs)) ?? false;+ const connected = list?.workers.some((worker) => workerConnected(worker, now)) ?? false;+ return running || (settingsOpen && !connected) ? 2000 : 10000;+}+export function lensStatus(lens: Lens, connected: boolean): string {const active = lens.jobs?.find((job) => ["queued", "running"].includes(job.status ?? ""));if (active) return connected ? active.stage ?? "Queued" : "Waiting for analyzer";@@ -31,19 +46,6 @@ export function nextCheckStatus(lens: Lens, now: number): string | null {return `Next check ${time} · ${relative}`;}-export function readiness(- activity: { traces: boolean; requests: boolean } | undefined,- activityError: unknown,- connected: boolean,- listError: unknown,-) {- const tracesReady = activity?.traces === true && !activityError;- const requestsReady = activity?.requests === true && !activityError;- const activityReady = tracesReady || requestsReady;- const ready = activityReady && connected && !listError;- return { tracesReady, requestsReady, activityReady, ready };-}-export type InvestigationActivity = "running" | "queued" | "idle";export function investigationActivity(lenses: readonly Lens[]): InvestigationActivity {diff --git a/ui/litellm-dashboard/src/components/lens/model/types.ts b/ui/litellm-dashboard/src/components/lens/model/types.tsindex e88ca490c7c..81cb6479897 100644--- a/ui/litellm-dashboard/src/components/lens/model/types.ts+++ b/ui/litellm-dashboard/src/components/lens/model/types.ts@@ -32,3 +32,17 @@ export type ActivitySelection = Pick<Settings, "source"> &>;export type Worker = LensList["workers"][number];++export interface RunWindow {+ agent_name?: string;+ start?: string;+ end?: string;+ lookback_hours?: number;+}++export interface AnalysisModelInfo {+ model_group: string;+ providers: string[];+ mode?: string | null;+ supported_openai_params?: string[] | null;+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/watches.ts b/ui/litellm-dashboard/src/components/lens/model/watches.tssimilarity index 98%rename from ui/litellm-dashboard/src/components/lens/setup/watches.tsrename to ui/litellm-dashboard/src/components/lens/model/watches.tsindex 4e3434a534a..206f5452e4b 100644--- a/ui/litellm-dashboard/src/components/lens/setup/watches.ts+++ b/ui/litellm-dashboard/src/components/lens/model/watches.ts@@ -1,4 +1,4 @@-import type { Settings } from "../model/types";+import type { Settings } from "./types";export interface Watch {id: string;diff --git a/ui/litellm-dashboard/src/components/lens/setup/GatewayFlow.tsx b/ui/litellm-dashboard/src/components/lens/onboarding/GatewayFlow.tsxsimilarity index 96%rename from ui/litellm-dashboard/src/components/lens/setup/GatewayFlow.tsxrename to ui/litellm-dashboard/src/components/lens/onboarding/GatewayFlow.tsxindex bc61078a18d..53775dc67b3 100644--- a/ui/litellm-dashboard/src/components/lens/setup/GatewayFlow.tsx+++ b/ui/litellm-dashboard/src/components/lens/onboarding/GatewayFlow.tsx@@ -1,4 +1,5 @@import { useId } from "react";+import { cn } from "@/lib/cva.config";import styles from "./LensIntroduction.module.css";const dotColors = [@@ -45,7 +46,7 @@ export function GatewayFlow() {<svgaria-hidden="true"viewBox="0 0 1000 108"- className={`${styles.flowGraphic} mt-2 h-auto w-full`}+ className={cn(styles.flowGraphic, "mt-2 h-auto w-full")}focusable="false"><defs>@@ -105,7 +106,7 @@ export function GatewayFlow() {<ellipse cx="500" cy="54" rx="44" ry="40" fill={`url(#${id}-glow)`} className={styles.gatewayGlow} /><g clipPath={`url(#${id}-after-gate)`}><g mask={`url(#${id}-organized-shape)`}>- <g className={`${styles.organizedDots} fill-indigo-500 dark:fill-indigo-400`}>+ <g className={cn(styles.organizedDots, "fill-indigo-500 dark:fill-indigo-400")}>{organizedColumns.map((column) => (<g key={column} opacity={0.6 + (((column + 8) * 3) % 8) * 0.05}>{[34, 44, 54, 64, 74].map((y) => (diff --git a/ui/litellm-dashboard/src/components/lens/onboarding/LensGettingStarted.tsx b/ui/litellm-dashboard/src/components/lens/onboarding/LensGettingStarted.tsxnew file mode 100644index 00000000000..7f27678c344--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/onboarding/LensGettingStarted.tsx@@ -0,0 +1,81 @@+"use client";++import { useRef } from "react";+import { Check, ShieldCheck } from "lucide-react";+import { Button } from "@/components/ui/button";+import type { LensReadiness } from "../hooks/useLensReadiness";+import { LensIntroduction } from "./LensIntroduction";+import { OnboardingSetup } from "./OnboardingSetup";++const PREREQUISITES = [+ { title: "LiteLLM gateway", detail: "Access to its configuration" },+ { title: "ClickHouse", detail: "Self-hosted or managed trace storage" },+ { title: "A server with Docker", detail: "To run the analysis worker" },+ { title: "An analysis model", detail: "Available through your gateway" },+] as const;++export interface LensGettingStartedProps {+ readonly state: LensReadiness;+ readonly onStart: () => void;+ readonly onExit: (to: "traces" | "investigations") => void;+ readonly onDemo?: () => void;+}++export function LensGettingStarted({ state, onStart, onExit, onDemo }: LensGettingStartedProps) {+ const setupRef = useRef<HTMLElement>(null);+ const exitTo = state.tracesReady ? "traces" : "investigations";+ const start = () => {+ onStart();+ setupRef.current?.scrollIntoView({ block: "start" });+ setupRef.current?.focus({ preventScroll: true });+ };+ return (+ <div className="w-full space-y-6">+ <LensIntroduction onStart={start} onDemo={onDemo} />+ <div className="grid items-start gap-6 xl:grid-cols-[minmax(0,1fr)_280px] xl:gap-8">+ <OnboardingSetup+ ref={setupRef}+ tabIndex={-1}+ state={state}+ onFocusCapture={onStart}+ action={+ (state.activityReady || state.hasInvestigations) && (+ <Button variant="outline" size="sm" onClick={() => onExit(exitTo)}>+ {exitTo === "traces" ? "View traces" : "View investigations"}+ </Button>+ )+ }+ />+ <Prerequisites />+ </div>+ </div>+ );+}++function Prerequisites() {+ return (+ <aside className="rounded-2xl border bg-card p-6" aria-labelledby="lens-prerequisites">+ <h2 id="lens-prerequisites" className="text-base font-semibold">+ Before you start+ </h2>+ <ul className="mt-5 space-y-5 text-sm">+ {PREREQUISITES.map((item) => (+ <li key={item.title} className="flex gap-3">+ <Check aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div>+ <p className="font-medium">{item.title}</p>+ <p className="mt-1 leading-5 text-muted-foreground">{item.detail}</p>+ </div>+ </li>+ ))}+ </ul>+ <div className="mt-5 flex gap-2 border-t pt-5 text-xs leading-5 text-muted-foreground">+ <ShieldCheck aria-hidden="true" className="mt-0.5 size-4 shrink-0" />+ <p>+ Your infrastructure stores the traces. Investigation content is sent to your selected model provider through+ the gateway.+ </p>+ </div>+ </aside>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/onboarding/LensIntroDialog.tsx b/ui/litellm-dashboard/src/components/lens/onboarding/LensIntroDialog.tsxnew file mode 100644index 00000000000..c7c29d8721b--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/onboarding/LensIntroDialog.tsx@@ -0,0 +1,80 @@+"use client";++import { useId, useState } from "react";+import { Loader2, XIcon } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";+import { Label } from "@/components/ui/label";+import { useStoredValue } from "@/lib/storage";+import { useLensReadiness } from "../hooks/useLensReadiness";+import { LENS_INTRO_DISMISSED, LENS_INTRO_SEEN } from "../storage";+import { LensGettingStarted, type LensGettingStartedProps } from "./LensGettingStarted";+import { useOnboarding } from "./OnboardingContext";++export interface LensIntro {+ readonly open: boolean;+ close(forever: boolean): void;+}++/** Opens on the first Lens visit of a session, or whenever the URL asks for setup. "Don't show this again" outlives the tab; a plain close only rests for the session. */+export function useLensIntro({ demo, settingUp }: { demo: boolean; settingUp: boolean }): LensIntro {+ const [dismissed, setDismissed] = useStoredValue(LENS_INTRO_DISMISSED);+ const [seen, setSeen] = useStoredValue(LENS_INTRO_SEEN);+ const close = (forever: boolean) => {+ setSeen(true);+ if (forever) setDismissed(true);+ };+ const firstVisit = !demo && !dismissed && !seen;+ return { open: settingUp || firstVisit, close };+}++export type LensIntroDialogProps = Omit<LensGettingStartedProps, "state"> & {+ open: boolean;+ onClose: (forever: boolean) => void;+};++export function LensIntroDialog({ open, onClose, ...gettingStarted }: LensIntroDialogProps) {+ const [forever, setForever] = useState(false);+ const checkboxId = useId();+ const close = () => onClose(forever);+ return (+ <Dialog open={open} onOpenChange={(next) => !next && close()}>+ <DialogContent+ showCloseButton={false}+ className="max-h-[calc(100vh-4rem)] gap-0 overflow-y-auto p-0 sm:max-w-4xl"+ >+ <div className="sticky top-0 z-raised flex items-center justify-end gap-3 bg-popover/90 px-4 py-2 backdrop-blur-sm">+ <Label htmlFor={checkboxId} className="gap-2 text-xs font-normal text-muted-foreground">+ <Checkbox id={checkboxId} checked={forever} onCheckedChange={(checked) => setForever(checked === true)} />+ Don’t show this again+ </Label>+ <Button variant="ghost" size="icon-sm" aria-label="Close" onClick={close}>+ <XIcon />+ </Button>+ </div>+ <DialogTitle className="sr-only">Get started with Lens</DialogTitle>+ <DialogDescription className="sr-only">+ What Lens does, and the steps to connect tracing, a worker and your first investigation.+ </DialogDescription>+ <div className="px-5 pb-5">+ <IntroContent {...gettingStarted} />+ </div>+ </DialogContent>+ </Dialog>+ );+}++function IntroContent(props: Omit<LensGettingStartedProps, "state">) {+ const { canViewInvestigations } = useOnboarding();+ const state = useLensReadiness(canViewInvestigations);+ if (state.loading)+ return (+ <p role="status" className="flex items-center gap-2 py-8 text-sm text-muted-foreground">+ <Loader2 aria-hidden="true" className="size-4 animate-spin" />+ Checking Lens setup…+ </p>+ );+ return <LensGettingStarted state={state} {...props} />;+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/LensIntroduction.module.css b/ui/litellm-dashboard/src/components/lens/onboarding/LensIntroduction.module.csssimilarity index 100%rename from ui/litellm-dashboard/src/components/lens/setup/LensIntroduction.module.cssrename to ui/litellm-dashboard/src/components/lens/onboarding/LensIntroduction.module.cssdiff --git a/ui/litellm-dashboard/src/components/lens/setup/LensIntroduction.tsx b/ui/litellm-dashboard/src/components/lens/onboarding/LensIntroduction.tsxsimilarity index 87%rename from ui/litellm-dashboard/src/components/lens/setup/LensIntroduction.tsxrename to ui/litellm-dashboard/src/components/lens/onboarding/LensIntroduction.tsxindex c4820a95517..3bf7979a1fb 100644--- a/ui/litellm-dashboard/src/components/lens/setup/LensIntroduction.tsx+++ b/ui/litellm-dashboard/src/components/lens/onboarding/LensIntroduction.tsx@@ -1,6 +1,7 @@import { useState } from "react";import { ArrowRight, ArrowUpRight, ChevronDown, ChevronRight } from "lucide-react";import { Button } from "@/components/ui/button";+import { cn } from "@/lib/cva.config";import styles from "./LensIntroduction.module.css";import { GatewayFlow } from "./GatewayFlow";@@ -21,7 +22,7 @@ function TraceExample({ highlighted, onHighlight }: EvidenceProps) {return (<sectionaria-labelledby="lens-sample-trace"- className={`${styles.sampleCard} min-w-0 rounded-xl border bg-card p-4`}+ className={cn(styles.sampleCard, "min-w-0 rounded-xl border bg-card p-4")}><div className="flex flex-wrap items-center justify-between gap-2 text-sm"><h3 id="lens-sample-trace" className="font-semibold">@@ -36,7 +37,7 @@ function TraceExample({ highlighted, onHighlight }: EvidenceProps) {"grid w-full grid-cols-[minmax(0,1fr)_minmax(48px,1fr)_2.5rem] items-center gap-2 text-left sm:gap-3";const content = (<>- <span className={`flex min-w-0 items-center gap-1 ${index > 0 ? "pl-2" : ""}`}>+ <span className={cn("flex min-w-0 items-center gap-1", index > 0 && "pl-2")}>{index === 0 ? (<ChevronDown aria-hidden="true" className="size-3 shrink-0" />) : (@@ -49,7 +50,11 @@ function TraceExample({ highlighted, onHighlight }: EvidenceProps) {</span><span aria-hidden="true" className="relative h-2.5 overflow-hidden rounded-sm bg-muted/70"><span- className={`absolute inset-y-0 rounded-sm ${linked ? styles.evidenceBar : ""} ${item.failed ? "bg-rose-400" : "bg-indigo-600 dark:bg-indigo-400"}`}+ className={cn(+ "absolute inset-y-0 rounded-sm",+ linked && styles.evidenceBar,+ item.failed ? "bg-rose-400" : "bg-indigo-600 dark:bg-indigo-400",+ )}style={{ left: `${(item.start / 14.2) * 100}%`, width: `${(item.duration / 14.2) * 100}%` }}/></span>@@ -61,7 +66,7 @@ function TraceExample({ highlighted, onHighlight }: EvidenceProps) {{linked ? (<buttontype="button"- className={`${rowClass} ${styles.evidenceLink}`}+ className={cn(rowClass, styles.evidenceLink)}data-evidence-link=""aria-label={`${item.name}, ${item.duration} seconds${item.failed ? ", failed" : ""}. Highlight related finding`}aria-controls="lens-linked-finding"@@ -78,11 +83,11 @@ function TraceExample({ highlighted, onHighlight }: EvidenceProps) {})}</ol><div className="mt-3 grid gap-3 border-t pt-3 sm:grid-cols-2">- <div id="lens-benchmark-output" className={`${styles.evidenceOutput} rounded-lg bg-muted/60 p-2.5`}>+ <div id="lens-benchmark-output" className={cn(styles.evidenceOutput, "rounded-lg bg-muted/60 p-2.5")}><p className="text-xs text-muted-foreground">run_benchmark · output</p><p className="mt-1.5 text-sm leading-4.5">Error: benchmark runner unavailable (503)</p></div>- <div id="lens-answer-output" className={`${styles.evidenceOutput} rounded-lg bg-muted/60 p-2.5`}>+ <div id="lens-answer-output" className={cn(styles.evidenceOutput, "rounded-lg bg-muted/60 p-2.5")}><p className="text-xs text-muted-foreground">answer · output</p><p className="mt-1.5 text-sm leading-4.5">“{sampleAnswer}”</p></div>@@ -95,7 +100,7 @@ function FindingExamples({ highlighted, onHighlight }: EvidenceProps) {return (<sectionaria-labelledby="lens-sample-findings"- className={`${styles.sampleCard} min-w-0 rounded-xl border bg-card p-4`}+ className={cn(styles.sampleCard, "min-w-0 rounded-xl border bg-card p-4")}><div className="flex flex-wrap items-center justify-between gap-2 text-sm"><h3 id="lens-sample-findings" className="font-semibold">@@ -104,11 +109,11 @@ function FindingExamples({ highlighted, onHighlight }: EvidenceProps) {<p className="text-xs text-muted-foreground">500 sample runs reviewed</p></div><div className="mt-3 divide-y border-t">- <article id="lens-linked-finding" className={`${styles.evidenceFinding} py-3`}>+ <article id="lens-linked-finding" className={cn(styles.evidenceFinding, "py-3")}><h4 className="text-sm font-semibold"><buttontype="button"- className={`${styles.evidenceLink} flex w-full items-start gap-2 text-left`}+ className={cn(styles.evidenceLink, "flex w-full items-start gap-2 text-left")}data-evidence-link=""aria-controls="lens-benchmark-output lens-answer-output"aria-pressed={highlighted}@@ -179,7 +184,7 @@ export function LensIntroduction({ onStart, onDemo }: { onStart: () => void; onD</div><GatewayFlow /><div- className={`${styles.examples} mt-4 grid items-stretch gap-3 md:grid-cols-2`}+ className={cn(styles.examples, "mt-4 grid items-stretch gap-3 md:grid-cols-2")}data-evidence-active={highlighted}><TraceExample highlighted={highlighted} onHighlight={toggleEvidence} />diff --git a/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingContext.tsx b/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingContext.tsxnew file mode 100644index 00000000000..c7a1a05c6f4--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingContext.tsx@@ -0,0 +1,24 @@+"use client";++import { createContext, useContext } from "react";+import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";++export interface Onboarding {+ readonly readOnly: boolean;+ readonly canViewInvestigations: boolean;+ readonly canInvestigate: boolean;+ readonly canMintTracingKey: boolean;+ connect(): void;+ create(): void;+ openTrace(trace: TraceSummary): void;+}++const OnboardingContext = createContext<Onboarding | null>(null);++export const OnboardingProvider = OnboardingContext.Provider;++export function useOnboarding(): Onboarding {+ const onboarding = useContext(OnboardingContext);+ if (!onboarding) throw new Error("useOnboarding needs an OnboardingProvider above it");+ return onboarding;+}diff --git a/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingSetup.tsx b/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingSetup.tsxnew file mode 100644index 00000000000..dc74659621c--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingSetup.tsx@@ -0,0 +1,52 @@+"use client";++import { useId, type ComponentProps, type ReactNode } from "react";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/cva.config";+import type { LensReadiness } from "../hooks/useLensReadiness";+import { useOnboarding } from "./OnboardingContext";+import { OnboardingSteps } from "./OnboardingSteps";++export type OnboardingSetupProps = Omit<ComponentProps<"section">, "children"> & {+ state: LensReadiness;+ action?: ReactNode;+};++export function OnboardingSetup({ state, action, className, ...props }: OnboardingSetupProps) {+ const { readOnly, canInvestigate } = useOnboarding();+ const titleId = useId();+ return (+ <section+ data-slot="onboarding-setup"+ aria-labelledby={titleId}+ className={cn("min-w-0 scroll-mt-4 outline-none", className)}+ {...props}+ >+ <div className="mb-6 flex flex-wrap items-center justify-between gap-3">+ <div>+ <h2 id={titleId} className="text-2xl font-semibold tracking-tight">+ Get Lens running+ </h2>+ <p className="mt-2 text-sm leading-6 text-muted-foreground">+ Each step checks your connection, so you’ll see when it’s working.+ </p>+ </div>+ {action}+ </div>+ <OnboardingSteps state={state} />+ {state.error && (+ <div role="alert" className="mt-4 flex flex-wrap items-center gap-3 text-sm text-destructive">+ <p>Could not check setup. {state.error}</p>+ <Button variant="outline" size="sm" onClick={state.refresh} disabled={state.checking}>+ Retry+ </Button>+ </div>+ )}+ {(readOnly || !canInvestigate) && (+ <p className="mt-4 text-sm text-muted-foreground">+ A gateway administrator can connect a worker and run investigations.+ </p>+ )}+ </section>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingSteps.tsx b/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingSteps.tsxnew file mode 100644index 00000000000..2b321a46c2e--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/onboarding/OnboardingSteps.tsx@@ -0,0 +1,251 @@+"use client";++import { useId, useRef, useState, type ReactNode } from "react";+import { ArrowRight, ChevronDown } from "lucide-react";+import { Button } from "@/components/ui/button";+import { TracingSetupFields } from "@/components/view_logs/TraceView/TracingSetupCard";+import { cn } from "@/lib/cva.config";+import { useLensAccessToken } from "../data/LensServices";+import type { LensReadiness } from "../hooks/useLensReadiness";+import { initialSetupStep } from "../model/readiness";+import { StepIndicator, type StepState } from "../ui/StepIndicator";+import { useOnboarding } from "./OnboardingContext";++type StepProps = { state: LensReadiness; goTo: (step: number) => void };++function useLocked() {+ const { readOnly, canInvestigate } = useOnboarding();+ return readOnly || !canInvestigate;+}++function StorageStep({ state, goTo }: StepProps) {+ const { readOnly, openTrace } = useOnboarding();+ const accessToken = useLensAccessToken();+ if (!state.tracingEnabled)+ return (+ <>+ <TracingSetupFields+ detail="Tracing is not enabled"+ accessToken={accessToken}+ onOpenTrace={openTrace}+ onCheck={state.refresh}+ checking={state.checking}+ readOnly={readOnly}+ />+ <ActivityContinuation state={state} />+ </>+ );+ return (+ <div className="space-y-4">+ <p role="status" className="text-sm text-success">+ Trace storage is connected+ </p>+ <Button onClick={() => goTo(1)}>+ Continue to your agent <ArrowRight aria-hidden="true" className="size-4" />+ </Button>+ <ActivityContinuation state={state} />+ </div>+ );+}++function continuationLabel(state: LensReadiness) {+ if (state.connected) return "Continue to investigation";+ return state.tracesReady ? "Continue to worker" : "Continue with request logs";+}++function ActivityContinuation({ state }: { state: LensReadiness }) {+ const { connect, create } = useOnboarding();+ const locked = useLocked();+ if (!state.activityReady) return null;+ return (+ <div className="mt-4">+ <Button onClick={state.connected ? create : connect} disabled={locked}>+ {continuationLabel(state)}+ <ArrowRight aria-hidden="true" className="size-4" />+ </Button>+ {state.requestsReady && !state.tracesReady && (+ <p className="mt-2 text-xs text-muted-foreground">+ Request logs are already available. You can investigate them now and add agent traces later.+ </p>+ )}+ </div>+ );+}++function AgentStep({ state }: StepProps) {+ const { readOnly, canMintTracingKey, openTrace } = useOnboarding();+ const accessToken = useLensAccessToken();+ if (!state.tracingEnabled)+ return (+ <>+ <p className="text-sm text-muted-foreground">Connect trace storage in step 1 before sending a trace.</p>+ <ActivityContinuation state={state} />+ </>+ );+ return (+ <>+ <div hidden={state.tracesReady}>+ <TracingSetupFields+ detail={null}+ accessToken={accessToken}+ onOpenTrace={(value) => {+ state.refresh();+ openTrace(value);+ }}+ onCheck={state.refresh}+ checking={state.checking}+ readOnly={readOnly}+ canMintTracingKey={canMintTracingKey}+ />+ </div>+ {state.tracesReady && (+ <p role="status" className="text-sm text-success">+ Your first trace is ready. Continue setup so Lens can investigate your agent’s behavior.+ </p>+ )}+ <ActivityContinuation state={state} />+ </>+ );+}++function WorkerStep({ state }: StepProps) {+ const { connect, create } = useOnboarding();+ const locked = useLocked();+ return (+ <div className="space-y-4">+ <p role="status" className="text-sm text-muted-foreground">+ {state.connected+ ? "Worker connected. You’re ready to create an investigation."+ : "The worker reviews recorded activity using a model on your gateway. You choose its analysis model and spending limit."}+ </p>+ {!state.activityReady && (+ <p className="text-sm text-muted-foreground">Record activity in step 2 before connecting a worker.</p>+ )}+ <Button onClick={state.connected ? create : connect} disabled={!state.activityReady || locked}>+ {state.connected ? "Continue to investigation" : "Connect worker"}+ <ArrowRight aria-hidden="true" className="size-4" />+ </Button>+ </div>+ );+}++function InvestigationStep({ state }: StepProps) {+ const { create } = useOnboarding();+ const locked = useLocked();+ return (+ <div className="space-y-4">+ <p className="text-sm leading-6 text-muted-foreground">+ Choose the activity to review and describe how your agent should behave. Lens will show findings with evidence+ and suggested changes.+ </p>+ {!state.ready && (+ <p className="text-sm text-muted-foreground">+ Recorded activity and a connected worker are required before you can run an investigation.+ </p>+ )}+ <Button onClick={create} disabled={!state.ready || locked}>+ New investigation <ArrowRight aria-hidden="true" className="size-4" />+ </Button>+ </div>+ );+}++interface StepDefinition {+ readonly title: string;+ readonly description: string;+ readonly complete: (state: LensReadiness) => boolean;+ readonly Content: (props: StepProps) => ReactNode;+}++const STEPS: readonly StepDefinition[] = [+ {+ title: "Enable tracing on the gateway",+ description: "Connect ClickHouse and restart the gateway.",+ complete: (state) => state.tracingEnabled,+ Content: StorageStep,+ },+ {+ title: "Send your first trace",+ description: "Capture your agent’s inputs, outputs, and tool calls.",+ complete: (state) => state.tracesReady,+ Content: AgentStep,+ },+ {+ title: "Connect a worker",+ description: "Choose a model and run the worker on your infrastructure.",+ complete: (state) => state.connected,+ Content: WorkerStep,+ },+ {+ title: "Run your first investigation",+ description: "Describe the expected behavior and review a sample of activity.",+ complete: (state) => state.hasInvestigations,+ Content: InvestigationStep,+ },+];++function stepState(complete: boolean, open: boolean): StepState {+ if (complete) return "complete";+ return open ? "current" : "upcoming";+}++export function OnboardingSteps({ state, className }: { state: LensReadiness; className?: string }) {+ const id = useId();+ const listRef = useRef<HTMLOListElement>(null);+ const [step, setStep] = useState(() => initialSetupStep(state));+ const goTo = (index: number) => {+ setStep(index);+ listRef.current?.querySelector<HTMLButtonElement>(`[aria-controls="${id}-${index}"]`)?.focus();+ };+ return (+ <ol+ ref={listRef}+ data-slot="onboarding-steps"+ className={cn("divide-y overflow-hidden rounded-2xl border bg-card", className)}+ >+ {STEPS.map(({ title, description, complete, Content }, index) => {+ const open = step === index;+ return (+ <li key={title}>+ <h3>+ <button+ type="button"+ id={`${id}-trigger-${index}`}+ aria-expanded={open}+ aria-controls={`${id}-${index}`}+ onClick={() => setStep(index)}+ className="group flex w-full items-start gap-4 p-5 text-left outline-none hover:bg-muted/30 focus-visible:bg-muted/50 sm:p-6"+ >+ <StepIndicator index={index} state={stepState(complete(state), open)} />+ <span className="min-w-0 flex-1">+ <span+ className={cn(+ "block text-sm font-medium sm:text-base",+ !open && "text-muted-foreground group-hover:text-foreground",+ )}+ >+ {title}+ </span>+ <span className="mt-1 block text-sm leading-6 font-normal text-muted-foreground">{description}</span>+ </span>+ <ChevronDown+ aria-hidden="true"+ className={cn("mt-1 size-4 shrink-0 text-muted-foreground", open && "rotate-180")}+ />+ </button>+ </h3>+ <div+ id={`${id}-${index}`}+ role="region"+ aria-labelledby={`${id}-trigger-${index}`}+ hidden={!open}+ className="px-5 pb-6 sm:pr-6 sm:pb-7 sm:pl-17"+ >+ <Content state={state} goTo={goTo} />+ </div>+ </li>+ );+ })}+ </ol>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/route.tsx b/ui/litellm-dashboard/src/components/lens/route.tssimilarity index 53%rename from ui/litellm-dashboard/src/components/lens/route.tsxrename to ui/litellm-dashboard/src/components/lens/route.tsindex abc5cf2c0ad..cd16165d5a5 100644--- a/ui/litellm-dashboard/src/components/lens/route.tsx+++ b/ui/litellm-dashboard/src/components/lens/route.ts@@ -4,14 +4,14 @@ import { parseAsBoolean, parseAsString, parseAsStringLiteral, useQueryStates } fimport { useCallback } from "react";import { OPEN_TRACE_PARSERS, RUN_FILTER_PARSERS } from "@/components/view_logs/TraceView/traceRouting";-export const LENS_TABS = { traces: "Traces", investigations: "Investigations" } as const;+export const LENS_TABS = { traces: "Traces", investigations: "Investigations", settings: "Settings" } as const;export type LensTab = keyof typeof LENS_TABS;const lensTabs = Object.keys(LENS_TABS) as LensTab[];-export const RESULT_TABS = ["findings", "checks", "runs", "activity"] as const;+const RESULT_TABS = ["findings", "checks", "runs", "activity"] as const;export type ResultTab = (typeof RESULT_TABS)[number];-export const FINDING_KINDS = ["issue", "pattern"] as const;-export const LENS_DIALOGS = ["new", "edit", "duplicate", "run_now", "workers", "monitoring"] as const;+const FINDING_KINDS = ["issue", "pattern"] as const;+export const LENS_DIALOGS = ["new", "edit", "duplicate", "run_now", "monitoring"] as const;export type LensDialog = (typeof LENS_DIALOGS)[number];const LENS_PARSERS = {@@ -25,7 +25,7 @@ const ISSUE_PARSERS = { issue: parseAsString };const LIST_PARSERS = { search: parseAsString.withDefault("") };-export const RESULT_PARSERS = {+const RESULT_PARSERS = {run: parseAsString.withDefault("latest"),section: parseAsStringLiteral(RESULT_TABS).withDefault("findings"),finding: parseAsString,@@ -69,7 +69,7 @@ export function useLensRoute(): LensRoute {const [{ tab, lens, demo, setup }, setParams] = useQueryStates(SESSION_PARSERS, { history: "push" });const setTab = useCallback((next: LensTab) => void setParams({ tab: next }), [setParams]);const setLensId = useCallback(- (next: string | null) => void setParams({ ...CLEARED_RESULTS, lens: next }),+ (next: string | null) => void setParams({ ...CLEARED_RESULTS, lens: next, issue: null }),[setParams],);const setDemo = useCallback(@@ -80,12 +80,15 @@ export function useLensRoute(): LensRoute {return { tab, lensId: lens, demo, settingUp: setup === "lens", setTab, setLensId, setDemo, setSetup };}+const ISSUE_ROUTE_PARSERS = { ...ISSUE_PARSERS, lens: LENS_PARSERS.lens, ...RESULT_PARSERS };++/** A peeked finding takes the panel over from any open investigation and starts from its summary. */export function useIssueRoute() {- const [{ issue }, setParams] = useQueryStates(ISSUE_PARSERS);+ const [{ issue }, setParams] = useQueryStates(ISSUE_ROUTE_PARSERS);return {issueKey: issue,setIssueKey: useCallback(- (next: string | null) => void setParams({ issue: next }, { history: "push" }),+ (next: string | null) => void setParams({ ...CLEARED_RESULTS, lens: null, issue: next }, { history: "push" }),[setParams],),};@@ -105,3 +108,72 @@ export function useDialogRoute() {const closeDialog = useCallback(() => void setParams({ dialog: null, target: null }), [setParams]);return { dialog, target, openDialog, closeDialog };}++const isResultTab = (tab: string): tab is ResultTab => (RESULT_TABS as readonly string[]).includes(tab);++type FindingKind = (typeof FINDING_KINDS)[number];++export interface EvidenceRef {+ readonly id: string;+ readonly span: string;+}++const NO_RESULT_OPEN = { finding: null, evidence: null, evidence_span: null } as const;++export function useRunRoute() {+ const [{ run }, setParams] = useQueryStates(RESULT_PARSERS);+ const selectRun = useCallback((id: string) => void setParams({ run: id, ...NO_RESULT_OPEN }), [setParams]);+ const openRun = useCallback(+ (id: string) => void setParams({ run: id, section: null, ...NO_RESULT_OPEN }),+ [setParams],+ );+ return { batchId: run, selectRun, openRun };+}++export function useSectionRoute() {+ const [{ section }, setParams] = useQueryStates(RESULT_PARSERS);+ const setSection = useCallback(+ (next: string) => void (isResultTab(next) && setParams({ section: next })),+ [setParams],+ );+ return { section, setSection };+}++/** Picking a finding starts from its summary, so any evidence stacked over the previous one is dropped. */+export function useFindingRoute() {+ const [{ finding }, setParams] = useQueryStates(RESULT_PARSERS);+ const setFindingId = useCallback(+ (next: string | null) =>+ void setParams({ finding: next, evidence: null, evidence_span: null }, { history: "push" }),+ [setParams],+ );+ return { findingId: finding, setFindingId };+}++/** A run opened from the Runs tab is evidence on its own, outside any finding. */+export function useRunEvidenceRoute() {+ const [{ finding, evidence }, setParams] = useQueryStates(RESULT_PARSERS);+ const selectRun = useCallback(+ (id: string | null) => void setParams({ finding: null, evidence: id, evidence_span: null }, { history: "push" }),+ [setParams],+ );+ return { runId: finding === null ? evidence : null, selectRun };+}++export function useFindingFilters() {+ const [{ kind, finding_status }, setParams] = useQueryStates(RESULT_PARSERS);+ const setKind = useCallback((next: FindingKind) => void setParams({ kind: next }), [setParams]);+ const setStatus = useCallback((next: string) => void setParams({ finding_status: next }), [setParams]);+ return { kind, setKind, status: finding_status, setStatus };+}++export function useEvidenceRoute() {+ const [{ evidence, evidence_span }, setParams] = useQueryStates(RESULT_PARSERS);+ const setEvidence = useCallback(+ (next: EvidenceRef | null) =>+ void setParams({ evidence: next?.id ?? null, evidence_span: next?.span || null }, { history: "push" }),+ [setParams],+ );+ const current: EvidenceRef | null = evidence === null ? null : { id: evidence, span: evidence_span ?? "" };+ return { evidence: current, setEvidence };+}diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/RunSearch.test.tsx b/ui/litellm-dashboard/src/components/lens/runSearch/RunSearch.test.tsxdeleted file mode 100644index 95c2447be20..00000000000--- a/ui/litellm-dashboard/src/components/lens/runSearch/RunSearch.test.tsx+++ /dev/null@@ -1,140 +0,0 @@-import { render, screen, waitFor, within } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { useState } from "react";-import { describe, expect, it, vi } from "vitest";--import { runs } from "./__fixtures__/runs";-import { RunSearch } from "./RunSearch";--function Harness({ initial = "" }: { initial?: string }) {- const [value, setValue] = useState(initial);- return (- <>- <RunSearch value={value} onChange={setValue} runs={runs} />- <button type="button" onClick={() => setValue("status:ok")}>- Load saved query- </button>- </>- );-}--/** Delivers each emitted value only when asked, like a throttled URL. */-function LaggingHarness() {- const [value, setValue] = useState("");- const [queue, setQueue] = useState<string[]>([]);- return (- <>- <RunSearch value={value} onChange={(next) => setQueue((q) => [...q, next])} runs={runs} />- <output aria-label="undelivered">{queue.join("|")}</output>- <button- type="button"- onClick={() => {- setValue(queue[0]);- setQueue(queue.slice(1));- }}- >- Deliver next- </button>- </>- );-}--const box = () => screen.getByRole("combobox", { name: "Search runs" });-const undelivered = () => screen.getByRole("status", { name: "undelivered" });-const listbox = () => screen.getByRole("listbox", { name: "Search suggestions" });--describe("RunSearch", () => {- it("builds a filter from the keyboard: field, then value", async () => {- const user = userEvent.setup();- render(<Harness />);- await user.click(box());- expect(box()).toHaveAttribute("aria-expanded", "true");- await user.keyboard("-sta");- expect(- within(listbox())- .getAllByRole("option")- .map((o) => o.textContent),- ).toEqual(["status"]);- await user.keyboard("{Enter}");- expect(box()).toHaveTextContent(/^-status:$/, { normalizeWhitespace: false });- expect(within(listbox()).getByRole("group", { name: "status" })).toBeVisible();- expect(within(listbox()).getByText("does not contain")).toBeVisible();-- await user.keyboard("{ArrowDown}");- const ok = within(listbox()).getByRole("option", { name: "ok" });- expect(ok).toHaveAttribute("aria-selected", "true");- expect(box()).toHaveAttribute("aria-activedescendant", ok.id);- await user.keyboard("{Enter}");- expect(box()).toHaveTextContent(/^-status:ok $/, { normalizeWhitespace: false });- expect(screen.queryByRole("listbox")).not.toBeInTheDocument();- expect(box()).toHaveAttribute("aria-expanded", "false");- });-- it("wraps arrow navigation and picks with Tab", async () => {- const user = userEvent.setup();- render(<Harness />);- await user.click(box());- await user.keyboard("{ArrowUp}");- expect(within(listbox()).getByRole("option", { name: "trace_id" })).toHaveAttribute("aria-selected", "true");- await user.keyboard("{ArrowDown}{ArrowDown}{Tab}");- expect(box()).toHaveTextContent(/^agent:$/, { normalizeWhitespace: false });- await user.keyboard("{ArrowDown}{ArrowDown}e");- expect(within(listbox()).getByRole("option", { name: "billing-agent" })).toHaveAttribute("aria-selected", "true");- });-- it("picks a suggestion with the mouse without losing focus", async () => {- const user = userEvent.setup();- render(<Harness />);- await user.click(box());- await user.keyboard("agent:");- await user.click(within(listbox()).getByRole("option", { name: "researcher" }));- expect(box()).toHaveTextContent(/^agent:researcher $/, { normalizeWhitespace: false });- expect(box()).toHaveFocus();- await user.keyboard("refund");- expect(box()).toHaveTextContent(/^agent:researcher refund$/, { normalizeWhitespace: false });- });-- it("stays one line: Enter with no menu adds nothing, and Escape closes the menu until ArrowDown", async () => {- const user = userEvent.setup();- render(<Harness />);- await user.click(box());- await user.keyboard("refund{Enter}");- expect(box()).toHaveTextContent(/^refund$/, { normalizeWhitespace: false });- await user.keyboard(" {Escape}");- expect(screen.queryByRole("listbox")).not.toBeInTheDocument();- await user.keyboard("{ArrowDown}");- expect(listbox()).toBeVisible();- });-- it("emits the query once typing pauses, not per keystroke", async () => {- const user = userEvent.setup();- const onChange = vi.fn();- render(<RunSearch value="" onChange={onChange} runs={runs} />);- await user.click(box());- await user.keyboard("refund");- await waitFor(() => expect(onChange).toHaveBeenCalledWith("refund"));- expect(onChange).toHaveBeenCalledOnce();- });-- it("keeps typing intact while the value it emitted arrives late", async () => {- const user = userEvent.setup();- render(<LaggingHarness />);- await user.click(box());- await user.keyboard("ab");- await waitFor(() => expect(undelivered()).toHaveTextContent(/^ab$/, { normalizeWhitespace: false }));- await user.keyboard("c");- await user.click(screen.getByRole("button", { name: "Deliver next" }));- await user.click(box());- await user.keyboard("d");- expect(box()).toHaveTextContent(/^abcd$/, { normalizeWhitespace: false });- await waitFor(() => expect(undelivered()).toHaveTextContent(/^abcd$/, { normalizeWhitespace: false }));- });-- it("shows a query set from outside, such as the URL", async () => {- const user = userEvent.setup();- render(<Harness initial="agent:triage" />);- expect(box()).toHaveTextContent("agent:triage");- await user.click(screen.getByRole("button", { name: "Load saved query" }));- expect(box()).toHaveTextContent(/^status:ok$/, { normalizeWhitespace: false });- });-});diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/RunSearch.tsx b/ui/litellm-dashboard/src/components/lens/runSearch/RunSearch.tsxdeleted file mode 100644index 15e2bc45a17..00000000000--- a/ui/litellm-dashboard/src/components/lens/runSearch/RunSearch.tsx+++ /dev/null@@ -1,257 +0,0 @@-"use client";--import "prosemirror-view/style/prosemirror.css";--import { useDebouncedCallback } from "@tanstack/react-pacer/debouncer";-import { ProseMirror, ProseMirrorDoc, reactKeys, useEditorEventCallback } from "@handlewithcare/react-prosemirror";-import {- Bot,- Box,- Braces,- CircleDashed,- CornerDownLeft,- Hash,- type LucideIcon,- Search,- SquareChevronRight,-} from "lucide-react";-import { Schema } from "prosemirror-model";-import { EditorState, TextSelection, type Transaction } from "prosemirror-state";-import { Decoration, DecorationSet, type EditorView } from "prosemirror-view";-import { useId, useMemo, useState } from "react";--import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";--import { parseRunQuery, type RunField } from "./runQuery";-import { suggest, type Suggestion, type SuggestionMenu } from "./suggestions";--const schema = new Schema({ nodes: { doc: { content: "text*" }, text: {} } });--const createState = (text: string) =>- EditorState.create({ schema, doc: schema.node("doc", null, text ? schema.text(text) : []), plugins: [reactKeys()] });--const EMIT_WAIT_MS = 150;-const KEEP_MENU_CLOSED = "runSearchKeepMenuClosed";--const FIELD_ICONS: Record<RunField, LucideIcon> = {- name: SquareChevronRight,- agent: Bot,- status: CircleDashed,- model: Box,- input: Braces,- trace_id: Hash,-};--const OPERATORS = [- { label: "equals", example: "foo:bar" },- { label: "not equals", example: "-foo:bar" },- { label: "wildcard match", example: "foo:*bar*" },- { label: "does not contain", example: "-foo:*bar*" },-];--function highlight(state: EditorState): DecorationSet {- const marks = parseRunQuery(state.doc.textContent).flatMap((clause) =>- clause.kind === "field"- ? [- Decoration.inline(clause.from, clause.keyTo, { class: "text-info" }),- Decoration.inline(clause.keyTo, clause.keyTo + 1, { class: "text-muted-foreground" }),- ]- : [],- );- return DecorationSet.create(state.doc, marks);-}--function applySuggestion(view: EditorView, item: Suggestion) {- const tr = view.state.tr.insertText(item.insert, item.from, item.to);- tr.setSelection(TextSelection.create(tr.doc, item.from + item.insert.length));- if (item.completesClause) tr.setMeta(KEEP_MENU_CLOSED, true);- view.dispatch(tr);-}--interface RunSearchProps {- value: string;- onChange: (value: string) => void;- /** Loaded runs, the source of value suggestions. */- runs: readonly TraceSummary[];-}--/** One query box for the runs list: free text plus `key:value` filters, with autocomplete for both. */-export function RunSearch({ value, onChange, runs }: RunSearchProps) {- const listId = useId();- const [state, setState] = useState(() => createState(value));- const [seenValue, setSeenValue] = useState(value);- const [unechoed, setUnechoed] = useState<readonly string[]>([]);- const [focused, setFocused] = useState(false);- const [menuOpen, setMenuOpen] = useState(true);- const [active, setActive] = useState(0);-- // `value` can trail the editor (the URL updates are throttled), so an echo of text we emitted is not an edit.- if (value !== seenValue) {- setSeenValue(value);- const echo = unechoed.indexOf(value);- if (echo >= 0) setUnechoed(unechoed.slice(echo + 1));- else if (value !== state.doc.textContent) {- setUnechoed([]);- setState(createState(value));- }- }-- const { selection } = state;- const text = state.doc.textContent;- const menu = useMemo(() => (selection.empty ? suggest(text, selection.head, runs) : null), [text, selection, runs]);- const items = menu?.groups.flatMap((group) => group.items) ?? [];- const shownMenu = focused && menuOpen ? menu : null;- const visible = shownMenu !== null;- const activeItem = visible ? items[Math.min(active, items.length - 1)] : undefined;-- const emit = useDebouncedCallback(- (text: string) => {- setUnechoed((current) => [...current, text]);- onChange(text);- },- { wait: EMIT_WAIT_MS },- );-- const dispatchTransaction = (tr: Transaction) => {- setState((current) => current.apply(tr));- if (tr.selectionSet || tr.docChanged) setActive(0);- if (!tr.docChanged) return;- setMenuOpen(!tr.getMeta(KEEP_MENU_CLOSED));- emit(tr.doc.textContent);- };-- const handleKeyDown = (view: EditorView, event: KeyboardEvent): boolean => {- if (event.key === "Escape" && visible) {- setMenuOpen(false);- return true;- }- if (event.key === "ArrowDown" && !visible) {- setMenuOpen(true);- return true;- }- if ((event.key === "ArrowDown" || event.key === "ArrowUp") && items.length > 0) {- const step = event.key === "ArrowDown" ? 1 : -1;- setActive((Math.min(active, items.length - 1) + step + items.length) % items.length);- return true;- }- if ((event.key === "Enter" || event.key === "Tab") && activeItem) {- applySuggestion(view, activeItem);- return true;- }- return false;- };-- return (- <ProseMirror- state={state}- dispatchTransaction={dispatchTransaction}- decorations={highlight}- handleKeyDown={handleKeyDown}- handleDOMEvents={{- focus: () => {- setFocused(true);- setMenuOpen(true);- return false;- },- blur: () => {- setFocused(false);- return false;- },- }}- transformPastedText={(pasted) => pasted.replace(/\s+/g, " ")}- attributes={{- role: "combobox",- "aria-label": "Search runs",- "aria-autocomplete": "list",- "aria-expanded": String(visible),- "aria-controls": listId,- ...(activeItem && { "aria-activedescendant": `${listId}-${activeItem.id}` }),- spellcheck: "false",- class: "min-w-0 flex-1 overflow-x-auto py-1.5 font-mono text-xs whitespace-pre outline-none",- }}- >- <div className="relative w-full flex-1">- <div className="flex h-8 items-center gap-2 rounded-md border border-input bg-transparent px-2.5 focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 dark:bg-input/30">- <Search className="size-3.5 shrink-0 text-muted-foreground" />- <div className="relative flex min-w-0 flex-1">- <ProseMirrorDoc />- {!text && (- <span className="pointer-events-none absolute inset-y-0 left-0 flex items-center font-mono text-xs text-muted-foreground">- Search runs, or filter like agent:researcher status:error- </span>- )}- </div>- </div>- {shownMenu && <SuggestionPanel id={listId} menu={shownMenu} activeId={activeItem?.id} />}- </div>- </ProseMirror>- );-}--function SuggestionPanel({ id, menu, activeId }: { id: string; menu: SuggestionMenu; activeId: string | undefined }) {- const pick = useEditorEventCallback((view, item: Suggestion) => applySuggestion(view, item));- return (- <div className="absolute top-full left-0 z-floating mt-1 w-full max-w-xl overflow-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-md">- <div id={id} role="listbox" aria-label="Search suggestions" className="max-h-80 overflow-y-auto p-1">- {menu.groups.map((group) => (- <div key={group.heading} role="group" aria-label={group.heading}>- <div className="px-2 pt-2 pb-1 text-xs text-muted-foreground">{group.heading}</div>- {group.items.map((item) => {- const Icon = FIELD_ICONS[item.field];- return (- <div- key={item.id}- id={`${id}-${item.id}`}- role="option"- aria-selected={item.id === activeId}- onMouseDown={(event) => event.preventDefault()}- onClick={() => pick(item)}- className="flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 font-mono text-xs aria-selected:bg-accent aria-selected:text-accent-foreground"- >- <Icon className="size-3.5 shrink-0 text-muted-foreground" />- <span className="truncate">{item.label}</span>- </div>- );- })}- </div>- ))}- {menu.showOperators && <OperatorHints />}- </div>- <div className="flex items-center gap-3 border-t border-border px-3 py-2 text-xs text-muted-foreground">- <span className="flex items-center gap-1">- <Kbd>↑</Kbd>- <Kbd>↓</Kbd>- Navigate- </span>- <span className="flex items-center gap-1">- <Kbd>- <CornerDownLeft className="size-3" />- </Kbd>- Select- </span>- </div>- </div>- );-}--function OperatorHints() {- return (- <div className="pb-1">- <div className="px-2 pt-2 pb-1 text-xs text-muted-foreground">Comparison operators</div>- {OPERATORS.map((op) => (- <div key={op.label} className="flex items-center justify-between px-2 py-1 font-mono text-xs">- <span className="text-warning">{op.label}</span>- <code className="rounded bg-muted px-1.5 text-muted-foreground">{op.example}</code>- </div>- ))}- </div>- );-}--function Kbd({ children }: { children: React.ReactNode }) {- return (- <kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded border border-border px-1 font-sans">- {children}- </kbd>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/runQuery.test.ts b/ui/litellm-dashboard/src/components/lens/runSearch/runQuery.test.tsdeleted file mode 100644index daef2607c02..00000000000--- a/ui/litellm-dashboard/src/components/lens/runSearch/runQuery.test.ts+++ /dev/null@@ -1,96 +0,0 @@-import { describe, expect, it } from "vitest";--import { run, runs } from "./__fixtures__/runs";-import { fieldValues, filterRuns } from "./runQuery";--const ids = (query: string) => filterRuns(runs, query).map((r) => r.trace_id);--describe("filterRuns", () => {- it("returns every run for an empty or blank query", () => {- expect(filterRuns(runs, " ")).toBe(runs);- });-- it("matches free text against input, name and trace id, ignoring case, with every term required", () => {- expect(ids("REFUND")).toEqual(["aaa111"]);- expect(ids("lead")).toEqual(["bbb222"]);- expect(ids("ccc3")).toEqual(["ccc333"]);- expect(ids("vector research")).toEqual(["bbb222"]);- expect(ids("vector refund")).toEqual([]);- });-- it("keeps a quoted phrase together", () => {- expect(ids('"my refund"')).toEqual(["aaa111"]);- expect(ids('"refund my"')).toEqual([]);- });-- it("splits runs by status, judged by recorded errors", () => {- expect(ids("status:error")).toEqual(["bbb222"]);- expect(ids("-status:error")).toEqual(["aaa111", "ccc333"]);- expect(ids("status:OK")).toEqual(["aaa111", "ccc333"]);- });-- it("matches a multi-valued field when any value matches, and negation when none does", () => {- expect(ids("agent:triage")).toEqual(["aaa111"]);- expect(ids("-agent:triage")).toEqual(["bbb222", "ccc333"]);- expect(ids("agent:cron")).toEqual(["ccc333"]);- expect(ids("model:gpt-5")).toEqual(["aaa111"]);- });-- it("requires a whole-value match unless the value has wildcards", () => {- expect(ids("agent:billing")).toEqual([]);- expect(ids("agent:*bill*")).toEqual(["aaa111"]);- expect(ids("agent:billing*")).toEqual(["aaa111"]);- expect(ids("agent:*agent")).toEqual(["aaa111"]);- expect(ids("-agent:*search*")).toEqual(["aaa111", "ccc333"]);- expect(ids("name:res.arch_lead")).toEqual([]);- });-- it("matches glob segments case-insensitively without overlapping exact anchors", () => {- const billing = run({ trace_id: "billing", agent_names: ["BILLING-agent"] });- const research = run({ trace_id: "research", agent_names: ["research-billing-agent"] });- const doubled = run({ trace_id: "doubled", agent_names: ["agent"] });- const globRuns = [billing, research, doubled];-- expect(filterRuns(globRuns, "agent:*bill*")).toEqual([billing, research]);- expect(filterRuns(globRuns, "agent:billing*")).toEqual([billing]);- expect(filterRuns(globRuns, "agent:*agent")).toEqual(globRuns);- expect(filterRuns([run({ name: "aa" })], "name:a*a")).toHaveLength(1);- expect(filterRuns([run({ name: "a" })], "name:a*a")).toHaveLength(0);- expect(filterRuns(globRuns, "agent:**")).toEqual(filterRuns(globRuns, "agent:*"));- });-- it("matches adversarial globs without catastrophic backtracking", () => {- const longValue = run({ agent_names: ["a".repeat(5000)] });- const pattern = `agent:${"a*".repeat(30)}b`;- const startedAt = performance.now();- const matches = filterRuns([longValue], pattern);- const elapsed = performance.now() - startedAt;-- expect(matches).toEqual([]);- expect(elapsed).toBeLessThan(100);- });-- it("searches the readable input text and quoted values with spaces", () => {- expect(ids('input:"*vector stores"')).toEqual(["bbb222"]);- expect(ids("trace_id:bbb222")).toEqual(["bbb222"]);- });-- it("combines field clauses with free text", () => {- expect(ids("agent:*e* -status:error refund")).toEqual(["aaa111"]);- });-- it("ignores a key still waiting for its value and treats unknown keys as text", () => {- expect(ids("agent:")).toEqual(["aaa111", "bbb222", "ccc333"]);- expect(ids("refund agent:")).toEqual(["aaa111"]);- expect(ids("foo:bar")).toEqual([]);- expect(filterRuns([run({ name: "foo:bar" })], "foo:bar")).toHaveLength(1);- });-});--describe("fieldValues", () => {- it("lists each distinct non-empty value once, sorted", () => {- expect(fieldValues(runs, "agent")).toEqual(["billing-agent", "cron", "researcher", "triage"]);- expect(fieldValues(runs, "status")).toEqual(["error", "ok"]);- expect(fieldValues([run({ models: [] })], "model")).toEqual([]);- });-});diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/runQuery.ts b/ui/litellm-dashboard/src/components/lens/runSearch/runQuery.tsdeleted file mode 100644index 5ea6ed1ff4c..00000000000--- a/ui/litellm-dashboard/src/components/lens/runSearch/runQuery.ts+++ /dev/null@@ -1,111 +0,0 @@-import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";-import { previewText, traceAgentNames } from "@/components/view_logs/TraceView/traceUtils";--type RunFieldGroup = "Run attributes" | "Content" | "Identity";--interface RunFieldSpec {- group: RunFieldGroup;- read: (run: TraceSummary) => readonly string[];- suggestValues: boolean;-}--const runStatus = (run: TraceSummary): string => (run.error_count > 0 ? "error" : "ok");--export const RUN_FIELDS = {- name: { group: "Run attributes", read: (run) => [run.name], suggestValues: true },- agent: { group: "Run attributes", read: traceAgentNames, suggestValues: true },- status: { group: "Run attributes", read: (run) => [runStatus(run)], suggestValues: true },- model: { group: "Run attributes", read: (run) => run.models, suggestValues: true },- input: { group: "Content", read: (run) => [previewText(run.input_preview)], suggestValues: false },- trace_id: { group: "Identity", read: (run) => [run.trace_id], suggestValues: false },-} as const satisfies Record<string, RunFieldSpec>;--export type RunField = keyof typeof RUN_FIELDS;--const isRunField = (key: string): key is RunField => Object.hasOwn(RUN_FIELDS, key);--interface Span {- from: number;- to: number;-}--export type QueryClause =- | (Span & { kind: "text"; value: string })- | (Span & { kind: "field"; field: RunField; negated: boolean; keyTo: number; value: string });--const unquote = (raw: string): string => raw.replace(/^"([^"]*)"?$/, "$1");--/** Whitespace-separated tokens; a double-quoted stretch keeps its spaces. */-function tokenize(text: string): (Span & { raw: string })[] {- return Array.from(text.matchAll(/(?:"[^"]*"?|\S)+/g), (match) => ({- raw: match[0],- from: match.index,- to: match.index + match[0].length,- }));-}--function parseToken({ raw, from, to }: Span & { raw: string }): QueryClause {- const match = /^(-?)([A-Za-z_]+):(.*)$/.exec(raw);- const key = match?.[2].toLowerCase() ?? "";- if (!match || !isRunField(key)) return { kind: "text", value: unquote(raw), from, to };- const negated = match[1] === "-";- return {- kind: "field",- field: key,- negated,- keyTo: from + match[1].length + match[2].length,- value: unquote(match[3]),- from,- to,- };-}--export const parseRunQuery = (text: string): QueryClause[] => tokenize(text).map(parseToken);--/** `bar` matches the whole value, `*bar*` is a glob; both ignore case. */-function valueMatcher(pattern: string): (value: string) => boolean {- const needle = pattern.toLowerCase();- if (!needle.includes("*")) return (value) => value.toLowerCase() === needle;- const segments = needle.split("*");- const first = segments[0];- const last = segments.at(-1);- const middle = segments.slice(1, -1).filter(Boolean);- return (value) => {- const candidate = value.toLowerCase();- if (first && !candidate.startsWith(first)) return false;- if (last && !candidate.endsWith(last)) return false;- const suffixStart = last ? candidate.length - last.length : candidate.length;- let cursor = first ? first.length : 0;- if (suffixStart < cursor) return false;- for (const segment of middle) {- const found = candidate.indexOf(segment, cursor);- if (found < 0 || found + segment.length > suffixStart) return false;- cursor = found + segment.length;- }- return true;- };-}--function matchesClause(run: TraceSummary, clause: QueryClause): boolean {- if (clause.kind === "text") {- const needle = clause.value.toLowerCase();- return [run.trace_id, previewText(run.input_preview), run.name].some((text) => text.toLowerCase().includes(needle));- }- // A key typed without a value yet narrows nothing, so the list does not blank out mid-typing.- if (!clause.value) return true;- const matches = RUN_FIELDS[clause.field].read(run).some(valueMatcher(clause.value));- return clause.negated ? !matches : matches;-}--/** Every clause must hold: free text searches input, name and trace id; `key:value` clauses target one field. */-export function filterRuns(runs: TraceSummary[], query: string): TraceSummary[] {- const clauses = parseRunQuery(query);- if (clauses.length === 0) return runs;- return runs.filter((run) => clauses.every((clause) => matchesClause(run, clause)));-}--export function fieldValues(runs: readonly TraceSummary[], field: RunField): string[] {- return Array.from(new Set(runs.flatMap((run) => RUN_FIELDS[field].read(run))))- .filter(Boolean)- .sort();-}diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/suggestions.test.ts b/ui/litellm-dashboard/src/components/lens/runSearch/suggestions.test.tsdeleted file mode 100644index 636a08fd165..00000000000--- a/ui/litellm-dashboard/src/components/lens/runSearch/suggestions.test.ts+++ /dev/null@@ -1,75 +0,0 @@-import { describe, expect, it } from "vitest";--import { run, runs } from "./__fixtures__/runs";-import { suggest, type Suggestion, type SuggestionMenu } from "./suggestions";--const atEnd = (text: string, source = runs) => suggest(text, text.length, source);-const items = (menu: SuggestionMenu | null): Suggestion[] => menu?.groups.flatMap((g) => g.items) ?? [];-const labels = (menu: SuggestionMenu | null) => items(menu).map((item) => item.label);-const apply = (text: string, item: Suggestion) => text.slice(0, item.from) + item.insert + text.slice(item.to);--describe("suggest", () => {- it("offers every field, grouped, in an empty box", () => {- const menu = atEnd("");- expect(menu?.groups.map((g) => g.heading)).toEqual(["Run attributes", "Content", "Identity"]);- expect(labels(menu)).toEqual(["name", "agent", "status", "model", "input", "trace_id"]);- expect(menu?.showOperators).toBe(false);- });-- it("narrows fields by the typed prefix and completes the key with a colon", () => {- const menu = atEnd("refund AG");- expect(labels(menu)).toEqual(["agent"]);- expect(apply("refund AG", items(menu)[0])).toBe("refund agent:");- expect(items(menu)[0].completesClause).toBe(false);- });-- it("keeps a leading minus when completing a negated key", () => {- expect(apply("-st", items(atEnd("-st"))[0])).toBe("-status:");- });-- it("offers nothing for free text that names no field", () => {- expect(atEnd("refund")).toBeNull();- expect(atEnd("foo:bar")).toBeNull();- });-- it("offers the loaded values and the operator help once a key has its colon", () => {- const menu = atEnd("agent:");- expect(menu?.groups.map((g) => g.heading)).toEqual(["agent"]);- expect(labels(menu)).toEqual(["billing-agent", "cron", "researcher", "triage"]);- expect(menu?.showOperators).toBe(true);- });-- it("narrows values by substring, ignoring wildcards, and drops operator help once a value is typed", () => {- const menu = atEnd("-agent:*AR*");- expect(labels(menu)).toEqual(["researcher"]);- expect(menu?.showOperators).toBe(false);- expect(atEnd("agent:zzz")).toBeNull();- });-- it("replaces only the value, adds a separating space at the end, and finishes the clause", () => {- const item = items(atEnd("-agent:bil"))[0];- expect(apply("-agent:bil", item)).toBe("-agent:billing-agent ");- expect(item.completesClause).toBe(true);- const text = "agent:tri refund";- expect(apply(text, items(suggest(text, 9, runs))[0])).toBe("agent:triage refund");- });-- it("quotes a value that contains spaces", () => {- const spaced = [run({ name: "Order lookup" })];- expect(apply("name:", items(atEnd("name:", spaced))[0])).toBe('name:"Order lookup" ');- });-- it("does not list values for free-form fields but still explains the operators", () => {- const menu = atEnd("input:");- expect(menu?.groups).toEqual([]);- expect(menu?.showOperators).toBe(true);- expect(atEnd("input:x")).toBeNull();- });-- it("offers fields in the gap between tokens, but nothing mid-token", () => {- const text = "refund status:ok";- expect(apply(text, items(suggest(text, 7, runs))[1])).toBe("refund agent: status:ok");- expect(suggest(text, 3, runs)).toBeNull();- expect(suggest("status:ok", 0, runs)).toBeNull();- });-});diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/suggestions.ts b/ui/litellm-dashboard/src/components/lens/runSearch/suggestions.tsdeleted file mode 100644index 80bbf1e7cc2..00000000000--- a/ui/litellm-dashboard/src/components/lens/runSearch/suggestions.ts+++ /dev/null@@ -1,91 +0,0 @@-import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";--import { fieldValues, parseRunQuery, RUN_FIELDS, type QueryClause, type RunField } from "./runQuery";--export interface Suggestion {- id: string;- label: string;- field: RunField;- /** Replaces `text.slice(from, to)`. */- from: number;- to: number;- insert: string;- /** A value finishes the clause and closes the menu; a field keeps it open for its values. */- completesClause: boolean;-}--export interface SuggestionGroup {- heading: string;- items: Suggestion[];-}--export interface SuggestionMenu {- groups: SuggestionGroup[];- showOperators: boolean;-}--const MAX_VALUES = 50;-const FIELDS = Object.keys(RUN_FIELDS) as RunField[];-const isSpace = (char: string | undefined) => char === undefined || /\s/.test(char);-const quoteIfNeeded = (value: string) => (/[\s"]/.test(value) ? `"${value.replaceAll('"', "")}"` : value);--function fieldMenu(prefix: string, negated: boolean, from: number, to: number): SuggestionMenu | null {- const fields = FIELDS.filter((field) => field.startsWith(prefix.toLowerCase()));- if (fields.length === 0) return null;- const groups = Array.from(new Set(fields.map((field) => RUN_FIELDS[field].group)), (heading) => ({- heading,- items: fields- .filter((field) => RUN_FIELDS[field].group === heading)- .map((field) => ({- id: `field:${field}`,- label: field,- field,- from,- to,- insert: `${negated ? "-" : ""}${field}:`,- completesClause: false,- })),- }));- return { groups, showOperators: false };-}--function valueMenu(- clause: Extract<QueryClause, { kind: "field" }>,- text: string,- runs: readonly TraceSummary[],-): SuggestionMenu | null {- const from = clause.keyTo + 1;- const needle = clause.value.replaceAll("*", "").toLowerCase();- const trailing = clause.to === text.length ? " " : "";- const values = RUN_FIELDS[clause.field].suggestValues ? fieldValues(runs, clause.field) : [];- const items = values- .filter((value) => value.toLowerCase().includes(needle))- .slice(0, MAX_VALUES)- .map((value) => ({- id: `value:${value}`,- label: value,- field: clause.field,- from,- to: clause.to,- insert: quoteIfNeeded(value) + trailing,- completesClause: true,- }));- const showOperators = clause.value === "";- if (items.length === 0 && !showOperators) return null;- return { groups: items.length ? [{ heading: clause.field, items }] : [], showOperators };-}--/** What to offer at the cursor: fields while a key is being typed, values once it has a colon. */-export function suggest(text: string, cursor: number, runs: readonly TraceSummary[]): SuggestionMenu | null {- const clause = parseRunQuery(text).find((c) => c.from < cursor && c.to === cursor);- if (!clause) {- const betweenTokens = isSpace(text[cursor - 1]) && isSpace(text[cursor]);- return betweenTokens ? fieldMenu("", false, cursor, cursor) : null;- }- if (clause.kind === "field") return valueMenu(clause, text, runs);- const raw = text.slice(clause.from, clause.to);- const negated = raw.startsWith("-");- const prefix = negated ? raw.slice(1) : raw;- if (/[:"]/.test(prefix)) return null;- return fieldMenu(prefix, negated, clause.from, clause.to);-}diff --git a/ui/litellm-dashboard/src/components/lens/services.ts b/ui/litellm-dashboard/src/components/lens/services.tsdeleted file mode 100644index d350e5cd1b3..00000000000--- a/ui/litellm-dashboard/src/components/lens/services.ts+++ /dev/null@@ -1,20 +0,0 @@-"use client";--import { createContext, useContext, useMemo } from "react";-import { apiClient } from "@/components/networking";-import type { TracesApi } from "@/components/view_logs/TraceView/tracesApi";-import { liveLensApi, type LensApi } from "./api/service";--export interface LensServices {- readonly lens: LensApi;- readonly traces: TracesApi;-}--export const LensApiContext = createContext<LensApi | null>(null);--/** Without a provider, falls back to the live HTTP implementation for the caller's token. */-export function useLensApi(accessToken: string): LensApi {- const provided = useContext(LensApiContext);- const live = useMemo(() => liveLensApi(apiClient, accessToken), [accessToken]);- return provided ?? live;-}diff --git a/ui/litellm-dashboard/src/components/lens/settings/LensSettings.tsx b/ui/litellm-dashboard/src/components/lens/settings/LensSettings.tsxnew file mode 100644index 00000000000..4ee7917cc00--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/LensSettings.tsx@@ -0,0 +1,84 @@+"use client";++import { useId, type ReactNode } from "react";+import { Activity, ArrowUpRight } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { StatusDot } from "@/components/shared/StatusDot";+import { useStoredValue } from "@/lib/storage";+import { LENS_INTRO_DISMISSED } from "../storage";+import { WorkerSettings } from "./worker/WorkerSettings";+import { SettingsCard, SettingsSection } from "./SettingsSection";+import type { LensList } from "../model/types";++const TRACING_DOCS = "https://docs.litellm.ai/docs/proxy/lens";++function TracingSection({ enabled, onOpenTraces }: { enabled: boolean; onOpenTraces: () => void }) {+ return (+ <SettingsSection heading="Tracing" description="Where your agents send runs so Lens can read them.">+ <SettingsCard className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex items-center gap-3 text-sm">+ <Activity aria-hidden="true" className="size-4 text-muted-foreground" />+ <span role="status" className="inline-flex items-center gap-2">+ <StatusDot state={enabled ? "ok" : "off"} />+ {enabled ? "Tracing enabled" : "Tracing is not enabled"}+ </span>+ </div>+ <div className="flex items-center gap-3">+ <a+ href={TRACING_DOCS}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 text-xs text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"+ >+ Docs+ <ArrowUpRight aria-hidden="true" className="size-3" />+ </a>+ <Button variant="outline" size="sm" onClick={onOpenTraces}>+ {enabled ? "Connect an agent" : "Enable tracing"}+ </Button>+ </div>+ </SettingsCard>+ </SettingsSection>+ );+}++function IntroductionSection() {+ const [dismissed, setDismissed] = useStoredValue(LENS_INTRO_DISMISSED);+ const id = useId();+ return (+ <SettingsSection heading="Introduction" description="The getting started dialog shown when you open Lens.">+ <SettingsCard className="flex items-center justify-between gap-3">+ <Label htmlFor={id} className="text-sm font-normal">+ Show the introduction on each new session+ </Label>+ <Switch id={id} checked={!dismissed} onCheckedChange={(show) => setDismissed(!show)} />+ </SettingsCard>+ </SettingsSection>+ );+}++export function LensSettings({+ list,+ workerReadyAction,+ onOpenTraces,+}: {+ list: LensList;+ /** Replaces the worker install card's Done button once the new worker connects. */+ workerReadyAction?: ReactNode;+ onOpenTraces: () => void;+}) {+ return (+ <div aria-label="Settings" role="region" className="flex w-full flex-col divide-y divide-border">+ <TracingSection enabled={list.tracing_enabled} onOpenTraces={onOpenTraces} />+ <SettingsSection+ heading="Analysis worker"+ description="Runs investigations on your server and bills model usage to an analysis key."+ >+ <WorkerSettings workers={list.workers} readyAction={workerReadyAction} />+ </SettingsSection>+ <IntroductionSection />+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/settings/SettingsSection.tsx b/ui/litellm-dashboard/src/components/lens/settings/SettingsSection.tsxnew file mode 100644index 00000000000..b2dd0eb3f1a--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/SettingsSection.tsx@@ -0,0 +1,33 @@+import type { ComponentProps } from "react";+import { cn } from "@/lib/cva.config";++export type SettingsSectionProps = ComponentProps<"section"> & { heading: string; description: string };++export function SettingsSection({ heading, description, className, children, ...props }: SettingsSectionProps) {+ return (+ <section+ data-slot="settings-section"+ aria-label={heading}+ {...props}+ className={cn("grid gap-4 py-6 first:pt-0 last:pb-0 md:grid-cols-[200px_minmax(0,1fr)] md:gap-8", className)}+ >+ <div className="space-y-1">+ <h2 className="text-sm font-semibold">{heading}</h2>+ <p className="text-xs leading-5 text-muted-foreground">{description}</p>+ </div>+ <div className="min-w-0 space-y-3">{children}</div>+ </section>+ );+}++export type SettingsCardProps = ComponentProps<"div">;++export function SettingsCard({ className, ...props }: SettingsCardProps) {+ return (+ <div+ data-slot="settings-card"+ {...props}+ className={cn("rounded-lg border border-border bg-card p-4", className)}+ />+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisAccessFields.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisAccessFields.tsxsimilarity index 89%rename from ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisAccessFields.tsxrename to ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisAccessFields.tsxindex ee84051f4f6..106b31aafcd 100644--- a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisAccessFields.tsx+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisAccessFields.tsx@@ -1,21 +1,21 @@"use client";import { Controller, useFormContext } from "react-hook-form";-import { lensQueries } from "../../api/queries";+import { lensQueries } from "../../data/queries";import { useQuery } from "@tanstack/react-query";-import { useLensApi } from "../../services";+import { useLensApi } from "../../data/LensServices";import { SearchSelect } from "@/components/shared/SearchSelect";import { Input } from "@/components/ui/input";import type { WorkerFormInput } from "./workerSchema";-export function AnalysisAccessFields({ accessToken }: { accessToken: string }) {+export function AnalysisAccessFields() {const {control,register,formState: { errors },} = useFormContext<WorkerFormInput>();- const api = useLensApi(accessToken);+ const api = useLensApi();const models = useQuery(lensQueries.models(api));return (<div className="space-y-5">diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyDetails.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyDetails.tsxsimilarity index 61%rename from ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyDetails.tsxrename to ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyDetails.tsxindex 3fa6a8bf433..f4927c92bbe 100644--- a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyDetails.tsx+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyDetails.tsx@@ -1,11 +1,8 @@"use client";-import { analysisKeyInfoQuery } from "../../api/queries";--import { useQuery } from "@tanstack/react-query";-import { useLensApi } from "../../services";import { Button } from "@/components/ui/button";import { runTime } from "../../model/format";+import { useAnalysisKeyInfo } from "./useAnalysisKeyInfo";function budgetLabel(amount: number | null, duration?: string | null): string {if (amount === null) return "No key budget";@@ -25,21 +22,39 @@ function budgetLabel(amount: number | null, duration?: string | null): string {return duration ? `${dollars} / ${periods[duration] ?? duration}` : `${dollars} total`;}-export function useAnalysisKeyInfo(accessToken: string, keyId?: string) {- const api = useLensApi(accessToken);- return useQuery(analysisKeyInfoQuery(api, keyId));+function modelsLabel(models: readonly string[]): string {+ return models.length ? models.join(", ") : "All models";+}++export function AnalysisKeySummary({ keyId }: { keyId: string }) {+ const key = useAnalysisKeyInfo(keyId);+ if (key.isLoading) return <p className="text-xs text-muted-foreground">Loading billing key…</p>;+ if (key.error || !key.data)+ return (+ <p role="alert" className="flex items-center gap-2 text-xs text-destructive">+ Could not load billing key+ <Button variant="link" size="xs" className="h-auto p-0" onClick={() => void key.refetch()}>+ Retry+ </Button>+ </p>+ );+ const info = key.data;+ const summary = [+ `Bills to ${info.key_alias || "an assigned virtual key"}`,+ modelsLabel(info.models),+ budgetLabel(info.max_budget, info.budget_duration),+ ].join(" · ");+ const inactive = info.status && info.status !== "active";+ return (+ <p className="truncate text-xs text-muted-foreground">+ {summary}+ {inactive && <span className="text-destructive"> · Key {info.status}</span>}+ </p>+ );}-export function AnalysisKeyDetails({- accessToken,- keyId,- showName = false,-}: {- accessToken: string;- keyId: string;- showName?: boolean;-}) {- const key = useAnalysisKeyInfo(accessToken, keyId);+export function AnalysisKeyDetails({ keyId }: { keyId: string }) {+ const key = useAnalysisKeyInfo(keyId);if (key.isLoading) return <p className="text-xs text-muted-foreground">Loading key permissions…</p>;if (key.error || !key.data)return (@@ -54,14 +69,8 @@ export function AnalysisKeyDetails({return (<div className="space-y-2 text-sm"><dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-5 gap-y-2">- {showName && (- <>- <dt className="text-muted-foreground">Billing key</dt>- <dd className="break-words">{info.key_alias || "Assigned virtual key"}</dd>- </>- )}<dt className="text-muted-foreground">Models</dt>- <dd className="break-words">{info.models.length ? info.models.join(", ") : "All models"}</dd>+ <dd className="break-words">{modelsLabel(info.models)}</dd><dt className="text-muted-foreground">Key limit</dt><dd>{budgetLabel(info.max_budget, info.budget_duration)}</dd></dl>diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyPicker.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyPicker.integration.test.tsxsimilarity index 91%rename from ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyPicker.integration.test.tsxrename to ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyPicker.integration.test.tsxindex 8031e2f130b..2873c6f18e6 100644--- a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyPicker.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyPicker.integration.test.tsx@@ -2,7 +2,8 @@ import { screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { FormProvider, useForm } from "react-hook-form";-import { renderWithProviders, testQueryClient } from "@/../tests/test-utils";+import { testQueryClient } from "@/../tests/test-utils";+import { renderWithLens } from "@/../tests/lens-test-utils";import { apiClient } from "@/components/networking";import { AnalysisKeyPicker } from "./AnalysisKeyPicker";import type { WorkerFormInput } from "./workerSchema";@@ -20,7 +21,7 @@ function AnalysisKeyPickerForm() {});return (<FormProvider {...form}>- <AnalysisKeyPicker accessToken="test" />+ <AnalysisKeyPicker /></FormProvider>);}@@ -44,7 +45,7 @@ describe("Lens billing key", () => {total_pages: 2,},);- renderWithProviders(<AnalysisKeyPickerForm />);+ renderWithLens(<AnalysisKeyPickerForm />);await user.click(screen.getByRole("combobox", { name: "Charge analysis to" }));await user.click(await screen.findByRole("option", { name: "Load more keys" }));await user.click(await screen.findByRole("option", { name: "Second page" }));diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyPicker.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyPicker.tsxsimilarity index 91%rename from ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyPicker.tsxrename to ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyPicker.tsxindex 7cbf56b85f8..58abc7eeb11 100644--- a/ui/litellm-dashboard/src/components/lens/setup/worker/AnalysisKeyPicker.tsx+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/AnalysisKeyPicker.tsx@@ -1,11 +1,11 @@"use client";-import { analysisKeysQuery, type Key } from "../../api/queries";+import { analysisKeysQuery, type Key } from "../../data/queries";import { Controller, useFormContext, useWatch } from "react-hook-form";import { useState } from "react";import { useInfiniteQuery } from "@tanstack/react-query";-import { useLensApi } from "../../services";+import { useLensApi } from "../../data/LensServices";import { AnalysisKeyDetails } from "./AnalysisKeyDetails";import type { WorkerFormInput } from "./workerSchema";import {@@ -17,10 +17,10 @@ import {ComboboxList,} from "@/components/ui/combobox";-export function AnalysisKeyPicker({ accessToken }: { accessToken: string }) {+export function AnalysisKeyPicker() {const { control } = useFormContext<WorkerFormInput>();const value = useWatch({ control, name: "analysisKey" });- const api = useLensApi(accessToken);+ const api = useLensApi();const [query, setQuery] = useState("");const [selected, setSelected] = useState<Key | null>(value ? { token: value } : null);@@ -82,7 +82,7 @@ export function AnalysisKeyPicker({ accessToken }: { accessToken: string }) {/></div></div>- {choice && <AnalysisKeyDetails accessToken={accessToken} keyId={choice.token} />}+ {choice && <AnalysisKeyDetails keyId={choice.token} />}{keyPages.error && (<p role="alert" className="text-sm text-destructive">{keyPages.error.message}diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerForm.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerForm.tsxsimilarity index 86%rename from ui/litellm-dashboard/src/components/lens/setup/worker/WorkerForm.tsxrename to ui/litellm-dashboard/src/components/lens/settings/worker/WorkerForm.tsxindex 54dfecfe460..fb1e7a57ee8 100644--- a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerForm.tsx+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerForm.tsx@@ -8,7 +8,7 @@ import { AnalysisKeyPicker } from "./AnalysisKeyPicker";import { AnalysisAccessFields } from "./AnalysisAccessFields";import type { WorkerFormInput } from "./workerSchema";-export function WorkerForm({ accessToken, editingWorker }: { accessToken: string; editingWorker: string | null }) {+export function WorkerForm({ editingWorker }: { editingWorker: string | null }) {const {control,register,@@ -17,11 +17,7 @@ export function WorkerForm({ accessToken, editingWorker }: { accessToken: stringconst useExisting = useWatch({ control, name: "useExisting" });return (<div className="min-w-0 space-y-5">- {useExisting ? (- <AnalysisKeyPicker accessToken={accessToken} />- ) : (- <AnalysisAccessFields accessToken={accessToken} />- )}+ {useExisting ? <AnalysisKeyPicker /> : <AnalysisAccessFields />}<details className="text-sm" open={editingWorker ? true : undefined}><summary className="cursor-pointer font-medium">Advanced options</summary><div className="mt-4 space-y-5">diff --git a/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerInstall.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerInstall.tsxnew file mode 100644index 00000000000..26760cedc17--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerInstall.tsx@@ -0,0 +1,104 @@+"use client";++import type { ComponentProps, ReactNode } from "react";+import { useMutation } from "@tanstack/react-query";+import { CheckCircle2, Copy, Loader2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/cva.config";+import type { WorkerCreated } from "../../model/types";+import { SettingsCard } from "../SettingsSection";+import { workerSetupCommand } from "./workerCommand";++const CLIPBOARD_FAILED = "Clipboard access failed. Allow clipboard access and try again.";++function useCopy() {+ return useMutation({ retry: false, mutationFn: (text: string) => navigator.clipboard.writeText(text) });+}++function InstallSteps({ address, created }: { address: string; created: WorkerCreated }) {+ const command = workerSetupCommand(address, created.token, created.image);+ const copyCommand = useCopy();+ const copyToken = useCopy();+ return (+ <>+ <Button variant="default" className="w-full gap-2" onClick={() => copyCommand.mutate(command)}>+ {copyCommand.isSuccess ? <CheckCircle2 className="size-4" /> : <Copy className="size-4" />}+ {copyCommand.isSuccess ? "Copied" : "Copy Docker command"}+ </Button>+ <details className="text-sm">+ <summary className="cursor-pointer text-muted-foreground">View command</summary>+ <p className="mt-3 text-xs text-muted-foreground">Contains a private worker token.</p>+ <pre+ aria-label="Docker command preview"+ className="mt-3 max-h-48 overflow-auto rounded-md bg-muted/40 p-3 text-xs leading-5"+ >+ {command}+ </pre>+ </details>+ <details className="text-sm">+ <summary className="cursor-pointer text-muted-foreground">Using Docker Compose or Helm?</summary>+ <p className="mt-3 text-muted-foreground">+ Save this private token as LENS_WORKER_TOKEN in Compose or in your Helm worker token secret. Keep it for+ future upgrades.+ </p>+ <Button variant="outline" className="mt-3" onClick={() => copyToken.mutate(created.token)}>+ {copyToken.isSuccess ? "Token copied" : "Copy worker token"}+ </Button>+ </details>+ <div className="space-y-3 border-t pt-5">+ <div role="status" className="flex items-center gap-2.5 text-sm">+ <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" /> Waiting for your worker to connect…+ </div>+ <details className="pl-6.5 text-sm text-muted-foreground">+ <summary className="cursor-pointer">Not connecting?</summary>+ <p className="mt-2 break-words leading-6">+ Check that Docker is running and can reach {address}. Inspect the container logs for connection or+ authentication errors. This page updates automatically.+ </p>+ </details>+ </div>+ {(copyCommand.isError || copyToken.isError) && (+ <p role="alert" className="text-sm text-destructive">+ {CLIPBOARD_FAILED}+ </p>+ )}+ </>+ );+}++export type WorkerInstallProps = ComponentProps<"div"> & {+ address: string;+ created: WorkerCreated;+ connected: boolean;+ /** Rendered once the worker connects, in place of the install steps. */+ children: ReactNode;+};++export function WorkerInstall({ address, created, connected, children, className, ...props }: WorkerInstallProps) {+ if (!connected)+ return (+ <SettingsCard {...props} data-slot="worker-install" className={cn("flex flex-col gap-5", className)}>+ <header className="space-y-1">+ <h3 className="text-base font-semibold">Run the worker</h3>+ <p className="text-sm text-muted-foreground">Run this command on a server with Docker.</p>+ </header>+ <InstallSteps address={address} created={created} />+ </SettingsCard>+ );+ return (+ <SettingsCard+ {...props}+ data-slot="worker-install"+ className={cn("flex flex-col items-center gap-5 text-center", className)}+ >+ <header className="flex flex-col items-center gap-3">+ <div className="flex size-12 items-center justify-center rounded-full bg-success/10 text-success">+ <CheckCircle2 className="size-6" />+ </div>+ <h3 className="text-base font-semibold">Worker connected</h3>+ <p className="text-sm text-muted-foreground">Ready to run investigations.</p>+ </header>+ {children}+ </SettingsCard>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerList.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerList.tsxnew file mode 100644index 00000000000..1d42a840ffa--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerList.tsx@@ -0,0 +1,65 @@+"use client";++import type { ComponentProps } from "react";+import { Button } from "@/components/ui/button";+import { useNow } from "@/hooks/useNow";+import { StatusDot, type StatusDotProps } from "@/components/shared/StatusDot";+import { cn } from "@/lib/cva.config";+import { workerConnected } from "../../model/status";+import { agoLabel } from "../../model/format";+import { AnalysisKeySummary } from "./AnalysisKeyDetails";+import type { LensList, Worker } from "../../model/types";++function workerStatus(worker: Worker, now: number): { state: StatusDotProps["state"]; label: string } {+ if (!worker.analysis_key_id) return { state: "warn", label: "Billing key required" };+ if (workerConnected(worker, now)) return { state: "ok", label: "Connected" };+ return { state: "off", label: `Not connected · last seen ${agoLabel(Date.parse(worker.last_seen), now)}` };+}++export type WorkerListProps = ComponentProps<"ul"> & {+ workers: LensList["workers"];+ onEditBilling: (worker: Worker) => void;+ onRevoke: (id: string) => void;+};++export function WorkerList({ workers, onEditBilling, onRevoke, className, ...props }: WorkerListProps) {+ const now = useNow(5000);+ return (+ <ul+ {...props}+ data-slot="worker-list"+ className={cn("divide-y divide-border rounded-lg border border-border bg-card", className)}+ >+ {workers+ .filter((w) => !w.revoked)+ .map((worker) => {+ const status = workerStatus(worker, now);+ return (+ <li key={worker.id} className="flex flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3 text-sm">+ <StatusDot state={status.state} className="shrink-0" />+ <div className="min-w-0 flex-1 space-y-0.5">+ <div className="flex flex-wrap items-baseline gap-x-2">+ <h3 className="font-medium">{worker.name}</h3>+ <span className="text-xs text-muted-foreground">{status.label}</span>+ </div>+ {worker.analysis_key_id && <AnalysisKeySummary keyId={worker.analysis_key_id} />}+ </div>+ <div className="flex items-center gap-1">+ <Button variant="outline" size="sm" onClick={() => onEditBilling(worker)}>+ Edit access+ </Button>+ <Button+ variant="ghost"+ size="sm"+ className="text-muted-foreground hover:text-destructive"+ onClick={() => onRevoke(worker.id)}+ >+ Revoke access+ </Button>+ </div>+ </li>+ );+ })}+ </ul>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerDialog.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerSettings.integration.test.tsxsimilarity index 65%rename from ui/litellm-dashboard/src/components/lens/setup/worker/WorkerDialog.integration.test.tsxrename to ui/litellm-dashboard/src/components/lens/settings/worker/WorkerSettings.integration.test.tsxindex 719b83cfe6b..4b26c75078d 100644--- a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerDialog.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerSettings.integration.test.tsx@@ -1,9 +1,14 @@import { screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";-import { renderWithProviders, testQueryClient } from "@/../tests/test-utils";+import { useQuery } from "@tanstack/react-query";+import { testQueryClient } from "@/../tests/test-utils";+import { renderWithLens } from "@/../tests/lens-test-utils";import { apiClient } from "@/components/networking";-import { WorkerDialog } from "./WorkerDialog";+import { lensQueries } from "../../data/queries";+import { useLensApi } from "../../data/LensServices";+import type { LensList } from "../../model/types";+import { WorkerSettings } from "./WorkerSettings";vi.mock("@/components/networking", () => ({apiClient: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() },@@ -23,6 +28,15 @@ const created = {},};+/** Mirrors the workspace: the worker rows come from the cached `/lens` list, so a mutation must refetch it to update them. */+function WorkerSettingsHost() {+ const api = useLensApi();+ const list = useQuery(lensQueries.list(api));+ return list.data ? <WorkerSettings workers={list.data.workers} /> : null;+}++const listCalls = () => vi.mocked(apiClient.get).mock.calls.filter(([path]) => path === "/lens").length;+describe("Worker setup", () => {beforeEach(() => {testQueryClient.clear();@@ -39,7 +53,7 @@ describe("Worker setup", () => {it("generates a complete command using one worker credential and the configured proxy address", async () => {vi.mocked(apiClient.post).mockResolvedValue(created);const user = userEvent.setup();- renderWithProviders(<WorkerDialog accessToken="admin" workers={[]} onClose={vi.fn()} onChanged={vi.fn()} />);+ const { rerender } = renderWithLens(<WorkerSettings workers={[]} />, { accessToken: "admin" });await user.click(screen.getByText("Advanced options"));await user.click(screen.getByRole("switch", { name: "Use an existing virtual key" }));expect(screen.getByRole("textbox", { name: "LiteLLM proxy URL" })).toHaveValue("https://gateway.example/proxy");@@ -62,22 +76,30 @@ describe("Worker setup", () => {await user.click(screen.getByText("Using Docker Compose or Helm?"));await user.click(screen.getByRole("button", { name: "Copy worker token" }));expect(await navigator.clipboard.readText()).toBe(created.token);- expect(screen.getByRole("button", { name: "Token copied" })).toBeVisible();+ expect(await screen.findByRole("button", { name: "Token copied" })).toBeVisible();+ rerender(<WorkerSettings workers={[{ ...created.worker, last_seen: new Date().toISOString() }]} />);+ expect(screen.getByRole("heading", { name: "Worker connected" })).toBeVisible();+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Done" }));+ expect(screen.getByRole("heading", { name: created.worker.name })).toBeVisible();+ expect(screen.getByText("Connected")).toBeVisible();});it("assigns billing to an existing worker without replacing its access token", async () => {const user = userEvent.setup();- const changed = vi.fn();- vi.mocked(apiClient.put).mockResolvedValue(created.worker);- renderWithProviders(- <WorkerDialog- accessToken="admin"- workers={[{ ...created.worker, analysis_key_id: null }]}- onClose={vi.fn()}- onChanged={changed}- />,- );- expect(screen.getByText("Billing key required")).toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Settings" }));+ const workers = vi.fn((): LensList["workers"] => [{ ...created.worker, analysis_key_id: null }]);+ vi.mocked(apiClient.get).mockImplementation(async (path) => {+ if (path === "/lens") return { lenses: [], workers: workers(), tracing_enabled: true };+ if (path === "/key/info") return { info: { models: ["analysis-model"], max_budget: 15, budget_duration: "1mo" } };+ return { keys: [{ token: "b".repeat(64), key_alias: "Analysis" }], total_pages: 1 };+ });+ vi.mocked(apiClient.put).mockImplementation(async () => {+ workers.mockReturnValue([created.worker]);+ return created.worker;+ });+ renderWithLens(<WorkerSettingsHost />, { accessToken: "admin" });+ expect(await screen.findByText("Billing key required")).toBeInTheDocument();+ const listedBefore = listCalls();+ await user.click(screen.getByRole("button", { name: "Edit access" }));await user.click(screen.getByRole("combobox", { name: "Charge analysis to" }));await user.click(await screen.findByRole("option", { name: "Analysis" }));await user.click(screen.getByRole("button", { name: "Save analysis access" }));@@ -85,23 +107,30 @@ describe("Worker setup", () => {accessToken: "admin",body: { analysis_key_id: "b".repeat(64) },});- expect(changed).toHaveBeenCalledOnce();+ expect(await screen.findByText(/Not connected/)).toBeVisible();+ expect(screen.queryByText("Billing key required")).not.toBeInTheDocument();+ expect(listCalls()).toBe(listedBefore + 1);expect(apiClient.post).not.toHaveBeenCalled();});it("requires revoking the current worker before setting up a replacement", async () => {const user = userEvent.setup();- const changed = vi.fn();- vi.mocked(apiClient.delete).mockResolvedValue(true);- const props = { accessToken: "admin", onClose: vi.fn(), onChanged: changed };- const view = renderWithProviders(<WorkerDialog {...props} workers={[created.worker]} />);+ const workers = vi.fn((): LensList["workers"] => [created.worker]);+ vi.mocked(apiClient.get).mockImplementation(async (path) =>+ path === "/lens" ? { lenses: [], workers: workers(), tracing_enabled: true } : { data: [] },+ );+ vi.mocked(apiClient.delete).mockImplementation(async () => {+ workers.mockReturnValue([{ ...created.worker, revoked: true }]);+ return true;+ });+ renderWithLens(<WorkerSettingsHost />, { accessToken: "admin" });+ const revoke = await screen.findByRole("button", { name: "Revoke access" });expect(screen.queryByRole("button", { name: "Add worker" })).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: "Get install command" })).not.toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Revoke access" }));+ await user.click(revoke);expect(apiClient.delete).toHaveBeenCalledWith("/lens/workers/worker", { accessToken: "admin" });- expect(changed).toHaveBeenCalledOnce();- view.rerender(<WorkerDialog {...props} workers={[{ ...created.worker, revoked: true }]} />);- expect(screen.getByRole("button", { name: "Get install command" })).toBeDisabled();+ expect(await screen.findByRole("button", { name: "Get install command" })).toBeDisabled();expect(screen.getByRole("combobox", { name: "Analysis model" })).toBeVisible();+ expect(listCalls()).toBe(2);});it("cleans up a newly created key when registration fails before retrying", async () => {const user = userEvent.setup();@@ -116,7 +145,7 @@ describe("Worker setup", () => {.mockResolvedValueOnce({}).mockResolvedValueOnce({ token_id: "retry-key-id" }).mockResolvedValueOnce(created);- renderWithProviders(<WorkerDialog accessToken="admin" workers={[]} onClose={vi.fn()} onChanged={vi.fn()} />);+ renderWithLens(<WorkerSettings workers={[]} />, { accessToken: "admin" });expect(screen.getByRole("button", { name: "Get install command" })).toBeDisabled();expect(screen.getByRole("textbox", { name: "LiteLLM proxy URL", hidden: true })).not.toBeVisible();await user.click(screen.getByRole("combobox", { name: "Analysis model" }));diff --git a/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerSettings.tsx b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerSettings.tsxnew file mode 100644index 00000000000..8a30908e51c--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/WorkerSettings.tsx@@ -0,0 +1,168 @@+"use client";++import { useState, type ReactNode } from "react";+import { FormProvider } from "react-hook-form";+import { Button } from "@/components/ui/button";+import { useZodForm } from "@/lib/forms/useZodForm";+import { useRevokeWorker } from "../../data/mutations";+import type { LensList, Worker } from "../../model/types";+import { useWorkerConnected } from "../../hooks/useWorkerConnected";+import { SettingsCard } from "../SettingsSection";+import { usePrepareWorker } from "./usePrepareWorker";+import { initialProxyAddress } from "./workerCommand";+import { WorkerForm } from "./WorkerForm";+import { WorkerInstall } from "./WorkerInstall";+import { WorkerList } from "./WorkerList";+import { workerFormSchema, type WorkerFormInput } from "./workerSchema";+import { workerScreen } from "./workerScreen";++function defaultWorkerFormValues(): WorkerFormInput {+ return {+ useExisting: false,+ analysisKey: null,+ access: { model: null, budget: "100" },+ address: typeof window === "undefined" ? "" : initialProxyAddress(),+ };+}++function ErrorText({ message }: { message: string | undefined }) {+ if (!message) return null;+ return (+ <p role="alert" className="text-sm text-destructive">+ {message}+ </p>+ );+}++function submitLabel(editing: Worker | null, busy: boolean): string {+ if (busy) return "Preparing…";+ return editing ? "Save analysis access" : "Get install command";+}++function WorkerFormCard({+ editing,+ busy,+ valid,+ onCancel,+ onSubmit,+ children,+}: {+ editing: Worker | null;+ busy: boolean;+ valid: boolean;+ onCancel: () => void;+ onSubmit: () => void;+ children: ReactNode;+}) {+ return (+ <SettingsCard className="flex flex-col gap-5">+ <header className="space-y-1">+ <h3 className="text-base font-semibold">{editing ? "Analysis access" : "Connect a worker"}</h3>+ <p className="text-sm text-muted-foreground">+ {editing ? "Choose which key pays for analysis." : "Deploy the worker on your server to run investigations."}+ </p>+ </header>+ <WorkerForm editingWorker={editing?.id ?? null} />+ <div className="flex justify-end gap-2">+ {editing && (+ <Button variant="outline" disabled={busy} onClick={onCancel}>+ Cancel+ </Button>+ )}+ <Button disabled={!valid || busy} onClick={onSubmit}>+ {submitLabel(editing, busy)}+ </Button>+ </div>+ {children}+ </SettingsCard>+ );+}++export function WorkerSettings({+ workers,+ readyAction,+}: {+ workers: LensList["workers"];+ /** Shown once a freshly installed worker connects; defaults to a Done button that returns to the list. */+ readyAction?: ReactNode;+}) {+ const revokeWorker = useRevokeWorker();+ const prepareWorker = usePrepareWorker();+ const form = useZodForm(workerFormSchema, {+ defaultValues: defaultWorkerFormValues(),+ mode: "onChange",+ });+ const { formState, reset, setValue } = form;+ const [editingId, setEditingId] = useState<string | null>(null);+ const created = prepareWorker.data ?? null;+ const connected = useWorkerConnected(created ? workers.filter((w) => w.id === created.worker.id) : null);+ const screenInput = { workers, created, editingId, connected };+ const screen = workerScreen(screenInput);+ const error = prepareWorker.error?.message ?? revokeWorker.error?.message;+ const cancelForm = () => {+ setEditingId(null);+ reset(defaultWorkerFormValues());+ };+ const editBilling = (worker: Worker) => {+ reset({ ...defaultWorkerFormValues(), useExisting: true, analysisKey: worker.analysis_key_id ?? null });+ prepareWorker.reset();+ setEditingId(worker.id);+ };+ const submit = (editing: Worker | null) =>+ form.handleSubmit((values) => {+ const registration = {+ address: values.address,+ useExisting: values.useExisting,+ analysisKey: values.analysisKey,+ access: values.access,+ editingWorker: editing?.id ?? null,+ };+ prepareWorker.mutate(registration, {+ onSuccess: (result) => {+ if (result) return;+ setEditingId(null);+ setValue("analysisKey", null);+ },+ });+ })();+ const revoke = (id: string) =>+ revokeWorker.mutate(id, {+ onSuccess: () => {+ setValue("analysisKey", null);+ setValue("useExisting", false);+ },+ });+ switch (screen.kind) {+ case "list":+ return (+ <>+ <WorkerList workers={workers} onEditBilling={editBilling} onRevoke={revoke} />+ <ErrorText message={error} />+ </>+ );+ case "form":+ return (+ <FormProvider {...form}>+ <WorkerFormCard+ editing={screen.editing}+ busy={prepareWorker.isPending}+ valid={formState.isValid}+ onCancel={cancelForm}+ onSubmit={() => void submit(screen.editing)}+ >+ <ErrorText message={error} />+ </WorkerFormCard>+ </FormProvider>+ );+ case "install":+ return (+ <WorkerInstall address={form.getValues("address")} created={screen.created} connected={screen.connected}>+ {readyAction ?? (+ <Button className="w-full" onClick={() => prepareWorker.reset()}>+ Done+ </Button>+ )}+ </WorkerInstall>+ );+ }+}diff --git a/ui/litellm-dashboard/src/components/lens/settings/worker/useAnalysisKeyInfo.ts b/ui/litellm-dashboard/src/components/lens/settings/worker/useAnalysisKeyInfo.tsnew file mode 100644index 00000000000..d41a8589b92--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/useAnalysisKeyInfo.ts@@ -0,0 +1,10 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { analysisKeyInfoQuery } from "../../data/queries";+import { useLensApi } from "../../data/LensServices";++export function useAnalysisKeyInfo(keyId?: string) {+ const api = useLensApi();+ return useQuery(analysisKeyInfoQuery(api, keyId));+}diff --git a/ui/litellm-dashboard/src/components/lens/settings/worker/usePrepareWorker.ts b/ui/litellm-dashboard/src/components/lens/settings/worker/usePrepareWorker.tsnew file mode 100644index 00000000000..b12522398e3--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/usePrepareWorker.ts@@ -0,0 +1,66 @@+"use client";++import { useMutation, useQueryClient } from "@tanstack/react-query";+import { lensKeys } from "../../data/queries";+import type { LensApi } from "../../data/service";+import { useLensApi } from "../../data/LensServices";+import type { WorkerCreated } from "../../model/types";+import { validateWorkerAddress, analysisAccessSchema, type AnalysisAccess } from "./workerSchema";++export interface WorkerRegistration {+ readonly address: string;+ readonly useExisting: boolean;+ readonly analysisKey: string | null;+ readonly access: AnalysisAccess;+ readonly editingWorker: string | null;+}++export async function createAnalysisKey(api: LensApi, access: AnalysisAccess): Promise<string> {+ const parsed = analysisAccessSchema.safeParse(access);+ if (!parsed.success) throw new Error(parsed.error.issues[0].message);+ const result = await api.generateAnalysisKey(parsed.data);+ if (!result.token_id) throw new Error("The proxy did not return the new key's ID");+ return result.token_id;+}++async function releaseUnusedKey(api: LensApi, keyId: string): Promise<void> {+ const current = await api.lenses();+ if (current.workers.some((worker) => !worker.revoked && worker.analysis_key_id === keyId)) return;+ await api.deleteKeys([keyId]);+}++async function prepareWorker(api: LensApi, registration: WorkerRegistration): Promise<WorkerCreated | null> {+ const { address, useExisting, analysisKey, access, editingWorker } = registration;+ validateWorkerAddress(address);+ const keyId = useExisting ? analysisKey : await createAnalysisKey(api, access);+ const newKey = useExisting ? null : keyId;+ try {+ if (editingWorker) {+ await api.setWorkerBillingKey(editingWorker, keyId);+ return null;+ }+ return await api.registerWorker(keyId);+ } catch (e) {+ const message = e instanceof Error ? e.message : "Could not create credential";+ if (!newKey) throw new Error(message);+ try {+ await releaseUnusedKey(api, newKey);+ } catch {+ throw new Error(+ `${message}. Could not confirm cleanup. Check the Lens analysis key in Virtual Keys before retrying.`,+ );+ }+ throw new Error(message);+ }+}++/** Registers a worker (or re-points its billing key), releasing a freshly minted key if registration fails. */+export function usePrepareWorker() {+ const api = useLensApi();+ const client = useQueryClient();+ return useMutation({+ retry: false,+ mutationFn: (registration: WorkerRegistration) => prepareWorker(api, registration),+ onSettled: () => client.invalidateQueries({ queryKey: lensKeys.list(api.scope) }),+ });+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/workerCommand.ts b/ui/litellm-dashboard/src/components/lens/settings/worker/workerCommand.tssimilarity index 100%rename from ui/litellm-dashboard/src/components/lens/setup/worker/workerCommand.tsrename to ui/litellm-dashboard/src/components/lens/settings/worker/workerCommand.tsdiff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/workerSchema.test.ts b/ui/litellm-dashboard/src/components/lens/settings/worker/workerSchema.test.tssimilarity index 100%rename from ui/litellm-dashboard/src/components/lens/setup/worker/workerSchema.test.tsrename to ui/litellm-dashboard/src/components/lens/settings/worker/workerSchema.test.tsdiff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/workerSchema.ts b/ui/litellm-dashboard/src/components/lens/settings/worker/workerSchema.tssimilarity index 100%rename from ui/litellm-dashboard/src/components/lens/setup/worker/workerSchema.tsrename to ui/litellm-dashboard/src/components/lens/settings/worker/workerSchema.tsdiff --git a/ui/litellm-dashboard/src/components/lens/settings/worker/workerScreen.test.ts b/ui/litellm-dashboard/src/components/lens/settings/worker/workerScreen.test.tsnew file mode 100644index 00000000000..bf352875dd2--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/workerScreen.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import type { Worker, WorkerCreated } from "../../model/types";+import { workerScreen, type WorkerScreenInput } from "./workerScreen";++const worker: Worker = {+ id: "worker",+ name: "Lens worker",+ last_seen: "1970-01-01T00:00:00Z",+ scope: { all_teams: true, api_key_hash: "", team_id: "" },+ revoked: false,+ analysis_key_id: "b".repeat(64),+};+const revoked: Worker = { ...worker, revoked: true };+const other: Worker = { ...worker, id: "other" };++const created: WorkerCreated = { token: "lens-test-token", image: "lens-worker:v1", worker };++const idle: WorkerScreenInput = { workers: [], created: null, editingId: null, connected: false };+const screenOf = (input: Partial<WorkerScreenInput>) => workerScreen({ ...idle, ...input });++describe("workerScreen", () => {+ it("shows the setup form when no active worker exists", () => {+ expect(screenOf({})).toEqual({ kind: "form", editing: null });+ expect(screenOf({ workers: [revoked] })).toEqual({ kind: "form", editing: null });+ });++ it("lists active workers until one is being edited", () => {+ expect(screenOf({ workers: [worker] })).toEqual({ kind: "list" });+ expect(screenOf({ workers: [worker], editingId: worker.id })).toEqual({ kind: "form", editing: worker });+ });++ it("drops a stale edit once that worker is revoked", () => {+ expect(screenOf({ workers: [revoked], editingId: worker.id })).toEqual({ kind: "form", editing: null });+ expect(screenOf({ workers: [revoked, other], editingId: worker.id })).toEqual({ kind: "list" });+ });++ it("keeps the install screen up after registration, whatever the list says", () => {+ expect(screenOf({ workers: [worker], created, editingId: worker.id })).toEqual({+ kind: "install",+ created,+ connected: false,+ });+ expect(screenOf({ created, connected: true })).toEqual({ kind: "install", created, connected: true });+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/settings/worker/workerScreen.ts b/ui/litellm-dashboard/src/components/lens/settings/worker/workerScreen.tsnew file mode 100644index 00000000000..c11d6692409--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/settings/worker/workerScreen.ts@@ -0,0 +1,21 @@+import type { LensList, Worker, WorkerCreated } from "../../model/types";++export type WorkerScreen =+ | { readonly kind: "list" }+ | { readonly kind: "form"; readonly editing: Worker | null }+ | { readonly kind: "install"; readonly created: WorkerCreated; readonly connected: boolean };++export interface WorkerScreenInput {+ readonly workers: LensList["workers"];+ readonly created: WorkerCreated | null;+ readonly editingId: string | null;+ readonly connected: boolean;+}++export function workerScreen({ workers, created, editingId, connected }: WorkerScreenInput): WorkerScreen {+ if (created) return { kind: "install", created, connected };+ const active = workers.filter((worker) => !worker.revoked);+ const editing = active.find((worker) => worker.id === editingId) ?? null;+ if (editing) return { kind: "form", editing };+ return active.length ? { kind: "list" } : { kind: "form", editing: null };+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetupDialog.integration.test.tsx b/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetup.integration.test.tsxsimilarity index 64%rename from ui/litellm-dashboard/src/components/lens/setup/InvestigationSetupDialog.integration.test.tsxrename to ui/litellm-dashboard/src/components/lens/setup/InvestigationSetup.integration.test.tsxindex 3ea43016929..14414539bf2 100644--- a/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetupDialog.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetup.integration.test.tsx@@ -1,12 +1,14 @@-import { fireEvent, screen, waitFor } from "@testing-library/react";+import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { renderWithProviders } from "@/../tests/test-utils";+import { mockAllIsIntersecting, setupIntersectionMocking } from "react-intersection-observer/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { testQueryClient } from "@/../tests/test-utils";+import { renderWithLens as renderWithProviders } from "@/../tests/lens-test-utils";import { MonitoringDialog } from "./MonitoringDialog";-import { InvestigationSetupDialog } from "./InvestigationSetupDialog";+import { InvestigationSetup } from "./InvestigationSetup";import { apiClient } from "@/components/networking";-import { initialWatches, watchChecks } from "./watches";-import { type Settings } from "../model/types";+import { initialWatches, watchChecks } from "../model/watches";+import { type AnalysisModelInfo, type Settings } from "../model/types";vi.mock("@/components/networking", () => ({ apiClient: { post: vi.fn(), get: vi.fn() } }));@@ -33,41 +35,83 @@ const settings: Settings = {],};+afterEach(() => testQueryClient.clear());++const analysisWorker = {+ id: "worker",+ name: "Worker",+ revoked: false,+ analysis_key_id: "a".repeat(64),+ scope: { all_teams: true, api_key_hash: "", team_id: "" },+ last_seen: "2026-10-01T12:00:00Z",+};++interface Gateway {+ readonly models?: readonly string[];+ readonly modelDetails?: readonly AnalysisModelInfo[];+ /** Models the lone worker's analysis key may use; one model becomes the setup's default. */+ readonly keyModels?: readonly string[];+ readonly agents?: readonly string[];+}++function gatewayResponse(path: string, gateway: Gateway): unknown {+ const { models = ["analysis"], modelDetails = [], keyModels = [], agents = [] } = gateway;+ if (path === "/models") return { data: models.map((id) => ({ id })) };+ if (path === "/model_group/info") return { data: modelDetails };+ if (path === "/lens") return { lenses: [], workers: keyModels.length ? [analysisWorker] : [], tracing_enabled: true };+ if (path === "/key/info") return { info: { models: keyModels, max_budget: null } };+ if (path === "/lens/agents") return agents;+ return [];+}++function mockGateway(gateway: Gateway = {}) {+ vi.mocked(apiClient.get).mockImplementation(async (path) => gatewayResponse(path, gateway));+}+beforeEach(() => {+ testQueryClient.clear();+ setupIntersectionMocking(vi.fn);vi.mocked(apiClient.get).mockReset();- vi.mocked(apiClient.get).mockResolvedValue([]);+ mockGateway();vi.mocked(apiClient.post).mockReset();vi.mocked(apiClient.post).mockResolvedValue({ eligible: 1, selected: 1, executions: [] });});-describe("Lens setup", () => {- it("preserves saved manual run selections when editing an investigation", async () => {+describe("Investigation setup", () => {+ it("preserves saved manual run selections when editing and lets the preview footer clear them", async () => {const user = userEvent.setup();+ vi.mocked(apiClient.post).mockResolvedValue({+ eligible: 2,+ selected: 2,+ executions: [+ { id: "saved-run", name: "Saved run", trace_id: "t1", source: "traces", start_time: "2026-10-01T12:00:00Z" },+ { id: "other-run", name: "Other run", trace_id: "t2", source: "traces", start_time: "2026-10-01T12:00:00Z" },+ ],+ });renderWithProviders(- <InvestigationSetupDialog+ <InvestigationSetup+ mode="edit"initial={{ ...settings, execution_ids: ["saved-run"] }}- models={["analysis"]}- accessToken="test"onClose={vi.fn()}onSave={vi.fn()}/>,);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));- expect(await screen.findByRole("button", { name: "Clear 1 selected runs" })).toBeInTheDocument();+ const preview = within(screen.getByRole("region", { name: "Matching activity" }));+ expect(await preview.findByRole("checkbox", { name: "Select Saved run" })).toBeChecked();+ expect(preview.getByText("1 selected for analysis")).toBeVisible();+ await waitFor(() => expect(screen.getByRole("button", { name: "Save changes" })).toBeEnabled());+ await user.click(preview.getByRole("button", { name: "Clear 1 selected runs" }));+ expect(preview.getByRole("checkbox", { name: "Select Saved run" })).not.toBeChecked();+ expect(preview.queryByRole("button", { name: /Clear/ })).not.toBeInTheDocument();+ expect(screen.getByRole("alert")).toHaveTextContent("Choose at least one run or turn off individual selection");+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();});it("preserves check identity and disabled state when a check is edited", async () => {const save = vi.fn().mockResolvedValue(undefined);const user = userEvent.setup();- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- models={["analysis"]}- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ renderWithProviders(<InvestigationSetup mode="edit" initial={settings} onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));fireEvent.change(screen.getByRole("textbox", { name: "Check 1" }), {target: { value: "Find repetitive searches\nInclude retries that add no information" },@@ -107,15 +151,8 @@ describe("Lens setup", () => {}: { eligible: 0, executions: [] };});- renderWithProviders(- <InvestigationSetupDialog- models={["analysis"]}- defaultModel="analysis"- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ mockGateway({ keyModels: ["analysis"] });+ renderWithProviders(<InvestigationSetup mode="new" onClose={vi.fn()} onSave={save} />);fireEvent.change(screen.getByRole("textbox", { name: "Investigation name" }), {target: { value: "Research follow-up" },});@@ -158,26 +195,44 @@ describe("Lens setup", () => {});});-it("searches providers and saves custom history while preserving existing schedule values", async () => {+it("walks the three steps in order, reopens a finished step from its summary, and keeps the preview beside them", async () => {const user = userEvent.setup();- const save = vi.fn().mockResolvedValue(undefined);- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- models={["review", "other"]}- modelDetails={[- { model_group: "review", providers: ["OpenAI"], mode: "chat", supported_openai_params: ["response_format"] },- { model_group: "other", providers: ["Anthropic"], mode: "chat" },- ]}- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ mockGateway({ keyModels: ["analysis"] });+ renderWithProviders(<InvestigationSetup mode="new" onClose={vi.fn()} onSave={vi.fn()} />);+ const steps = within(screen.getByRole("list", { name: "Investigation setup" }));+ expect(steps.getByRole("button", { name: /^Activity/ })).toHaveAttribute("aria-current", "step");+ expect(steps.getByRole("button", { name: /^Run/ })).toBeDisabled();+ expect(screen.getByRole("region", { name: "Matching activity" })).toBeVisible();+ expect(screen.queryByRole("textbox", { name: "What should the agent be doing?" })).not.toBeInTheDocument();+ await user.type(screen.getByRole("combobox", { name: "Agent (optional)" }), "support_agent");+ await user.keyboard("{Escape}");await user.click(screen.getByRole("button", { name: "Continue" }));+ expect(steps.getByRole("button", { name: /^Activity.*support_agent/ })).toBeEnabled();+ expect(screen.queryByRole("textbox", { name: "Investigation name" })).not.toBeInTheDocument();+ expect(screen.getByRole("textbox", { name: "What should the agent be doing?" })).toBeVisible();await user.click(screen.getByRole("button", { name: "Continue" }));+ expect(screen.getByRole("checkbox", { name: "Keep watching for new traces" })).toBeVisible();+ expect(screen.getByRole("region", { name: "Matching activity" })).toBeVisible();+ await user.click(steps.getByRole("button", { name: /^Activity/ }));+ expect(screen.getByRole("textbox", { name: "Investigation name" })).toBeVisible();+ expect(screen.queryByRole("checkbox", { name: "Keep watching for new traces" })).not.toBeInTheDocument();+});++it("searches providers and saves custom history while preserving existing schedule values", async () => {+ const user = userEvent.setup();+ const save = vi.fn().mockResolvedValue(undefined);+ mockGateway({+ models: ["review", "other"],+ modelDetails: [+ { model_group: "review", providers: ["OpenAI"], mode: "chat", supported_openai_params: ["response_format"] },+ { model_group: "other", providers: ["Anthropic"], mode: "chat" },+ ],+ });+ renderWithProviders(<InvestigationSetup mode="edit" initial={settings} onClose={vi.fn()} onSave={save} />);await user.selectOptions(screen.getByRole("combobox", { name: "Review the last unit" }), "1");fireEvent.change(screen.getByRole("spinbutton", { name: "Review the last" }), { target: { value: "3" } });+ await user.click(screen.getByRole("button", { name: "Continue" }));+ await user.click(screen.getByRole("button", { name: "Continue" }));expect(screen.getByText(/is no longer available/)).toBeVisible();await user.clear(screen.getByRole("combobox", { name: "Analysis model" }));await user.type(screen.getByRole("combobox", { name: "Analysis model" }), "OpenAI");@@ -203,15 +258,7 @@ it("configures monitoring separately and rejects a zero interval", async () => {it("allows retrying an investigation save after a server error", async () => {const user = userEvent.setup();const save = vi.fn().mockRejectedValueOnce(new Error("boom")).mockResolvedValue(undefined);- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- models={["analysis"]}- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ renderWithProviders(<InvestigationSetup mode="edit" initial={settings} onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));const saveButton = screen.getByRole("button", { name: "Save changes" });@@ -245,19 +292,18 @@ it("keeps the draft when readiness changes and blocks a run until the worker recconst props = {initial: settings,mode: "duplicate" as const,- models: ["analysis"],accessToken: "test",onClose: vi.fn(),onSave: save,};- const view = renderWithProviders(<InvestigationSetupDialog {...props} ready />);+ const view = renderWithProviders(<InvestigationSetup {...props} ready />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.type(screen.getByRole("textbox", { name: "What should the agent be doing?" }), "Finish the report");- view.rerender(<InvestigationSetupDialog {...props} ready={false} />);+ view.rerender(<InvestigationSetup {...props} ready={false} />);expect(screen.getByRole("textbox", { name: "What should the agent be doing?" })).toHaveValue("Finish the report");await user.click(screen.getByRole("button", { name: "Continue" }));expect(screen.getByRole("button", { name: "Run investigation" })).toBeDisabled();- view.rerender(<InvestigationSetupDialog {...props} ready />);+ view.rerender(<InvestigationSetup {...props} ready />);await waitFor(() => expect(screen.getByRole("button", { name: "Run investigation" })).toBeEnabled());});@@ -265,15 +311,7 @@ it.each(["empty", "error"])("allows editing saved settings when the preview is %if (state === "error") vi.mocked(apiClient.post).mockRejectedValue(new Error("Storage unavailable"));else vi.mocked(apiClient.post).mockResolvedValue({ eligible: 0, selected: 0, executions: [] });const user = userEvent.setup();- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- models={["analysis"]}- accessToken="test"- onClose={vi.fn()}- onSave={vi.fn()}- />,- );+ renderWithProviders(<InvestigationSetup mode="edit" initial={settings} onClose={vi.fn()} onSave={vi.fn()} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));expect(screen.getByRole("button", { name: "Save changes" })).toBeEnabled();@@ -284,17 +322,11 @@ it.each(["empty", "error"])("allows editing saved settings when the preview is %it.each(["loading", "error"])("saves edits with the existing model while models are %s", async (state) => {const user = userEvent.setup();const save = vi.fn().mockResolvedValue(undefined);- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- models={[]}- modelsLoading={state === "loading"}- modelsError={state === "error" ? "Temporarily unavailable" : undefined}- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ vi.mocked(apiClient.get).mockImplementation((path) => {+ if (path !== "/models") return Promise.resolve(gatewayResponse(path, {}));+ return state === "loading" ? new Promise(() => {}) : Promise.reject(new Error("Temporarily unavailable"));+ });+ renderWithProviders(<InvestigationSetup mode="edit" initial={settings} onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));fireEvent.change(screen.getByRole("textbox", { name: "What should the agent be doing?" }), {target: { value: "Include verified sources" },@@ -309,17 +341,12 @@ it.each(["loading", "error"])("saves edits with the existing model while modelsit.each(["new", "duplicate"] as const)("blocks a %s investigation until its model is verified", async (mode) => {const user = userEvent.setup();const save = vi.fn();- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- mode={mode}- models={[]}- modelsError="Temporarily unavailable"- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,+ vi.mocked(apiClient.get).mockImplementation((path) =>+ path === "/models"+ ? Promise.reject(new Error("Temporarily unavailable"))+ : Promise.resolve(gatewayResponse(path, {})),);+ renderWithProviders(<InvestigationSetup initial={settings} mode={mode} onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));expect(await screen.findByText("1 matching run")).toBeInTheDocument();@@ -330,16 +357,7 @@ it.each(["new", "duplicate"] as const)("blocks a %s investigation until its modeit("keeps a duplicated investigation's schedule off and saves the interval once switched on", async () => {const user = userEvent.setup();const save = vi.fn().mockResolvedValue(undefined);- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- mode="duplicate"- models={["analysis"]}- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ renderWithProviders(<InvestigationSetup initial={settings} mode="duplicate" onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));await waitFor(() => expect(screen.getByRole("button", { name: "Run investigation" })).toBeEnabled());@@ -357,15 +375,8 @@ it("keeps a duplicated investigation's schedule off and saves the interval onceit("watches new investigations every 15 minutes by default, outside advanced options", async () => {const user = userEvent.setup();const save = vi.fn().mockResolvedValue(undefined);- renderWithProviders(- <InvestigationSetupDialog- models={["analysis"]}- defaultModel="analysis"- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ mockGateway({ keyModels: ["analysis"] });+ renderWithProviders(<InvestigationSetup mode="new" onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));const watching = await screen.findByRole("checkbox", { name: "Keep watching for new traces" });@@ -376,6 +387,45 @@ it("watches new investigations every 15 minutes by default, outside advanced optexpect(save).toHaveBeenCalledWith(expect.objectContaining({ enabled: true, interval_minutes: 15 }));});+it("appends the next preview page as the list scrolls near its end, then stops at the last page", async () => {+ const run = (id: string) => ({+ id,+ name: `Run ${id}`,+ trace_id: id,+ source: "traces",+ start_time: "2026-10-01T12:00:00Z",+ span_count: 2,+ });+ let finishSecondPage = (): void => {};+ vi.mocked(apiClient.post).mockImplementation((_path, options) => {+ const { offset } = options?.body as { offset: number };+ const firstPage = { eligible: 2, selected: 2, executions: [run("one")], next_offset: 1 };+ const secondPage = { eligible: 2, selected: 2, executions: [run("two")], next_offset: null };+ if (offset === 0) return Promise.resolve(firstPage);+ return new Promise((resolve) => {+ finishSecondPage = () => resolve(secondPage);+ });+ });+ renderWithProviders(<InvestigationSetup mode="edit" initial={settings} onClose={vi.fn()} onSave={vi.fn()} />);+ expect(await screen.findByText("Run one")).toBeVisible();+ expect(screen.getByText(/Showing 1 of 2/)).toBeVisible();+ expect(screen.getByRole("status")).toHaveTextContent("2 matching runs");+ const nextPageCalls = () =>+ vi.mocked(apiClient.post).mock.calls.filter(([, options]) => (options?.body as { offset: number }).offset === 1);+ expect(nextPageCalls()).toHaveLength(0);+ act(() => mockAllIsIntersecting(true));+ await waitFor(() => expect(nextPageCalls()).toHaveLength(1));+ expect(screen.getByText("Run one")).toBeVisible();+ expect(screen.getByRole("status")).toHaveTextContent("2 matching runs");+ act(() => finishSecondPage());+ expect(await screen.findByText("Run two")).toBeVisible();+ expect(screen.getByText("Run one")).toBeVisible();+ expect(screen.queryByText(/Showing/)).not.toBeInTheDocument();+ expect(screen.queryByTestId("preview-placeholder")).not.toBeInTheDocument();+ act(() => mockAllIsIntersecting(true));+ expect(nextPageCalls()).toHaveLength(1);+});+it("does not silently analyze everything after individual selection is enabled", async () => {const user = userEvent.setup();vi.mocked(apiClient.post).mockResolvedValue({@@ -392,15 +442,7 @@ it("does not silently analyze everything after individual selection is enabled",},],});- renderWithProviders(- <InvestigationSetupDialog- initial={settings}- models={["analysis"]}- accessToken="test"- onClose={vi.fn()}- onSave={vi.fn()}- />,- );+ renderWithProviders(<InvestigationSetup mode="edit" initial={settings} onClose={vi.fn()} onSave={vi.fn()} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByText("Advanced options"));@@ -415,9 +457,7 @@ it("refreshes agent suggestions when the first activity arrives", async () => {try {const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });vi.mocked(apiClient.post).mockResolvedValue({ eligible: 0, selected: 0, executions: [] });- renderWithProviders(- <InvestigationSetupDialog models={["analysis"]} accessToken="test" onClose={vi.fn()} onSave={vi.fn()} />,- );+ renderWithProviders(<InvestigationSetup mode="new" onClose={vi.fn()} onSave={vi.fn()} />);await vi.advanceTimersByTimeAsync(400);await user.click(screen.getByRole("combobox", { name: "Agent (optional)" }));expect(await screen.findByText(/No matches. You can enter/)).toBeVisible();@@ -437,7 +477,7 @@ it("refreshes agent suggestions when the first activity arrives", async () => {},],});- vi.mocked(apiClient.get).mockResolvedValue(["support-agent"]);+ mockGateway({ agents: ["support-agent"] });await vi.advanceTimersByTimeAsync(15000);await user.click(screen.getByRole("combobox", { name: "Agent (optional)" }));expect(await screen.findByRole("option", { name: "support-agent" })).toBeVisible();@@ -446,20 +486,34 @@ it("refreshes agent suggestions when the first activity arrives", async () => {}});+it("fetches one preview for two keystrokes inside the debounce window", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });+ renderWithProviders(<InvestigationSetup mode="new" onClose={vi.fn()} onSave={vi.fn()} />);+ await user.click(screen.getByText("Advanced filters"));+ const previewsFor = (teamId: string) =>+ vi+ .mocked(apiClient.post)+ .mock.calls.filter(([, options]) => (options?.body as { settings: Settings }).settings.team_id === teamId);+ await user.type(screen.getByRole("textbox", { name: "Team ID (optional)" }), "ab");+ expect(previewsFor("a")).toHaveLength(0);+ expect(previewsFor("ab")).toHaveLength(0);+ expect(screen.getByRole("status")).toHaveTextContent("Finding matching activity…");+ await vi.advanceTimersByTimeAsync(350);+ await waitFor(() => expect(previewsFor("ab")).toHaveLength(1));+ expect(previewsFor("a")).toHaveLength(0);+ expect(await screen.findByText("1 matching run")).toBeVisible();+ } finally {+ vi.useRealTimers();+ }+});+it.each(["empty", "error"])("blocks a new investigation when its preview is %s", async (state) => {if (state === "error") vi.mocked(apiClient.post).mockRejectedValue(new Error("Storage unavailable"));else vi.mocked(apiClient.post).mockResolvedValue({ eligible: 0, selected: 0, executions: [] });const user = userEvent.setup();- renderWithProviders(- <InvestigationSetupDialog- mode="duplicate"- initial={settings}- models={["analysis"]}- accessToken="test"- onClose={vi.fn()}- onSave={vi.fn()}- />,- );+ renderWithProviders(<InvestigationSetup mode="duplicate" initial={settings} onClose={vi.fn()} onSave={vi.fn()} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));expect(screen.getByRole("button", { name: "Run investigation" })).toBeDisabled();@@ -467,17 +521,8 @@ it.each(["empty", "error"])("blocks a new investigation when its preview is %s",it("exposes an unsupported inherited model before allowing a run", async () => {const user = userEvent.setup();- renderWithProviders(- <InvestigationSetupDialog- mode="duplicate"- initial={settings}- models={["analysis"]}- modelDetails={[{ model_group: "analysis", mode: "embedding", providers: [] }]}- accessToken="test"- onClose={vi.fn()}- onSave={vi.fn()}- />,- );+ mockGateway({ modelDetails: [{ model_group: "analysis", mode: "embedding", providers: [] }] });+ renderWithProviders(<InvestigationSetup mode="duplicate" initial={settings} onClose={vi.fn()} onSave={vi.fn()} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));expect(screen.getByText("Choose a chat model that supports JSON output.")).toBeVisible();@@ -486,14 +531,13 @@ it("exposes an unsupported inherited model before allowing a run", async () => {});it("saves a discovered agent independently of the application name", async () => {- vi.mocked(apiClient.get).mockResolvedValue(["research_agent", "support_agent"]);+ mockGateway({ agents: ["research_agent", "support_agent"] });const user = userEvent.setup();const save = vi.fn();renderWithProviders(- <InvestigationSetupDialog+ <InvestigationSetup+ mode="edit"initial={{ ...settings, service: "shared-service" }}- models={["analysis"]}- accessToken="test"onClose={vi.fn()}onSave={save}/>,@@ -514,15 +558,8 @@ describe("Watch for", () => {it("saves exactly the presets the user toggled, by click and by number key", async () => {const save = vi.fn().mockResolvedValue(undefined);const user = userEvent.setup();- renderWithProviders(- <InvestigationSetupDialog- models={["analysis"]}- defaultModel="analysis"- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ mockGateway({ keyModels: ["analysis"] });+ renderWithProviders(<InvestigationSetup mode="new" onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(tile("unhappy"));tile("unsolved").focus();@@ -545,15 +582,7 @@ describe("Watch for", () => {...settings,checks: [{ id: "watch_invented", instruction: "old wording", enabled: true }, settings.checks[1]],};- renderWithProviders(- <InvestigationSetupDialog- initial={initial}- models={["analysis"]}- accessToken="test"- onClose={vi.fn()}- onSave={save}- />,- );+ renderWithProviders(<InvestigationSetup mode="edit" initial={initial} onClose={vi.fn()} onSave={save} />);await user.click(screen.getByRole("button", { name: "Continue" }));expect(tile("invented")).toHaveAttribute("aria-pressed", "true");expect(tile("unsolved")).toHaveAttribute("aria-pressed", "false");@@ -569,19 +598,12 @@ describe("Watch for", () => {it("lets a run start from presets alone and blocks it once nothing is selected", async () => {const user = userEvent.setup();- renderWithProviders(- <InvestigationSetupDialog- models={["analysis"]}- defaultModel="analysis"- accessToken="test"- onClose={vi.fn()}- onSave={vi.fn()}- />,- );+ mockGateway({ keyModels: ["analysis"] });+ renderWithProviders(<InvestigationSetup mode="new" onClose={vi.fn()} onSave={vi.fn()} />);await user.click(screen.getByRole("button", { name: "Continue" }));await user.click(screen.getByRole("button", { name: "Continue" }));expect(await screen.findByRole("button", { name: "Run and monitor" })).toBeInTheDocument();- await user.click(screen.getByRole("button", { name: "Back" }));+ await user.click(screen.getByRole("button", { name: /^Criteria/ }));for (const name of ["unsolved", "blocked", "unhappy"]) await user.click(tile(name));await user.click(screen.getByRole("button", { name: "Continue" }));expect(screen.getByRole("alert")).toHaveTextContent(diff --git a/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetup.tsx b/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetup.tsxnew file mode 100644index 00000000000..324d4a4a724--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetup.tsx@@ -0,0 +1,235 @@+"use client";++import { FormProvider, useWatch, type UseFormReturn } from "react-hook-form";+import { useEffect, useState } from "react";+import { ChevronLeft } from "lucide-react";+import { useZodForm } from "@/lib/forms/useZodForm";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import {+ investigationSchema,+ investigationDefaults,+ investigationSettings,+ investigationStepFields,+ type InvestigationInput,+ type InvestigationOutput,+ type SetupStep as SetupStepId,+} from "./investigationSchema";+import { nextSetupStep, SetupStep, SetupSteps } from "./SetupSteps";+import { ScopeFields } from "./fields/ScopeFields";+import { SampleFields } from "./fields/SampleFields";+import { ExpectationsFields } from "./fields/ExpectationsFields";+import { RunFields } from "./fields/RunFields";+import { MatchingActivityPreview } from "./MatchingActivityPreview";+import { useMatchingActivity } from "./useMatchingActivity";+import { useAnalysisModels } from "./fields/useAnalysisModels";+import { modelGate } from "./fields/analysisModels";+import { Inspector } from "@/components/shared/Inspector";+import { TraceEvidence } from "../investigations/Evidence";+import { FINDING_PANEL_WIDTH_KEY } from "../storage";+import type { Execution } from "./useMatchingActivity";+import { durationLabel } from "../model/format";+import { type Settings } from "../model/types";++type SetupMode = "new" | "edit" | "duplicate";++const TITLES: Record<SetupMode, string> = {+ new: "New investigation",+ edit: "Edit investigation",+ duplicate: "Duplicate investigation",+};++function saveLabelFor(mode: SetupMode, repeat: boolean): string {+ if (mode === "edit") return "Save changes";+ return repeat ? "Run and monitor" : "Run investigation";+}++function activitySummary(selection: InvestigationInput["selection"]): string {+ const who = selection.agent_name || selection.service || "All activity";+ const conditions = selection.filters.length ? ` · ${selection.filters.length} conditions` : "";+ return `${who} · Last ${durationLabel(selection.lookback_hours ?? 24, "hours")}${conditions}`;+}++function criteriaSummary(values: Pick<InvestigationInput, "context" | "watching" | "questions">): string {+ const checks = values.watching.length + values.questions.filter((q) => q.instruction.trim()).length;+ const checksLabel = `${checks} ${checks === 1 ? "check" : "checks"}`;+ const headline = values.context.split("\n")[0]?.trim();+ return headline ? `${headline} · ${checksLabel}` : checksLabel;+}++interface SetupProps {+ initial?: Settings;+ mode: SetupMode;+ defaultSource?: Settings["source"];+ ready?: boolean;+ onClose: () => void;+ onSave: (settings: Settings) => Promise<void>;+}++/** Replaces the Investigations tab body: a three-step setup on the left, the activity it matches on the right. */+export function InvestigationSetup(props: SetupProps) {+ const { initial, mode, defaultSource = "traces" } = props;+ const form = useZodForm(investigationSchema, {+ defaultValues: investigationDefaults(initial, mode, defaultSource),+ mode: "onChange",+ });+ return (+ <FormProvider {...form}>+ <SetupEditor {...props} form={form} />+ </FormProvider>+ );+}++function SetupEditor({+ initial,+ mode,+ ready = true,+ onClose,+ onSave,+ form,+}: SetupProps & { form: UseFormReturn<InvestigationInput, unknown, InvestigationOutput> }) {+ const analysis = useAnalysisModels();+ const [step, setStep] = useState<SetupStepId>("activity");+ const [error, setError] = useState("");+ const [trace, setTrace] = useState<Execution | null>(null);+ const { control, register, setValue, subscribe, trigger, formState } = form;+ const [selectedModel, repeat, selection, context, watching, questions] = useWatch({+ control,+ name: ["selectedModel", "repeat", "selection", "context", "watching", "questions"],+ });+ const activity = useMatchingActivity();+ const traceRuns = activity.preview.page.executions.filter((run) => run.source === "traces");+ const model = selectedModel ?? analysis.defaultModel ?? "";+ useEffect(+ () =>+ subscribe({+ name: [+ "selection.source",+ "selection.service",+ "selection.agent_name",+ "selection.filters",+ "selection.lookback_hours",+ "selection.team_id",+ ],+ formState: { values: true },+ callback: ({ values }) => {+ if (values.selection.execution_ids.length) setValue("selection.execution_ids", []);+ },+ }),+ [setValue, subscribe],+ );+ const next = async () => {+ const following = nextSetupStep(step);+ if (following && (await trigger(investigationStepFields[step]))) setStep(following);+ };+ const save = form.handleSubmit(async (values) => {+ setError("");+ try {+ await onSave(investigationSettings(values, initial, model));+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Could not save investigation");+ }+ });+ const gate = modelGate(analysis, model, mode === "edit" && model === initial?.model);+ const runReady = mode === "edit" || (ready && activity.canReview);+ const formReady = formState.isValid && !formState.isSubmitting;+ const canSave = formReady && gate.modelValid && runReady;+ const saveLabel = saveLabelFor(mode, repeat);+ const offline = !ready && mode !== "edit";+ return (+ <section aria-label={TITLES[mode]} className="flex min-w-0 flex-1 flex-col gap-6">+ <header className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex items-start gap-1">+ <Button+ variant="ghost"+ size="icon-sm"+ className="-ml-2 shrink-0 text-muted-foreground"+ aria-label="Back to investigations"+ disabled={formState.isSubmitting}+ onClick={onClose}+ >+ <ChevronLeft className="size-5" />+ </Button>+ <div>+ <h2 className="text-lg font-semibold tracking-tight">{TITLES[mode]}</h2>+ <p className="text-xs text-muted-foreground">+ Matching activity on the right updates as you change the setup.+ </p>+ </div>+ </div>+ <Button variant="outline" disabled={formState.isSubmitting} onClick={onClose}>+ Cancel+ </Button>+ </header>+ {offline && (+ <p role="status" className="text-sm text-warning">+ The worker or trace storage is unavailable. Your draft is safe; you can start when it reconnects.+ </p>+ )}+ <div className="grid min-w-0 gap-8 lg:grid-cols-2">+ <SetupSteps aria-label="Investigation setup" current={step} onOpen={setStep}>+ <SetupStep+ id="activity"+ heading="Activity"+ description="Which traces or requests to review"+ summary={activitySummary(selection)}+ >+ <label className="grid gap-2 text-sm font-medium">+ Investigation name+ <Input {...register("name")} placeholder="e.g. Support quality" />+ </label>+ <ScopeFields {...activity.scope} />+ <SampleFields />+ <div className="flex justify-end pt-1">+ <Button onClick={() => void next()}>Continue</Button>+ </div>+ </SetupStep>+ <SetupStep+ id="criteria"+ heading="Criteria"+ description="What the agent should do and what to watch for"+ summary={criteriaSummary({ context, watching, questions })}+ >+ <ExpectationsFields />+ <div className="flex justify-end pt-1">+ <Button onClick={() => void next()}>Continue</Button>+ </div>+ </SetupStep>+ <SetupStep id="run" heading="Run" description="Schedule, analysis model, and budget" summary="">+ <RunFields models={analysis} gate={gate} />+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ <div className="flex justify-end pt-1">+ <Button disabled={!canSave} onClick={() => void save()}>+ {formState.isSubmitting ? "Saving…" : saveLabel}+ </Button>+ </div>+ </SetupStep>+ </SetupSteps>+ <Inspector.Root+ items={traceRuns}+ itemKey={(run) => run.id}+ selected={trace}+ onSelectedChange={setTrace}+ noun="run"+ storageKey={FINDING_PANEL_WIDTH_KEY}+ >+ <MatchingActivityPreview {...activity.preview} className="min-w-0 lg:sticky lg:top-0" onOpen={setTrace} />+ <Inspector.Panel label="Run details" testId="run-panel">+ {(run: Execution) => (+ <TraceEvidence+ traceId={run.trace_id}+ traceRef={run.trace_ref}+ initialSpanId={null}+ onBack={() => setTrace(null)}+ />+ )}+ </Inspector.Panel>+ </Inspector.Root>+ </div>+ </section>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetupDialog.tsx b/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetupDialog.tsxdeleted file mode 100644index ac747f904ea..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/InvestigationSetupDialog.tsx+++ /dev/null@@ -1,205 +0,0 @@-"use client";--import { FormProvider, useWatch } from "react-hook-form";-import { useZodForm } from "@/lib/forms/useZodForm";-import {- investigationSchema,- investigationDefaults,- investigationSettings,- investigationStepFields,-} from "./investigationSchema";-import { ScopeStep } from "./steps/ScopeStep";-import { ExpectationsStep } from "./steps/ExpectationsStep";-import { RunStep } from "./steps/RunStep";--import { useEffect, useState } from "react";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogDescription,- DialogFooter,-} from "@/components/ui/dialog";-import { type Settings } from "../model/types";-import { type AnalysisModelInfo } from "./fields/analysisModels";-import { cn } from "@/lib/cva.config";--export function InvestigationSetupDialog({- initial,- mode = initial ? "edit" : "new",- models,- modelDetails = [],- modelsLoading = false,- modelsError,- defaultModel,- defaultSource = "traces",- accessToken,- ready = true,- onClose,- onSave,-}: {- initial?: Settings;- mode?: "new" | "edit" | "duplicate";- models: string[];- modelDetails?: AnalysisModelInfo[];- modelsLoading?: boolean;- modelsError?: string;- defaultModel?: string;- defaultSource?: Settings["source"];- accessToken: string;- ready?: boolean;- onClose: () => void;- onSave: (settings: Settings) => Promise<void>;-}) {- const [step, setStep] = useState(0);- const [previewReady, setPreviewReady] = useState(false);- const [error, setError] = useState("");- const form = useZodForm(investigationSchema, {- defaultValues: investigationDefaults(initial, mode, defaultSource),- mode: "onChange",- });- const { control, setValue, subscribe, trigger, formState } = form;- const [selectedModel, repeat] = useWatch({- control,- name: ["selectedModel", "repeat"],- });- const model = selectedModel ?? defaultModel ?? "";- useEffect(- () =>- subscribe({- name: [- "selection.source",- "selection.service",- "selection.agent_name",- "selection.filters",- "selection.lookback_hours",- "selection.team_id",- ],- formState: { values: true },- callback: ({ values }) => {- if (values.selection.execution_ids.length) setValue("selection.execution_ids", []);- },- }),- [setValue, subscribe],- );- const next = async () => {- if (await trigger(investigationStepFields[step])) setStep(step + 1);- };- const save = form.handleSubmit(async (values) => {- setError("");- try {- await onSave(investigationSettings(values, initial, model));- } catch (cause) {- setError(cause instanceof Error ? cause.message : "Could not save investigation");- }- });- const unsupported = modelDetails.some((m) => m.model_group === model && m.mode && m.mode !== "chat");- const canRun = ready || mode === "edit";- const modelsReady = !modelsLoading && !modelsError;- const unavailable = !!model && modelsReady && !models.includes(model);- const supported = !unsupported && !unavailable;- const preservingSavedModel = mode === "edit" && model === initial?.model;- const modelReady = modelsReady || preservingSavedModel;- const modelValid = !!model && supported && modelReady;- const runReady = canRun && (mode === "edit" || previewReady);- const formReady = formState.isValid && !formState.isSubmitting;- const canSave = formReady && modelValid && runReady;- const createLabel = repeat ? "Run and monitor" : "Run investigation";- const saveLabel = mode === "edit" ? "Save changes" : createLabel;- const headings = [- "Which activity should we investigate?",- "What should Lens look for?",- mode === "edit" ? "Review changes" : "Ready to investigate",- ];- return (- <FormProvider {...form}>- <Dialog- open- onOpenChange={(open) => {- if (!open && !formState.isSubmitting) onClose();- }}- >- <DialogContent- className={cn(- "flex max-h-[90dvh] flex-col gap-6 overflow-hidden",- ["sm:max-w-xl", "sm:max-w-2xl", "sm:max-w-3xl"][step],- )}- >- <DialogHeader>- <DialogTitle className="text-xl">{headings[step]}</DialogTitle>- <DialogDescription className="sr-only">- {- [- "Start with an agent, or use filters to investigate any recorded activity.",- "Describe the expected behavior, the questions you have, or both.",- "Review the selected activity, then start your investigation.",- ][step]- }- </DialogDescription>- </DialogHeader>- <nav aria-label="Investigation setup" className="flex gap-2 text-xs">- {["Activity", "Expectations", "Run"].map((label, index) => (- <button- key={label}- disabled={index > step || formState.isSubmitting}- aria-current={index === step ? "step" : undefined}- onClick={() => {- setStep(index);- }}- data-state={index === step ? "active" : "inactive"}- className="flex-1 border-t-2 border-border pt-2 text-left text-muted-foreground data-[state=active]:border-foreground data-[state=active]:font-medium data-[state=active]:text-foreground"- >- {index + 1}. {label}- </button>- ))}- </nav>- <div className="min-h-0 overflow-y-auto pr-1 space-y-5">- {(step === 0 || step === 2) && (- <ScopeStep step={step} accessToken={accessToken} setPreviewReady={setPreviewReady} />- )}- {step === 1 && <ExpectationsStep />}- {step === 2 && (- <RunStep- modelValid={modelValid}- models={models}- modelDetails={modelDetails}- modelsLoading={modelsLoading}- modelsError={modelsError}- unavailable={unavailable}- unsupported={unsupported}- />- )}- {!ready && mode !== "edit" && (- <p role="status" className="text-sm text-amber-700">- The worker or trace storage is unavailable. Your draft is safe; you can start when it reconnects.- </p>- )}- {error && (- <p role="alert" className="text-sm text-destructive">- {error}- </p>- )}- </div>- <DialogFooter className="border-t pt-4">- <Button- variant="outline"- disabled={formState.isSubmitting}- onClick={() => (step ? setStep(step - 1) : onClose())}- >- {step ? "Back" : "Cancel"}- </Button>- {step < 2 ? (- <Button onClick={() => void next()}>Continue</Button>- ) : (- <Button disabled={!canSave} onClick={() => void save()}>- {formState.isSubmitting ? "Saving…" : saveLabel}- </Button>- )}- </DialogFooter>- </DialogContent>- </Dialog>- </FormProvider>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/setup/LensGettingStarted.tsx b/ui/litellm-dashboard/src/components/lens/setup/LensGettingStarted.tsxdeleted file mode 100644index 01b62c864da..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/LensGettingStarted.tsx+++ /dev/null@@ -1,227 +0,0 @@-"use client";--import { useRef, useState } from "react";-import { useQuery } from "@tanstack/react-query";-import { Check, ShieldCheck } from "lucide-react";-import { Button } from "@/components/ui/button";-import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";-import { lensQueries } from "../api/queries";-import { useSaveLens } from "../api/mutations";-import { useLensApi } from "../services";-import { TraceSheet } from "../investigations/TraceSheet";-import { useAnalysisKeyInfo } from "./worker/AnalysisKeyDetails";-import { WorkerDialog } from "./worker/WorkerDialog";-import { InvestigationSetupDialog } from "./InvestigationSetupDialog";-import { LensIntroduction } from "./LensIntroduction";-import type { LensSetupState } from "./useLensSetup";-import type { Settings } from "../model/types";-import { initialSetupStep, LensSetupSteps } from "./LensSetupSteps";--export function LensGettingStarted({- accessToken,- state,- readOnly,- canInvestigate,- canMintTracingKey,- onStart,- onExit,- onCreated,- onDemo,-}: {- accessToken: string;- state: LensSetupState;- readOnly: boolean;- canInvestigate: boolean;- canMintTracingKey: boolean;- onStart: () => void;- onExit: () => void;- onCreated: (id: string) => void;- onDemo?: () => void;-}) {- const setupRef = useRef<HTMLElement>(null);- const [step, setStep] = useState(() => initialSetupStep(state));- const [workerOpen, setWorkerOpen] = useState(false);- const [investigationOpen, setInvestigationOpen] = useState(false);- const [trace, setTrace] = useState<TraceSummary | null>(null);- const selectStep = (index: number) => {- onStart();- setStep(index);- setupRef.current?.querySelector<HTMLButtonElement>(`[aria-controls="lens-setup-step-${index}"]`)?.focus();- };- const canLeave = state.tracesReady || state.requestsReady || state.hasInvestigations;- const start = () => {- onStart();- setupRef.current?.scrollIntoView({ block: "start" });- setupRef.current?.focus({ preventScroll: true });- };- const connectWorker = () => {- selectStep(2);- setWorkerOpen(true);- };- const createInvestigation = () => {- selectStep(3);- setInvestigationOpen(true);- };-- return (- <div className="mx-auto w-full max-w-7xl space-y-8 py-3 sm:space-y-10 sm:py-4">- <LensIntroduction onStart={start} onDemo={onDemo} />- <div className="grid items-start gap-6 xl:grid-cols-[minmax(0,1fr)_280px] xl:gap-8">- <section- ref={setupRef}- tabIndex={-1}- aria-labelledby="lens-setup-title"- className="min-w-0 scroll-mt-4 outline-none"- onFocusCapture={onStart}- >- <div className="mb-6 flex flex-wrap items-center justify-between gap-3">- <div>- <h2 id="lens-setup-title" className="text-2xl font-semibold tracking-tight">- Get Lens running- </h2>- <p className="mt-2 text-sm leading-6 text-muted-foreground">- Each step checks your connection, so you’ll see when it’s working.- </p>- </div>- {canLeave && (- <Button variant="outline" size="sm" onClick={onExit}>- {state.tracesReady ? "View traces" : "View investigations"}- </Button>- )}- </div>- <LensSetupSteps- step={step}- state={state}- accessToken={accessToken}- readOnly={readOnly}- canInvestigate={canInvestigate}- canMintTracingKey={canMintTracingKey}- onStep={selectStep}- onConnect={connectWorker}- onCreate={createInvestigation}- onTrace={setTrace}- />- {state.error && (- <div role="alert" className="mt-4 flex flex-wrap items-center gap-3 text-sm text-destructive">- <p>Could not check setup. {state.error}</p>- <Button variant="outline" size="sm" onClick={state.refresh} disabled={state.checking}>- Retry- </Button>- </div>- )}- {(readOnly || !canInvestigate) && (- <p className="mt-4 text-sm text-muted-foreground">- A gateway administrator can connect a worker and run investigations.- </p>- )}- </section>- <aside className="rounded-2xl border bg-card p-6" aria-labelledby="lens-prerequisites">- <h2 id="lens-prerequisites" className="text-base font-semibold">- Before you start- </h2>- <ul className="mt-5 space-y-5 text-sm">- {[- { title: "LiteLLM gateway", detail: "Access to its configuration" },- { title: "ClickHouse", detail: "Self-hosted or managed trace storage" },- { title: "A server with Docker", detail: "To run the analysis worker" },- { title: "An analysis model", detail: "Available through your gateway" },- ].map((item) => (- <li key={item.title} className="flex gap-3">- <Check aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-muted-foreground" />- <div>- <p className="font-medium">{item.title}</p>- <p className="mt-1 leading-5 text-muted-foreground">{item.detail}</p>- </div>- </li>- ))}- </ul>- <div className="mt-5 flex gap-2 border-t pt-5 text-xs leading-5 text-muted-foreground">- <ShieldCheck aria-hidden="true" className="mt-0.5 size-4 shrink-0" />- <p>- Your infrastructure stores the traces. Investigation content is sent to your selected model provider- through the gateway.- </p>- </div>- </aside>- </div>- {workerOpen && (- <WorkerDialog- accessToken={accessToken}- workers={state.workers}- onClose={() => setWorkerOpen(false)}- onChanged={state.refresh}- onReady={- state.ready- ? () => {- setWorkerOpen(false);- createInvestigation();- }- : undefined- }- />- )}- {investigationOpen && (- <FirstInvestigation- accessToken={accessToken}- state={state}- onClose={() => setInvestigationOpen(false)}- onCreated={onCreated}- />- )}- {trace && (- <TraceSheet- open- traceId={trace.trace_id}- traceRef={trace.trace_ref}- accessToken={accessToken}- onClose={() => setTrace(null)}- />- )}- </div>- );-}--function FirstInvestigation({- accessToken,- state,- onClose,- onCreated,-}: {- accessToken: string;- state: LensSetupState;- onClose: () => void;- onCreated: (id: string) => void;-}) {- const api = useLensApi(accessToken);- const saveLens = useSaveLens(accessToken);- const models = useQuery({ ...lensQueries.models(api) });- const modelDetails = useQuery({ ...lensQueries.modelDetails(api) });- const workers = state.workers.filter((worker) => !worker.revoked);- const analysisAccess = useAnalysisKeyInfo(- accessToken,- workers.length === 1 ? workers[0].analysis_key_id ?? undefined : undefined,- );- const defaultModel = analysisAccess.data?.models.length === 1 ? analysisAccess.data.models[0] : undefined;- const save = async (settings: Settings) => {- if (!state.ready)- throw new Error("Wait for recorded activity and a connected worker before starting an investigation");- const saved = await saveLens.mutateAsync({ settings });- state.refresh();- onCreated(saved.id);- };-- return (- <InvestigationSetupDialog- accessToken={accessToken}- ready={state.ready}- defaultSource={!state.tracesReady && state.requestsReady ? "requests" : "traces"}- defaultModel={defaultModel}- models={models.data?.data.map((model) => model.id) ?? []}- modelDetails={modelDetails.data?.data ?? []}- modelsLoading={models.isLoading}- modelsError={models.error?.message}- onClose={onClose}- onSave={save}- />- );-}diff --git a/ui/litellm-dashboard/src/components/lens/setup/LensSetupSteps.tsx b/ui/litellm-dashboard/src/components/lens/setup/LensSetupSteps.tsxdeleted file mode 100644index cdf95ef25ef..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/LensSetupSteps.tsx+++ /dev/null@@ -1,229 +0,0 @@-import { ArrowRight, Check, ChevronDown } from "lucide-react";-import { Button } from "@/components/ui/button";-import { TracingSetupFields } from "@/components/view_logs/TraceView/TracingSetupCard";-import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";-import type { LensSetupState } from "./useLensSetup";-import { cn } from "@/lib/cva.config";--type StepProps = {- accessToken: string;- state: LensSetupState;- readOnly: boolean;- canInvestigate: boolean;- canMintTracingKey: boolean;- onStep: (step: number) => void;- onTrace: (trace: TraceSummary) => void;- onConnect: () => void;- onCreate: () => void;-};--export function initialSetupStep(state: LensSetupState) {- if (state.tracesReady || state.requestsReady) return state.connected ? 3 : 2;- return state.tracingEnabled ? 1 : 0;-}--function StorageStep({ state, onStep, ...props }: StepProps) {- if (!state.tracingEnabled)- return (- <>- <TracingSetupFields- detail="Tracing is not enabled"- accessToken={props.accessToken}- onOpenTrace={props.onTrace}- onCheck={state.refresh}- checking={state.checking}- readOnly={props.readOnly}- />- <ActivityContinuation state={state} {...props} />- </>- );- return (- <div className="space-y-4">- <p role="status" className="text-sm text-success">- Trace storage is connected- </p>- <Button onClick={() => onStep(1)}>- Continue to your agent <ArrowRight aria-hidden="true" className="size-4" />- </Button>- <ActivityContinuation state={state} {...props} />- </div>- );-}--function continuationLabel(state: LensSetupState) {- if (state.connected) return "Continue to investigation";- return state.tracesReady ? "Continue to worker" : "Continue with request logs";-}--function ActivityContinuation({- state,- onConnect,- onCreate,- readOnly,- canInvestigate,-}: Pick<StepProps, "state" | "onConnect" | "onCreate" | "readOnly" | "canInvestigate">) {- if (!state.tracesReady && !state.requestsReady) return null;- return (- <div className="mt-4">- <Button onClick={state.connected ? onCreate : onConnect} disabled={readOnly || !canInvestigate}>- {continuationLabel(state)}- <ArrowRight aria-hidden="true" className="size-4" />- </Button>- {state.requestsReady && !state.tracesReady && (- <p className="mt-2 text-xs text-muted-foreground">- Request logs are already available. You can investigate them now and add agent traces later.- </p>- )}- </div>- );-}--function AgentStep({ state, ...props }: StepProps) {- if (!state.tracingEnabled)- return (- <>- <p className="text-sm text-muted-foreground">Connect trace storage in step 1 before sending a trace.</p>- <ActivityContinuation state={state} {...props} />- </>- );- return (- <>- <div hidden={state.tracesReady}>- <TracingSetupFields- detail={null}- accessToken={props.accessToken}- onOpenTrace={(value) => {- state.refresh();- props.onTrace(value);- }}- onCheck={state.refresh}- checking={state.checking}- readOnly={props.readOnly}- canMintTracingKey={props.canMintTracingKey}- />- </div>- {state.tracesReady && (- <p role="status" className="text-sm text-success">- Your first trace is ready. Continue setup so Lens can investigate your agent’s behavior.- </p>- )}- <ActivityContinuation state={state} {...props} />- </>- );-}--function WorkerStep({ state, onConnect, onCreate, readOnly, canInvestigate }: StepProps) {- const activityReady = state.tracesReady || state.requestsReady;- return (- <div className="space-y-4">- <p role="status" className="text-sm text-muted-foreground">- {state.connected- ? "Worker connected. You’re ready to create an investigation."- : "The worker reviews recorded activity using a model on your gateway. You choose its analysis model and spending limit."}- </p>- {!activityReady && (- <p className="text-sm text-muted-foreground">Record activity in step 2 before connecting a worker.</p>- )}- <Button onClick={state.connected ? onCreate : onConnect} disabled={!activityReady || readOnly || !canInvestigate}>- {state.connected ? "Continue to investigation" : "Connect worker"}- <ArrowRight aria-hidden="true" className="size-4" />- </Button>- </div>- );-}--function InvestigationStep({ state, onCreate, readOnly, canInvestigate }: StepProps) {- return (- <div className="space-y-4">- <p className="text-sm leading-6 text-muted-foreground">- Choose the activity to review and describe how your agent should behave. Lens will show findings with evidence- and suggested changes.- </p>- {!state.ready && (- <p className="text-sm text-muted-foreground">- Recorded activity and a connected worker are required before you can run an investigation.- </p>- )}- <Button onClick={onCreate} disabled={!state.ready || readOnly || !canInvestigate}>- New investigation <ArrowRight aria-hidden="true" className="size-4" />- </Button>- </div>- );-}--export function LensSetupSteps({ step, ...props }: StepProps & { step: number }) {- const items = [- {- title: "Enable tracing on the gateway",- description: "Connect ClickHouse and restart the gateway.",- complete: props.state.tracingEnabled,- content: <StorageStep {...props} />,- },- {- title: "Send your first trace",- description: "Capture your agent’s inputs, outputs, and tool calls.",- complete: props.state.tracesReady,- content: <AgentStep {...props} />,- },- {- title: "Connect a worker",- description: "Choose a model and run the worker on your infrastructure.",- complete: props.state.connected,- content: <WorkerStep {...props} />,- },- {- title: "Run your first investigation",- description: "Describe the expected behavior and review a sample of activity.",- complete: props.state.hasInvestigations,- content: <InvestigationStep {...props} />,- },- ];- return (- <ol className="divide-y overflow-hidden rounded-2xl border bg-card">- {items.map((item, index) => (- <li key={item.title}>- <h3>- <button- type="button"- aria-expanded={step === index}- aria-controls={`lens-setup-step-${index}`}- onClick={() => props.onStep(index)}- className="group flex w-full items-start gap-4 p-5 text-left outline-none hover:bg-muted/30 focus-visible:bg-muted/50 sm:p-6"- >- <span- className={cn(- "flex size-8 shrink-0 items-center justify-center rounded-full text-sm font-medium",- item.complete ? "bg-success/10 text-success" : "border text-muted-foreground",- !item.complete && step === index && "border-primary bg-primary text-primary-foreground",- )}- aria-label={item.complete ? `Step ${index + 1} complete` : `Step ${index + 1}`}- >- {item.complete ? <Check aria-hidden="true" className="size-4" /> : index + 1}- </span>- <span className="min-w-0 flex-1">- <span- className={cn(- "block text-sm font-medium sm:text-base",- step !== index && "text-muted-foreground group-hover:text-foreground",- )}- >- {item.title}- </span>- <span className="mt-1 block text-sm leading-6 font-normal text-muted-foreground">- {item.description}- </span>- </span>- <ChevronDown- aria-hidden="true"- className={`mt-1 size-4 shrink-0 text-muted-foreground ${step === index ? "rotate-180" : ""}`}- />- </button>- </h3>- <div id={`lens-setup-step-${index}`} hidden={step !== index} className="px-5 pb-6 sm:pr-6 sm:pb-7 sm:pl-18">- {item.content}- </div>- </li>- ))}- </ol>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/setup/MatchingActivity.tsx b/ui/litellm-dashboard/src/components/lens/setup/MatchingActivity.tsxdeleted file mode 100644index 38971aa19af..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/MatchingActivity.tsx+++ /dev/null@@ -1,166 +0,0 @@-"use client";--import { ScopeFields } from "./fields/ScopeFields";-import { SampleFields } from "./fields/SampleFields";-import { MatchingActivityPreview } from "./MatchingActivityPreview";-import { useFormContext, useWatch } from "react-hook-form";-import type { InvestigationInput } from "./investigationSchema";--import { lensQueries } from "../api/queries";--import { useEffect, useId, useState, type ReactNode } from "react";-import { useQuery } from "@tanstack/react-query";-import { useLensApi } from "../services";-import { Button } from "@/components/ui/button";--import { TraceSheet } from "../investigations/TraceSheet";-import { durationLabel } from "../model/format";-import { cn } from "@/lib/cva.config";--const selectClass = "h-9 w-full rounded-md border border-input bg-background px-3 text-sm";--export function MatchingActivity({- accessToken,- mode = "scope",- onPreviewReady,- manualSelection = false,- nameField,-}: {- accessToken: string;- mode?: "scope" | "activity";- onPreviewReady?: (ready: boolean) => void;- manualSelection?: boolean;- nameField?: ReactNode;-}) {- const { control, setValue } = useFormContext<InvestigationInput>();- const selection = useWatch({ control, name: "selection" });- const api = useLensApi(accessToken);- const id = useId();- const [offset, setOffset] = useState(0);- const [scope, setScope] = useState(selection);- const [trace, setTrace] = useState<{ id: string; ref?: string } | null>(null);- const [asOf, setAsOf] = useState(() => new Date().toISOString());- const serialized = JSON.stringify({ ...selection, execution_ids: [] });- useEffect(() => {- const timer = setTimeout(() => {- setScope(JSON.parse(serialized) as InvestigationInput["selection"]);- setOffset(0);- setAsOf(new Date().toISOString());- }, 350);- return () => clearTimeout(timer);- }, [serialized]);- const historyHours = selection.lookback_hours ?? 24;- const validWindow = Number.isInteger(historyHours) && historyHours >= 1;- const percent = scope.sample_percent ?? 100;- const cap = scope.sample_size;- const validCap = cap == null || (Number.isInteger(cap) && cap > 0);- const validSampling = percent > 0 && percent <= 100 && validCap;- const validFilters = (scope.filters ?? []).every((f) => f.key.trim() && f.value.trim());- const valid = validWindow && validSampling && validFilters;- const discovery = useQuery(lensQueries.discovery(api, { value: selection, asOf, enabled: validWindow }));- const agents = useQuery(lensQueries.agents(api, asOf, selection.source));- const previewInput = { scope, offset, asOf, enabled: valid };- const preview = useQuery(lensQueries.preview(api, previewInput));- const empty = preview.data?.eligible === 0;- useEffect(() => {- if (!empty || !valid) return;- const timer = window.setTimeout(() => setAsOf(new Date().toISOString()), 15000);- return () => window.clearTimeout(timer);- }, [empty, valid, asOf]);- const refreshPreview = () => {- setOffset(0);- setAsOf(new Date().toISOString());- };- const runs = discovery.data?.executions ?? [];- const services = [...new Set(runs.map((r) => r.service).filter(Boolean))].sort();- const names = selection.source === "requests" ? services : agents.data ?? [];- const attributes = runs.flatMap((r) => r.metadata ?? []);- const keys = [...new Set(attributes.map((a) => a.key).filter((key) => !key.startsWith("litellm.")))].sort();- const pending = serialized !== JSON.stringify(scope) || preview.isFetching;- const ready = !pending && valid;- const hasSelection = !manualSelection || !!selection.execution_ids.length;- const hasMatches = !preview.error && (preview.data?.selected ?? 0) > 0;- const canReview = ready && hasMatches && hasSelection;- useEffect(() => {- onPreviewReady?.(canReview);- }, [canReview, onPreviewReady]);- const windowLabel = validWindow- ? `Last ${durationLabel(selection.lookback_hours ?? 24, "hours")}`- : "Choose a valid history window";- const previewTitle = () => {- if (pending) return "Finding matching activity…";- if (!validWindow) return "Choose a history window between 1 hour and 365 days";- if (!valid) return "Complete your condition to preview matches";- if (!preview.data) return "Preview unavailable";- const noun = selection.source === "requests" ? "request" : "run";- return `${preview.data.eligible} matching ${noun}${preview.data.eligible === 1 ? "" : "s"}`;- };- return (- <div className={cn(mode === "activity" ? "grid gap-6 sm:grid-cols-2" : "space-y-5")}>- <div className="space-y-5">- {mode === "scope" ? (- <ScopeFields- nameField={nameField}- names={names}- agentsLoading={agents.isFetching}- agentsError={agents.isError}- retryAgents={() => void agents.refetch()}- attributes={attributes}- keys={keys}- id={id}- />- ) : (- <SampleFields />- )}- {manualSelection && !!selection.execution_ids.length && (- <Button- variant="outline"- size="sm"- onClick={() => setValue("selection.execution_ids", [], { shouldValidate: true })}- >- Clear {selection.execution_ids.length} selected runs- </Button>- )}- </div>- {mode === "activity" && (- <MatchingActivityPreview- offset={offset}- onPage={setOffset}- onSelect={(runId, checked) =>- setValue(- "selection.execution_ids",- checked ? [...selection.execution_ids, runId] : selection.execution_ids.filter((id) => id !== runId),- { shouldValidate: true },- )- }- manualSelection={manualSelection}- selectedIds={selection.execution_ids}- selectedCount={- manualSelection- ? Math.min(- Math.ceil((selection.execution_ids.length * (selection.sample_percent ?? 100)) / 100),- selection.sample_size ?? Infinity,- )- : preview.data?.selected ?? 0- }- title={previewTitle()}- windowLabel={windowLabel}- ready={ready}- error={preview.error}- data={preview.data}- onRetry={refreshPreview}- onOpen={(run) => setTrace({ id: run.trace_id, ref: run.trace_ref })}- />- )}- {trace && (- <TraceSheet- open- traceId={trace.id}- traceRef={trace.ref}- accessToken={accessToken}- onClose={() => setTrace(null)}- />- )}- </div>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/setup/MatchingActivityPreview.tsx b/ui/litellm-dashboard/src/components/lens/setup/MatchingActivityPreview.tsxindex f6047f95a70..e54ac6b8c77 100644--- a/ui/litellm-dashboard/src/components/lens/setup/MatchingActivityPreview.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/MatchingActivityPreview.tsx@@ -1,107 +1,134 @@"use client";+import { useEffect, useState, type ComponentProps } from "react";import { ChevronRight, RotateCw } from "lucide-react";+import { useInView } from "react-intersection-observer";import { Button } from "@/components/ui/button";+import { cn } from "@/lib/cva.config";-import { type Sample } from "../model/types";import { runTime } from "../model/format";+import type { Execution, MatchingPreview } from "./useMatchingActivity";-export function RunList({ executions }: { executions: Sample["executions"] }) {+const PREFETCH_MARGIN = "0px 0px 240px 0px";++type RunRowProps = ComponentProps<"div"> & { run: Execution };++function RunRow({ run, className, ...props }: RunRowProps) {+ const steps = `${run.span_count} ${run.span_count === 1 ? "step" : "steps"}`;return (- <div className="divide-y">- {executions.map((run) => (- <div key={run.id} className="py-3">- <p className="text-sm font-medium">{run.name}</p>- <p className="mt-1 text-xs text-muted-foreground">- {runTime(run.start_time)} ·{" "}- {run.source === "traces" ? `${run.span_count} ${run.span_count === 1 ? "step" : "steps"}` : "LLM request"}- </p>- </div>- ))}+ <div data-slot="run-row" className={cn("min-w-0 py-3", className)} {...props}>+ <p className="text-sm font-medium">{run.name}</p>+ <p className="mt-1 text-xs text-muted-foreground">+ {runTime(run.start_time)} · {run.source === "traces" ? steps : "LLM request"}+ </p></div>);}+type PreviewFooterProps = ComponentProps<"div"> & Pick<MatchingPreview, "page" | "selection">;++/** Selection count and a way to undo manual picks; hidden while every match is simply going to be analyzed. */+function PreviewFooter({ page, selection, className, ...props }: PreviewFooterProps) {+ const partial = page.eligible != null && page.executions.length < page.eligible;+ const count = selection?.count ?? page.selected;+ const picked = selection?.ids.length ?? 0;+ const everything = count === page.eligible && !partial && picked === 0;+ if (page.eligible == null || everything) return null;+ return (+ <div+ data-slot="preview-footer"+ className={cn("flex flex-wrap items-center justify-between gap-3 border-t px-4 py-3", className)}+ {...props}+ >+ <p className="text-xs text-muted-foreground">+ {count} selected for analysis+ {partial && (+ <>+ {" "}+ · Showing {page.executions.length} of {page.eligible}+ </>+ )}+ </p>+ {selection && picked > 0 && (+ <Button variant="outline" size="sm" onClick={selection.clear}>+ Clear {picked} selected runs+ </Button>+ )}+ </div>+ );+}++export type MatchingActivityPreviewProps = ComponentProps<"section"> &+ MatchingPreview & {+ onOpen: (run: Execution) => void;+ };+export function MatchingActivityPreview({- offset,- onPage,- onSelect,- selectedIds,- manualSelection,- selectedCount,- title,- windowLabel,- ready,- error,- data,+ status,+ page,+ selection,onOpen,- onRetry,-}: {- offset: number;- onPage: (offset: number) => void;- onSelect: (id: string, checked: boolean) => void;- selectedIds: string[];- manualSelection: boolean;- selectedCount: number;- title: string;- windowLabel: string;- ready: boolean;- error: Error | null;- data: Sample | undefined;- onRetry: () => void;- onOpen: (run: Sample["executions"][number]) => void;-}) {- const paginated = data?.next_offset != null || offset > 0;- const showSelection = selectedCount !== data?.eligible || paginated;- const selectionData = ready && showSelection ? data : undefined;+ className,+ ...props+}: MatchingActivityPreviewProps) {+ const [scroller, setScroller] = useState<HTMLDivElement | null>(null);+ const { ref: tailRef, inView: nearTail } = useInView({ root: scroller, rootMargin: PREFETCH_MARGIN });+ const { loadMore, loadingMore } = page;+ const canContinue = status.ready && page.hasMore && page.executions.length > 0;+ useEffect(() => {+ if (nearTail && canContinue && !loadingMore) loadMore();+ }, [nearTail, canContinue, loadingMore, loadMore]);return (- <section aria-label="Matching activity" className="self-start rounded-lg border">+ <section+ aria-label="Matching activity"+ data-slot="matching-activity-preview"+ className={cn("self-start rounded-lg border", className)}+ {...props}+ ><div className="border-b px-4 py-3"><div className="flex items-center justify-between gap-2"><p className="text-sm font-medium" role="status">- {title}+ {status.title}</p><Buttonvariant="ghost"size="icon-xs"aria-label="Refresh matching activity"- onClick={onRetry}- disabled={!ready}+ onClick={status.refresh}+ disabled={!status.ready}><RotateCw className="size-3" /></Button></div>- <p className="mt-1 text-xs text-muted-foreground">{windowLabel} · No analysis cost</p>+ <p className="mt-1 text-xs text-muted-foreground">{status.windowLabel} · No analysis cost</p></div>- <div className="max-h-64 overflow-y-auto px-4">- {ready && error && (+ <div ref={setScroller} aria-busy={loadingMore} className="max-h-[60dvh] overflow-y-auto px-4">+ {status.ready && status.error && (<p role="alert" className="py-3 text-sm text-destructive">- {error.message}{" "}- <Button variant="link" onClick={onRetry}>+ {status.error.message}{" "}+ <Button variant="link" onClick={status.refresh}>Retry preview</Button></p>)}- {ready && data?.eligible === 0 && (+ {status.ready && page.eligible === 0 && (<p className="py-4 text-sm text-muted-foreground">No matches. Try removing a condition or check that your agent records this metadata. Recent trace updatesneed two minutes to settle.</p>)}- {ready &&- data?.executions.map((run) => (+ {status.ready &&+ page.executions.map((run) => (<div key={run.id} className="flex items-center justify-between gap-3 border-b last:border-0">- {manualSelection && (+ {selection && (<inputtype="checkbox"aria-label={`Select ${run.name}`}- checked={selectedIds.includes(run.id)}- onChange={(e) => onSelect(run.id, e.target.checked)}+ checked={selection.ids.includes(run.id)}+ onChange={(e) => selection.toggle(run.id, e.target.checked)}/>)}- <div className="min-w-0">- <RunList executions={[run]} />- </div>+ <RunRow run={run} />{run.source === "traces" && (<Button variant="ghost" size="icon-sm" aria-label={`Open ${run.name}`} onClick={() => onOpen(run)}><ChevronRight className="size-4" />@@ -109,41 +136,13 @@ export function MatchingActivityPreview({)}</div>))}- </div>- {selectionData && (- <div className="border-t px-4 py-3 space-y-2">- <p className="text-xs text-muted-foreground">- {selectedCount} selected for analysis- {paginated && (- <>- {" "}- · Showing {offset + (selectionData.executions.length ? 1 : 0)}–- {offset + selectionData.executions.length} of {selectionData.eligible}- </>- )}+ {canContinue && (+ <p ref={tailRef} data-testid="preview-placeholder" className="py-3 text-xs text-muted-foreground">+ Loading more…</p>- {paginated && (- <div className="flex justify-between">- <Button- size="sm"- variant="ghost"- disabled={offset === 0}- onClick={() => onPage(Math.max(0, offset - 100))}- >- Previous- </Button>- <Button- size="sm"- variant="ghost"- disabled={selectionData.next_offset == null}- onClick={() => onPage(selectionData.next_offset ?? offset)}- >- Next- </Button>- </div>- )}- </div>- )}+ )}+ </div>+ {status.ready && <PreviewFooter page={page} selection={selection} />}</section>);}diff --git a/ui/litellm-dashboard/src/components/lens/setup/MonitoringDialog.tsx b/ui/litellm-dashboard/src/components/lens/setup/MonitoringDialog.tsxindex 9ddac5dd281..920f971a2d1 100644--- a/ui/litellm-dashboard/src/components/lens/setup/MonitoringDialog.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/MonitoringDialog.tsx@@ -74,7 +74,7 @@ export function MonitoringDialog({Each investigation looks back over the saved time range. The interval starts after the previous run finishes.</p>{!ready && (- <p role="status" className="text-sm text-amber-700">+ <p role="status" className="text-sm text-warning">Reconnect the worker before enabling monitoring.</p>)}diff --git a/ui/litellm-dashboard/src/components/lens/setup/SetupSteps.test.tsx b/ui/litellm-dashboard/src/components/lens/setup/SetupSteps.test.tsxnew file mode 100644index 00000000000..eb68ba77aa4--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/SetupSteps.test.tsx@@ -0,0 +1,55 @@+import { useState } from "react";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it } from "vitest";+import type { SetupStep as SetupStepId } from "./investigationSchema";+import { SetupStep, SetupSteps } from "./SetupSteps";++function Stepper({ initial }: { initial: SetupStepId }) {+ const [current, setCurrent] = useState<SetupStepId>(initial);+ return (+ <SetupSteps aria-label="Steps" current={current} onOpen={setCurrent}>+ <SetupStep id="activity" heading="Activity" description="Pick activity" summary="support_agent · Last day">+ <input aria-label="Agent" />+ </SetupStep>+ <SetupStep id="criteria" heading="Criteria" description="Describe checks" summary="2 checks">+ <textarea aria-label="Expectations" />+ </SetupStep>+ <SetupStep id="run" heading="Run" description="Schedule and budget" summary="">+ <button type="button">Run</button>+ </SetupStep>+ </SetupSteps>+ );+}++describe("SetupSteps", () => {+ it("shows the current step's fields, finished steps as summaries and later steps as descriptions", () => {+ render(<Stepper initial="criteria" />);+ const steps = within(screen.getByRole("list", { name: "Steps" }));+ const activity = steps.getByRole("button", { name: /^Activity/ });+ expect(activity).toBeEnabled();+ expect(activity).toHaveTextContent("support_agent · Last day");+ expect(activity).not.toHaveTextContent("Pick activity");+ const criteria = steps.getByRole("button", { name: /^Criteria/ });+ expect(criteria).toHaveAttribute("aria-current", "step");+ expect(criteria).toHaveTextContent("Describe checks");+ const run = steps.getByRole("button", { name: /^Run/ });+ expect(run).toBeDisabled();+ expect(run).toHaveTextContent("Schedule and budget");+ expect(screen.getByRole("textbox", { name: "Expectations" })).toBeVisible();+ expect(screen.queryByRole("textbox", { name: "Agent" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Run" })).not.toBeInTheDocument();+ });++ it("reopens a finished step from its summary and collapses the one that was open", async () => {+ const user = userEvent.setup();+ render(<Stepper initial="run" />);+ await user.click(screen.getByRole("button", { name: /^Criteria/ }));+ expect(screen.getByRole("textbox", { name: "Expectations" })).toBeVisible();+ expect(screen.queryByRole("button", { name: "Run" })).not.toBeInTheDocument();+ const run = screen.getByRole("button", { name: /^Run/ });+ expect(run).toBeDisabled();+ expect(run).toHaveTextContent("Schedule and budget");+ expect(screen.getByRole("button", { name: /^Activity/ })).toHaveTextContent("support_agent · Last day");+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/setup/SetupSteps.tsx b/ui/litellm-dashboard/src/components/lens/setup/SetupSteps.tsxnew file mode 100644index 00000000000..df805b52262--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/SetupSteps.tsx@@ -0,0 +1,79 @@+"use client";++import { createContext, useContext, type ComponentProps } from "react";+import { cn } from "@/lib/cva.config";+import { StepIndicator, type StepState } from "../ui/StepIndicator";+import { SETUP_STEPS, type SetupStep as SetupStepId } from "./investigationSchema";++interface StepsContext {+ readonly current: SetupStepId;+ readonly onOpen: (step: SetupStepId) => void;+}++const Steps = createContext<StepsContext | null>(null);++function useSteps(): StepsContext {+ const context = useContext(Steps);+ if (!context) throw new Error("SetupStep must be rendered inside SetupSteps");+ return context;+}++export function nextSetupStep(step: SetupStepId): SetupStepId | undefined {+ return SETUP_STEPS[SETUP_STEPS.indexOf(step) + 1];+}++function stepState(distance: number): StepState {+ if (distance === 0) return "current";+ return distance < 0 ? "complete" : "upcoming";+}++export type SetupStepsProps = ComponentProps<"ol"> & {+ current: SetupStepId;+ onOpen: (step: SetupStepId) => void;+};++/** Vertical stepper: finished steps collapse to a summary and reopen on click, the current one shows its fields. */+export function SetupSteps({ current, onOpen, className, ...props }: SetupStepsProps) {+ return (+ <Steps.Provider value={{ current, onOpen }}>+ <ol data-slot="setup-steps" className={cn("min-w-0", className)} {...props} />+ </Steps.Provider>+ );+}++export type SetupStepProps = ComponentProps<"li"> & {+ id: SetupStepId;+ heading: string;+ description: string;+ summary: string;+};++export function SetupStep({ id, heading, description, summary, className, children, ...props }: SetupStepProps) {+ const { current, onOpen } = useSteps();+ const position = SETUP_STEPS.indexOf(id);+ const state = stepState(position - SETUP_STEPS.indexOf(current));+ return (+ <li+ data-slot="setup-step"+ data-state={state}+ className={cn("group relative flex gap-4 [&:not(:last-child)]:pb-8", className)}+ {...props}+ >+ <span aria-hidden="true" className="absolute top-7 bottom-0 left-3.5 w-px bg-border group-last:hidden" />+ <StepIndicator aria-hidden="true" index={position} state={state} />+ <div className="min-w-0 flex-1 pt-0.5">+ <button+ type="button"+ disabled={state !== "complete"}+ aria-current={state === "current" ? "step" : undefined}+ onClick={() => onOpen(id)}+ className="flex w-full flex-col items-start gap-0.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:cursor-default"+ >+ <span className="text-sm font-semibold group-data-[state=upcoming]:text-muted-foreground">{heading}</span>+ <span className="text-xs text-muted-foreground">{state === "complete" ? summary : description}</span>+ </button>+ {state === "current" && <div className="mt-4 space-y-5">{children}</div>}+ </div>+ </li>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/WatchPicker.tsx b/ui/litellm-dashboard/src/components/lens/setup/WatchPicker.tsxindex cbc34b0c73a..bc60c8eea6f 100644--- a/ui/litellm-dashboard/src/components/lens/setup/WatchPicker.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/WatchPicker.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useRef, useState, type KeyboardEvent } from "react";-import { watches } from "./watches";+import { watches } from "../model/watches";import { cn } from "@/lib/cva.config";const dotColors = ["#8b5cf6", "#22b3e8", "#e3a32b", "#eb6b93", "#22b3e8", "#8b5cf6", "#e3a32b", "#eb6b93"];diff --git a/ui/litellm-dashboard/src/components/lens/setup/fields/AnalysisModelField.tsx b/ui/litellm-dashboard/src/components/lens/setup/fields/AnalysisModelField.tsxindex 1f1473e61fa..c9c2d9914d3 100644--- a/ui/litellm-dashboard/src/components/lens/setup/fields/AnalysisModelField.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/fields/AnalysisModelField.tsx@@ -2,24 +2,16 @@import { Controller, useFormContext, useWatch } from "react-hook-form";import { SearchSelect } from "@/components/shared/SearchSelect";-import { analysisModelOptions, type AnalysisModelInfo } from "./analysisModels";+import { analysisModelOptions, type ModelGate } from "./analysisModels";+import type { AnalysisModels } from "./useAnalysisModels";import type { InvestigationInput } from "../investigationSchema";-export function AnalysisModelField({- models,- modelDetails,- modelsLoading,- modelsError,- unavailable,- unsupported,-}: {- models: string[];- modelDetails: AnalysisModelInfo[];- modelsLoading: boolean;- modelsError?: string;- unavailable: boolean;- unsupported: boolean;-}) {+export interface AnalysisModelFieldProps {+ readonly models: AnalysisModels;+ readonly gate: ModelGate;+}++export function AnalysisModelField({ models, gate }: AnalysisModelFieldProps) {const { control } = useFormContext<InvestigationInput>();const model = useWatch({ control, name: "selectedModel" });return (@@ -31,26 +23,26 @@ export function AnalysisModelField({render={({ field }) => (<SearchSelectaria-label="Analysis model"- options={analysisModelOptions(models, modelDetails)}+ options={analysisModelOptions(models.models, models.modelDetails)}value={field.value ?? ""}onValueChange={(value) => field.onChange(value ?? "")}- placeholder={modelsLoading ? "Loading models…" : "Choose a model"}- disabled={modelsLoading}+ placeholder={models.modelsLoading ? "Loading models…" : "Choose a model"}+ disabled={models.modelsLoading}emptyText="No matching models configured on this gateway"/>)}/>- {modelsError && (+ {models.modelsError && (<p role="alert" className="text-sm text-destructive">- Could not load models: {modelsError}+ Could not load models: {models.modelsError}</p>)}- {unavailable && (+ {gate.unavailable && (<p role="alert" className="text-sm text-destructive">{model} is no longer available. Choose another analysis model.</p>)}- {unsupported && (+ {gate.unsupported && (<p role="alert" className="text-sm text-destructive">Choose a chat model that supports JSON output.</p>diff --git a/ui/litellm-dashboard/src/components/lens/setup/steps/ExpectationsStep.tsx b/ui/litellm-dashboard/src/components/lens/setup/fields/ExpectationsFields.tsxsimilarity index 98%rename from ui/litellm-dashboard/src/components/lens/setup/steps/ExpectationsStep.tsxrename to ui/litellm-dashboard/src/components/lens/setup/fields/ExpectationsFields.tsxindex 128d58b8126..91c9df8da81 100644--- a/ui/litellm-dashboard/src/components/lens/setup/steps/ExpectationsStep.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/fields/ExpectationsFields.tsx@@ -9,7 +9,7 @@ import { WatchPicker } from "../WatchPicker";import { Controller, useFieldArray, useFormContext } from "react-hook-form";import type { InvestigationInput } from "../investigationSchema";-export function ExpectationsStep() {+export function ExpectationsFields() {const {control,register,diff --git a/ui/litellm-dashboard/src/components/lens/setup/fields/MetadataFilters.tsx b/ui/litellm-dashboard/src/components/lens/setup/fields/MetadataFilters.tsxindex 99ecafb70cb..148f3110aea 100644--- a/ui/litellm-dashboard/src/components/lens/setup/fields/MetadataFilters.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/fields/MetadataFilters.tsx@@ -1,22 +1,15 @@"use client";+import { useId } from "react";import { Plus, X } from "lucide-react";+import { useFieldArray, useFormContext, useWatch } from "react-hook-form";import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import type { Sample } from "../../model/types";--import { useFieldArray, useFormContext, useWatch } from "react-hook-form";import type { InvestigationInput } from "../investigationSchema";-export function MetadataFilters({- attributes,- keys,- id,-}: {- attributes: NonNullable<Sample["executions"][number]["metadata"]>;- keys: string[];- id: string;-}) {+import type { ScopeOptions } from "../useMatchingActivity";++export function MetadataFilters({ attributes, keys }: Pick<ScopeOptions, "attributes" | "keys">) {+ const id = useId();const {control,register,diff --git a/ui/litellm-dashboard/src/components/lens/setup/steps/RunStep.tsx b/ui/litellm-dashboard/src/components/lens/setup/fields/RunFields.tsxsimilarity index 80%rename from ui/litellm-dashboard/src/components/lens/setup/steps/RunStep.tsxrename to ui/litellm-dashboard/src/components/lens/setup/fields/RunFields.tsxindex 7f177b8262d..a746cfd0893 100644--- a/ui/litellm-dashboard/src/components/lens/setup/steps/RunStep.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/fields/RunFields.tsx@@ -1,30 +1,12 @@"use client";-import { Controller, useFormContext, useWatch } from "react-hook-form";-import type { InvestigationInput } from "../investigationSchema";+import { Controller, useFormContext, useWatch } from "react-hook-form";import { Input } from "@/components/ui/input";-import { DurationInput } from "@/components/shared/DurationInput";-import { type AnalysisModelInfo } from "../fields/analysisModels";+import type { InvestigationInput } from "../investigationSchema";+import { AnalysisModelField, type AnalysisModelFieldProps } from "./AnalysisModelField";-import { AnalysisModelField } from "../fields/AnalysisModelField";-export function RunStep({- modelValid,- models,- modelDetails,- modelsLoading,- modelsError,- unavailable,- unsupported,-}: {- modelValid: boolean;- models: string[];- modelDetails: AnalysisModelInfo[];- modelsLoading: boolean;- modelsError?: string;- unavailable: boolean;- unsupported: boolean;-}) {+export function RunFields({ models, gate }: AnalysisModelFieldProps) {const {control,register,@@ -54,17 +36,10 @@ export function RunStep({</p>)}</div>- <details open={!modelValid || undefined}>+ <details open={!gate.modelValid || undefined}><summary className="cursor-pointer text-sm font-medium">Advanced options</summary><div className="mt-4 space-y-5">- <AnalysisModelField- models={models}- modelDetails={modelDetails}- modelsLoading={modelsLoading}- modelsError={modelsError}- unavailable={unavailable}- unsupported={unsupported}- />+ <AnalysisModelField models={models} gate={gate} /><div className="grid gap-5 sm:grid-cols-2"><label className="grid content-start gap-2 text-sm font-medium">Maximum runs (optional)diff --git a/ui/litellm-dashboard/src/components/lens/setup/fields/ScopeFields.tsx b/ui/litellm-dashboard/src/components/lens/setup/fields/ScopeFields.tsxindex d2003e42b9d..5441f7dcd8d 100644--- a/ui/litellm-dashboard/src/components/lens/setup/fields/ScopeFields.tsx+++ b/ui/litellm-dashboard/src/components/lens/setup/fields/ScopeFields.tsx@@ -1,6 +1,6 @@"use client";-import { useState, type ReactNode } from "react";+import { useState } from "react";import { Controller, useFormContext, useWatch } from "react-hook-form";import {Combobox,@@ -11,30 +11,14 @@ import {ComboboxEmpty,} from "@/components/ui/combobox";import { Input } from "@/components/ui/input";-import type { Sample } from "../../model/types";import type { InvestigationInput } from "../investigationSchema";+import type { ScopeOptions } from "../useMatchingActivity";import { MetadataFilters } from "./MetadataFilters";+const selectClass = "h-9 w-full rounded-md border border-input bg-background px-3 text-sm";-export function ScopeFields({- nameField,- names,- agentsLoading,- agentsError,- retryAgents,- attributes,- keys,- id,-}: {- nameField?: ReactNode;- names: string[];- agentsLoading: boolean;- agentsError: boolean;- retryAgents: () => void;- attributes: NonNullable<Sample["executions"][number]["metadata"]>;- keys: string[];- id: string;-}) {++export function ScopeFields({ names, agentsLoading, agentsError, retryAgents, attributes, keys }: ScopeOptions) {const { control, register, setValue } = useFormContext<InvestigationInput>();const selection = useWatch({ control, name: "selection" });const filters = selection.filters ?? [];@@ -46,7 +30,6 @@ export function ScopeFields({const nameLabel = selection.source === "requests" ? "Model group (optional)" : "Agent (optional)";return (<>- {nameField}<label className="grid gap-2 text-sm font-medium">{nameLabel}<Controller@@ -121,7 +104,7 @@ export function ScopeFields({<p className="text-xs leading-5 text-muted-foreground">Match any recorded metadata, such as a user ID, environment, or tag. All conditions must match.</p>- <MetadataFilters attributes={attributes} keys={keys} id={id} />+ <MetadataFilters attributes={attributes} keys={keys} /><label className="grid gap-2 text-sm">Team ID (optional)<Input {...register("selection.team_id")} placeholder="All accessible teams" />diff --git a/ui/litellm-dashboard/src/components/lens/setup/fields/analysisModels.ts b/ui/litellm-dashboard/src/components/lens/setup/fields/analysisModels.tsindex 5f621808ea1..68502a7fc8c 100644--- a/ui/litellm-dashboard/src/components/lens/setup/fields/analysisModels.ts+++ b/ui/litellm-dashboard/src/components/lens/setup/fields/analysisModels.ts@@ -1,8 +1,20 @@-export interface AnalysisModelInfo {- model_group: string;- providers: string[];- mode?: string | null;- supported_openai_params?: string[] | null;+import type { AnalysisModelInfo } from "../../model/types";+import type { AnalysisModels } from "./useAnalysisModels";++export interface ModelGate {+ readonly modelValid: boolean;+ readonly unavailable: boolean;+ readonly unsupported: boolean;+}++/** An edit may keep its saved model while the model list is loading or failing; a new run needs a verified one. */+export function modelGate(models: AnalysisModels, model: string, preservingSavedModel: boolean): ModelGate {+ const unsupported = models.modelDetails.some((m) => m.model_group === model && m.mode && m.mode !== "chat");+ const modelsReady = !models.modelsLoading && !models.modelsError;+ const unavailable = !!model && modelsReady && !models.models.includes(model);+ const supported = !unsupported && !unavailable;+ const verified = modelsReady || preservingSavedModel;+ return { modelValid: !!model && supported && verified, unavailable, unsupported };}export function analysisModelOptions(models: string[], details: AnalysisModelInfo[]) {diff --git a/ui/litellm-dashboard/src/components/lens/setup/fields/useAnalysisModels.ts b/ui/litellm-dashboard/src/components/lens/setup/fields/useAnalysisModels.tsnew file mode 100644index 00000000000..05c198e87ae--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/fields/useAnalysisModels.ts@@ -0,0 +1,33 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { lensQueries } from "../../data/queries";+import { useLensApi } from "../../data/LensServices";+import type { AnalysisModelInfo } from "../../model/types";+import { useAnalysisKeyInfo } from "../../settings/worker/useAnalysisKeyInfo";++export interface AnalysisModels {+ readonly models: string[];+ readonly modelDetails: AnalysisModelInfo[];+ readonly modelsLoading: boolean;+ readonly modelsError?: string;+ /** The only model a lone worker's analysis key can use, so the setup can preselect it. */+ readonly defaultModel?: string;+}++export function useAnalysisModels(): AnalysisModels {+ const api = useLensApi();+ const models = useQuery(lensQueries.models(api));+ const modelDetails = useQuery(lensQueries.modelDetails(api));+ const list = useQuery(lensQueries.list(api));+ const activeWorkers = list.data?.workers.filter((worker) => !worker.revoked) ?? [];+ const defaultKeyId = activeWorkers.length === 1 ? activeWorkers[0].analysis_key_id : undefined;+ const keyInfo = useAnalysisKeyInfo(defaultKeyId ?? undefined);+ return {+ models: models.data?.data.map((model) => model.id) ?? [],+ modelDetails: modelDetails.data?.data ?? [],+ modelsLoading: models.isLoading,+ modelsError: models.error?.message,+ defaultModel: keyInfo.data?.models.length === 1 ? keyInfo.data.models[0] : undefined,+ };+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.test-d.ts b/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.test-d.tsnew file mode 100644index 00000000000..51e9d1bc64a--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.test-d.ts@@ -0,0 +1,23 @@+import { describe, expectTypeOf, test } from "vitest";+import type { FieldPath } from "react-hook-form";+import type { InvestigationField, InvestigationInput, SetupStep } from "./investigationSchema";+import { investigationStepFields } from "./investigationSchema";++describe("investigation step fields", () => {+ test("every step field is a path react-hook-form can validate", () => {+ expectTypeOf<InvestigationField>().toExtend<FieldPath<InvestigationInput>>();+ });++ test("step fields are the form's top-level fields with selection expanded one level", () => {+ expectTypeOf<InvestigationField>().toEqualTypeOf<+ Exclude<keyof InvestigationInput, "selection"> | `selection.${keyof InvestigationInput["selection"]}`+ >();+ });++ test("a step that is not in the stepper has no field list", () => {+ expectTypeOf(investigationStepFields).toHaveProperty("activity");+ expectTypeOf<keyof typeof investigationStepFields>().toEqualTypeOf<SetupStep>();+ // @ts-expect-error summary is not a setup step+ expectTypeOf(investigationStepFields.summary);+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.test.ts b/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.test.tsindex 7b034dcbe2c..2e71efe2e3b 100644--- a/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.test.ts+++ b/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.test.ts@@ -3,9 +3,11 @@ import {investigationDefaults,investigationSchema,investigationSettings,+ investigationStepFields,+ SETUP_STEPS,type InvestigationInput,} from "./investigationSchema";-import { watchChecks } from "./watches";+import { watchChecks } from "../model/watches";const defaults = investigationDefaults(undefined, "new", "traces");@@ -140,3 +142,12 @@ describe("investigation validation", () => {});});});++describe("investigationStepFields", () => {+ it("assigns every form field to exactly one step", () => {+ const { selection, ...rest } = defaults;+ const formFields = [...Object.keys(rest), ...Object.keys(selection).map((key) => `selection.${key}`)].sort();+ const stepFields = SETUP_STEPS.flatMap((step) => investigationStepFields[step]).sort();+ expect(stepFields).toEqual(formFields);+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.ts b/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.tsindex 78db823bab8..f5726f73f8d 100644--- a/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.ts+++ b/ui/litellm-dashboard/src/components/lens/setup/investigationSchema.ts@@ -1,8 +1,7 @@import { z } from "zod";-import type { FieldPath } from "react-hook-form";import type { Settings } from "../model/types";import { normalizeFilters } from "./filters";-import { initialWatches, isWatch, watchChecks } from "./watches";+import { initialWatches, isWatch, watchChecks } from "../model/watches";const selectionFields = {source: z.enum(["traces", "requests", "both"]),@@ -147,21 +146,41 @@ export const investigationSchema = draftSchemaexport type InvestigationInput = z.input<typeof investigationSchema>;export type InvestigationOutput = z.output<typeof investigationSchema>;-export const investigationStepFields: readonly FieldPath<InvestigationInput>[][] = [- ["name", "selection.source", "selection.service", "selection.agent_name", "selection.filters", "selection.team_id"],- ["context", "questions", "watching"],- [- "selection.execution_ids",- "selection.lookback_hours",- "selection.sample_size",- "selection.sample_percent",- "selectedModel",- "budget",- "interval",- "repeat",- "manualSelection",- ],-];+export const SETUP_STEPS = ["activity", "criteria", "run"] as const;+export type SetupStep = (typeof SETUP_STEPS)[number];++type SelectionField = `selection.${keyof InvestigationInput["selection"]}`;+export type InvestigationField = Exclude<keyof InvestigationInput, "selection"> | SelectionField;++/** Every form field belongs to exactly one setup step; adding a schema field without a step fails to type-check. */+const stepOfField = {+ name: "activity",+ "selection.source": "activity",+ "selection.service": "activity",+ "selection.agent_name": "activity",+ "selection.filters": "activity",+ "selection.team_id": "activity",+ "selection.lookback_hours": "activity",+ "selection.sample_percent": "activity",+ context: "criteria",+ questions: "criteria",+ watching: "criteria",+ "selection.execution_ids": "run",+ "selection.sample_size": "run",+ selectedModel: "run",+ budget: "run",+ interval: "run",+ repeat: "run",+ manualSelection: "run",+} as const satisfies Record<InvestigationField, SetupStep>;++const fields = Object.keys(stepOfField) as readonly InvestigationField[];++export const investigationStepFields: Readonly<Record<SetupStep, readonly InvestigationField[]>> = {+ activity: fields.filter((field) => stepOfField[field] === "activity"),+ criteria: fields.filter((field) => stepOfField[field] === "criteria"),+ run: fields.filter((field) => stepOfField[field] === "run"),+};function activitySelectionDefaults(initial: Settings | undefined,diff --git a/ui/litellm-dashboard/src/components/lens/setup/steps/ScopeStep.tsx b/ui/litellm-dashboard/src/components/lens/setup/steps/ScopeStep.tsxdeleted file mode 100644index e78c96afc22..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/steps/ScopeStep.tsx+++ /dev/null@@ -1,38 +0,0 @@-"use client";-import { useFormContext, useWatch } from "react-hook-form";-import type { InvestigationInput } from "../investigationSchema";--import { Input } from "@/components/ui/input";--import { MatchingActivity } from "../MatchingActivity";--export function ScopeStep({- step,- accessToken,- setPreviewReady,-}: {- step: number;- accessToken: string;- setPreviewReady: (value: boolean) => void;-}) {- const { control, register } = useFormContext<InvestigationInput>();- const name = useWatch({ control, name: "name" });- const manualSelection = useWatch({ control, name: "manualSelection" });- return (- <MatchingActivity- key={step}- accessToken={accessToken}- nameField={- step === 0 ? (- <label className="grid gap-2 text-sm font-medium">- Investigation name- <Input {...register("name")} placeholder="e.g. Support quality" />- </label>- ) : undefined- }- mode={step === 0 ? "scope" : "activity"}- onPreviewReady={setPreviewReady}- manualSelection={manualSelection}- />- );-}diff --git a/ui/litellm-dashboard/src/components/lens/setup/useDebouncedValue.test.tsx b/ui/litellm-dashboard/src/components/lens/setup/useDebouncedValue.test.tsxnew file mode 100644index 00000000000..2a91b671404--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/useDebouncedValue.test.tsx@@ -0,0 +1,38 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useDebouncedValue } from "./useDebouncedValue";++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++describe("useDebouncedValue", () => {+ it("settles once on the latest value when changes arrive within the wait", () => {+ const { result, rerender } = renderHook(({ value }) => useDebouncedValue(value, 350), {+ initialProps: { value: { team: "" } },+ });+ const initialSettledAt = result.current.settledAt;+ rerender({ value: { team: "a" } });+ act(() => vi.advanceTimersByTime(200));+ rerender({ value: { team: "ab" } });+ act(() => vi.advanceTimersByTime(340));+ expect(result.current).toMatchObject({ value: { team: "" }, pending: true });+ act(() => vi.advanceTimersByTime(10));+ expect(result.current).toMatchObject({ value: { team: "ab" }, pending: false });+ expect(result.current.settledAt > initialSettledAt).toBe(true);+ });++ it("ignores a new reference with the same content", () => {+ const { result, rerender } = renderHook(({ value }) => useDebouncedValue(value, 350), {+ initialProps: { value: { filters: [{ key: "env", value: "prod" }] } },+ });+ const settledAt = result.current.settledAt;+ rerender({ value: { filters: [{ key: "env", value: "prod" }] } });+ expect(result.current.pending).toBe(false);+ rerender({ value: { filters: [{ key: "env", value: "stage" }] } });+ act(() => vi.advanceTimersByTime(300));+ rerender({ value: { filters: [{ key: "env", value: "stage" }] } });+ act(() => vi.advanceTimersByTime(50));+ expect(result.current).toMatchObject({ value: { filters: [{ key: "env", value: "stage" }] }, pending: false });+ expect(result.current.settledAt).not.toBe(settledAt);+ });+});diff --git a/ui/litellm-dashboard/src/components/lens/setup/useDebouncedValue.ts b/ui/litellm-dashboard/src/components/lens/setup/useDebouncedValue.tsnew file mode 100644index 00000000000..5a44fb59a35--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/useDebouncedValue.ts@@ -0,0 +1,36 @@+"use client";++import { hashKey } from "@tanstack/react-query";+import { useEffect, useRef, useState } from "react";++interface Settled<T> {+ readonly value: T;+ readonly key: string;+ readonly at: string;+}++export interface DebouncedValue<T> {+ readonly value: T;+ readonly pending: boolean;+ readonly settledAt: string;+}++/** Debounces by structure, so a value that only changed by reference neither restarts the wait nor settles again. */+export function useDebouncedValue<T>(value: T, wait: number): DebouncedValue<T> {+ const key = hashKey([value]);+ const [settled, setSettled] = useState<Settled<T>>(() => ({ value, key, at: new Date().toISOString() }));+ const latest = useRef(value);+ const pending = key !== settled.key;+ useEffect(() => {+ latest.current = value;+ });+ useEffect(() => {+ if (!pending) return;+ const timer = window.setTimeout(+ () => setSettled({ value: latest.current, key, at: new Date().toISOString() }),+ wait,+ );+ return () => window.clearTimeout(timer);+ }, [key, pending, wait]);+ return { value: settled.value, pending, settledAt: settled.at };+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/useLensSetup.ts b/ui/litellm-dashboard/src/components/lens/setup/useLensSetup.tsdeleted file mode 100644index 12903e8a15c..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/useLensSetup.ts+++ /dev/null@@ -1,59 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { useNow } from "@/hooks/useNow";-import { isTracingNotEnabled, useTraceAvailability } from "@/components/view_logs/TraceView/useAgentTraces";-import { lensQueries } from "../api/queries";-import { workerConnected } from "../model/status";-import { useLensApi } from "../services";--function traceSetupState(traces: ReturnType<typeof useTraceAvailability>, configured: boolean) {- const disabled = isTracingNotEnabled(traces.error);- return {- tracesReady: traces.data === true && !traces.error,- tracingEnabled: !disabled && (traces.isSuccess || configured),- missingTraces: disabled || traces.data === false,- error: disabled ? null : traces.error,- };-}--export function useLensSetup(accessToken: string, enabled: boolean, canInvestigate: boolean, settingUp: boolean) {- const api = useLensApi(accessToken);- const now = useNow(2000);- const traces = useTraceAvailability(accessToken, enabled);- const list = useQuery({ ...lensQueries.list(api, settingUp), enabled: enabled && canInvestigate });- const activity = useQuery(lensQueries.activity(api, enabled && canInvestigate && list.isSuccess));- const data = list.data ?? { lenses: [], workers: [], tracing_enabled: false };- const traceState = traceSetupState(traces, data.tracing_enabled);- const hasRequests = activity.data?.requests === true;- const requestsReady = hasRequests && !activity.error;- const connected = data.workers.some((worker) => workerConnected(worker, now));- const hasInvestigations = data.lenses.length > 0;- const activityReady = traceState.tracesReady || requestsReady;- const activityError = activityReady ? null : traceState.error || activity.error;- const error = list.error || activityError;- const loadingActivity = !activityReady && list.isSuccess && activity.isPending;- const loadingInvestigations = canInvestigate && (list.isPending || loadingActivity);- const refresh = () => {- void traces.refetch();- if (canInvestigate) {- void list.refetch();- void activity.refetch();- }- };- return {- tracingEnabled: traceState.tracingEnabled,- tracesReady: traceState.tracesReady,- requestsReady,- hasRequests,- connected,- hasInvestigations,- missingTraces: traceState.missingTraces,- loading: (!activityReady && traces.isPending) || loadingInvestigations,- checking: traces.isFetching || list.isFetching || activity.isFetching,- ready: activityReady && connected && !error,- workers: data.workers,- error: error?.message,- refresh,- };-}--export type LensSetupState = ReturnType<typeof useLensSetup>;diff --git a/ui/litellm-dashboard/src/components/lens/setup/useMatchingActivity.ts b/ui/litellm-dashboard/src/components/lens/setup/useMatchingActivity.tsnew file mode 100644index 00000000000..6a6cdf69d48--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/setup/useMatchingActivity.ts@@ -0,0 +1,192 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";+import { useFormContext, useWatch } from "react-hook-form";+import { lensKeys, lensQueries } from "../data/queries";+import { useLensApi } from "../data/LensServices";+import { durationLabel } from "../model/format";+import type { Sample } from "../model/types";+import { useDebouncedValue } from "./useDebouncedValue";+import type { InvestigationInput } from "./investigationSchema";++const PREVIEW_DEBOUNCE_MS = 350;+const EMPTY_PREVIEW_POLL_MS = 15000;++type Selection = InvestigationInput["selection"];+type PreviewPageData = Pick<Sample, "eligible" | "selected">;++export type Execution = Sample["executions"][number];+export type Attribute = NonNullable<Execution["metadata"]>[number];++export interface ScopeOptions {+ readonly names: readonly string[];+ readonly agentsLoading: boolean;+ readonly agentsError: boolean;+ readonly retryAgents: () => void;+ readonly attributes: readonly Attribute[];+ readonly keys: readonly string[];+}++export interface PreviewStatus {+ readonly title: string;+ readonly windowLabel: string;+ readonly ready: boolean;+ readonly error: Error | null;+ readonly refresh: () => void;+}++export interface PreviewPage {+ readonly eligible: number | undefined;+ readonly selected: number;+ readonly executions: readonly Execution[];+ readonly hasMore: boolean;+ readonly loadingMore: boolean;+ readonly loadMore: () => void;+}++/** Present only while the user picks individual runs; `count` applies the sampling settings to the picks. */+export interface PreviewSelection {+ readonly ids: readonly string[];+ readonly count: number;+ readonly toggle: (id: string, checked: boolean) => void;+ readonly clear: () => void;+}++export interface MatchingPreview {+ readonly status: PreviewStatus;+ readonly page: PreviewPage;+ readonly selection: PreviewSelection | null;+}++export interface MatchingActivity {+ readonly scope: ScopeOptions;+ readonly preview: MatchingPreview;+ readonly canReview: boolean;+}++function validWindow(selection: Selection): boolean {+ const hours = selection.lookback_hours ?? 24;+ return Number.isInteger(hours) && hours >= 1;+}++function validScope(scope: Selection): boolean {+ const percent = scope.sample_percent ?? 100;+ const cap = scope.sample_size;+ const validCap = cap == null || (Number.isInteger(cap) && cap > 0);+ const validSampling = percent > 0 && percent <= 100 && validCap;+ const validFilters = (scope.filters ?? []).every((f) => f.key.trim() && f.value.trim());+ return validWindow(scope) && validSampling && validFilters;+}++function previewTitle(+ state: { pending: boolean; validWindow: boolean; valid: boolean },+ source: Selection["source"],+ data: PreviewPageData | undefined,+): string {+ if (!state.validWindow) return "Choose a history window between 1 hour and 365 days";+ if (!state.valid) return "Complete your condition to preview matches";+ if (state.pending) return "Finding matching activity…";+ if (!data) return "Preview unavailable";+ const noun = source === "requests" ? "request" : "run";+ return `${data.eligible} matching ${noun}${data.eligible === 1 ? "" : "s"}`;+}++function manualSelectedCount(selection: Selection): number {+ const sampled = Math.ceil((selection.execution_ids.length * (selection.sample_percent ?? 100)) / 100);+ return Math.min(sampled, selection.sample_size ?? Infinity);+}++function manualPicks(selection: Selection, setExecutionIds: (ids: readonly string[]) => void): PreviewSelection {+ const ids = selection.execution_ids;+ return {+ ids,+ count: manualSelectedCount(selection),+ toggle: (id, checked) => setExecutionIds(checked ? [...ids, id] : ids.filter((other) => other !== id)),+ clear: () => setExecutionIds([]),+ };+}++function windowLabel(selection: Selection): string {+ if (!validWindow(selection)) return "Choose a valid history window";+ return `Last ${durationLabel(selection.lookback_hours ?? 24, "hours")}`;+}++function useScopeFieldOptions(api: ReturnType<typeof useLensApi>, selection: Selection): ScopeOptions {+ const discovery = useQuery(lensQueries.discovery(api, { value: selection, enabled: validWindow(selection) }));+ const agents = useQuery(lensQueries.agents(api, selection.source));+ const runs = discovery.data?.executions ?? [];+ const services = [...new Set(runs.map((r) => r.service).filter(Boolean))].sort();+ const attributes = runs.flatMap((r) => r.metadata ?? []);+ return {+ names: selection.source === "requests" ? services : agents.data ?? [],+ agentsLoading: agents.isFetching,+ agentsError: agents.isError,+ retryAgents: () => void agents.refetch(),+ attributes,+ keys: [...new Set(attributes.map((a) => a.key).filter((key) => !key.startsWith("litellm.")))].sort(),+ };+}++/** Live preview of the activity a draft selection matches, debounced so typing a filter does not spam the API. */+export function useMatchingActivity(): MatchingActivity {+ const { control, setValue } = useFormContext<InvestigationInput>();+ const [selection, manualSelection] = useWatch({ control, name: ["selection", "manualSelection"] });+ const api = useLensApi();+ const client = useQueryClient();+ const {+ value: scope,+ pending: settling,+ settledAt,+ } = useDebouncedValue<Selection>({ ...selection, execution_ids: [] }, PREVIEW_DEBOUNCE_MS);+ const [refreshedAt, setRefreshedAt] = useState(settledAt);+ const asOf = settledAt > refreshedAt ? settledAt : refreshedAt;+ const windowValid = validWindow(selection);+ const valid = windowValid && validScope(scope);+ const scopeFields = useScopeFieldOptions(api, selection);+ const preview = useInfiniteQuery(lensQueries.preview(api, { scope, asOf, enabled: valid }));+ const firstPage = preview.data?.pages[0];+ const executions = preview.data?.pages.flatMap((page) => page.executions) ?? [];+ const empty = firstPage?.eligible === 0;+ const refresh = useCallback(() => {+ setRefreshedAt(new Date().toISOString());+ void client.invalidateQueries({ queryKey: lensKeys.discoveries() });+ void client.invalidateQueries({ queryKey: lensKeys.agents(api.scope) });+ }, [api.scope, client]);+ useEffect(() => {+ if (!empty || !valid) return;+ const timer = window.setTimeout(refresh, EMPTY_PREVIEW_POLL_MS);+ return () => window.clearTimeout(timer);+ }, [empty, valid, asOf, refresh]);+ const pending = settling || preview.isLoading || preview.isPlaceholderData;+ const ready = !pending && valid;+ const setExecutionIds = (next: readonly string[]) =>+ setValue("selection.execution_ids", [...next], { shouldValidate: true });+ const picked = manualSelection ? manualPicks(selection, setExecutionIds) : null;+ const hasMatches = !preview.error && (firstPage?.selected ?? 0) > 0;+ const hasSelection = !picked || picked.ids.length > 0;+ return {+ scope: scopeFields,+ preview: {+ status: {+ title: previewTitle({ pending, validWindow: windowValid, valid }, selection.source, firstPage),+ windowLabel: windowLabel(selection),+ ready,+ error: preview.error,+ refresh,+ },+ page: {+ eligible: firstPage?.eligible,+ selected: firstPage?.selected ?? 0,+ executions,+ hasMore: preview.hasNextPage,+ loadingMore: preview.isFetchingNextPage,+ loadMore: () => {+ if (preview.hasNextPage && !preview.isFetching) void preview.fetchNextPage({ cancelRefetch: false });+ },+ },+ selection: picked,+ },+ canReview: ready && hasMatches && hasSelection,+ };+}diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerDialog.tsx b/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerDialog.tsxdeleted file mode 100644index 2bc37941de6..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerDialog.tsx+++ /dev/null@@ -1,196 +0,0 @@-"use client";-import { WorkerList } from "./WorkerList";--import { initialProxyAddress } from "./workerCommand";-import { usePrepareWorker, useRevokeWorker } from "../../api/mutations";-import { WorkerInstall } from "./WorkerInstall";-import { WorkerForm } from "./WorkerForm";--import { useNow } from "@/hooks/useNow";--import { FormProvider } from "react-hook-form";-import { useState } from "react";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogDescription,- DialogFooter,-} from "@/components/ui/dialog";-import { CheckCircle2 } from "lucide-react";-import { workerConnected } from "../../model/status";-import { workerFormSchema, type WorkerFormInput } from "./workerSchema";-import type { LensList, WorkerCreated } from "../../model/types";-import { useZodForm } from "@/lib/forms/useZodForm";-import { cn } from "@/lib/cva.config";--function defaultWorkerFormValues(): WorkerFormInput {- return {- useExisting: false,- analysisKey: null,- access: { model: null, budget: "100" },- address: typeof window === "undefined" ? "" : initialProxyAddress(),- };-}--export function WorkerDialog({- accessToken,- workers,- onClose,- onChanged,- onReady,-}: {- accessToken: string;- workers: LensList["workers"];- onClose: () => void;- onChanged: () => void;- onReady?: () => void;-}) {- const revokeWorker = useRevokeWorker(accessToken);- const now = useNow(2000);- const form = useZodForm(workerFormSchema, {- defaultValues: defaultWorkerFormValues(),- mode: "onChange",- });- const { formState, reset, setValue } = form;- const [editingWorker, setEditingWorker] = useState<string | null>(null);- const [copied, setCopied] = useState(false);- const [created, setCreated] = useState<WorkerCreated | null>(null);- const [error, setError] = useState("");- const connected = created- ? workers.some((w) => w.id === created.worker.id && workerConnected(w, now))- : workers.some((w) => workerConnected(w, now));- const formVisible = !workers.some((w) => !w.revoked) || !!editingWorker;- const uninstalledScreen = formVisible ? "form" : "list";- const screen = created ? "install" : uninstalledScreen;- const createdTitle = connected ? "Worker connected" : "Run the worker";- const formTitle = editingWorker ? "Analysis access" : "Connect a worker";- const baseTitle = formVisible ? formTitle : "Analysis worker";- const dialogTitle = created ? createdTitle : baseTitle;- const actionLabel = editingWorker ? "Save analysis access" : "Get install command";- const cancelForm = () => {- if (!workers.some((w) => !w.revoked)) {- onClose();- return;- }- setEditingWorker(null);- reset(defaultWorkerFormValues());- };- const editBilling = (worker: LensList["workers"][number]) => {- reset({- ...defaultWorkerFormValues(),- useExisting: true,- analysisKey: worker.analysis_key_id ?? null,- });- setCreated(null);- setEditingWorker(worker.id);- };- const onPrepared = (created: WorkerCreated | null) => {- if (created) setCreated(created);- else {- setEditingWorker(null);- setValue("analysisKey", null);- }- };- const prepareWorker = usePrepareWorker(accessToken, { onChanged, onPrepared });- const createWorker = form.handleSubmit(async (values) => {- setError("");- try {- const registration = {- address: values.address,- useExisting: values.useExisting,- analysisKey: values.analysisKey,- access: values.access,- editingWorker,- };- await prepareWorker.mutateAsync(registration);- } catch (e) {- setError(e instanceof Error ? e.message : "Could not create credential");- }- });- const revoke = async (id: string) => {- try {- await revokeWorker.mutateAsync(id);- setValue("analysisKey", null);- setValue("useExisting", false);- onChanged();- } catch (e) {- setError(e instanceof Error ? e.message : "Could not revoke worker");- }- };- const setupDescription = created- ? "Run this command on a server with Docker."- : "Deploy the worker on your server to run investigations.";- const awaitingConnection = !editingWorker && !connected;- const describeSetup = awaitingConnection && (formVisible || !!created);- const completed = !!created && connected;- const modalSize = cn(- created && connected && "sm:max-w-sm p-8",- created && !connected && "sm:max-w-lg",- !created && "sm:max-w-xl",- );- const description = describeSetup ? setupDescription : "Worker status and model access";- return (- <FormProvider {...form}>- <Dialog- open- onOpenChange={(open) => {- if (!open && !formState.isSubmitting) onClose();- }}- >- <DialogContent className={cn("max-h-[90dvh] overflow-y-auto", modalSize)}>- <DialogHeader className={cn(completed && "items-center gap-3 text-center sm:text-center")}>- {completed && (- <div className="flex size-12 items-center justify-center rounded-full bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-400">- <CheckCircle2 className="size-6" />- </div>- )}- <DialogTitle className="text-xl leading-7">{dialogTitle}</DialogTitle>- <DialogDescription className={cn(!(describeSetup || completed) && "sr-only")}>- {completed ? "Ready to run investigations." : description}- </DialogDescription>- </DialogHeader>- {screen === "form" && <WorkerForm accessToken={accessToken} editingWorker={editingWorker} />}- {screen === "install" && created ? (- <WorkerInstall- connected={connected}- address={form.getValues("address")}- created={created}- copied={copied}- setCopied={setCopied}- setError={setError}- onReady={onReady}- onClose={onClose}- />- ) : null}- {screen === "form" && (- <DialogFooter>- <Button variant="outline" disabled={formState.isSubmitting} onClick={cancelForm}>- Cancel- </Button>- <Button disabled={!formState.isValid || formState.isSubmitting} onClick={() => void createWorker()}>- {formState.isSubmitting ? "Preparing…" : actionLabel}- </Button>- </DialogFooter>- )}- {screen === "list" && (- <WorkerList- workers={workers}- now={now}- accessToken={accessToken}- editBilling={editBilling}- revoke={revoke}- />- )}- {error && (- <p role="alert" className="text-sm text-destructive">- {error}- </p>- )}- </DialogContent>- </Dialog>- </FormProvider>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerInstall.tsx b/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerInstall.tsxdeleted file mode 100644index efeef194652..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerInstall.tsx+++ /dev/null@@ -1,104 +0,0 @@-"use client";--import { useState } from "react";-import { Button } from "@/components/ui/button";--import { CheckCircle2, Copy, Loader2 } from "lucide-react";-import type { WorkerCreated } from "../../model/types";--import { workerSetupCommand } from "./workerCommand";-export function WorkerInstall({- connected,- address,- created,- copied,- setCopied,- setError,- onReady,- onClose,-}: {- connected: boolean;- address: string;- created: WorkerCreated;- copied: boolean;- setCopied: (value: boolean) => void;- setError: (message: string) => void;- onReady?: () => void;- onClose: () => void;-}) {- const [tokenCopied, setTokenCopied] = useState(false);- return (- <div className="min-w-0 space-y-5">- {!connected && (- <>- <Button- variant="default"- className="w-full gap-2"- onClick={async () => {- try {- await navigator.clipboard.writeText(workerSetupCommand(address, created.token, created.image));- setCopied(true);- } catch {- setError("Clipboard access failed. Allow clipboard access and try again.");- }- }}- >- {copied ? <CheckCircle2 className="size-4" /> : <Copy className="size-4" />}- {copied ? "Copied" : "Copy Docker command"}- </Button>- <details className="text-sm">- <summary className="cursor-pointer text-muted-foreground">View command</summary>- <p className="mt-3 text-xs text-muted-foreground">Contains a private worker token.</p>- <pre- aria-label="Docker command preview"- className="mt-3 max-h-48 overflow-auto rounded-md bg-muted/40 p-3 text-xs leading-5"- >- {workerSetupCommand(address, created.token, created.image)}- </pre>- </details>- <details className="text-sm">- <summary className="cursor-pointer text-muted-foreground">Using Docker Compose or Helm?</summary>- <p className="mt-3 text-muted-foreground">- Save this private token as LENS_WORKER_TOKEN in Compose or in your Helm worker token secret. Keep it for- future upgrades.- </p>- <Button- variant="outline"- className="mt-3"- onClick={async () => {- try {- await navigator.clipboard.writeText(created.token);- setTokenCopied(true);- } catch {- setError("Clipboard access failed. Allow clipboard access and try again.");- }- }}- >- {tokenCopied ? "Token copied" : "Copy worker token"}- </Button>- </details>- </>- )}- {!connected && (- <div className="space-y-3 border-t pt-5">- <div role="status" className="flex items-center gap-2.5 text-sm">- <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" /> Waiting for your worker to- connect…- </div>- <details className="pl-6.5 text-sm text-muted-foreground">- <summary className="cursor-pointer">Not connecting?</summary>- <p className="mt-2 break-words leading-6">- Check that Docker is running and can reach {address}. Inspect the container logs for connection or- authentication errors. This page updates automatically.- </p>- </details>- </div>- )}- {connected && (- <Button className="w-full" onClick={onReady ?? onClose}>- {onReady ? "New investigation" : "Done"}- </Button>- )}- </div>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerList.tsx b/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerList.tsxdeleted file mode 100644index 9109aaf078b..00000000000--- a/ui/litellm-dashboard/src/components/lens/setup/worker/WorkerList.tsx+++ /dev/null@@ -1,62 +0,0 @@-"use client";--import { Button } from "@/components/ui/button";--import { CheckCircle2 } from "lucide-react";-import { workerConnected } from "../../model/status";-import { AnalysisKeyDetails } from "./AnalysisKeyDetails";-import type { LensList } from "../../model/types";--function workerStatus(worker: LensList["workers"][number], now: number): string {- if (!worker.analysis_key_id) return "Billing key required";- return workerConnected(worker, now) ? "Connected" : "Not connected";-}--export function WorkerList({- workers,- now,- accessToken,- editBilling,- revoke,-}: {- workers: LensList["workers"];- now: number;- accessToken: string;- editBilling: (worker: LensList["workers"][number]) => void;- revoke: (id: string) => Promise<void>;-}) {- return (- <>- {workers- .filter((w) => !w.revoked)- .map((worker) => {- const connected = workerConnected(worker, now);- return (- <section key={worker.id} className="space-y-5 text-sm">- <div className="flex items-center justify-between gap-3">- {workers.filter((w) => !w.revoked).length > 1 && <h3 className="font-medium">{worker.name}</h3>}- <span- data-state={connected ? "active" : "inactive"}- className="flex items-center gap-2 text-muted-foreground data-[state=active]:text-emerald-700 dark:data-[state=active]:text-emerald-400"- >- {connected && <CheckCircle2 className="size-4" />}- {workerStatus(worker, now)}- </span>- </div>- {worker.analysis_key_id && (- <AnalysisKeyDetails accessToken={accessToken} keyId={worker.analysis_key_id} showName />- )}- <div className="flex flex-wrap items-center justify-between gap-2">- <Button variant="outline" size="sm" onClick={() => editBilling(worker)}>- Settings- </Button>- <Button variant="ghost" size="sm" onClick={() => revoke(worker.id)}>- Revoke access- </Button>- </div>- </section>- );- })}- </>- );-}diff --git a/ui/litellm-dashboard/src/components/lens/storage.ts b/ui/litellm-dashboard/src/components/lens/storage.tsnew file mode 100644index 00000000000..5542de43631--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/storage.ts@@ -0,0 +1,6 @@+import { z } from "zod";+import { storageKey } from "@/lib/storage";++export const FINDING_PANEL_WIDTH_KEY = "litellm.lens.findingPanelWidth";+export const LENS_INTRO_DISMISSED = storageKey("local", "lens.intro.dismissed", z.boolean(), false);+export const LENS_INTRO_SEEN = storageKey("session", "lens.intro.seen", z.boolean(), false);diff --git a/ui/litellm-dashboard/src/components/lens/ui/StateMessage.tsx b/ui/litellm-dashboard/src/components/lens/ui/StateMessage.tsxnew file mode 100644index 00000000000..d9570b62f93--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/ui/StateMessage.tsx@@ -0,0 +1,39 @@+import type { ComponentProps, ReactNode } from "react";+import { cva, cn } from "@/lib/cva.config";++const stateIcon = cva("flex size-10 items-center justify-center rounded-full", {+ variants: {+ tone: { muted: "bg-muted text-muted-foreground", destructive: "bg-destructive/10 text-destructive" },+ },+ defaultVariants: { tone: "muted" },+});++export type StateMessageProps = Omit<ComponentProps<"div">, "title"> & {+ role: "status" | "alert";+ icon: ReactNode;+ tone?: "muted" | "destructive";+ title: string;+ description: ReactNode;+};++export function StateMessage({ icon, tone, title, description, children, className, ...props }: StateMessageProps) {+ return (+ <div+ data-slot="state-message"+ className={cn(+ "m-auto flex max-w-sm flex-col items-center gap-3 py-16 text-center animate-in fade-in-0 duration-300 motion-reduce:animate-none",+ className,+ )}+ {...props}+ >+ <span aria-hidden="true" className={stateIcon({ tone })}>+ {icon}+ </span>+ <div className="flex flex-col gap-1">+ <p className="text-sm font-medium text-foreground">{title}</p>+ <p className="text-sm text-muted-foreground">{description}</p>+ </div>+ {children && <div className="mt-1 flex items-center gap-2">{children}</div>}+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/ui/StepIndicator.tsx b/ui/litellm-dashboard/src/components/lens/ui/StepIndicator.tsxnew file mode 100644index 00000000000..20309bc8e0c--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/ui/StepIndicator.tsx@@ -0,0 +1,37 @@+import type { ComponentProps } from "react";+import { Check } from "lucide-react";+import { cva, cn } from "@/lib/cva.config";++export type StepState = "complete" | "current" | "upcoming";++const stepIndicator = cva(+ "z-raised flex size-7 shrink-0 items-center justify-center rounded-full bg-card text-xs font-medium",+ {+ variants: {+ state: {+ complete: "bg-success/10 text-success",+ current: "bg-foreground text-background",+ upcoming: "border text-muted-foreground",+ },+ },+ },+);++export type StepIndicatorProps = Omit<ComponentProps<"span">, "children"> & {+ state: StepState;+ index: number;+};++export function StepIndicator({ state, index, className, ...props }: StepIndicatorProps) {+ return (+ <span+ data-slot="step-indicator"+ data-state={state}+ aria-label={state === "complete" ? `Step ${index + 1} complete` : `Step ${index + 1}`}+ className={cn(stepIndicator({ state }), className)}+ {...props}+ >+ {state === "complete" ? <Check aria-hidden="true" className="size-3.5" /> : index + 1}+ </span>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/ui/frame.ts b/ui/litellm-dashboard/src/components/lens/ui/frame.tsnew file mode 100644index 00000000000..0a8bd20fb32--- /dev/null+++ b/ui/litellm-dashboard/src/components/lens/ui/frame.ts@@ -0,0 +1,30 @@+import { cva } from "@/lib/cva.config";++export const frameCard = cva("flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl bg-card", {+ variants: { session: { live: "border border-foreground/15", demo: "border-2 border-info" } },+ defaultVariants: { session: "live" },+});++export const frameTab = cva("relative z-raised rounded-t-2xl bg-card", {+ variants: {+ session: {+ live: "-mb-px border-x border-t border-foreground/15",+ demo: "-mb-0.5 border-x-2 border-t-2 border-info",+ },+ },+ defaultVariants: { session: "live" },+});++export const frameCorner = cva("block size-full shadow-[0_0_0_12px_var(--card)]", {+ variants: {+ session: { live: "border-foreground/15", demo: "border-info" },+ side: { left: "rounded-br-xl", right: "rounded-bl-xl" },+ },+ compoundVariants: [+ { session: "live", side: "left", className: "border-r border-b" },+ { session: "live", side: "right", className: "border-l border-b" },+ { session: "demo", side: "left", className: "border-r-2 border-b-2" },+ { session: "demo", side: "right", className: "border-l-2 border-b-2" },+ ],+ defaultVariants: { session: "live" },+});diff --git a/ui/litellm-dashboard/src/components/shared/Inspector.test.tsx b/ui/litellm-dashboard/src/components/shared/Inspector.test.tsxnew file mode 100644index 00000000000..10b482162b9--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/Inspector.test.tsx@@ -0,0 +1,321 @@+import { fireEvent, render, screen, within } from "@testing-library/react";+import { HotkeysProvider } from "react-hotkeys-hook";+import { useState } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { clampPanelWidth, Inspector } from "./Inspector";++interface Note {+ id: string;+ title: string;+}++const notes: Note[] = [+ { id: "a", title: "first" },+ { id: "b", title: "second" },+ { id: "c", title: "third" },+];+const noteKey = (note: Note) => note.id;+const STORAGE_KEY = "test.inspector.width";++function Notes({+ initial = null,+ items = notes,+ onSelectedChange,+ fullScreen,+ onFullScreenChange,+ extra,+}: {+ initial?: Note | null;+ items?: readonly Note[];+ onSelectedChange?: (note: Note | null) => void;+ fullScreen?: boolean;+ onFullScreenChange?: (fullScreen: boolean) => void;+ extra?: React.ReactNode;+}) {+ const [selected, setSelected] = useState<Note | null>(initial);+ return (+ <HotkeysProvider>+ {extra}+ <Inspector.Root+ items={items}+ itemKey={noteKey}+ selected={selected}+ onSelectedChange={(note) => {+ setSelected(note);+ onSelectedChange?.(note);+ }}+ noun="note"+ storageKey={STORAGE_KEY}+ fullScreen={fullScreen}+ onFullScreenChange={onFullScreenChange}+ >+ <table>+ <tbody>+ {items.map((note) => (+ <Inspector.Row key={note.id} item={note} render={<tr tabIndex={0} />}>+ <td>{note.title}</td>+ </Inspector.Row>+ ))}+ </tbody>+ </table>+ <Inspector.Panel label="Note details" testId="note-panel">+ {(note: Note) => <div data-testid="note-body">note {note.title}</div>}+ </Inspector.Panel>+ </Inspector.Root>+ </HotkeysProvider>+ );+}++const panel = () => screen.getByRole("complementary", { name: "Note details" });+const row = (title: string) => screen.getByRole("row", { name: title });++const mockReducedMotion = (reduce: boolean) =>+ vi.spyOn(window, "matchMedia").mockImplementation(+ (query: string) =>+ ({+ matches: reduce && query.includes("reduce"),+ media: query,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }) as unknown as MediaQueryList,+ );++afterEach(() => {+ vi.restoreAllMocks();+ window.localStorage.clear();+});++describe("clampPanelWidth", () => {+ it("keeps at least 700px and a 100px strip of list on wide screens", () => {+ expect(clampPanelWidth(100, 1600)).toBe(700);+ expect(clampPanelWidth(2000, 1600)).toBe(1500);+ expect(clampPanelWidth(900, 1600)).toBe(900);+ });++ it("never exceeds the screen on viewports narrower than the minimum width", () => {+ expect(clampPanelWidth(900, 600)).toBe(600);+ expect(clampPanelWidth(100, 600)).toBe(600);+ });+});++describe("Inspector", () => {+ it("opens an item from its row, marks the row selected, and toggles it closed on a second press", () => {+ render(<Notes />);+ expect(screen.queryByRole("complementary")).not.toBeInTheDocument();+ expect(row("second")).toHaveAttribute("data-state", "idle");++ fireEvent.click(row("second"));+ expect(screen.getByTestId("note-body")).toHaveTextContent("note second");+ expect(row("second")).toHaveAttribute("aria-selected", "true");+ expect(row("second")).toHaveAttribute("data-state", "selected");+ expect(row("second")).toHaveAttribute("data-slot", "inspector-row");+ expect(row("first")).toHaveAttribute("aria-selected", "false");++ fireEvent.click(row("second"));+ expect(row("second")).toHaveAttribute("data-state", "idle");+ });++ it("opens a focused row with Enter or Space but not from keys inside it", () => {+ mockReducedMotion(true);+ render(<Notes />);+ fireEvent.keyDown(row("third"), { key: "Enter" });+ expect(screen.getByTestId("note-body")).toHaveTextContent("note third");+ fireEvent.keyDown(within(row("third")).getByText("third"), { key: " " });+ expect(screen.getByTestId("note-body")).toHaveTextContent("note third");+ fireEvent.keyDown(row("third"), { key: " " });+ expect(screen.queryByTestId("note-body")).not.toBeInTheDocument();+ });++ it("steps with J / K and the header arrows, showing the position and disabling at the ends", () => {+ mockReducedMotion(true);+ render(<Notes initial={notes[0]} />);+ expect(panel()).toHaveTextContent("1 / 3");+ expect(screen.getByRole("button", { name: "Previous note (K)" })).toBeDisabled();++ fireEvent.keyDown(document.body, { key: "j" });+ expect(screen.getByTestId("note-body")).toHaveTextContent("note second");+ fireEvent.click(screen.getByRole("button", { name: "Next note (J)" }));+ expect(panel()).toHaveTextContent("3 / 3");+ expect(screen.getByRole("button", { name: "Next note (J)" })).toBeDisabled();+ fireEvent.keyDown(document.body, { key: "k" });+ expect(screen.getByTestId("note-body")).toHaveTextContent("note second");++ fireEvent.keyDown(document.body, { key: "Escape" });+ expect(screen.queryByRole("complementary")).not.toBeInTheDocument();+ });+ it("lists the active shortcuts in the panel footer", () => {+ mockReducedMotion(true);+ render(<Notes initial={notes[0]} />);+ expect(within(panel()).getByLabelText("Keyboard shortcuts")).toHaveTextContent("J/K noteEsc close");+ });++ it("shows an item that is not in the list and steps from the top of the list", () => {+ mockReducedMotion(true);+ render(<Notes initial={{ id: "z", title: "elsewhere" }} />);+ expect(screen.getByTestId("note-body")).toHaveTextContent("note elsewhere");+ expect(panel()).not.toHaveTextContent("/ 3");+ expect(screen.getByRole("button", { name: "Previous note (K)" })).toBeDisabled();+ fireEvent.keyDown(document.body, { key: "j" });+ expect(screen.getByTestId("note-body")).toHaveTextContent("note first");+ });++ it("leaves J, K and Escape to an open menu or listbox", () => {+ const onSelectedChange = vi.fn();+ render(+ <Notes+ initial={notes[1]}+ onSelectedChange={onSelectedChange}+ extra={+ <>+ <div role="menu">+ <button type="button">menu item</button>+ </div>+ <div role="listbox">+ <button type="button">option</button>+ </div>+ </>+ }+ />,+ );+ for (const target of [screen.getByText("menu item"), screen.getByText("option")]) {+ for (const key of ["j", "k", "Escape"]) fireEvent.keyDown(target, { key });+ }+ expect(onSelectedChange).not.toHaveBeenCalled();+ fireEvent.keyDown(document.body, { key: "j" });+ expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith(notes[2]);+ });++ it("closes on a press outside the panel but not inside it, on a row, in a dialog, or on its overlay", () => {+ const onSelectedChange = vi.fn();+ render(+ <Notes+ initial={notes[0]}+ onSelectedChange={onSelectedChange}+ extra={+ <>+ <button type="button">outside</button>+ <div role="dialog">dialog</div>+ <div data-slot="sheet-overlay">overlay</div>+ </>+ }+ />,+ );+ fireEvent.mouseDown(screen.getByTestId("note-body"));+ fireEvent.mouseDown(within(row("second")).getByText("second"));+ fireEvent.mouseDown(screen.getByText("dialog"));+ fireEvent.mouseDown(screen.getByText("overlay"));+ fireEvent.mouseDown(screen.getByText("outside"), { button: 2 });+ expect(onSelectedChange).not.toHaveBeenCalled();+ fireEvent.mouseDown(screen.getByText("outside"));+ expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith(null);+ });++ it("remembers a resized width per storage key and restores it after full screen", () => {+ const onFullScreenChange = vi.fn();+ function Controlled() {+ const [fullScreen, setFullScreen] = useState(false);+ return (+ <Notes+ initial={notes[0]}+ fullScreen={fullScreen}+ onFullScreenChange={(next) => {+ setFullScreen(next);+ onFullScreenChange(next);+ }}+ />+ );+ }+ render(<Controlled />);+ fireEvent.keyDown(screen.getByRole("separator", { name: "Resize note panel" }), { key: "ArrowLeft" });+ const resizedWidth = panel().style.width;+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe(String(Number.parseInt(resizedWidth, 10)));++ fireEvent.click(screen.getByRole("button", { name: "Enter full screen" }));+ expect(onFullScreenChange).toHaveBeenLastCalledWith(true);+ expect(panel()).toHaveStyle({ width: "100%" });+ expect(screen.queryByRole("separator", { name: "Resize note panel" })).not.toBeInTheDocument();+ fireEvent.keyDown(document.body, { key: "j" });+ expect(panel()).toHaveStyle({ width: "100%" });++ fireEvent.click(screen.getByRole("button", { name: "Exit full screen" }));+ expect(panel()).toHaveStyle({ width: resizedWidth });+ });++ it("manages full screen itself when the parent does not", () => {+ mockReducedMotion(true);+ render(<Notes initial={notes[0]} />);+ fireEvent.click(screen.getByRole("button", { name: "Enter full screen" }));+ expect(panel()).toHaveStyle({ width: "100%" });+ fireEvent.keyDown(document.body, { key: "Escape" });+ expect(screen.queryByRole("complementary")).not.toBeInTheDocument();+ });++ it("hands J, K and Escape to an open inspector nested inside its panel and takes them back when it closes", () => {+ mockReducedMotion(true);+ const outer = vi.fn();+ const inner = vi.fn();+ function Nested() {+ const [innerNote, setInnerNote] = useState<Note | null>(notes[0]);+ return (+ <HotkeysProvider>+ <Inspector.Root+ items={notes}+ itemKey={noteKey}+ selected={notes[1]}+ onSelectedChange={outer}+ noun="note"+ storageKey="outer"+ >+ <Inspector.Panel label="Outer">+ {() => (+ <Inspector.Root+ items={notes}+ itemKey={noteKey}+ selected={innerNote}+ onSelectedChange={(note) => {+ inner(note);+ setInnerNote(note);+ }}+ noun="reply"+ storageKey="inner"+ >+ <Inspector.Panel label="Inner">{(note: Note) => <span>reply {note.title}</span>}</Inspector.Panel>+ </Inspector.Root>+ )}+ </Inspector.Panel>+ </Inspector.Root>+ </HotkeysProvider>+ );+ }+ render(<Nested />);+ fireEvent.keyDown(document.body, { key: "j" });+ expect(inner).toHaveBeenLastCalledWith(notes[1]);+ expect(outer).not.toHaveBeenCalled();++ fireEvent.keyDown(document.body, { key: "Escape" });+ expect(inner).toHaveBeenLastCalledWith(null);+ expect(screen.queryByRole("complementary", { name: "Inner" })).not.toBeInTheDocument();+ expect(outer).not.toHaveBeenCalled();++ fireEvent.keyDown(document.body, { key: "k" });+ expect(outer).toHaveBeenLastCalledWith(notes[0]);+ });++ it("unmounts right away on close when the user prefers reduced motion", () => {+ mockReducedMotion(true);+ render(<Notes initial={notes[0]} />);+ fireEvent.click(screen.getByRole("button", { name: "Close note (Esc)" }));+ expect(screen.queryByRole("complementary")).not.toBeInTheDocument();+ });++ it("plays the exit animation before unmounting when motion is allowed", () => {+ mockReducedMotion(false);+ render(<Notes initial={notes[0]} />);+ fireEvent.click(screen.getByRole("button", { name: "Close (Esc)" }));+ expect(panel()).toHaveClass("animate-trace-drawer-out");+ expect(panel()).toHaveAttribute("data-state", "closing");+ fireEvent.animationEnd(panel());+ expect(screen.queryByRole("complementary")).not.toBeInTheDocument();+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/Inspector.tsx b/ui/litellm-dashboard/src/components/shared/Inspector.tsxnew file mode 100644index 00000000000..ad698ddd37c--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/Inspector.tsx@@ -0,0 +1,349 @@+"use client";++import { mergeProps } from "@base-ui/react/merge-props";+import { useRender } from "@base-ui/react/use-render";+import { ArrowLeft, ChevronDown, ChevronsRight, ChevronUp, Maximize2, Minimize2, X } from "lucide-react";+import {+ createContext,+ type KeyboardEvent,+ type PointerEvent,+ type ReactNode,+ type RefObject,+ useCallback,+ useContext,+ useEffect,+ useRef,+ useState,+} from "react";+import { useLocalStorage, useMediaQuery, useOnClickOutside, useWindowSize } from "usehooks-ts";++import { ShortcutHints } from "@/components/shared/ShortcutHints";+import { useShortcut } from "@/components/shared/useShortcut";+import { cn } from "@/lib/cva.config";++const MIN_WIDTH = 700;+const MIN_LEFT_GAP = 100;+const DEFAULT_FRACTION = 0.56;+const KEY_STEP = 32;+const ROW_SLOT = "inspector-row";+const OVERLAYS = "[data-slot='sheet-overlay'], [data-slot='dialog-overlay'], [data-slot='alert-dialog-overlay']";+const KEEPS_PANEL_OPEN = `[data-slot='${ROW_SLOT}'], [role='dialog'], [role='menu'], [role='listbox'], [data-radix-popper-content-wrapper], ${OVERLAYS}`;++export const clampPanelWidth = (width: number, viewport: number): number => {+ const max = Math.max(Math.min(MIN_WIDTH, viewport), viewport - MIN_LEFT_GAP);+ return Math.round(Math.min(Math.max(width, Math.min(MIN_WIDTH, max)), max));+};++interface InspectorState<T> {+ readonly itemKey: (item: T) => string;+ readonly selected: T | null;+ readonly index: number;+ readonly total: number;+ readonly noun: string;+ readonly storageKey: string;+ readonly fullScreen: boolean;+ readonly toggle: (item: T) => void;+ readonly step: (delta: number) => void;+ readonly close: () => void;+ readonly setFullScreen: (fullScreen: boolean) => void;+ /** Called by an open Inspector nested inside this one; returns the release. */+ readonly claim: () => () => void;+}++const InspectorContext = createContext<unknown>(null);++export function useInspector<T>(): InspectorState<T> {+ const state = useContext(InspectorContext);+ if (state === null) throw new Error("Inspector parts must be rendered inside Inspector.Root");+ return state as InspectorState<T>;+}++export interface InspectorRootProps<T> {+ readonly items: readonly T[];+ readonly itemKey: (item: T) => string;+ readonly selected: T | null;+ readonly onSelectedChange: (item: T | null) => void;+ /** Names the item in button labels and the J/K hint, e.g. "trace". */+ readonly noun: string;+ /** localStorage key remembering the panel width for this surface. */+ readonly storageKey: string;+ readonly fullScreen?: boolean;+ readonly defaultFullScreen?: boolean;+ readonly onFullScreenChange?: (fullScreen: boolean) => void;+ readonly children: ReactNode;+}++/** Owns which item is open: rows toggle it, J/K step through `items`, Escape closes, the panel shows it. */+function Root<T>({+ items,+ itemKey,+ selected,+ onSelectedChange,+ noun,+ storageKey,+ fullScreen: controlledFullScreen,+ defaultFullScreen = false,+ onFullScreenChange,+ children,+}: InspectorRootProps<T>) {+ const parent = useContext(InspectorContext) as InspectorState<never> | null;+ const [claims, setClaims] = useState(0);+ const claim = useCallback(() => {+ setClaims((count) => count + 1);+ return () => setClaims((count) => count - 1);+ }, []);+ const [ownFullScreen, setOwnFullScreen] = useState(defaultFullScreen);+ const fullScreen = controlledFullScreen ?? ownFullScreen;+ const setFullScreen = (next: boolean) => {+ setOwnFullScreen(next);+ onFullScreenChange?.(next);+ };+ const selectedKey = selected === null ? null : itemKey(selected);+ const index = selectedKey === null ? -1 : items.findIndex((item) => itemKey(item) === selectedKey);+ const open = selected !== null;+ const parentClaim = parent?.claim;+ useEffect(() => (parentClaim && open ? parentClaim() : undefined), [parentClaim, open]);+ const keys = open && claims === 0;+ const step = (delta: number) => {+ const next = items[index + delta];+ if (next !== undefined) onSelectedChange(next);+ };+ const close = () => onSelectedChange(null);+ const toggle = (item: T) => onSelectedChange(itemKey(item) === selectedKey ? null : item);+ useShortcut("escape", close, { enabled: keys, description: "close" });+ useShortcut("j", () => step(1), { enabled: keys, description: noun });+ useShortcut("k", () => step(-1), { enabled: keys, description: noun });+ const state: InspectorState<T> = {+ itemKey,+ selected,+ index,+ total: items.length,+ noun,+ storageKey,+ fullScreen,+ toggle,+ step,+ close,+ setFullScreen,+ claim,+ };+ return <InspectorContext.Provider value={state}>{children}</InspectorContext.Provider>;+}++export type InspectorRowProps<T> = useRender.ComponentProps<"div"> & { readonly item: T };++const activates = (event: KeyboardEvent<HTMLElement>): boolean =>+ event.target === event.currentTarget && (event.key === "Enter" || event.key === " ");++/** A list entry that opens its item on click or Enter/Space and reads `data-state="selected"` while open. */+function Row<T>({ item, render, ...props }: InspectorRowProps<T>) {+ const { itemKey, selected, toggle } = useInspector<T>();+ const isSelected = selected !== null && itemKey(selected) === itemKey(item);+ const own = {+ "aria-selected": isSelected,+ onClick: () => toggle(item),+ onKeyDown: (event: KeyboardEvent<HTMLElement>) => {+ if (!activates(event)) return;+ event.preventDefault();+ toggle(item);+ },+ };+ const rendered = {+ defaultTagName: "div" as const,+ render,+ state: { slot: ROW_SLOT, state: isSelected ? "selected" : "idle" },+ props: mergeProps<"div">(own, props),+ };+ return useRender(rendered);+}++function usePanelWidth(storageKey: string) {+ const { width: viewport } = useWindowSize();+ const [stored, setStored] = useLocalStorage<number | null>(storageKey, null, {+ serializer: String,+ deserializer: (raw) => (Number.isFinite(Number(raw)) ? Number(raw) : null),+ });+ const width = clampPanelWidth(stored ?? viewport * DEFAULT_FRACTION, viewport);+ const update = useCallback((next: number) => setStored(clampPanelWidth(next, window.innerWidth)), [setStored]);+ return [width, update] as const;+}++/** Keeps the last item on screen through the exit animation, then lets the panel unmount. */+function useExitPresence<T>(item: T | null, itemKey: (item: T) => string) {+ const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");+ const [lastShown, setLastShown] = useState<T | null>(item);+ const [exitedKey, setExitedKey] = useState<string | null>(null);+ if (item !== null && item !== lastShown) setLastShown(item);+ if (item !== null && exitedKey !== null) setExitedKey(null);+ const shown = item ?? lastShown;+ const closing = item === null && shown !== null;+ const exited = closing && (reduceMotion || exitedKey === itemKey(shown));+ const onExited = () => {+ if (closing) setExitedKey(itemKey(shown));+ };+ return { shown: exited ? null : shown, closing, onExited };+}++function ResizeHandle({ noun, width, onResize }: { noun: string; width: number; onResize: (width: number) => void }) {+ const [dragging, setDragging] = useState(false);++ const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {+ event.preventDefault();+ event.currentTarget.setPointerCapture(event.pointerId);+ setDragging(true);+ };+ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {+ if (dragging) onResize(window.innerWidth - event.clientX);+ };+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key === "ArrowLeft") onResize(width + KEY_STEP);+ else if (event.key === "ArrowRight") onResize(width - KEY_STEP);+ else return;+ event.preventDefault();+ event.stopPropagation();+ };++ return (+ <div+ role="separator"+ aria-orientation="vertical"+ aria-label={`Resize ${noun} panel`}+ aria-valuenow={width}+ aria-valuemin={MIN_WIDTH}+ tabIndex={0}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={() => setDragging(false)}+ onPointerCancel={() => setDragging(false)}+ onKeyDown={onKeyDown}+ className="group/handle absolute inset-y-0 -left-2.5 z-raised flex w-5 cursor-col-resize justify-center outline-none"+ >+ <span+ className={cn(+ "h-full w-[0.67px] bg-border transition-[width,background-color] duration-150 group-hover/handle:w-0.5 group-focus-visible/handle:w-0.5 group-focus-visible/handle:bg-trace-brand motion-reduce:transition-none",+ dragging && "w-0.5 bg-trace-brand",+ )}+ />+ </div>+ );+}++function HeaderButton({+ label,+ disabled = false,+ onClick,+ children,+}: {+ label: string;+ disabled?: boolean;+ onClick: () => void;+ children: ReactNode;+}) {+ return (+ <button+ type="button"+ aria-label={label}+ title={label}+ disabled={disabled}+ onClick={onClick}+ className="grid size-7 place-items-center rounded-[4px] text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none"+ >+ {children}+ </button>+ );+}++function Header() {+ const { index, total, noun, step, close, fullScreen, setFullScreen } = useInspector();+ return (+ <div data-slot="inspector-header" className="flex h-[37px] shrink-0 items-center gap-1 border-b border-border px-2">+ <HeaderButton label="Close (Esc)" onClick={close}>+ <ChevronsRight className="size-4" />+ </HeaderButton>+ <span className="mx-1 h-4 w-px bg-border" />+ <HeaderButton label={`Next ${noun} (J)`} disabled={index < 0 || index >= total - 1} onClick={() => step(1)}>+ <ChevronDown className="size-4" />+ </HeaderButton>+ <HeaderButton label={`Previous ${noun} (K)`} disabled={index <= 0} onClick={() => step(-1)}>+ <ChevronUp className="size-4" />+ </HeaderButton>+ {index >= 0 && (+ <span className="ml-1 font-mono text-[11px] text-muted-foreground tabular-nums">+ {index + 1} / {total}+ </span>+ )}+ <div className="ml-auto flex items-center gap-1">+ <HeaderButton+ label={fullScreen ? "Exit full screen" : "Enter full screen"}+ onClick={() => setFullScreen(!fullScreen)}+ >+ {fullScreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}+ </HeaderButton>+ <HeaderButton label={`Close ${noun} (Esc)`} onClick={close}>+ <X className="size-4" />+ </HeaderButton>+ </div>+ </div>+ );+}++export interface InspectorPanelProps<T> {+ readonly label: string;+ readonly testId?: string;+ readonly children: (item: T) => ReactNode;+}++/** Resizable right-hand panel showing the open item; the list stays clickable beside it. */+function Panel<T>({ label, testId, children }: InspectorPanelProps<T>) {+ const { selected, itemKey, noun, storageKey, fullScreen, close } = useInspector<T>();+ const [width, setWidth] = usePanelWidth(storageKey);+ const panelRef = useRef<HTMLElement>(null);+ const { shown, closing, onExited } = useExitPresence(selected, itemKey);++ useOnClickOutside(panelRef as RefObject<HTMLElement>, (event) => {+ if (selected === null || (event instanceof MouseEvent && event.button !== 0)) return;+ if (event.target instanceof Element && event.target.closest(KEEPS_PANEL_OPEN) !== null) return;+ close();+ });++ if (shown === null) return null;+ return (+ <aside+ ref={panelRef}+ aria-label={label}+ data-slot="inspector-panel"+ data-state={closing ? "closing" : "open"}+ data-testid={testId}+ style={{ width: fullScreen ? "100%" : width }}+ onAnimationEnd={(event) => {+ if (event.target === event.currentTarget) onExited();+ }}+ className={cn(+ "fixed inset-y-0 right-0 z-overlay flex origin-right flex-col bg-background shadow-[0_10px_15px_-3px_rgba(16,24,40,0.1),0_4px_6px_-4px_rgba(16,24,40,0.1)] motion-reduce:animate-none",+ closing ? "animate-trace-drawer-out" : "animate-trace-drawer-in",+ )}+ >+ {!fullScreen && <ResizeHandle noun={noun} width={width} onResize={setWidth} />}+ <Header />+ <div className="flex min-h-0 flex-1 flex-col">{children(shown)}</div>+ <ShortcutHints className="min-h-10 shrink-0 border-t border-border px-3 py-1.5" />+ </aside>+ );+}++/** Returns from content stacked inside the panel, such as evidence opened over a finding. */+function BackLink({ label, onClick }: { label: string; onClick: () => void }) {+ return (+ <button+ type="button"+ onClick={onClick}+ data-slot="inspector-back"+ className="-ml-1 inline-flex max-w-full items-center gap-1 rounded px-1 text-xs text-muted-foreground hover:text-foreground"+ >+ <ArrowLeft aria-hidden="true" className="size-3 shrink-0" />+ <span className="truncate">{label}</span>+ </button>+ );+}++export const Inspector = { Root, Row, Panel, BackLink } as const;diff --git a/ui/litellm-dashboard/src/components/shared/InspectorTable.test.tsx b/ui/litellm-dashboard/src/components/shared/InspectorTable.test.tsxnew file mode 100644index 00000000000..416d31bc940--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/InspectorTable.test.tsx@@ -0,0 +1,106 @@+import {+ getCoreRowModel,+ getExpandedRowModel,+ useReactTable,+ type ColumnDef,+ type TableOptions,+} from "@tanstack/react-table";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { useState } from "react";+import { describe, expect, it } from "vitest";++import { Inspector } from "./Inspector";+import { InspectorTable } from "./InspectorTable";++interface Node {+ readonly id: string;+ readonly children?: readonly Node[];+}++const TREE: Node[] = [+ { id: "a", children: [{ id: "a1" }, { id: "a2" }] },+ { id: "b", children: [{ id: "b1" }] },+ { id: "c" },+];++const COLUMNS: ColumnDef<Node>[] = [+ {+ id: "name",+ header: "Name",+ cell: ({ row }) => (+ <span>+ <InspectorTable.Indent row={row} toggleLabel={(expanded) => `${expanded ? "Hide" : "Show"} ${row.id}`} />+ {row.id}+ </span>+ ),+ },+];++function Tree() {+ const [selected, setSelected] = useState<Node | null>(null);+ const tableOptions: TableOptions<Node> = {+ data: TREE,+ columns: COLUMNS,+ getRowId: (node) => node.id,+ getSubRows: (node) => node.children?.slice(),+ initialState: { expanded: true },+ getCoreRowModel: getCoreRowModel(),+ getExpandedRowModel: getExpandedRowModel(),+ };+ const table = useReactTable(tableOptions);+ return (+ <Inspector.Root+ items={table.getRowModel().rows.map((row) => row.original)}+ itemKey={(node: Node) => node.id}+ selected={selected}+ onSelectedChange={setSelected}+ noun="node"+ storageKey="inspector-table-test"+ >+ <InspectorTable.Root table={table}>+ <InspectorTable.Grid aria-label="Nodes">+ <InspectorTable.Body<Node> rowHeight={() => 36}>+ {(row) => <InspectorTable.Row row={row} item={row.original} aria-label={row.id} />}+ </InspectorTable.Body>+ </InspectorTable.Grid>+ </InspectorTable.Root>+ <Inspector.Panel label="Node">{(node: Node) => <p>Open: {node.id}</p>}</Inspector.Panel>+ </Inspector.Root>+ );+}++const rowNames = () =>+ within(screen.getByRole("table", { name: "Nodes" }))+ .getAllByRole("row")+ .map((row) => row.getAttribute("aria-label"))+ .filter(Boolean);++describe("InspectorTable tree", () => {+ it("collapses and re-expands one parent's rows without touching its siblings", async () => {+ const user = userEvent.setup();+ render(<Tree />);+ expect(rowNames()).toEqual(["a", "a1", "a2", "b", "b1", "c"]);++ await user.click(screen.getByRole("button", { name: "Hide a" }));+ expect(rowNames()).toEqual(["a", "b", "b1", "c"]);++ await user.click(screen.getByRole("button", { name: "Show a" }));+ expect(rowNames()).toEqual(["a", "a1", "a2", "b", "b1", "c"]);+ expect(screen.queryByRole("button", { name: /c$/ })).not.toBeInTheDocument();+ });++ it("opens rows without toggling them, and J walks only the visible rows", async () => {+ const user = userEvent.setup();+ render(<Tree />);+ await user.click(screen.getByRole("button", { name: "Hide a" }));+ expect(screen.queryByText(/^Open:/)).not.toBeInTheDocument();++ await user.click(screen.getByRole("row", { name: "a" }));+ expect(screen.getByText("Open: a")).toBeInTheDocument();+ await user.keyboard("j");+ expect(screen.getByText("Open: b")).toBeInTheDocument();+ await user.keyboard("j");+ expect(screen.getByText("Open: b1")).toBeInTheDocument();+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/InspectorTable.tsx b/ui/litellm-dashboard/src/components/shared/InspectorTable.tsxnew file mode 100644index 00000000000..d5443fe9ac1--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/InspectorTable.tsx@@ -0,0 +1,179 @@+"use client";++import "@/components/shared/DataTable/columnMeta";++import { flexRender, type Row as TanStackRow, type Table as TanStackTable } from "@tanstack/react-table";+import { useVirtualizer } from "@tanstack/react-virtual";+import { ChevronRight } from "lucide-react";+import { createContext, Fragment, useContext, useState, type ComponentProps, type ReactNode } from "react";++import { Inspector } from "@/components/shared/Inspector";+import { TableBody, TableCell, TableHead, TableHeader } from "@/components/ui/table";+import { cn } from "@/lib/cva.config";++const OVERSCAN_ROWS = 12;+const NUMERIC = "text-right tabular-nums";+const ROW =+ "cursor-pointer border-b border-border/60 transition-colors duration-150 hover:bg-trace-row-hover focus-visible:outline-2 focus-visible:outline-ring data-[state=selected]:bg-trace-row-selected data-[state=selected]:shadow-[inset_2px_0_0_var(--trace-brand)] data-[state=selected]:hover:bg-trace-row-selected motion-reduce:transition-none";++interface InspectorTableState<T> {+ readonly table: TanStackTable<T>;+ readonly scroller: HTMLDivElement | null;+}++const InspectorTableContext = createContext<unknown>(null);++export function useInspectorTable<T>(): InspectorTableState<T> {+ const state = useContext(InspectorTableContext);+ if (state === null) throw new Error("InspectorTable parts must be rendered inside InspectorTable.Root");+ return state as InspectorTableState<T>;+}++type RootProps<T> = ComponentProps<"div"> & { readonly table: TanStackTable<T> };++function Root<T>({ table, className, children, ...props }: RootProps<T>) {+ const [scroller, setScroller] = useState<HTMLDivElement | null>(null);+ return (+ <InspectorTableContext.Provider value={{ table, scroller }}>+ <div+ ref={setScroller}+ data-slot="inspector-table"+ className={cn("min-h-0 flex-1 overflow-auto", className)}+ {...props}+ >+ {children}+ </div>+ </InspectorTableContext.Provider>+ );+}++/** A column without `size` takes the remaining width. */+function Grid({ className, children, ...props }: ComponentProps<"table">) {+ const { table } = useInspectorTable();+ return (+ <table data-slot="table" className={cn("w-full table-fixed border-collapse text-left", className)} {...props}>+ <colgroup>+ {table.getVisibleLeafColumns().map((column) => (+ <col key={column.id} style={{ width: column.columnDef.size }} />+ ))}+ </colgroup>+ {children}+ </table>+ );+}++function Header({ hidden = false }: { readonly hidden?: boolean }) {+ const { table } = useInspectorTable();+ return (+ <TableHeader+ className={hidden ? "sr-only" : "sticky top-0 z-sticky bg-[color-mix(in_oklab,var(--muted)_40%,var(--card))]"}+ >+ {table.getHeaderGroups().map((group) => (+ <tr key={group.id} className="h-8 border-border text-xs tracking-wider text-muted-foreground uppercase">+ {group.headers.map(({ id, column, isPlaceholder, getContext }) => (+ <TableHead+ key={id}+ className={cn(+ "h-auto px-3 text-muted-foreground",+ column.columnDef.meta?.numeric && NUMERIC,+ column.columnDef.meta?.headerClassName,+ )}+ >+ {isPlaceholder ? null : flexRender(column.columnDef.header, getContext())}+ </TableHead>+ ))}+ </tr>+ ))}+ </TableHeader>+ );+}++interface BodyProps<T> {+ readonly rowHeight: (row: TanStackRow<T>) => number;+ readonly children: (row: TanStackRow<T>) => ReactNode;+ readonly after?: ReactNode;+}++function Body<T>({ rowHeight, children, after }: BodyProps<T>) {+ const { table, scroller } = useInspectorTable<T>();+ const rows = table.getRowModel().rows;+ const virtualizerOptions = {+ count: rows.length,+ getScrollElement: () => scroller,+ estimateSize: (index: number) => rowHeight(rows[index]),+ overscan: OVERSCAN_ROWS,+ getItemKey: (index: number) => rows[index].id,+ };+ const virtualizer = useVirtualizer(virtualizerOptions);+ const items = virtualizer.getVirtualItems();+ const padTop = items[0]?.start ?? 0;+ const padBottom = virtualizer.getTotalSize() - (items.at(-1)?.end ?? 0);+ return (+ <TableBody>+ {padTop > 0 && <tr aria-hidden style={{ height: padTop }} />}+ {items.map(({ key, index }) => (+ <Fragment key={key}>{children(rows[index])}</Fragment>+ ))}+ {padBottom > 0 && <tr aria-hidden style={{ height: padBottom }} />}+ {after}+ </TableBody>+ );+}++type RowProps<T> = ComponentProps<"tr"> & { readonly row: TanStackRow<T>; readonly item: unknown };++function Row<T>({ row, item, className, ...props }: RowProps<T>) {+ return (+ <Inspector.Row item={item} render={<tr data-slot="table-row" className={cn(ROW, className)} {...props} />}>+ {row.getVisibleCells().map(({ id, column, getContext }) => (+ <TableCell+ key={id}+ className={cn("px-3 py-0", column.columnDef.meta?.numeric && NUMERIC, column.columnDef.meta?.className)}+ >+ {flexRender(column.columnDef.cell, getContext())}+ </TableCell>+ ))}+ </Inspector.Row>+ );+}++interface IndentProps<T> {+ readonly row: TanStackRow<T>;+ readonly toggleLabel?: (expanded: boolean) => string;+ readonly className?: string;+}++function Indent<T>({ row, toggleLabel = (expanded) => (expanded ? "Collapse" : "Expand"), className }: IndentProps<T>) {+ if (row.depth > 0) {+ const last = row.getParentRow()?.subRows.at(-1)?.id === row.id;+ return (+ <span aria-hidden="true" className={cn("relative w-6 shrink-0", className)}>+ <span className={cn("absolute top-0 left-3 w-px bg-border", last ? "h-1/2" : "h-full")} />+ <span className="absolute top-1/2 left-3 h-px w-3 bg-border" />+ </span>+ );+ }+ if (!row.getCanExpand()) return <span aria-hidden="true" className="size-6 shrink-0" />;+ const expanded = row.getIsExpanded();+ return (+ <button+ type="button"+ aria-expanded={expanded}+ aria-label={toggleLabel(expanded)}+ onClick={(event) => {+ event.stopPropagation();+ row.toggleExpanded();+ }}+ className="inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground"+ >+ <ChevronRight+ className={cn(+ "size-3.5 transition-transform duration-150 motion-reduce:transition-none",+ expanded && "rotate-90",+ )}+ />+ </button>+ );+}++export const InspectorTable = { Root, Grid, Header, Body, Row, Indent } as const;diff --git a/ui/litellm-dashboard/src/components/shared/ShortcutHints.test.tsx b/ui/litellm-dashboard/src/components/shared/ShortcutHints.test.tsxnew file mode 100644index 00000000000..c20f6b6b0df--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/ShortcutHints.test.tsx@@ -0,0 +1,46 @@+import { render, screen } from "@testing-library/react";+import { HotkeysProvider } from "react-hotkeys-hook";+import { describe, expect, it, vi } from "vitest";++import { ShortcutHints } from "./ShortcutHints";+import { BoundShortcut as Bound } from "./__fixtures__/BoundShortcut";++const hintText = () => screen.getByLabelText("Keyboard shortcuts").textContent;++describe("ShortcutHints", () => {+ it("lists what is bound, merging keys that share a description and letting the pane own a shared key", () => {+ const onPress = vi.fn();+ const { rerender } = render(+ <HotkeysProvider>+ <Bound id="j" keys={["j", "trace"]} layer="panel" onPress={onPress} />+ <Bound id="k" keys={["k", "trace"]} layer="panel" onPress={onPress} />+ <Bound id="esc" keys={["escape", "close trace"]} layer="panel" onPress={onPress} />+ <Bound id="down" keys={["down", "step"]} layer="pane" onPress={onPress} />+ <Bound id="up" keys={["up", "step"]} layer="pane" onPress={onPress} />+ <Bound id="paneEsc" keys={["escape", "close pane"]} layer="pane" onPress={onPress} />+ <ShortcutHints />+ </HotkeysProvider>,+ );+ expect(hintText()).toBe("↑/↓ stepJ/K traceEsc close pane");++ rerender(+ <HotkeysProvider>+ <Bound id="j" keys={["j", "trace"]} layer="panel" onPress={onPress} />+ <Bound id="k" keys={["k", "trace"]} layer="panel" onPress={onPress} />+ <Bound id="esc" keys={["escape", "close trace"]} layer="panel" onPress={onPress} />+ <ShortcutHints />+ </HotkeysProvider>,+ );+ expect(hintText()).toBe("J/K traceEsc close trace");+ });++ it("renders nothing while no shortcut is bound", () => {+ render(+ <HotkeysProvider>+ <Bound id="off" keys={["j", "trace"]} layer="panel" enabled={false} onPress={vi.fn()} />+ <ShortcutHints />+ </HotkeysProvider>,+ );+ expect(screen.queryByLabelText("Keyboard shortcuts")).not.toBeInTheDocument();+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/ShortcutHints.tsx b/ui/litellm-dashboard/src/components/shared/ShortcutHints.tsxnew file mode 100644index 00000000000..6ed5b374cbe--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/ShortcutHints.tsx@@ -0,0 +1,94 @@+"use client";++import { Fragment, type ReactNode } from "react";+import { useHotkeysContext } from "react-hotkeys-hook";++import { cn } from "@/lib/cva.config";++type BoundShortcut = ReturnType<typeof useHotkeysContext>["hotkeys"][number];++export interface ShortcutHint {+ readonly keys: readonly string[];+ readonly description: string;+}++const KEY_LABELS: Readonly<Record<string, string>> = {+ arrowup: "↑",+ arrowdown: "↓",+ arrowleft: "←",+ arrowright: "→",+ escape: "Esc",+};+const ARROWS: readonly string[] = ["arrowup", "arrowdown", "arrowleft", "arrowright"];++export const keyLabel = (key: string): string => KEY_LABELS[key] ?? key.toUpperCase();++const keyRank = (key: string): number => {+ const arrow = ARROWS.indexOf(key);+ if (arrow >= 0) return arrow;+ return key === "escape" ? Number.MAX_SAFE_INTEGER : ARROWS.length + key.charCodeAt(0);+};++const plainKey = (shortcut: BoundShortcut): string | null => {+ const single = Boolean(shortcut.description) && shortcut.keys?.length === 1;+ const modified = [shortcut.alt, shortcut.ctrl, shortcut.meta, shortcut.shift].some(Boolean);+ return single && !modified ? shortcut.keys?.[0] ?? null : null;+};++const innermost = (current: BoundShortcut, next: BoundShortcut): BoundShortcut =>+ next.metadata?.layer === "pane" ? next : current;++const mergeAdjacent = (hints: readonly ShortcutHint[], key: string, description: string): readonly ShortcutHint[] => {+ const last = hints.at(-1);+ if (last?.description !== description) return [...hints, { keys: [key], description }];+ return [...hints.slice(0, -1), { keys: [...last.keys, key], description }];+};++/** One hint per key with the innermost binding winning; keys that share a description read as one hint. */+export function shortcutHints(shortcuts: readonly BoundShortcut[]): readonly ShortcutHint[] {+ const winners = shortcuts.reduce((byKey, shortcut) => {+ const key = plainKey(shortcut);+ if (key === null) return byKey;+ const current = byKey.get(key);+ return new Map(byKey).set(key, current ? innermost(current, shortcut) : shortcut);+ }, new Map<string, BoundShortcut>());+ return [...winners.entries()]+ .sort(([a], [b]) => keyRank(a) - keyRank(b))+ .reduce<+ readonly ShortcutHint[]+ >((hints, [key, shortcut]) => mergeAdjacent(hints, key, shortcut.description ?? ""), []);+}++function Kbd({ children }: { children: ReactNode }) {+ return (+ <kbd className="rounded-sm border border-border border-b-2 bg-muted px-[3px] font-mono text-muted-foreground">+ {children}+ </kbd>+ );+}++/** The shortcuts active right now, read from what is bound rather than typed by hand. */+export function ShortcutHints({ className }: { className?: string }) {+ const { hotkeys } = useHotkeysContext();+ const hints = shortcutHints(hotkeys);+ if (hints.length === 0) return null;+ return (+ <div+ aria-label="Keyboard shortcuts"+ data-slot="shortcut-hints"+ className={cn("flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", className)}+ >+ {hints.map((hint) => (+ <span key={hint.keys.join("/")} className="whitespace-nowrap">+ {hint.keys.map((key, index) => (+ <Fragment key={key}>+ {index > 0 && "/"}+ <Kbd>{keyLabel(key)}</Kbd>+ </Fragment>+ ))}{" "}+ {hint.description}+ </span>+ ))}+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/shared/SidePanel.tsx b/ui/litellm-dashboard/src/components/shared/SidePanel.tsxdeleted file mode 100644index f79d497a4ad..00000000000--- a/ui/litellm-dashboard/src/components/shared/SidePanel.tsx+++ /dev/null@@ -1,239 +0,0 @@-"use client";--import { ArrowLeft, ChevronDown, ChevronsRight, ChevronUp, Maximize2, Minimize2, X } from "lucide-react";-import { useCallback, useRef, useState, type ReactNode, type RefObject } from "react";-import { useEventListener, useLocalStorage, useMediaQuery, useOnClickOutside, useWindowSize } from "usehooks-ts";--import { cn } from "@/lib/cva.config";-import { ignoresLetterShortcut } from "@/components/view_logs/letterShortcut";--const WIDTH_KEY = "litellm.agentTraces.drawerWidth";-const MIN_WIDTH = 700;-const MIN_LEFT_GAP = 100;-const DEFAULT_FRACTION = 0.56;-const KEY_STEP = 32;--export const clampDrawerWidth = (width: number, viewport: number): number => {- const max = Math.max(Math.min(MIN_WIDTH, viewport), viewport - MIN_LEFT_GAP);- return Math.round(Math.min(Math.max(width, Math.min(MIN_WIDTH, max)), max));-};--export const PANEL_TRIGGER = { "data-side-panel-trigger": "" } as const;--const KEEPS_PANEL_OPEN =- "[data-side-panel-trigger], [role='dialog'], [role='menu'], [role='listbox'], [data-radix-popper-content-wrapper]";--const OWNS_ITS_KEYS = "[role='dialog'], [role='menu'], [role='listbox']";--const insideKeyOwner = (event: KeyboardEvent): boolean =>- event.target instanceof Element && event.target.closest(OWNS_ITS_KEYS) !== null;--function useDrawerWidth() {- const { width: viewport } = useWindowSize();- const [stored, setStored] = useLocalStorage<number | null>(WIDTH_KEY, null, {- serializer: String,- deserializer: (raw) => (Number.isFinite(Number(raw)) ? Number(raw) : null),- });- const width = clampDrawerWidth(stored ?? viewport * DEFAULT_FRACTION, viewport);- const update = useCallback((next: number) => setStored(clampDrawerWidth(next, window.innerWidth)), [setStored]);- return [width, update] as const;-}--function useExitPresence<T>(item: T | null, itemKey: (item: T) => string) {- const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");- const [lastShown, setLastShown] = useState<T | null>(item);- const [exitedKey, setExitedKey] = useState<string | null>(null);- if (item !== null && item !== lastShown) setLastShown(item);- if (item !== null && exitedKey !== null) setExitedKey(null);- const shown = item ?? lastShown;- const closing = item === null && shown !== null;- const exited = closing && (reduceMotion || exitedKey === itemKey(shown));- const onExited = () => {- if (closing) setExitedKey(itemKey(shown));- };- return { shown: exited ? null : shown, closing, onExited };-}--function ResizeHandle({ noun, width, onResize }: { noun: string; width: number; onResize: (width: number) => void }) {- const [dragging, setDragging] = useState(false);-- const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {- event.preventDefault();- event.currentTarget.setPointerCapture(event.pointerId);- setDragging(true);- };- const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {- if (dragging) onResize(window.innerWidth - event.clientX);- };- const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {- if (event.key === "ArrowLeft") onResize(width + KEY_STEP);- else if (event.key === "ArrowRight") onResize(width - KEY_STEP);- else return;- event.preventDefault();- event.stopPropagation();- };-- return (- <div- role="separator"- aria-orientation="vertical"- aria-label={`Resize ${noun} panel`}- aria-valuenow={width}- aria-valuemin={MIN_WIDTH}- tabIndex={0}- onPointerDown={onPointerDown}- onPointerMove={onPointerMove}- onPointerUp={() => setDragging(false)}- onPointerCancel={() => setDragging(false)}- onKeyDown={onKeyDown}- className="group/handle absolute inset-y-0 -left-2.5 z-raised flex w-5 cursor-col-resize justify-center outline-none"- >- <span- className={cn(- "h-full w-[0.67px] bg-border transition-[width,background-color] duration-150 group-hover/handle:w-0.5 group-focus-visible/handle:w-0.5 group-focus-visible/handle:bg-trace-brand motion-reduce:transition-none",- dragging && "w-0.5 bg-trace-brand",- )}- />- </div>- );-}--function HeaderButton({- label,- disabled = false,- onClick,- children,-}: {- label: string;- disabled?: boolean;- onClick: () => void;- children: ReactNode;-}) {- return (- <button- type="button"- aria-label={label}- title={label}- disabled={disabled}- onClick={onClick}- className="grid size-7 place-items-center rounded-[4px] text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none"- >- {children}- </button>- );-}--export interface SidePanelProps<T> {- item: T | null;- itemKey: (item: T) => string;- noun: string;- label: string;- testId?: string;- index: number;- total: number;- onStep: (delta: number) => void;- onClose: () => void;- fullScreen: boolean;- onFullScreenChange: (fullScreen: boolean) => void;- children: (item: T) => ReactNode;-}--export function SidePanel<T>({- item,- itemKey,- noun,- label,- testId,- index,- total,- onStep,- onClose,- fullScreen,- onFullScreenChange,- children,-}: SidePanelProps<T>) {- const [width, setWidth] = useDrawerWidth();- const panelRef = useRef<HTMLElement>(null);- const { shown, closing, onExited } = useExitPresence(item, itemKey);-- useEventListener("keydown", (event) => {- if (item === null || ignoresLetterShortcut(event) || insideKeyOwner(event)) return;- if (event.key === "Escape") {- event.preventDefault();- onClose();- } else if (event.key === "j") {- event.preventDefault();- onStep(1);- } else if (event.key === "k") {- event.preventDefault();- onStep(-1);- }- });-- useOnClickOutside(panelRef as RefObject<HTMLElement>, (event) => {- if (item === null || (event instanceof MouseEvent && event.button !== 0)) return;- if (event.target instanceof Element && event.target.closest(KEEPS_PANEL_OPEN) !== null) return;- onClose();- });-- if (shown === null) return null;- return (- <aside- ref={panelRef}- aria-label={label}- data-testid={testId}- style={{ width: fullScreen ? "100%" : width }}- onAnimationEnd={(event) => {- if (event.target === event.currentTarget) onExited();- }}- className={cn(- "fixed inset-y-0 right-0 z-overlay flex origin-right flex-col bg-background shadow-[0_10px_15px_-3px_rgba(16,24,40,0.1),0_4px_6px_-4px_rgba(16,24,40,0.1)] motion-reduce:animate-none",- closing ? "animate-trace-drawer-out" : "animate-trace-drawer-in",- )}- >- {!fullScreen && <ResizeHandle noun={noun} width={width} onResize={setWidth} />}- <div className="flex h-[37px] shrink-0 items-center gap-1 border-b border-border px-2">- <HeaderButton label="Close (Esc)" onClick={onClose}>- <ChevronsRight className="size-4" />- </HeaderButton>- <span className="mx-1 h-4 w-px bg-border" />- <HeaderButton label={`Next ${noun} (J)`} disabled={index < 0 || index >= total - 1} onClick={() => onStep(1)}>- <ChevronDown className="size-4" />- </HeaderButton>- <HeaderButton label={`Previous ${noun} (K)`} disabled={index <= 0} onClick={() => onStep(-1)}>- <ChevronUp className="size-4" />- </HeaderButton>- {index >= 0 && (- <span className="ml-1 font-mono text-[11px] text-muted-foreground tabular-nums">- {index + 1} / {total}- </span>- )}- <div className="ml-auto flex items-center gap-1">- <HeaderButton- label={fullScreen ? "Exit full screen" : "Enter full screen"}- onClick={() => onFullScreenChange(!fullScreen)}- >- {fullScreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}- </HeaderButton>- <HeaderButton label={`Close ${noun} (Esc)`} onClick={onClose}>- <X className="size-4" />- </HeaderButton>- </div>- </div>- <div className="flex min-h-0 flex-1 flex-col">{children(shown)}</div>- </aside>- );-}--export function PanelBackLink({ label, onClick }: { label: string; onClick: () => void }) {- return (- <button- type="button"- onClick={onClick}- className="-ml-1 inline-flex max-w-full items-center gap-1 rounded px-1 text-xs text-muted-foreground hover:text-foreground"- >- <ArrowLeft aria-hidden="true" className="size-3 shrink-0" />- <span className="truncate">{label}</span>- </button>- );-}diff --git a/ui/litellm-dashboard/src/components/shared/StatusDot.tsx b/ui/litellm-dashboard/src/components/shared/StatusDot.tsxindex 31b7a72e62f..6b7fcd2be3a 100644--- a/ui/litellm-dashboard/src/components/shared/StatusDot.tsx+++ b/ui/litellm-dashboard/src/components/shared/StatusDot.tsx@@ -5,6 +5,7 @@ import { cn } from "@/lib/cva.config";const colors = {ok: "fill-emerald-500 text-emerald-500",warn: "fill-amber-500 text-amber-500",+ error: "fill-red-500 text-red-500",off: "fill-slate-400 text-slate-400",};diff --git a/ui/litellm-dashboard/src/components/shared/__fixtures__/BoundShortcut.tsx b/ui/litellm-dashboard/src/components/shared/__fixtures__/BoundShortcut.tsxnew file mode 100644index 00000000000..e11236084e2--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/__fixtures__/BoundShortcut.tsx@@ -0,0 +1,19 @@+import { type ShortcutLayer, useShortcut } from "../useShortcut";++/** Binds one shortcut and reports which binding fired. */+export function BoundShortcut({+ id,+ keys,+ layer,+ enabled = true,+ onPress,+}: {+ id: string;+ keys: readonly [string, string];+ layer: ShortcutLayer;+ enabled?: boolean;+ onPress: (id: string) => void;+}) {+ useShortcut(keys[0], () => onPress(id), { layer, enabled, description: keys[1] });+ return null;+}diff --git a/ui/litellm-dashboard/src/components/shared/dotField/DotField.tsx b/ui/litellm-dashboard/src/components/shared/dotField/DotField.tsxnew file mode 100644index 00000000000..d95bb11768d--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/dotField/DotField.tsx@@ -0,0 +1,152 @@+"use client";++import {+ createContext,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ComponentProps,+ type RefObject,+} from "react";+import { useMediaQuery, useResizeObserver } from "usehooks-ts";++import { cn } from "@/lib/cva.config";++import {+ DOT_COLS,+ DOT_PITCH,+ FAILED_COLOR,+ FIELD_HEIGHT,+ columnDots,+ type Dot,+ type DotBand,+ type DotColumn,+} from "./dots";++interface DotFieldState {+ columns: readonly DotColumn[];+ max: number;+ band: DotBand | null;+ hover: number | null;+}++const DotFieldContext = createContext<DotFieldState | null>(null);++function useDotField(): DotFieldState {+ const state = useContext(DotFieldContext);+ if (!state) throw new Error("DotField parts must be rendered inside DotFieldRoot");+ return state;+}++export type DotFieldRootProps = ComponentProps<"div"> & {+ columns: readonly DotColumn[];+ band?: DotBand | null;+ hover?: number | null;+};++/** Positioned box sized to the dot grid. Overlays (cursors, brackets, hit areas) compose as children. */+export function DotFieldRoot({ columns, band = null, hover = null, className, style, ...props }: DotFieldRootProps) {+ const state = useMemo<DotFieldState>(+ () => ({ columns, max: Math.max(1, ...columns.map((column) => column.total)), band, hover }),+ [columns, band, hover],+ );+ return (+ <DotFieldContext.Provider value={state}>+ <div+ data-slot="dot-field"+ className={cn("relative", className)}+ style={{ height: FIELD_HEIGHT, ...style }}+ {...props}+ />+ </DotFieldContext.Provider>+ );+}++function dotColor(lit: boolean, dot: Dot, grid: string): string {+ if (!lit) return grid;+ if (dot.kind === "failed") return FAILED_COLOR;+ return dot.kind === "series" ? dot.color : grid;+}++function dotRadius(lit: boolean, hovered: boolean): number {+ if (!lit) return 0.9;+ return hovered ? 2.4 : 1.9;+}++function drawDots(canvas: HTMLCanvasElement, { columns, max, band, hover }: DotFieldState, progress: number) {+ const context = canvas.getContext("2d");+ const width = canvas.clientWidth;+ if (!context || width === 0) return;+ const ratio = window.devicePixelRatio || 1;+ canvas.width = Math.round(width * ratio);+ canvas.height = Math.round(FIELD_HEIGHT * ratio);+ context.setTransform(ratio, 0, 0, ratio, 0, 0);+ context.clearRect(0, 0, width, FIELD_HEIGHT);+ const grid = document.documentElement.classList.contains("dark") ? "rgba(255,255,255,0.08)" : "rgba(15,23,42,0.08)";+ const columnWidth = width / columns.length;+ const pitch = columnWidth / DOT_COLS;+ columns.forEach((column, i) => {+ const dots = columnDots(column, max, i * 7919 + column.total);+ const visible = Math.ceil(dots.length * progress);+ const dimmed = band !== null && (i < band.lo || i > band.hi);+ dots.forEach((dot, index) => {+ const lit = dot.kind !== "grid" && index < visible;+ context.globalAlpha = lit ? (dimmed ? 0.15 : 1) * (column.opacity ?? 1) : 1;+ context.fillStyle = dotColor(lit, dot, grid);+ context.beginPath();+ context.arc(+ i * columnWidth + pitch * ((index % DOT_COLS) + 0.5),+ FIELD_HEIGHT - DOT_PITCH * (Math.floor(index / DOT_COLS) + 0.5),+ dotRadius(lit, hover === i),+ 0,+ Math.PI * 2,+ );+ context.fill();+ });+ });+ context.globalAlpha = 1;+}++function useRiseIn(): number {+ const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");+ const [progress, setProgress] = useState(0);+ useEffect(() => {+ if (reduceMotion) {+ setProgress(1);+ return;+ }+ const start = performance.now();+ let frame = requestAnimationFrame(function rise(now) {+ const t = Math.min(1, (now - start) / 700);+ setProgress(1 - (1 - t) ** 3);+ if (t < 1) frame = requestAnimationFrame(rise);+ });+ return () => cancelAnimationFrame(frame);+ }, [reduceMotion]);+ return progress;+}++export type DotFieldCanvasProps = ComponentProps<"canvas">;++/** The dots themselves, painted on a canvas pinned to the bottom of the root. */+export function DotFieldCanvas({ className, style, ...props }: DotFieldCanvasProps) {+ const state = useDotField();+ const canvas = useRef<HTMLCanvasElement>(null);+ const progress = useRiseIn();+ const { width, height } = useResizeObserver({ ref: canvas as RefObject<HTMLCanvasElement> });+ useEffect(() => {+ if (canvas.current) drawDots(canvas.current, state, progress);+ }, [state, progress, width, height]);+ return (+ <canvas+ ref={canvas}+ data-slot="dot-field-canvas"+ aria-hidden="true"+ className={cn("pointer-events-none absolute inset-x-0 bottom-0 w-full", className)}+ style={{ height: FIELD_HEIGHT, ...style }}+ {...props}+ />+ );+}diff --git a/ui/litellm-dashboard/src/components/shared/dotField/dots.test.ts b/ui/litellm-dashboard/src/components/shared/dotField/dots.test.tsnew file mode 100644index 00000000000..a3471f0b02d--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/dotField/dots.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";++import { DOT_COLS, DOT_ROWS, NEUTRAL_COLOR, SERIES_COLORS, columnDots, litDots, seriesColor } from "./dots";++const capacity = DOT_ROWS * DOT_COLS;+const column = (total: number, failed = 0, series: string[] = []) => ({ total, failed, series });+const count = (dots: ReturnType<typeof columnDots>, kind: string) => dots.filter((dot) => dot.kind === kind).length;++describe("litDots", () => {+ it("lights nothing for an empty column and at least one full row for any items", () => {+ expect(litDots(0, 10)).toBe(0);+ expect(litDots(1, 1000)).toBe(DOT_COLS);+ });++ it("fills the busiest column and keeps quieter columns visible with square-root scaling", () => {+ expect(litDots(4, 4)).toBe(capacity);+ expect(litDots(1, 4)).toBe(capacity / 2);+ });+});++describe("columnDots", () => {+ it("always returns one dot per slot in the column", () => {+ expect(columnDots(column(0), 4, 1)).toHaveLength(capacity);+ expect(count(columnDots(column(0), 4, 1), "grid")).toBe(capacity);+ });++ it("puts failures above the successes", () => {+ const dots = columnDots(column(4, 1, ["a", "a", "a"]), 4, 3);+ const lastSeries = dots.findLastIndex((dot) => dot.kind === "series");+ const firstFailed = dots.findIndex((dot) => dot.kind === "failed");+ expect(firstFailed).toBeGreaterThan(lastSeries);+ expect(count(dots, "failed")).toBeGreaterThan(0);+ });++ it("colors successes by series in bands sized by each series' share", () => {+ const other = ["beta", "gamma", "delta", "omega", "zeta"].find(+ (name) => seriesColor(name) !== seriesColor("alpha"),+ );+ if (!other) throw new Error("palette maps every candidate to one color");+ const dots = columnDots(column(4, 0, ["alpha", "alpha", "alpha", other]), 4, 5);+ const colors = dots.flatMap((dot) => (dot.kind === "series" ? [dot.color] : []));+ const alpha = colors.filter((color) => color === seriesColor("alpha")).length;+ const beta = colors.filter((color) => color === seriesColor(other)).length;+ expect(alpha).toBeGreaterThan(beta * 2);+ expect(beta).toBeGreaterThan(0);+ });++ it("keeps the bottom row solid so even a single item reads as a mark", () => {+ const dots = columnDots(column(1, 0, ["a"]), 1000, 9);+ expect(dots.slice(0, DOT_COLS).every((dot) => dot.kind === "series")).toBe(true);+ });++ it("is deterministic for the same column and seed so the field does not flicker on re-render", () => {+ expect(columnDots(column(3, 1, ["a", "b"]), 4, 11)).toEqual(columnDots(column(3, 1, ["a", "b"]), 4, 11));+ });+});++describe("seriesColor", () => {+ it("gives each series a stable color from the palette", () => {+ expect(seriesColor("claude-code")).toBe(seriesColor("claude-code"));+ expect(SERIES_COLORS).toContain(seriesColor("claude-code"));+ });++ it("keeps an unnamed series neutral so it never looks like a named one", () => {+ expect(seriesColor("")).toBe(NEUTRAL_COLOR);+ expect(SERIES_COLORS).not.toContain(seriesColor(""));+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/dotField/dots.ts b/ui/litellm-dashboard/src/components/shared/dotField/dots.tsnew file mode 100644index 00000000000..5cfc4cf75af--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/dotField/dots.ts@@ -0,0 +1,57 @@+export const SERIES_COLORS = ["#0011b3", "#3b5bfd", "#7c93ff", "#22b3e8"] as const;+export const NEUTRAL_COLOR = "#94a3b8";+export const FAILED_COLOR = "#e5484d";+export const DOT_ROWS = 12;+export const DOT_COLS = 2;+export const DOT_PITCH = 6;+export const FIELD_HEIGHT = DOT_ROWS * DOT_PITCH;++export type Dot = { kind: "series"; color: string } | { kind: "failed" } | { kind: "grid" };++/** One column of the field: how many items it holds, how many failed, and the series name of each success. */+export interface DotColumn {+ total: number;+ failed: number;+ series: readonly string[];+ opacity?: number;+}++/** Column-index band [lo, hi], inclusive. Columns outside it are dimmed. */+export interface DotBand {+ lo: number;+ hi: number;+}++const hash = (seed: number, value: number): number => Math.imul(seed ^ Math.imul(value, 0x9e3779b1), 0x85ebca6b) >>> 0;++export function seriesColor(name: string): string {+ if (!name) return NEUTRAL_COLOR;+ const code = Array.from(name).reduce((total, char) => hash(total, char.charCodeAt(0)), 7);+ return SERIES_COLORS[code % SERIES_COLORS.length];+}++/** Lit dot count for a column: square-root scaled against the busiest column so sparse traffic still reads. */+export function litDots(total: number, max: number, capacity = DOT_ROWS * DOT_COLS): number {+ if (total === 0 || max === 0) return 0;+ return Math.max(DOT_COLS, Math.round(Math.sqrt(total / max) * capacity));+}++/**+ * Bottom-up dots for one column. Successes fill from the bottom in series-colored bands sized by each series'+ * share; failures sit on top. A stable sprinkle of gaps (seeded per column) keeps the field organic.+ */+export function columnDots(column: DotColumn, max: number, seed: number): readonly Dot[] {+ const capacity = DOT_ROWS * DOT_COLS;+ const lit = litDots(column.total, max, capacity);+ const failed =+ column.failed === 0 ? 0 : Math.min(lit, Math.max(DOT_COLS, Math.round((column.failed / column.total) * lit)));+ const ok = lit - failed;+ const series = column.series.length ? column.series : [""];+ return Array.from({ length: capacity }, (_, index): Dot => {+ if (index >= lit) return { kind: "grid" };+ const gap = index >= DOT_COLS && hash(seed + 1, index) % 100 < 12;+ if (gap) return { kind: "grid" };+ if (index >= ok) return { kind: "failed" };+ return { kind: "series", color: seriesColor(series[Math.floor((index / ok) * series.length)]) };+ });+}diff --git a/ui/litellm-dashboard/src/components/shared/search/SearchBox.test.tsx b/ui/litellm-dashboard/src/components/shared/search/SearchBox.test.tsxnew file mode 100644index 00000000000..97bc5f777fa--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/SearchBox.test.tsx@@ -0,0 +1,250 @@+import { render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { useEffect, useState } from "react";+import { describe, expect, it, vi } from "vitest";++import { NOTE_INDEX, type NoteField, NOTE_QUERY, notes } from "./__fixtures__/notes";+import { SearchBox } from "./SearchBox";+import type { SearchQuery } from "./searchQuery";+import { itemValues, type ValueSource } from "./valueSource";++/** A toy API: each filter becomes a flag, so the test can read the translation off the footer. */+function notesCli(query: SearchQuery<string>): string {+ const flags = [...query.text, ...query.filters.map((f) => `--${f.field}${f.op === "neq" ? "!" : ""}=${f.value}`)];+ return `notes ${flags.join(" ")}`.trim();+}++function NoteSearchWithHint({ value, onChange }: { value: string; onChange: (value: string) => void }) {+ return (+ <SearchBox.Root+ language={NOTE_QUERY}+ values={itemValues(NOTE_INDEX, notes)}+ value={value}+ onValueChange={onChange}+ label="Search notes"+ >+ <SearchBox.Input placeholder="Search notes" />+ <SearchBox.Suggestions>+ <SearchBox.CopyCommand title="The notes CLI takes the same flags" command={notesCli} />+ </SearchBox.Suggestions>+ </SearchBox.Root>+ );+}++function NoteSearch({+ value,+ onChange,+ values = itemValues(NOTE_INDEX, notes),+}: {+ value: string;+ onChange: (value: string) => void;+ values?: ValueSource<NoteField>;+}) {+ return (+ <SearchBox.Root language={NOTE_QUERY} values={values} value={value} onValueChange={onChange} label="Search notes">+ <SearchBox.Input placeholder="Search notes" />+ <SearchBox.Suggestions />+ </SearchBox.Root>+ );+}++function Harness({ initial = "" }: { initial?: string }) {+ const [value, setValue] = useState(initial);+ return (+ <>+ <NoteSearch value={value} onChange={setValue} />+ <button type="button" onClick={() => setValue("tag:cron")}>+ Load saved query+ </button>+ </>+ );+}++/** Delivers each emitted value only when asked, like a throttled URL. */+function LaggingHarness() {+ const [value, setValue] = useState("");+ const [queue, setQueue] = useState<string[]>([]);+ return (+ <>+ <NoteSearch value={value} onChange={(next) => setQueue((q) => [...q, next])} />+ <output aria-label="undelivered">{queue.join("|")}</output>+ <button+ type="button"+ onClick={() => {+ setValue(queue[0]);+ setQueue(queue.slice(1));+ }}+ >+ Deliver next+ </button>+ </>+ );+}++const box = () => screen.getByRole("combobox", { name: "Search notes" });+const undelivered = () => screen.getByRole("status", { name: "undelivered" });+const listbox = () => screen.getByRole("listbox", { name: "Search suggestions" });++describe("SearchBox", () => {+ it("builds a filter from the keyboard: field, then value", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ expect(screen.getByText("Search notes")).toBeVisible();+ await user.click(box());+ expect(box()).toHaveAttribute("aria-expanded", "true");+ await user.keyboard("-ta");+ expect(screen.queryByText("Search notes")).not.toBeInTheDocument();+ expect(+ within(listbox())+ .getAllByRole("option")+ .map((o) => o.textContent),+ ).toEqual(["tag"]);+ await user.keyboard("{Enter}");+ expect(box()).toHaveTextContent(/^-tag:$/, { normalizeWhitespace: false });+ expect(within(listbox()).getByRole("group", { name: "tag" })).toBeVisible();+ expect(within(listbox()).getByText("does not contain")).toBeVisible();++ await user.keyboard("{ArrowDown}");+ const cron = within(listbox()).getByRole("option", { name: "cron" });+ expect(cron).toHaveAttribute("aria-selected", "true");+ expect(box()).toHaveAttribute("aria-activedescendant", cron.id);+ await user.keyboard("{Enter}");+ expect(box()).toHaveTextContent(/^-tag:cron $/, {+ normalizeWhitespace: false,+ });+ expect(screen.queryByRole("listbox")).not.toBeInTheDocument();+ expect(box()).toHaveAttribute("aria-expanded", "false");+ });++ it("wraps arrow navigation and picks with Tab", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ await user.click(box());+ await user.keyboard("{ArrowUp}");+ expect(within(listbox()).getByRole("option", { name: "id" })).toHaveAttribute("aria-selected", "true");+ await user.keyboard("{ArrowDown}{ArrowDown}{Tab}");+ expect(box()).toHaveTextContent(/^tag:$/, { normalizeWhitespace: false });+ await user.keyboard("{ArrowDown}{ArrowDown}e");+ expect(within(listbox()).getByRole("option", { name: "researcher" })).toHaveAttribute("aria-selected", "true");+ });++ it("picks a suggestion with the mouse without losing focus", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ await user.click(box());+ await user.keyboard("tag:");+ await user.click(within(listbox()).getByRole("option", { name: "researcher" }));+ expect(box()).toHaveTextContent(/^tag:researcher $/, {+ normalizeWhitespace: false,+ });+ expect(box()).toHaveFocus();+ await user.keyboard("refund");+ expect(box()).toHaveTextContent(/^tag:researcher refund$/, {+ normalizeWhitespace: false,+ });+ });++ it("stays one line: Enter with no menu adds nothing, and Escape closes the menu until ArrowDown", async () => {+ const user = userEvent.setup();+ render(<Harness />);+ await user.click(box());+ await user.keyboard("refund{Enter}");+ expect(box()).toHaveTextContent(/^refund$/, { normalizeWhitespace: false });+ await user.keyboard(" {Escape}");+ expect(screen.queryByRole("listbox")).not.toBeInTheDocument();+ await user.keyboard("{ArrowDown}");+ expect(listbox()).toBeVisible();+ });++ it("emits the query once typing pauses, not per keystroke", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<NoteSearch value="" onChange={onChange} />);+ await user.click(box());+ await user.keyboard("refund");+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("refund"));+ expect(onChange).toHaveBeenCalledOnce();+ });++ it("keeps typing intact while the value it emitted arrives late", async () => {+ const user = userEvent.setup();+ render(<LaggingHarness />);+ await user.click(box());+ await user.keyboard("ab");+ await waitFor(() =>+ expect(undelivered()).toHaveTextContent(/^ab$/, {+ normalizeWhitespace: false,+ }),+ );+ await user.keyboard("c");+ await user.click(screen.getByRole("button", { name: "Deliver next" }));+ await user.click(box());+ await user.keyboard("d");+ expect(box()).toHaveTextContent(/^abcd$/, { normalizeWhitespace: false });+ await waitFor(() =>+ expect(undelivered()).toHaveTextContent(/^abcd$/, {+ normalizeWhitespace: false,+ }),+ );+ });++ it("shows a query set from outside, such as the URL", async () => {+ const user = userEvent.setup();+ render(<Harness initial="tag:triage" />);+ expect(box()).toHaveTextContent("tag:triage");+ await user.click(screen.getByRole("button", { name: "Load saved query" }));+ expect(box()).toHaveTextContent(/^tag:cron$/, {+ normalizeWhitespace: false,+ });+ });++ it("asks the value source for the field and prefix at the cursor, showing a loading row until it answers", async () => {+ const user = userEvent.setup();+ const asked: string[] = [];+ const facets: ValueSource<NoteField> = {+ useValues(field, prefix) {+ const [answer, setAnswer] = useState<readonly string[] | null>(null);+ useEffect(() => {+ if (field === null) return;+ asked.push(`${field}:${prefix}`);+ setAnswer(null);+ const timer = setTimeout(() => setAnswer(["remote-researcher", "remote-review"]), 20);+ return () => clearTimeout(timer);+ }, [field, prefix]);+ if (field === null) return { values: [], loading: false };+ return answer ? { values: answer, loading: false } : { values: [], loading: true };+ },+ };+ render(<NoteSearch value="" onChange={vi.fn()} values={facets} />);+ await user.click(box());+ await user.keyboard("body:x tag:re");+ expect(within(listbox()).getByRole("status")).toHaveTextContent("Loading values…");+ const option = await within(listbox()).findByRole("option", {+ name: "remote-researcher",+ });+ expect(within(listbox()).queryByRole("status")).not.toBeInTheDocument();+ await user.click(option);+ expect(box()).toHaveTextContent(/^body:x tag:remote-researcher $/, {+ normalizeWhitespace: false,+ });+ expect(asked).toEqual(["tag:", "tag:r", "tag:re"]);+ });++ it("copies the command for the current query from the footer and keeps the box open", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(<NoteSearchWithHint value="" onChange={onChange} />);+ expect(screen.queryByRole("button", { name: "Copy as curl" })).not.toBeInTheDocument();+ await user.click(box());+ expect(screen.getByTitle("The notes CLI takes the same flags")).toBeVisible();+ await user.keyboard("-tag:cr");+ await user.click(screen.getByRole("button", { name: "Copy as curl" }));+ expect(await navigator.clipboard.readText()).toBe("notes --tag!=cr");+ expect(screen.getByRole("button", { name: "Copied" })).toBeVisible();+ expect(box()).toHaveAttribute("aria-expanded", "true");+ await user.keyboard("o");+ expect(screen.getByRole("button", { name: "Copy as curl" })).toBeVisible();+ await user.click(screen.getByRole("button", { name: "Copy as curl" }));+ expect(await navigator.clipboard.readText()).toBe("notes --tag!=cro");+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/search/SearchBox.tsx b/ui/litellm-dashboard/src/components/shared/search/SearchBox.tsxnew file mode 100644index 00000000000..ad9b5268b60--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/SearchBox.tsx@@ -0,0 +1,389 @@+"use client";++import "prosemirror-view/style/prosemirror.css";++import { useDebouncedCallback } from "@tanstack/react-pacer/debouncer";+import { ProseMirror, ProseMirrorDoc, reactKeys, useEditorEventCallback } from "@handlewithcare/react-prosemirror";+import { Check, Copy, CornerDownLeft, type LucideIcon, Search } from "lucide-react";+import { Schema } from "prosemirror-model";+import { EditorState, Plugin, TextSelection, type Transaction } from "prosemirror-state";+import { Decoration, DecorationSet, type EditorView } from "prosemirror-view";+import { type ComponentProps, createContext, type ReactNode, useContext, useId, useMemo, useState } from "react";++import { Button } from "@/components/ui/button";+import { cn } from "@/lib/cva.config";++import { parseQuery, type QueryClause, type QueryLanguage } from "./language";+import { type SearchQuery, toSearchQuery } from "./searchQuery";+import { completingField, completingPrefix, suggest, type Suggestion, type SuggestionMenu } from "./suggestions";+import { NO_VALUES, type ValueSource } from "./valueSource";++const schema = new Schema({ nodes: { doc: { content: "text*" }, text: {} } });++const EMIT_WAIT_MS = 150;+const KEEP_MENU_CLOSED = "searchBoxKeepMenuClosed";++const OPERATORS = [+ { label: "equals", example: "foo:bar" },+ { label: "not equals", example: "-foo:bar" },+ { label: "wildcard match", example: "foo:*bar*" },+ { label: "does not contain", example: "-foo:*bar*" },+];++/** Colours each `key:` so the filters stand out from free text. */+function clauseHighlight<F extends string>(language: QueryLanguage<F>): Plugin {+ return new Plugin({+ props: {+ decorations(state) {+ const marks = parseQuery(language, state.doc.textContent).flatMap((clause) =>+ clause.kind === "field"+ ? [+ Decoration.inline(clause.from, clause.keyTo, {+ class: "text-info",+ }),+ Decoration.inline(clause.keyTo, clause.keyTo + 1, {+ class: "text-muted-foreground",+ }),+ ]+ : [],+ );+ return DecorationSet.create(state.doc, marks);+ },+ },+ });+}++const createState = <F extends string>(language: QueryLanguage<F>, text: string) =>+ EditorState.create({+ schema,+ doc: schema.node("doc", null, text ? schema.text(text) : []),+ plugins: [reactKeys(), clauseHighlight(language)],+ });++function applySuggestion(view: EditorView, item: Suggestion<string>) {+ const tr = view.state.tr.insertText(item.insert, item.from, item.to);+ tr.setSelection(TextSelection.create(tr.doc, item.from + item.insert.length));+ if (item.completesClause) tr.setMeta(KEEP_MENU_CLOSED, true);+ view.dispatch(tr);+}++interface SearchBoxState {+ readonly listId: string;+ readonly text: string;+ readonly clauses: readonly QueryClause<string>[];+ /** The menu while it is open, or null when closed. */+ readonly menu: SuggestionMenu<string> | null;+ readonly activeId: string | undefined;+ readonly icon: (field: string) => LucideIcon;+}++const SearchBoxContext = createContext<SearchBoxState | null>(null);++function useSearchBox(): SearchBoxState {+ const state = useContext(SearchBoxContext);+ if (!state) throw new Error("SearchBox parts must be rendered inside SearchBox.Root");+ return state;+}++export type SearchBoxRootProps<F extends string> = Omit<ComponentProps<"div">, "onChange"> & {+ language: QueryLanguage<F>;+ /** Where value suggestions come from: the loaded items, or a server lookup. */+ values: ValueSource<F>;+ value: string;+ onValueChange: (value: string) => void;+ /** Accessible name of the combobox. */+ label: string;+};++/** A one-line query editor: free text plus `key:value` filters. Owns the text, the menu and the keyboard. */+function Root<F extends string>({+ language,+ values,+ value,+ onValueChange,+ label,+ className,+ children,+ ...props+}: SearchBoxRootProps<F>) {+ const listId = useId();+ const [state, setState] = useState(() => createState(language, value));+ const [seenValue, setSeenValue] = useState(value);+ const [unechoed, setUnechoed] = useState<readonly string[]>([]);+ const [focused, setFocused] = useState(false);+ const [menuOpen, setMenuOpen] = useState(true);+ const [active, setActive] = useState(0);++ // `value` can trail the editor (the URL updates are throttled), so an echo of text we emitted is not an edit.+ if (value !== seenValue) {+ setSeenValue(value);+ const echo = unechoed.indexOf(value);+ if (echo >= 0) setUnechoed(unechoed.slice(echo + 1));+ else if (value !== state.doc.textContent) {+ setUnechoed([]);+ setState(createState(language, value));+ }+ }++ const { selection } = state;+ const text = state.doc.textContent;+ const clauses = useMemo(() => parseQuery(language, text), [language, text]);+ const completing = selection.empty ? completingField(language, text, selection.head) : null;+ const fetched = values.useValues(completing, completingPrefix(language, text, selection.head));+ const menu = useMemo(() => {+ if (!selection.empty) return null;+ return suggest(language, text, selection.head, (field) => (field === completing ? fetched : NO_VALUES));+ }, [language, text, selection, completing, fetched]);+ const options = menu?.groups.flatMap((group) => group.items) ?? [];+ const shownMenu = focused && menuOpen ? menu : null;+ const visible = shownMenu !== null;+ const activeItem = visible ? options[Math.min(active, options.length - 1)] : undefined;+ const context = useMemo<SearchBoxState>(+ () => ({+ listId,+ text,+ clauses,+ menu: shownMenu,+ activeId: activeItem?.id,+ icon: (field) => language.fields[field as F].icon,+ }),+ [listId, text, clauses, shownMenu, activeItem, language],+ );++ const emit = useDebouncedCallback(+ (next: string) => {+ setUnechoed((current) => [...current, next]);+ onValueChange(next);+ },+ { wait: EMIT_WAIT_MS },+ );++ const dispatchTransaction = (tr: Transaction) => {+ setState((current) => current.apply(tr));+ if (tr.selectionSet || tr.docChanged) setActive(0);+ if (!tr.docChanged) return;+ setMenuOpen(!tr.getMeta(KEEP_MENU_CLOSED));+ emit(tr.doc.textContent);+ };++ const handleKeyDown = (view: EditorView, event: KeyboardEvent): boolean => {+ if (event.key === "Escape" && visible) {+ setMenuOpen(false);+ return true;+ }+ if (event.key === "ArrowDown" && !visible) {+ setMenuOpen(true);+ return true;+ }+ if ((event.key === "ArrowDown" || event.key === "ArrowUp") && options.length > 0) {+ const step = event.key === "ArrowDown" ? 1 : -1;+ setActive((Math.min(active, options.length - 1) + step + options.length) % options.length);+ return true;+ }+ if ((event.key === "Enter" || event.key === "Tab") && activeItem) {+ applySuggestion(view, activeItem);+ return true;+ }+ return false;+ };++ return (+ <ProseMirror+ state={state}+ dispatchTransaction={dispatchTransaction}+ handleKeyDown={handleKeyDown}+ handleDOMEvents={{+ focus: () => {+ setFocused(true);+ setMenuOpen(true);+ return false;+ },+ blur: () => {+ setFocused(false);+ return false;+ },+ }}+ transformPastedText={(pasted) => pasted.replace(/\s+/g, " ")}+ attributes={{+ role: "combobox",+ "aria-label": label,+ "aria-autocomplete": "list",+ "aria-expanded": String(visible),+ "aria-controls": listId,+ ...(activeItem && {+ "aria-activedescendant": `${listId}-${activeItem.id}`,+ }),+ spellcheck: "false",+ class: "min-w-0 flex-1 overflow-x-auto py-1.5 font-mono text-xs whitespace-pre outline-none",+ }}+ >+ <SearchBoxContext.Provider value={context}>+ <div data-slot="search-box" className={cn("relative w-full flex-1", className)} {...props}>+ {children}+ </div>+ </SearchBoxContext.Provider>+ </ProseMirror>+ );+}++export type SearchBoxInputProps = ComponentProps<"div"> & {+ placeholder: string;+};++/** The bordered field holding the editor; shows `placeholder` while the query is empty. */+function Input({ placeholder, className, ...props }: SearchBoxInputProps) {+ const { text } = useSearchBox();+ return (+ <div+ data-slot="search-box-input"+ className={cn(+ "flex h-8 items-center gap-2 rounded-md border border-input bg-transparent px-2.5 focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 dark:bg-input/30",+ className,+ )}+ {...props}+ >+ <Search className="size-3.5 shrink-0 text-muted-foreground" />+ <div className="relative flex min-w-0 flex-1">+ <ProseMirrorDoc />+ {!text && (+ <span className="pointer-events-none absolute inset-y-0 left-0 flex items-center font-mono text-xs text-muted-foreground">+ {placeholder}+ </span>+ )}+ </div>+ </div>+ );+}++export type SearchBoxSuggestionsProps = ComponentProps<"div">;++/**+ * The autocomplete listbox under the input: fields, then values, with operator help and key hints.+ * `children` render in the footer beside the key hints, e.g. a `CopyCommand`.+ */+function Suggestions({ className, children, ...props }: SearchBoxSuggestionsProps) {+ const { listId, menu, activeId, icon } = useSearchBox();+ const pick = useEditorEventCallback((view, item: Suggestion<string>) => applySuggestion(view, item));+ if (!menu) return null;+ return (+ <div+ data-slot="search-box-suggestions"+ className={cn(+ "absolute top-full left-0 z-floating mt-1 w-full max-w-xl overflow-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-md",+ className,+ )}+ {...props}+ >+ <div id={listId} role="listbox" aria-label="Search suggestions" className="max-h-80 overflow-y-auto p-1">+ {menu.groups.map((group) => (+ <div key={group.heading} role="group" aria-label={group.heading}>+ <div className="px-2 pt-2 pb-1 text-xs text-muted-foreground">{group.heading}</div>+ {group.items.map((item) => {+ const Icon = icon(item.field);+ return (+ <div+ key={item.id}+ id={`${listId}-${item.id}`}+ role="option"+ aria-selected={item.id === activeId}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => pick(item)}+ className="flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 font-mono text-xs aria-selected:bg-accent aria-selected:text-accent-foreground"+ >+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate">{item.label}</span>+ </div>+ );+ })}+ </div>+ ))}+ {menu.loading && (+ <div role="status" className="px-2 py-1.5 font-mono text-xs text-muted-foreground">+ Loading values…+ </div>+ )}+ {menu.showOperators && <OperatorHints />}+ </div>+ <div className="flex items-center gap-3 border-t border-border px-3 py-2 text-xs text-muted-foreground">+ <span className="flex items-center gap-1">+ <Kbd>↑</Kbd>+ <Kbd>↓</Kbd>+ Navigate+ </span>+ <span className="flex items-center gap-1">+ <Kbd>+ <CornerDownLeft className="size-3" />+ </Kbd>+ Select+ </span>+ {children}+ </div>+ </div>+ );+}++export type SearchBoxCopyCommandProps<F extends string> = {+ /** Explains what gets copied; shown on hover. */+ title: string;+ /** The runnable command for the current query. */+ command: (query: SearchQuery<F>) => string;+};++type CopyOutcome = { readonly command: string; readonly outcome: "copied" | "failed" } | null;++const copyLabel = (last: CopyOutcome, command: string): string => {+ if (last?.command !== command) return "Copy as curl";+ return last.outcome === "copied" ? "Copied" : "Copy failed";+};++/** Puts the current query on the clipboard as an API call, from the suggestions footer. */+function CopyCommand<F extends string>({ title, command }: SearchBoxCopyCommandProps<F>) {+ const { clauses } = useSearchBox();+ const [last, setLast] = useState<CopyOutcome>(null);+ const current = useMemo(() => command(toSearchQuery(clauses as readonly QueryClause<F>[])), [command, clauses]);+ const copy = () =>+ navigator.clipboard.writeText(current).then(+ () => setLast({ command: current, outcome: "copied" }),+ () => setLast({ command: current, outcome: "failed" }),+ );+ const label = copyLabel(last, current);+ return (+ <Button+ type="button"+ variant="ghost"+ size="xs"+ title={title}+ data-slot="search-box-copy-command"+ className="ml-auto shrink-0"+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => void copy()}+ >+ {label === "Copied" ? <Check /> : <Copy />}+ {label}+ </Button>+ );+}++function OperatorHints() {+ return (+ <div className="pb-1">+ <div className="px-2 pt-2 pb-1 text-xs text-muted-foreground">Comparison operators</div>+ {OPERATORS.map((op) => (+ <div key={op.label} className="flex items-center justify-between px-2 py-1 font-mono text-xs">+ <span className="text-warning">{op.label}</span>+ <code className="rounded bg-muted px-1.5 text-muted-foreground">{op.example}</code>+ </div>+ ))}+ </div>+ );+}++function Kbd({ children }: { children: ReactNode }) {+ return (+ <kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded border border-border px-1 font-sans">+ {children}+ </kbd>+ );+}++export const SearchBox = { Root, Input, Suggestions, CopyCommand } as const;diff --git a/ui/litellm-dashboard/src/components/shared/search/__fixtures__/notes.ts b/ui/litellm-dashboard/src/components/shared/search/__fixtures__/notes.tsnew file mode 100644index 00000000000..a745233e764--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/__fixtures__/notes.ts@@ -0,0 +1,47 @@+import { Braces, Hash, Tag, Type } from "lucide-react";++import type { ClientIndex } from "../evaluate";+import type { FieldSpec, QueryLanguage } from "../language";++export interface Note {+ readonly id: string;+ readonly title: string;+ readonly tags: readonly string[];+ readonly body: string;+}++const NOTE_FIELDS = {+ title: { group: "Note", icon: Type, suggestValues: true },+ tag: { group: "Note", icon: Tag, suggestValues: true },+ body: { group: "Content", icon: Braces, suggestValues: false },+ id: { group: "Identity", icon: Hash, suggestValues: false },+} as const satisfies Record<string, FieldSpec>;++export type NoteField = keyof typeof NOTE_FIELDS;++export const NOTE_QUERY: QueryLanguage<NoteField> = { fields: NOTE_FIELDS };++export const NOTE_INDEX: ClientIndex<Note, NoteField> = {+ read: {+ title: (note) => [note.title],+ tag: (note) => note.tags,+ body: (note) => [note.body],+ id: (note) => [note.id],+ },+ freeText: (note) => [note.id, note.body, note.title],+};++export const note = (overrides: Partial<Note>): Note => ({+ id: "note",+ title: "note",+ tags: [],+ body: "",+ ...overrides,+});++const refundOverrides = { id: "aaa111", title: "support", body: "Where is my refund?", tags: ["billing", "triage"] };+const refund = note(refundOverrides);+const researchOverrides = { id: "bbb222", title: "research_lead", body: "Compare vector stores", tags: ["researcher"] };+const research = note(researchOverrides);+const plain = note({ id: "ccc333", title: "health", tags: ["cron"] });+export const notes = [refund, research, plain];diff --git a/ui/litellm-dashboard/src/components/shared/search/evaluate.test.ts b/ui/litellm-dashboard/src/components/shared/search/evaluate.test.tsnew file mode 100644index 00000000000..c67824514a9--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/evaluate.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vitest";++import { note, NOTE_INDEX, NOTE_QUERY, notes } from "./__fixtures__/notes";+import { evaluate, fieldValues, filterItems } from "./evaluate";++const ids = (text: string) => filterItems(NOTE_QUERY, NOTE_INDEX, notes, text).map((n) => n.id);++describe("evaluate", () => {+ it("returns the same array for an empty query", () => {+ expect(evaluate(NOTE_INDEX, notes, { text: [], filters: [] })).toBe(notes);+ });++ it("applies each op the way the wire contract defines it", () => {+ const by = (op: "eq" | "neq" | "glob" | "nglob", value: string) =>+ evaluate(NOTE_INDEX, notes, { text: [], filters: [{ field: "tag", op, value }] }).map((n) => n.id);+ expect(by("eq", "TRIAGE")).toEqual(["aaa111"]);+ expect(by("eq", "tri")).toEqual([]);+ expect(by("neq", "triage")).toEqual(["bbb222", "ccc333"]);+ expect(by("glob", "*search*")).toEqual(["bbb222"]);+ expect(by("nglob", "*search*")).toEqual(["aaa111", "ccc333"]);+ });++ it("requires every term and every filter", () => {+ expect(+ evaluate(NOTE_INDEX, notes, { text: ["refund"], filters: [{ field: "tag", op: "eq", value: "billing" }] }),+ ).toHaveLength(1);+ expect(+ evaluate(NOTE_INDEX, notes, { text: ["refund"], filters: [{ field: "tag", op: "eq", value: "cron" }] }),+ ).toHaveLength(0);+ expect(evaluate(NOTE_INDEX, notes, { text: ["vector", "refund"], filters: [] })).toHaveLength(0);+ });+});++describe("filterItems", () => {+ it("matches free text against the index's free-text fields only, ignoring case", () => {+ expect(ids("REFUND")).toEqual(["aaa111"]);+ expect(ids("ccc3")).toEqual(["ccc333"]);+ expect(ids("billing")).toEqual([]);+ expect(ids('"my refund"')).toEqual(["aaa111"]);+ expect(ids('"refund my"')).toEqual([]);+ });++ it("matches a multi-valued field when any value matches, and negation when none does", () => {+ expect(ids("tag:triage")).toEqual(["aaa111"]);+ expect(ids("-tag:triage")).toEqual(["bbb222", "ccc333"]);+ expect(ids("-tag:*search*")).toEqual(["aaa111", "ccc333"]);+ });++ it("searches quoted values with spaces in a free-form field and combines with free text", () => {+ expect(ids('body:"*vector stores"')).toEqual(["bbb222"]);+ expect(ids("tag:*e* -tag:researcher refund")).toEqual(["aaa111"]);+ });++ it("ignores a key still waiting for its value and treats unknown keys as text", () => {+ expect(ids("tag:")).toEqual(["aaa111", "bbb222", "ccc333"]);+ expect(ids("refund tag:")).toEqual(["aaa111"]);+ expect(ids("foo:bar")).toEqual([]);+ expect(filterItems(NOTE_QUERY, NOTE_INDEX, [note({ title: "foo:bar" })], "foo:bar")).toHaveLength(1);+ });+});++describe("fieldValues", () => {+ it("lists each distinct non-empty value once, sorted", () => {+ expect(fieldValues(NOTE_INDEX, notes, "tag")).toEqual(["billing", "cron", "researcher", "triage"]);+ expect(fieldValues(NOTE_INDEX, [...notes, note({ title: "" })], "title")).toEqual([+ "health",+ "research_lead",+ "support",+ ]);+ expect(fieldValues(NOTE_INDEX, [note({ tags: [] })], "tag")).toEqual([]);+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/search/evaluate.ts b/ui/litellm-dashboard/src/components/shared/search/evaluate.tsnew file mode 100644index 00000000000..6c14b9979cd--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/evaluate.ts@@ -0,0 +1,42 @@+import { parseQuery, type QueryLanguage, valueMatcher } from "./language";+import { type SearchFilter, type SearchQuery, toSearchQuery } from "./searchQuery";++/** How to read a language's fields off items already in memory. */+export interface ClientIndex<T, F extends string> {+ readonly read: Readonly<Record<F, (item: T) => readonly string[]>>;+ /** What a bare word searches. */+ readonly freeText: (item: T) => readonly string[];+}++function matchesFilter<T, F extends string>(index: ClientIndex<T, F>, item: T, filter: SearchFilter<F>): boolean {+ const matches = index.read[filter.field](item).some(valueMatcher(filter.value));+ return filter.op === "neq" || filter.op === "nglob" ? !matches : matches;+}++function matchesText<T, F extends string>(index: ClientIndex<T, F>, item: T, term: string): boolean {+ const needle = term.toLowerCase();+ return index.freeText(item).some((text) => text.toLowerCase().includes(needle));+}++/** The in-memory counterpart of a server search: every term and filter of `query` must hold. */+export function evaluate<T, F extends string>(index: ClientIndex<T, F>, items: T[], query: SearchQuery<F>): T[] {+ if (query.text.length === 0 && query.filters.length === 0) return items;+ return items.filter(+ (item) =>+ query.text.every((term) => matchesText(index, item, term)) &&+ query.filters.every((filter) => matchesFilter(index, item, filter)),+ );+}++export const filterItems = <T, F extends string>(+ language: QueryLanguage<F>,+ index: ClientIndex<T, F>,+ items: T[],+ text: string,+): T[] => evaluate(index, items, toSearchQuery(parseQuery(language, text)));++export function fieldValues<T, F extends string>(index: ClientIndex<T, F>, items: readonly T[], field: F): string[] {+ return Array.from(new Set(items.flatMap((item) => index.read[field](item))))+ .filter(Boolean)+ .sort();+}diff --git a/ui/litellm-dashboard/src/components/shared/search/language.test.ts b/ui/litellm-dashboard/src/components/shared/search/language.test.tsnew file mode 100644index 00000000000..60d3e459188--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/language.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";++import { NOTE_QUERY } from "./__fixtures__/notes";+import { parseQuery, valueMatcher } from "./language";++describe("parseQuery", () => {+ it("splits clauses on whitespace, keeps quoted stretches, and only promotes known keys to fields", () => {+ expect(parseQuery(NOTE_QUERY, 'refund -Tag:"a b" foo:bar tag:')).toEqual([+ { kind: "text", value: "refund", from: 0, to: 6 },+ { kind: "field", field: "tag", negated: true, keyTo: 11, value: "a b", from: 7, to: 17 },+ { kind: "text", value: "foo:bar", from: 18, to: 25 },+ { kind: "field", field: "tag", negated: false, keyTo: 29, value: "", from: 26, to: 30 },+ ]);+ });+});++describe("valueMatcher", () => {+ it("requires a whole-value match, ignoring case, unless the pattern has wildcards", () => {+ expect(valueMatcher("billing")("BILLING")).toBe(true);+ expect(valueMatcher("bill")("billing")).toBe(false);+ expect(valueMatcher("*bill*")("research-billing-agent")).toBe(true);+ expect(valueMatcher("bill*")("billing")).toBe(true);+ expect(valueMatcher("*age")("triage")).toBe(true);+ expect(valueMatcher("res.arch")("research")).toBe(false);+ });++ it("matches glob segments in order without overlapping the exact anchors", () => {+ expect(valueMatcher("a*a")("aa")).toBe(true);+ expect(valueMatcher("a*a")("a")).toBe(false);+ expect(valueMatcher("**")("x")).toBe(valueMatcher("*")("x"));+ expect(valueMatcher("a*b*c")("a-c-b-c")).toBe(true);+ expect(valueMatcher("a*c*b")("a-c-b-c")).toBe(false);+ });++ it("matches adversarial globs without catastrophic backtracking", () => {+ const startedAt = performance.now();+ const matched = valueMatcher(`${"a*".repeat(30)}b`)("a".repeat(5000));+ expect(matched).toBe(false);+ expect(performance.now() - startedAt).toBeLessThan(100);+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/search/language.ts b/ui/litellm-dashboard/src/components/shared/search/language.tsnew file mode 100644index 00000000000..9200d96a10a--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/language.ts@@ -0,0 +1,89 @@+import type { LucideIcon } from "lucide-react";++export interface FieldSpec {+ readonly group: string;+ readonly icon: LucideIcon;+ /** The field has an enumerable value set worth offering once the key has its colon. */+ readonly suggestValues: boolean;+}++/** The `key:value` vocabulary of one search box. Where the data lives is the evaluator's concern, not the language's. */+export interface QueryLanguage<F extends string> {+ readonly fields: Readonly<Record<F, FieldSpec>>;+}++interface Span {+ readonly from: number;+ readonly to: number;+}++export type QueryClause<F extends string> =+ | (Span & { readonly kind: "text"; readonly value: string })+ | (Span & {+ readonly kind: "field";+ readonly field: F;+ readonly negated: boolean;+ readonly keyTo: number;+ readonly value: string;+ });++export type FieldClause<F extends string> = Extract<QueryClause<F>, { kind: "field" }>;++export const languageFields = <F extends string>(language: QueryLanguage<F>): F[] =>+ Object.keys(language.fields) as F[];++const unquote = (raw: string): string => raw.replace(/^"([^"]*)"?$/, "$1");++/** Whitespace-separated tokens; a double-quoted stretch keeps its spaces. */+function tokenize(text: string): (Span & { raw: string })[] {+ return Array.from(text.matchAll(/(?:"[^"]*"?|\S)+/g), (match) => ({+ raw: match[0],+ from: match.index,+ to: match.index + match[0].length,+ }));+}++function parseToken<F extends string>(+ language: QueryLanguage<F>,+ { raw, from, to }: Span & { raw: string },+): QueryClause<F> {+ const match = /^(-?)([A-Za-z_]+):(.*)$/.exec(raw);+ const key = match?.[2].toLowerCase() ?? "";+ if (!match || !Object.hasOwn(language.fields, key)) return { kind: "text", value: unquote(raw), from, to };+ return {+ kind: "field",+ field: key as F,+ negated: match[1] === "-",+ keyTo: from + match[1].length + match[2].length,+ value: unquote(match[3]),+ from,+ to,+ };+}++export const parseQuery = <F extends string>(language: QueryLanguage<F>, text: string): QueryClause<F>[] =>+ tokenize(text).map((token) => parseToken(language, token));++/** `bar` matches the whole value, `*bar*` is a glob; both ignore case. */+export function valueMatcher(pattern: string): (value: string) => boolean {+ const needle = pattern.toLowerCase();+ if (!needle.includes("*")) return (value) => value.toLowerCase() === needle;+ const segments = needle.split("*");+ const first = segments[0];+ const last = segments.at(-1);+ const middle = segments.slice(1, -1).filter(Boolean);+ return (value) => {+ const candidate = value.toLowerCase();+ if (first && !candidate.startsWith(first)) return false;+ if (last && !candidate.endsWith(last)) return false;+ const suffixStart = last ? candidate.length - last.length : candidate.length;+ let cursor = first ? first.length : 0;+ if (suffixStart < cursor) return false;+ for (const segment of middle) {+ const found = candidate.indexOf(segment, cursor);+ if (found < 0 || found + segment.length > suffixStart) return false;+ cursor = found + segment.length;+ }+ return true;+ };+}diff --git a/ui/litellm-dashboard/src/components/shared/search/searchQuery.test.ts b/ui/litellm-dashboard/src/components/shared/search/searchQuery.test.tsnew file mode 100644index 00000000000..2a37adede45--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/searchQuery.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";++import { NOTE_QUERY } from "./__fixtures__/notes";+import { parseQuery } from "./language";+import { toSearchQuery } from "./searchQuery";++const query = (text: string) => toSearchQuery(parseQuery(NOTE_QUERY, text));++describe("toSearchQuery", () => {+ it("turns clauses into terms and typed filters, choosing the op from negation and wildcards", () => {+ expect(query('refund "vector stores" tag:cron -tag:*bill* title:*lead -id:aaa111')).toEqual({+ text: ["refund", "vector stores"],+ filters: [+ { field: "tag", op: "eq", value: "cron" },+ { field: "tag", op: "nglob", value: "*bill*" },+ { field: "title", op: "glob", value: "*lead" },+ { field: "id", op: "neq", value: "aaa111" },+ ],+ });+ });++ it("drops a key still waiting for its value and empty quoted terms, so typing never blanks the list", () => {+ expect(query('tag: -title: ""')).toEqual({ text: [], filters: [] });+ expect(query("refund tag:")).toEqual({ text: ["refund"], filters: [] });+ });++ it("keeps an unknown key as free text", () => {+ expect(query("foo:bar")).toEqual({ text: ["foo:bar"], filters: [] });+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/search/searchQuery.ts b/ui/litellm-dashboard/src/components/shared/search/searchQuery.tsnew file mode 100644index 00000000000..397901dc21f--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/searchQuery.ts@@ -0,0 +1,35 @@+import type { QueryClause } from "./language";++export type FilterOp = "eq" | "neq" | "glob" | "nglob";++export interface SearchFilter<F extends string> {+ readonly field: F;+ readonly op: FilterOp;+ readonly value: string;+}++/**+ * The wire shape of a query: what a server or the client evaluator consumes.+ * `eq` is a case-insensitive whole-value match; `glob` treats `*` as a wildcard; the `n` forms negate.+ * Every text term and every filter must hold.+ */+export interface SearchQuery<F extends string> {+ readonly text: readonly string[];+ readonly filters: readonly SearchFilter<F>[];+}++const filterOp = (negated: boolean, value: string): FilterOp => {+ if (value.includes("*")) return negated ? "nglob" : "glob";+ return negated ? "neq" : "eq";+};++/** A key typed without a value yet narrows nothing, so the list does not blank out mid-typing. */+export function toSearchQuery<F extends string>(clauses: readonly QueryClause<F>[]): SearchQuery<F> {+ const text = clauses.flatMap((clause) => (clause.kind === "text" && clause.value ? [clause.value] : []));+ const filters = clauses.flatMap((clause) =>+ clause.kind === "field" && clause.value+ ? [{ field: clause.field, op: filterOp(clause.negated, clause.value), value: clause.value }]+ : [],+ );+ return { text, filters };+}diff --git a/ui/litellm-dashboard/src/components/shared/search/suggestions.test.ts b/ui/litellm-dashboard/src/components/shared/search/suggestions.test.tsnew file mode 100644index 00000000000..1e1dedd30bf--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/suggestions.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from "vitest";++import { type Note, note, NOTE_INDEX, type NoteField, NOTE_QUERY, notes } from "./__fixtures__/notes";+import { fieldValues } from "./evaluate";+import { completingField, completingPrefix, suggest, type Suggestion, type SuggestionMenu } from "./suggestions";+import type { FieldValues } from "./valueSource";++const lookupIn =+ (source: readonly Note[]) =>+ (field: NoteField): FieldValues => ({ values: fieldValues(NOTE_INDEX, source, field), loading: false });+const at = (text: string, cursor: number, source = notes) => suggest(NOTE_QUERY, text, cursor, lookupIn(source));+const atEnd = (text: string, source = notes) => at(text, text.length, source);+const items = (menu: SuggestionMenu<NoteField> | null): Suggestion<NoteField>[] =>+ menu?.groups.flatMap((g) => g.items) ?? [];+const labels = (menu: SuggestionMenu<NoteField> | null) => items(menu).map((item) => item.label);+const apply = (text: string, item: Suggestion<NoteField>) =>+ text.slice(0, item.from) + item.insert + text.slice(item.to);++describe("suggest", () => {+ it("offers every field, grouped in declaration order, in an empty box", () => {+ const menu = atEnd("");+ expect(menu?.groups.map((g) => g.heading)).toEqual(["Note", "Content", "Identity"]);+ expect(labels(menu)).toEqual(["title", "tag", "body", "id"]);+ expect(menu?.showOperators).toBe(false);+ });++ it("narrows fields by the typed prefix and completes the key with a colon", () => {+ const menu = atEnd("refund TA");+ expect(labels(menu)).toEqual(["tag"]);+ expect(apply("refund TA", items(menu)[0])).toBe("refund tag:");+ expect(items(menu)[0].completesClause).toBe(false);+ });++ it("keeps a leading minus when completing a negated key", () => {+ expect(apply("-ta", items(atEnd("-ta"))[0])).toBe("-tag:");+ });++ it("offers nothing for free text that names no field", () => {+ expect(atEnd("refund")).toBeNull();+ expect(atEnd("foo:bar")).toBeNull();+ });++ it("offers the source's values and the operator help once a key has its colon", () => {+ const menu = atEnd("tag:");+ expect(menu?.groups.map((g) => g.heading)).toEqual(["tag"]);+ expect(labels(menu)).toEqual(["billing", "cron", "researcher", "triage"]);+ expect(items(menu).every((item) => item.field === "tag")).toBe(true);+ expect(menu?.showOperators).toBe(true);+ });++ it("narrows values by substring, ignoring wildcards, and drops operator help once a value is typed", () => {+ const menu = atEnd("-tag:*AR*");+ expect(labels(menu)).toEqual(["researcher"]);+ expect(menu?.showOperators).toBe(false);+ expect(atEnd("tag:zzz")).toBeNull();+ });++ it("keeps the menu open while values load, and closes it once an empty answer arrives", () => {+ const loading = suggest(NOTE_QUERY, "tag:zzz", 7, () => ({ values: [], loading: true }));+ expect(loading).toEqual({ groups: [], showOperators: false, loading: true });+ expect(suggest(NOTE_QUERY, "tag:zzz", 7, () => ({ values: [], loading: false }))).toBeNull();+ });++ it("replaces only the value, adds a separating space at the end, and finishes the clause", () => {+ const item = items(atEnd("-tag:bil"))[0];+ expect(apply("-tag:bil", item)).toBe("-tag:billing ");+ expect(item.completesClause).toBe(true);+ const text = "tag:tri refund";+ expect(apply(text, items(at(text, 7))[0])).toBe("tag:triage refund");+ });++ it("quotes a value that contains spaces", () => {+ const spaced = [note({ title: "Order lookup" })];+ expect(apply("title:", items(atEnd("title:", spaced))[0])).toBe('title:"Order lookup" ');+ });++ it("never asks the source for a free-form field, but still explains the operators", () => {+ const asked: NoteField[] = [];+ const menu = suggest(NOTE_QUERY, "body:", 5, (field) => {+ asked.push(field);+ return { values: ["leak"], loading: false };+ });+ expect(asked).toEqual([]);+ expect(menu?.groups).toEqual([]);+ expect(menu?.showOperators).toBe(true);+ expect(atEnd("body:x")).toBeNull();+ });++ it("offers fields in the gap between tokens, but nothing mid-token", () => {+ const text = "refund tag:cron";+ expect(apply(text, items(at(text, 7))[1])).toBe("refund tag: tag:cron");+ expect(at(text, 3)).toBeNull();+ expect(at("tag:cron", 0)).toBeNull();+ });+});++describe("completingField", () => {+ it("names the enumerable field whose value sits at the cursor, with the typed prefix", () => {+ expect(completingField(NOTE_QUERY, "refund -tag:*bi", 15)).toBe("tag");+ expect(completingPrefix(NOTE_QUERY, "refund -tag:*bi", 15)).toBe("bi");+ expect(completingField(NOTE_QUERY, "tag:cron refund", 15)).toBeNull();+ expect(completingField(NOTE_QUERY, "tag:cron", 2)).toBeNull();+ expect(completingField(NOTE_QUERY, "body:x", 6)).toBeNull();+ expect(completingPrefix(NOTE_QUERY, "ta", 2)).toBe("");+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/search/suggestions.ts b/ui/litellm-dashboard/src/components/shared/search/suggestions.tsnew file mode 100644index 00000000000..fd06dae96fc--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/suggestions.ts@@ -0,0 +1,132 @@+import { type FieldClause, languageFields, parseQuery, type QueryLanguage } from "./language";+import type { FieldValues } from "./valueSource";++export interface Suggestion<F extends string> {+ readonly id: string;+ readonly label: string;+ readonly field: F;+ /** Replaces `text.slice(from, to)`. */+ readonly from: number;+ readonly to: number;+ readonly insert: string;+ /** A value finishes the clause and closes the menu; a field keeps it open for its values. */+ readonly completesClause: boolean;+}++export interface SuggestionGroup<F extends string> {+ readonly heading: string;+ readonly items: readonly Suggestion<F>[];+}++export interface SuggestionMenu<F extends string> {+ readonly groups: readonly SuggestionGroup<F>[];+ readonly showOperators: boolean;+ /** Values are still on their way from the source. */+ readonly loading: boolean;+}++type Target<F extends string> =+ | {+ readonly kind: "field";+ readonly prefix: string;+ readonly negated: boolean;+ readonly from: number;+ readonly to: number;+ }+ | { readonly kind: "value"; readonly clause: FieldClause<F> };++const MAX_VALUES = 50;+const isSpace = (char: string | undefined) => char === undefined || /\s/.test(char);+const quoteIfNeeded = (value: string) => (/[\s"]/.test(value) ? `"${value.replaceAll('"', "")}"` : value);++function target<F extends string>(language: QueryLanguage<F>, text: string, cursor: number): Target<F> | null {+ const clause = parseQuery(language, text).find((c) => c.from < cursor && c.to === cursor);+ if (!clause) {+ const betweenTokens = isSpace(text[cursor - 1]) && isSpace(text[cursor]);+ return betweenTokens ? { kind: "field", prefix: "", negated: false, from: cursor, to: cursor } : null;+ }+ if (clause.kind === "field") return { kind: "value", clause };+ const raw = text.slice(clause.from, clause.to);+ const negated = raw.startsWith("-");+ const prefix = negated ? raw.slice(1) : raw;+ if (/[:"]/.test(prefix)) return null;+ return { kind: "field", prefix, negated, from: clause.from, to: clause.to };+}++/** The field whose value is being typed at the cursor, so a source can be asked for its values. */+export function completingField<F extends string>(language: QueryLanguage<F>, text: string, cursor: number): F | null {+ const found = target(language, text, cursor);+ return found?.kind === "value" && language.fields[found.clause.field].suggestValues ? found.clause.field : null;+}++/** The substring typed so far for the value at the cursor, wildcards stripped. */+export function completingPrefix<F extends string>(language: QueryLanguage<F>, text: string, cursor: number): string {+ const found = target(language, text, cursor);+ return found?.kind === "value" ? found.clause.value.replaceAll("*", "") : "";+}++function fieldMenu<F extends string>(+ language: QueryLanguage<F>,+ { prefix, negated, from, to }: Extract<Target<F>, { kind: "field" }>,+): SuggestionMenu<F> | null {+ const fields = languageFields(language).filter((field) => field.startsWith(prefix.toLowerCase()));+ if (fields.length === 0) return null;+ const groups = Array.from(new Set(fields.map((field) => language.fields[field].group)), (heading) => ({+ heading,+ items: fields+ .filter((field) => language.fields[field].group === heading)+ .map((field) => ({+ id: `field:${field}`,+ label: field,+ field,+ from,+ to,+ insert: `${negated ? "-" : ""}${field}:`,+ completesClause: false,+ })),+ }));+ return { groups, showOperators: false, loading: false };+}++function valueMenu<F extends string>(+ clause: FieldClause<F>,+ text: string,+ { values, loading }: FieldValues,+): SuggestionMenu<F> | null {+ const from = clause.keyTo + 1;+ const needle = clause.value.replaceAll("*", "").toLowerCase();+ const trailing = clause.to === text.length ? " " : "";+ const suggestions = values+ .filter((value) => value.toLowerCase().includes(needle))+ .slice(0, MAX_VALUES)+ .map((value) => ({+ id: `value:${value}`,+ label: value,+ field: clause.field,+ from,+ to: clause.to,+ insert: quoteIfNeeded(value) + trailing,+ completesClause: true,+ }));+ const showOperators = clause.value === "";+ if (suggestions.length === 0 && !showOperators && !loading) return null;+ return { groups: suggestions.length ? [{ heading: clause.field, items: suggestions }] : [], showOperators, loading };+}++/** What to offer at the cursor: fields while a key is being typed, values once it has a colon. */+export function suggest<F extends string>(+ language: QueryLanguage<F>,+ text: string,+ cursor: number,+ lookup: (field: F) => FieldValues,+): SuggestionMenu<F> | null {+ const found = target(language, text, cursor);+ if (!found) return null;+ if (found.kind === "field") return fieldMenu(language, found);+ const { field } = found.clause;+ return valueMenu(+ found.clause,+ text,+ language.fields[field].suggestValues ? lookup(field) : { values: [], loading: false },+ );+}diff --git a/ui/litellm-dashboard/src/components/shared/search/valueSource.ts b/ui/litellm-dashboard/src/components/shared/search/valueSource.tsnew file mode 100644index 00000000000..6a6da9579b3--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/search/valueSource.ts@@ -0,0 +1,21 @@+import { type ClientIndex, fieldValues } from "./evaluate";++export interface FieldValues {+ readonly values: readonly string[];+ readonly loading: boolean;+}++export const NO_VALUES: FieldValues = { values: [], loading: false };++/** Where a search box gets the values it offers for a field; a server facet lookup or the loaded items. */+export interface ValueSource<F extends string> {+ /** A hook: `field` is the key being completed at the cursor, or null when none is. */+ useValues(field: F | null, prefix: string): FieldValues;+}++/** Values seen in the items already in memory. */+export function itemValues<T, F extends string>(index: ClientIndex<T, F>, items: readonly T[]): ValueSource<F> {+ return {+ useValues: (field) => (field === null ? NO_VALUES : { values: fieldValues(index, items, field), loading: false }),+ };+}diff --git a/ui/litellm-dashboard/src/components/shared/useShortcut.test.tsx b/ui/litellm-dashboard/src/components/shared/useShortcut.test.tsxnew file mode 100644index 00000000000..eaa82d6f15b--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/useShortcut.test.tsx@@ -0,0 +1,76 @@+import { fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { HotkeysProvider } from "react-hotkeys-hook";+import { describe, expect, it, vi } from "vitest";++import { BoundShortcut as Bound } from "./__fixtures__/BoundShortcut";++describe("useShortcut", () => {+ it("lets a pane claim a key so the panel around it does not also act on it", () => {+ const onPress = vi.fn();+ render(+ <HotkeysProvider>+ <Bound id="panel" keys={["escape", "close"]} layer="panel" onPress={onPress} />+ <Bound id="pane" keys={["escape", "close"]} layer="pane" onPress={onPress} />+ </HotkeysProvider>,+ );+ fireEvent.keyDown(document.body, { key: "Escape" });+ expect(onPress.mock.calls).toEqual([["pane"]]);+ });++ it("falls back to the panel binding once the pane's shortcut is disabled", () => {+ const onPress = vi.fn();+ render(+ <HotkeysProvider>+ <Bound id="panel" keys={["escape", "close"]} layer="panel" onPress={onPress} />+ <Bound id="pane" keys={["escape", "close"]} layer="pane" enabled={false} onPress={onPress} />+ </HotkeysProvider>,+ );+ fireEvent.keyDown(document.body, { key: "Escape" });+ expect(onPress.mock.calls).toEqual([["panel"]]);+ });++ it("yields to typing, modified presses, and widgets that own their keys", async () => {+ const user = userEvent.setup();+ const onPress = vi.fn();+ render(+ <HotkeysProvider>+ <input aria-label="search" />+ <div role="menu">+ <button type="button">menu item</button>+ </div>+ <div role="tablist">+ <button type="button" role="tab">+ tab+ </button>+ </div>+ <Bound id="panel" keys={["j", "trace"]} layer="panel" onPress={onPress} />+ <Bound id="pane" keys={["right", "fold"]} layer="pane" onPress={onPress} />+ </HotkeysProvider>,+ );+ fireEvent.keyDown(screen.getByLabelText("search"), { key: "j" });+ fireEvent.keyDown(screen.getByText("menu item"), { key: "j" });+ fireEvent.keyDown(screen.getByRole("tab"), { key: "ArrowRight" });+ await user.keyboard("{Meta>}j{/Meta}{Control>}j{/Control}{Shift>}j{/Shift}");+ expect(onPress).not.toHaveBeenCalled();+ fireEvent.keyDown(screen.getByRole("tab"), { key: "j" });+ await user.keyboard("{ArrowRight}");+ expect(onPress.mock.calls).toEqual([["panel"], ["pane"]]);+ });++ it("keeps working for a modal while focus sits inside its dialog", () => {+ const onPress = vi.fn();+ render(+ <HotkeysProvider>+ <div role="dialog">+ <button type="button">inside</button>+ </div>+ <Bound id="modal" keys={["j", "log"]} layer="modal" onPress={onPress} />+ <Bound id="panel" keys={["k", "trace"]} layer="panel" onPress={onPress} />+ </HotkeysProvider>,+ );+ fireEvent.keyDown(screen.getByText("inside"), { key: "j" });+ fireEvent.keyDown(screen.getByText("inside"), { key: "k" });+ expect(onPress.mock.calls).toEqual([["modal"]]);+ });+});diff --git a/ui/litellm-dashboard/src/components/shared/useShortcut.ts b/ui/litellm-dashboard/src/components/shared/useShortcut.tsnew file mode 100644index 00000000000..ae486d33d5a--- /dev/null+++ b/ui/litellm-dashboard/src/components/shared/useShortcut.ts@@ -0,0 +1,51 @@+import { type HotkeyCallback, useHotkeys } from "react-hotkeys-hook";++const KEY_OWNERS = "[role='dialog'], [role='menu'], [role='listbox'], [role='combobox']";+const PANE_KEY_OWNERS = `${KEY_OWNERS}, [role='tablist'], [role='separator']`;+const CAPTURE = { capture: true } as const;++/**+ * Where a shortcut lives decides whose keys it yields to.+ * panel: a side panel over the page; yields to dialogs, menus and listboxes opened on top of it.+ * pane: a pane inside a panel; runs first and claims the key so the panel does not also act on it.+ * modal: a dialog that owns every key while open.+ */+export type ShortcutLayer = "panel" | "pane" | "modal";++export interface ShortcutOptions {+ readonly description: string;+ readonly enabled?: boolean;+ readonly layer?: ShortcutLayer;+}++const ownedElsewhere =+ (selector: string | null) =>+ (event: KeyboardEvent): boolean => {+ if (event.defaultPrevented || selector === null) return event.defaultPrevented;+ const insideOwner = event.target instanceof Element && event.target.closest(selector) !== null;+ return insideOwner;+ };++const IGNORES: Readonly<Record<ShortcutLayer, (event: KeyboardEvent) => boolean>> = {+ panel: ownedElsewhere(KEY_OWNERS),+ pane: ownedElsewhere(PANE_KEY_OWNERS),+ modal: ownedElsewhere(null),+};++/** One plain-key shortcut. Typing targets and modified presses such as Cmd+J never trigger it. */+export function useShortcut(+ key: string,+ run: HotkeyCallback,+ { description, enabled = true, layer = "panel" }: ShortcutOptions,+): void {+ const options = {+ description,+ enabled,+ useKey: true,+ preventDefault: true,+ ignoreEventWhen: IGNORES[layer],+ eventListenerOptions: layer === "pane" ? CAPTURE : undefined,+ metadata: { layer },+ };+ useHotkeys(key, run, options);+}diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/constants.ts b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/constants.tsindex 2771b9b15fe..535fa8cd02f 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/constants.ts+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/constants.ts@@ -13,13 +13,6 @@ export const METADATA_MAX_HEIGHT = 300;export const TAB_REQUEST = "request" as const;export const TAB_RESPONSE = "response" as const;-// Keyboard shortcuts-export const KEY_ESCAPE = "Escape";-export const KEY_J_LOWER = "j";-export const KEY_J_UPPER = "J";-export const KEY_K_LOWER = "k";-export const KEY_K_UPPER = "K";-// Typographyexport const FONT_FAMILY_MONO = "monospace";export const FONT_SIZE_SMALL = 12;diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.test.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.test.tsxindex f20d35583dc..aec56296917 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.test.tsx@@ -11,12 +11,12 @@ describe("useKeyboardNavigation", () => {const props = { isOpen: true, currentLog: logs[0], allLogs: logs, onClose: vi.fn(), onSelectLog };renderHook(() => useKeyboardNavigation(props));- fireEvent.keyDown(window, { key: "j", metaKey: true });- fireEvent.keyDown(window, { key: "j", ctrlKey: true });- fireEvent.keyDown(window, { key: "j", altKey: true });+ fireEvent.keyDown(document.body, { key: "j", metaKey: true });+ fireEvent.keyDown(document.body, { key: "j", ctrlKey: true });+ fireEvent.keyDown(document.body, { key: "j", altKey: true });expect(onSelectLog).not.toHaveBeenCalled();- fireEvent.keyDown(window, { key: "j" });+ fireEvent.keyDown(document.body, { key: "j" });expect(onSelectLog).toHaveBeenCalledExactlyOnceWith(logs[1]);});});diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.ts b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.tsindex a8a0d44db7d..6d30b75f312 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.ts+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.ts@@ -1,7 +1,6 @@-import { useEffect } from "react";+import { useShortcut } from "@/components/shared/useShortcut";+import { LogEntry } from "../columns";-import { ignoresLetterShortcut } from "../letterShortcut";-import { KEY_ESCAPE, KEY_J_LOWER, KEY_J_UPPER, KEY_K_LOWER, KEY_K_UPPER } from "./constants";interface UseKeyboardNavigationProps {isOpen: boolean;@@ -11,15 +10,7 @@ interface UseKeyboardNavigationProps {onSelectLog?: (log: LogEntry) => void;}-/**- * Custom hook for keyboard navigation in the log details drawer.- * Handles J/K for next/previous and Escape for close.- *- * Keyboard shortcuts:- * - J: Navigate to next log (down)- * - K: Navigate to previous log (up)- * - Escape: Close drawer- */+/** J and K step through the open log's neighbours and Escape closes the drawer. */export function useKeyboardNavigation({isOpen,currentLog,@@ -27,51 +18,18 @@ export function useKeyboardNavigation({onClose,onSelectLog,}: UseKeyboardNavigationProps) {- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- if (ignoresLetterShortcut(e)) return;-- if (!isOpen) return;-- switch (e.key) {- case KEY_ESCAPE:- onClose();- break;- case KEY_J_LOWER:- case KEY_J_UPPER:- selectNextLog();- break;- case KEY_K_LOWER:- case KEY_K_UPPER:- selectPreviousLog();- break;- }- };-- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [isOpen, currentLog, allLogs]);-- const selectNextLog = () => {- if (!currentLog || !allLogs.length || !onSelectLog) return;-- const currentIndex = allLogs.findIndex((l) => l.request_id === currentLog.request_id);- if (currentIndex < allLogs.length - 1) {- onSelectLog(allLogs[currentIndex + 1]);- }+ const index = currentLog ? allLogs.findIndex((log) => log.request_id === currentLog.request_id) : -1;+ const selectAt = (next: number) => {+ const log = allLogs[next];+ if (currentLog && log) onSelectLog?.(log);};-+ const selectNextLog = () => selectAt(index + 1);const selectPreviousLog = () => {- if (!currentLog || !allLogs.length || !onSelectLog) return;-- const currentIndex = allLogs.findIndex((l) => l.request_id === currentLog.request_id);- if (currentIndex > 0) {- onSelectLog(allLogs[currentIndex - 1]);- }- };-- return {- selectNextLog,- selectPreviousLog,+ if (index > 0) selectAt(index - 1);};+ const modal = { layer: "modal", enabled: isOpen } as const;+ useShortcut("escape", onClose, { ...modal, description: "close" });+ useShortcut("j", selectNextLog, { ...modal, description: "log" });+ useShortcut("k", selectPreviousLog, { ...modal, description: "log" });+ return { selectNextLog, selectPreviousLog };}diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesPage.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesPage.tsxindex 35928b19665..8d8e78866d1 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesPage.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesPage.tsx@@ -7,7 +7,7 @@ import { AgentTracesSection } from "./AgentTracesSection";import { useTracesLive } from "./tracesApi";import { useRangeHoursRouting } from "./traceRouting";-const TIME_FORMAT = "YYYY-MM-DDTHH:mm";+const TIME_FORMAT = "YYYY-MM-DDTHH:mm:ss";export default function AgentTracesPage({accessToken,@@ -32,11 +32,18 @@ export default function AgentTracesPage({[anchor, rangeHours],);+ const isLiveTail = live && sourceLive;+const changeRange = (hours: number) => {setRangeHours(hours);setAnchor(moment());};+ const changeLive = (next: boolean) => {+ setLive(next);+ setAnchor(moment());+ };+return (<div className="flex min-h-0 flex-1 flex-col"><AgentTracesSection@@ -44,11 +51,11 @@ export default function AgentTracesPage({isActive={isActive}startTime={startTime}endTime={endTime}- isCustomDate={false}- isLiveTail={live && sourceLive}+ isCustomDate={!isLiveTail}+ isLiveTail={isLiveTail}readOnly={readOnly}canMintTracingKey={canMintTracingKey}- timeControls={{ rangeHours, onRangeHoursChange: changeRange, onLiveChange: setLive }}+ timeControls={{ rangeHours, onRangeHoursChange: changeRange, onLiveChange: changeLive }}/></div>);diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.integration.test.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.integration.test.tsxindex 73075cbbcea..bf68f31f0cb 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.integration.test.tsx@@ -7,9 +7,9 @@ import { ApiError } from "@/lib/http/client";import { renderWithProviders, testQueryClient } from "../../../../tests/test-utils";import traceList from "./__fixtures__/trace_list.json";-import { LensPreviewContext } from "@/components/lens/LensPreviewButton";+import { LensPreviewContext } from "./LensPreviewButton";import AgentTracesPage from "./AgentTracesPage";-import { filterRuns } from "@/components/lens/runSearch/runQuery";+import { filterRuns } from "./runSearch/runQuery";import { AgentTracesSection, type TimeControls } from "./AgentTracesSection";import type { TracePage, TraceSummary } from "./traceTypes";@@ -384,7 +384,7 @@ describe("AgentTracesSection", () => {const agentCell = (row: HTMLElement) => within(row).getAllByRole("cell")[1];expect(agentCell(sdkRun)).toHaveTextContent(/^research-bot$/);- expect(agentCell(sdkRun)).toHaveAttribute("title", "research-bot · Claude Agent SDK");+ expect(within(agentCell(sdkRun)).getByTitle("research-bot · Claude Agent SDK")).toBeInTheDocument();expect(within(sdkRun).getByRole("img", { name: "Claude Agent SDK logo", hidden: true })).toHaveAttribute("src",expect.stringContaining("anthropic.svg"),@@ -423,7 +423,7 @@ describe("AgentTracesSection", () => {expect(rows[0]).toHaveAttribute("aria-selected", "false");fireEvent.click(rows[1]);- fireEvent.keyDown(window, { key: "Escape" });+ fireEvent.keyDown(document.body, { key: "Escape" });expect(rows[1]).toHaveAttribute("aria-selected", "false");});@@ -433,15 +433,36 @@ describe("AgentTracesSection", () => {const rows = await screen.findAllByTestId("agent-trace-row");fireEvent.click(rows[0]);- fireEvent.keyDown(window, { key: "j" });+ fireEvent.keyDown(document.body, { key: "j" });expect(screen.getByTestId("run-view")).toHaveTextContent(`run ${runs[1].trace_id}`);- fireEvent.keyDown(window, { key: "k" });+ fireEvent.keyDown(document.body, { key: "k" });expect(screen.getByTestId("run-view")).toHaveTextContent(`run ${runs[0].trace_id}`);expect(screen.getByRole("button", { name: "Previous trace (K)" })).toBeDisabled();fireEvent.click(screen.getByRole("button", { name: "Next trace (J)" }));expect(screen.getByTestId("run-view")).toHaveTextContent(`run ${runs[1].trace_id}`);});+ it("opens full screen from a shared link and drops it from the URL on close", async () => {+ vi.mocked(agentTraceListCall).mockResolvedValue(traceList as TracePage);+ const onUrlUpdate = vi.fn();+ renderWithProviders(+ <AgentTracesSection+ accessToken="sk-test"+ isActive+ startTime="2026-09-29T00:00"+ endTime="2026-09-30T00:00"+ isCustomDate={false}+ isLiveTail={false}+ />,+ { searchParams: `?trace=${runs[0].trace_id}&fullscreen=true`, onUrlUpdate },+ );+ const drawer = await screen.findByRole("complementary", { name: "Trace details" });+ expect(drawer).toHaveStyle({ width: "100%" });+ fireEvent.click(screen.getByRole("button", { name: "Close trace (Esc)" }));+ await waitFor(() => expect(lastUrl(onUrlUpdate).has("trace")).toBe(false));+ expect(lastUrl(onUrlUpdate).has("fullscreen")).toBe(false);+ });+it("narrows the list to the zoom window named in the URL and clears it on request", async () => {vi.mocked(agentTraceListCall).mockResolvedValue(traceList as TracePage);const startMs = Date.parse(runs[0].start_time);@@ -490,7 +511,7 @@ describe("AgentTracesSection", () => {expect(lastUrl(onUrlUpdate).get("trace_ref")).toBe(runs[1].trace_ref ?? null);expect(onUrlUpdate.mock.lastCall?.[0].options.history).toBe("push");- fireEvent.keyDown(window, { key: "Escape" });+ fireEvent.keyDown(document.body, { key: "Escape" });await waitFor(() => expect(lastUrl(onUrlUpdate).has("trace")).toBe(false));expect(rows[1]).toHaveAttribute("aria-selected", "false");});@@ -568,25 +589,6 @@ describe("AgentTracesSection", () => {expect(screen.queryByTestId("timeline-selection")).not.toBeInTheDocument();expect(rowCount()).toBe(runs.length);});-- it("clears timeline zoom when refreshed", async () => {- vi.mocked(agentTraceListCall).mockResolvedValue(traceList as TracePage);- renderWindowed({ rangeHours: 24, onRangeHoursChange: () => {}, onLiveChange: () => {} });- await screen.findAllByTestId("agent-trace-row");- const area = screen.getByTestId("timeline-area");- const x = (bucket: number) => bucket * 10 + 5;-- fireEvent.pointerDown(area, { clientX: x(0), pointerId: 1 });- fireEvent.pointerMove(area, { clientX: x(1), pointerId: 1 });- fireEvent.pointerUp(area, { clientX: x(1), pointerId: 1 });- expect(screen.getByTestId("timeline-selection")).toBeInTheDocument();- expect(screen.queryAllByTestId("agent-trace-row")).toHaveLength(0);-- fireEvent.click(screen.getByRole("button", { name: "Refresh" }));-- expect(screen.queryByTestId("timeline-selection")).not.toBeInTheDocument();- expect(screen.getAllByTestId("agent-trace-row")).toHaveLength(runs.length);- });});describe("AgentTracesPage", () => {@@ -596,37 +598,36 @@ describe("AgentTracesPage", () => {vi.mocked(apiClient.get).mockResolvedValue({ data: [] });});- it("shows the actual range, switches presets from the popover, and toggles Live", async () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("names the rolling preset while Live and pins the actual range once paused", async () => {+ const pausedAt = Date.parse("2026-10-03T12:00:00.500");+ vi.useFakeTimers({ toFake: ["Date"], now: pausedAt });vi.mocked(agentTraceListCall).mockResolvedValue(traceList as TracePage);renderWithProviders(<AgentTracesPage accessToken="sk-test" />);await screen.findByTestId("runs-table");const trigger = screen.getByRole("button", { name: "Time range" });- expect(trigger).toHaveTextContent(/ to /);+ const live = screen.getByRole("button", { name: "Live" });+ expect(live).toHaveAttribute("aria-pressed", "true");+ expect(trigger).toHaveTextContent("Last 24 hours");fireEvent.click(trigger);fireEvent.click(await screen.findByRole("menuitemradio", { name: "Last 7 days" }));+ expect(trigger).toHaveTextContent("Last 7 days");await waitFor(() => {const last = vi.mocked(agentTraceListCall).mock.calls.at(-1)?.[0];expect((last?.endMs ?? 0) - (last?.startMs ?? 0)).toBeGreaterThanOrEqual(7 * 24 * 3600 * 1000 - 60_000);});- const live = screen.getByRole("button", { name: "Live" });- expect(live).toHaveAttribute("aria-pressed", "true");fireEvent.click(live);expect(live).toHaveAttribute("aria-pressed", "false");- expect(screen.getByRole("button", { name: "Refresh" })).toBeEnabled();- });-- it("refreshes the trace list", async () => {- vi.mocked(agentTraceListCall).mockResolvedValue(traceList as TracePage);- renderWithProviders(<AgentTracesPage accessToken="sk-test" />);- await screen.findByTestId("runs-table");-- const callsBeforeRefresh = vi.mocked(agentTraceListCall).mock.calls.length;- fireEvent.click(screen.getByRole("button", { name: "Refresh" }));+ expect(trigger).toHaveTextContent(/ to /);+ expect(trigger).not.toHaveTextContent("Last 7 days");- await waitFor(() => expect(vi.mocked(agentTraceListCall).mock.calls.length).toBeGreaterThan(callsBeforeRefresh));+ await waitFor(() => expect(vi.mocked(agentTraceListCall).mock.calls.at(-1)?.[0].endMs).toBe(pausedAt - 500));});it("keeps the time controls on an empty range the user picked, instead of showing onboarding", async () => {diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.tsxindex ac0d2f14991..7d04a709825 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesSection.tsx@@ -3,12 +3,12 @@import moment from "moment";import { useMemo, useState } from "react";-import { filterRuns } from "@/components/lens/runSearch/runQuery";-import { RunsToolbar } from "@/components/lens/runSearch/RunsToolbar";+import { filterRuns } from "./runSearch/runQuery";+import { RunsToolbar } from "./runSearch/RunsToolbar";+import { Inspector } from "@/components/shared/Inspector";import { Button } from "@/components/ui/button";import { AgentTracesTable } from "./AgentTracesTable";-import { RunDrawer } from "./RunDrawer";import {type TraceRef,traceKey,@@ -18,12 +18,15 @@ import {useZoomRouting,} from "./traceRouting";import type { TraceSummary } from "./traceTypes";+import { RunView } from "./TraceDrawer";import { TimeRangeControls } from "./TimeRangeControls";import { TracesTimeline, type TimeWindow } from "./TracesTimeline";import { TracingSetupCard } from "./TracingSetupCard";import { useTracesLive } from "./tracesApi";import { type AgentTracesResult, traceWindowStartMs, useAgentTraces, useTraceAvailability } from "./useAgentTraces";+const DRAWER_WIDTH_KEY = "litellm.agentTraces.drawerWidth";+const filterByWindow = (runs: TraceSummary[], range: TimeWindow): TraceSummary[] =>runs.filter((run) => {const t = moment(run.start_time).valueOf();@@ -113,6 +116,7 @@ export function AgentTracesSection({);const filtered = useMemo(() => filterRuns(traces.traces, query), [traces.traces, query]);const runs = useMemo(() => (zoom ? filterByWindow(filtered, zoom) : filtered), [filtered, zoom]);+ const runRefs = useMemo(() => runs.map(traceRefOf), [runs]);const changeRange = (hours: number, apply: (hours: number) => void) => {setZoom(null);@@ -154,56 +158,58 @@ export function AgentTracesSection({);}- const toggleRun = (trace: TraceSummary | null) => {- const ref: TraceRef | null = trace && traceRefOf(trace);- openRun(ref !== null && openTrace !== null && traceKey(ref) === traceKey(openTrace) ? null : ref);- };-return (- <div className="flex min-h-[560px] flex-1 flex-col overflow-hidden bg-card">- {checkHistory && <TraceHistoryError history={history} />}- <TracesReceived received={setup.received} />- <RunDrawer- trace={openTrace}- runs={runs}- accessToken={accessToken}- selection={selection}- onSelect={openRun}- fullScreen={fullScreen}- onFullScreenChange={setFullScreen}- />- <RunsToolbar query={query} onQueryChange={setQuery} runs={traces.traces}>- {timeControls && (- <TimeRangeControls- range={zoom ?? range}- rangeHours={timeControls.rangeHours}- onRangeHoursChange={(hours) => changeRange(hours, timeControls.onRangeHoursChange)}- live={isLiveTail}- showLive={live}- onLiveChange={timeControls.onLiveChange}- onRefresh={() => {- setZoom(null);- checkTraces();- }}- refreshing={traces.isFetching}- />- )}- </RunsToolbar>- <TracesTimeline runs={filtered} range={range} selection={zoom} onSelect={setZoom} />- <AgentTracesTable- traces={runs}- isLoading={traces.isLoading || (checkHistory && history.isLoading)}- error={traces.error}- hasMore={traces.hasMore}- isFetching={traces.isFetching}- onRetry={traces.hasMore ? traces.loadMore : traces.refetch}- onLoadMore={traces.loadMore}- onOpenTrace={toggleRun}- selectedKey={openTrace === null ? null : traceKey(openTrace)}- rangeEmpty={traces.traces.length === 0}- onSetUpTracing={() => setShowSetup(true)}- />- </div>+ <Inspector.Root+ items={runRefs}+ itemKey={traceKey}+ selected={openTrace}+ onSelectedChange={openRun}+ noun="trace"+ storageKey={DRAWER_WIDTH_KEY}+ fullScreen={fullScreen}+ onFullScreenChange={setFullScreen}+ >+ <div className="flex min-h-[560px] flex-1 flex-col overflow-hidden bg-card">+ {checkHistory && <TraceHistoryError history={history} />}+ <TracesReceived received={setup.received} />+ <Inspector.Panel label="Trace details" testId="run-drawer">+ {(shown: TraceRef) => (+ <RunView+ traceId={shown.traceId}+ traceRef={shown.traceRef}+ selection={selection}+ accessToken={accessToken}+ onBack={() => openRun(null)}+ embedded+ />+ )}+ </Inspector.Panel>+ <RunsToolbar query={query} onQueryChange={setQuery} runs={traces.traces} range={zoom ?? range}>+ {timeControls && (+ <TimeRangeControls+ fixedRange={zoom ?? (isLiveTail ? null : range)}+ rangeHours={timeControls.rangeHours}+ onRangeHoursChange={(hours) => changeRange(hours, timeControls.onRangeHoursChange)}+ live={isLiveTail}+ showLive={live}+ onLiveChange={timeControls.onLiveChange}+ />+ )}+ </RunsToolbar>+ <TracesTimeline runs={filtered} range={range} selection={zoom} onSelect={setZoom} />+ <AgentTracesTable+ traces={runs}+ isLoading={traces.isLoading || (checkHistory && history.isLoading)}+ error={traces.error}+ hasMore={traces.hasMore}+ isFetching={traces.isFetching}+ onRetry={traces.hasMore ? traces.loadMore : traces.refetch}+ onLoadMore={traces.loadMore}+ rangeEmpty={traces.traces.length === 0}+ onSetUpTracing={() => setShowSetup(true)}+ />+ </div>+ </Inspector.Root>);}diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.test.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.test.tsxindex d46c30d1e05..b03cd8a07dd 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.test.tsx@@ -2,23 +2,39 @@ import { fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { renderWithProviders } from "../../../../tests/test-utils";+import { Inspector } from "@/components/shared/Inspector";import traceList from "./__fixtures__/trace_list.json";import { AgentTracesTable } from "./AgentTracesTable";+import { traceKey } from "./traceRouting";import type { TracePage, TraceSummary } from "./traceTypes";+const inList = (table: React.ReactElement) => (+ <Inspector.Root+ items={[]}+ itemKey={traceKey}+ selected={null}+ onSelectedChange={vi.fn()}+ noun="trace"+ storageKey="test"+ >+ {table}+ </Inspector.Root>+);+const renderEmpty = (rangeEmpty: boolean) => {const onSetUpTracing = vi.fn();render(- <AgentTracesTable- traces={[]}- isLoading={false}- error={null}- hasMore={false}- onLoadMore={vi.fn()}- onOpenTrace={vi.fn()}- rangeEmpty={rangeEmpty}- onSetUpTracing={onSetUpTracing}- />,+ inList(+ <AgentTracesTable+ traces={[]}+ isLoading={false}+ error={null}+ hasMore={false}+ onLoadMore={vi.fn()}+ rangeEmpty={rangeEmpty}+ onSetUpTracing={onSetUpTracing}+ />,+ ),);return onSetUpTracing;};@@ -45,15 +61,16 @@ describe("AgentTracesTable virtualization", () => {it("renders only the rows near the viewport as the list scrolls", () => {renderWithProviders(- <AgentTracesTable- traces={manyRuns}- isLoading={false}- error={null}- hasMore={false}- onLoadMore={vi.fn()}- onOpenTrace={vi.fn()}- onSetUpTracing={vi.fn()}- />,+ inList(+ <AgentTracesTable+ traces={manyRuns}+ isLoading={false}+ error={null}+ hasMore={false}+ onLoadMore={vi.fn()}+ onSetUpTracing={vi.fn()}+ />,+ ),);expect(screen.getAllByTestId("agent-trace-row").length).toBeLessThan(50);expect(screen.getByText("question 0")).toBeInTheDocument();diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.tsxindex a7f9b6cb6b5..1b85f26fbf5 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/AgentTracesTable.tsx@@ -1,19 +1,19 @@"use client";+import { getCoreRowModel, useReactTable, type ColumnDef, type TableOptions } from "@tanstack/react-table";import { ArrowDown, ChevronRight } from "lucide-react";-import { useVirtualizer } from "@tanstack/react-virtual";-import { useEffect, useState } from "react";+import { useEffect } from "react";import { useInView } from "react-intersection-observer";-import { PANEL_TRIGGER } from "@/components/shared/SidePanel";+import { InspectorTable, useInspectorTable } from "@/components/shared/InspectorTable";import { Button } from "@/components/ui/button";import { formatActivityTimestamp, formatRunTimestamp, localTimeZoneAbbreviation } from "@/utils/activityTimestamp";-import { cn } from "@/lib/cva.config";import { SpanIcon } from "./SpanIcon";import { StatusMark } from "./StatusMark";import { FrameworkLogo, traceFramework } from "./TraceFramework";import type { TraceSummary } from "./traceTypes";+import { traceRefOf } from "./traceRouting";import { fmtMs, previewText, traceDisplayName, traceAgentNames } from "./traceUtils";interface AgentTracesTableProps {@@ -24,8 +24,6 @@ interface AgentTracesTableProps {isFetching?: boolean;onRetry?: () => void;onLoadMore: () => void;- onOpenTrace: (trace: TraceSummary) => void;- selectedKey?: string | null;rangeEmpty?: boolean;onSetUpTracing: () => void;}@@ -39,28 +37,114 @@ export const formatCost = (cost: number): string => {const firstLine = (text: string): string => text.split("\n")[0] ?? text;const runKey = (run: TraceSummary): string => run.trace_ref || run.trace_id;-const TH = "px-3 font-medium";const PREFETCH_MARGIN = "0px 0px 480px 0px";const PLACEHOLDER_ROWS = [0, 1, 2];const ROW_HEIGHT = 36;-const OVERSCAN_ROWS = 12;-const TH_NUM = "px-3 text-right font-medium";-const TD_NUM = "px-3 text-right font-mono tabular-nums text-muted-foreground";+const MUTED_NUM = "font-mono text-muted-foreground";+const NUM = "font-mono text-foreground";function AgentCell({ run }: { run: TraceSummary }) {const framework = traceFramework(run);const agents = traceAgentNames(run).join(", ");const title = [agents, framework?.label].filter(Boolean).join(" · ");return (- <td className="px-3 text-muted-foreground" title={title}>- <div className="flex min-w-0 items-center gap-1.5">- {framework ? <FrameworkLogo framework={framework} /> : <SpanIcon type="agent" size="sm" />}- <span className="truncate">{agents || framework?.label || "—"}</span>- </div>- </td>+ <div className="flex min-w-0 items-center gap-1.5 text-muted-foreground" title={title}>+ {framework ? <FrameworkLogo framework={framework} /> : <SpanIcon type="agent" size="sm" />}+ <span className="truncate">{agents || framework?.label || "—"}</span>+ </div>);}+function InputCell({ run }: { run: TraceSummary }) {+ return (+ <div className="flex min-w-0 items-center gap-2">+ <StatusMark status={run.error_count > 0 ? "error" : "ok"} subtle />+ <span className="truncate text-foreground">+ {firstLine(previewText(run.input_preview)) || traceDisplayName(run)}+ </span>+ {run.resolution_limited && (+ <span+ className="shrink-0 text-xs text-muted-foreground"+ title="This run is too large to calculate all totals in this view"+ >+ Partial totals+ </span>+ )}+ <span className="hidden shrink-0 font-mono text-xs text-muted-foreground 2xl:inline">{run.trace_id}</span>+ </div>+ );+}++const RUN_COLUMNS: ColumnDef<TraceSummary>[] = [+ {+ id: "time",+ size: 170,+ header: () => (+ <span className="inline-flex items-center gap-1 whitespace-nowrap">+ Time <ArrowDown className="size-2.5" />+ <span className="font-normal normal-case tracking-normal text-muted-foreground/70">+ {localTimeZoneAbbreviation()}+ </span>+ </span>+ ),+ cell: ({ row }) => (+ <span title={formatActivityTimestamp(row.original.start_time)}>+ {formatRunTimestamp(row.original.start_time)}+ </span>+ ),+ meta: { className: "font-mono tabular-nums text-muted-foreground" },+ },+ { id: "agent", size: 160, header: "Agent", cell: ({ row }) => <AgentCell run={row.original} /> },+ { id: "input", header: "Input", cell: ({ row }) => <InputCell run={row.original} /> },+ {+ id: "agents",+ size: 72,+ header: "Agents",+ cell: ({ row }) => row.original.agent_count.toLocaleString(),+ meta: { numeric: true, className: MUTED_NUM },+ },+ {+ id: "steps",+ size: 74,+ header: "Steps",+ cell: ({ row }) => row.original.span_count.toLocaleString(),+ meta: { numeric: true, className: MUTED_NUM },+ },+ {+ id: "duration",+ size: 86,+ header: "Duration",+ cell: ({ row }) => fmtMs(row.original.duration_ms),+ meta: { numeric: true, className: NUM },+ },+ {+ id: "cost",+ size: 80,+ header: "Cost",+ cell: ({ row }) => (row.original.spend == null ? "—" : formatCost(row.original.spend)),+ meta: { numeric: true, className: NUM },+ },+ {+ id: "failed",+ size: 72,+ header: "Failed",+ cell: ({ row }) =>+ row.original.error_count > 0 ? (+ <StatusMark status="error" count={row.original.error_count} />+ ) : (+ <span className="font-mono text-muted-foreground/60">0</span>+ ),+ meta: { numeric: true },+ },+ {+ id: "open",+ size: 32,+ header: "",+ cell: () => <ChevronRight className="size-3 text-muted-foreground/60" />,+ meta: { className: "px-0" },+ },+];+function PlaceholderRow({ rowRef }: { rowRef?: (node: Element | null) => void }) {return (<tr ref={rowRef} aria-hidden data-testid="runs-placeholder" className="h-9 border-b border-border/60">@@ -77,6 +161,15 @@ function PlaceholderRow({ rowRef }: { rowRef?: (node: Element | null) => void }));}+function LoadMoreRows({ isFetching, onLoadMore }: { isFetching: boolean; onLoadMore: () => void }) {+ const { scroller } = useInspectorTable();+ const { ref: tailRef, inView: nearTail } = useInView({ root: scroller, rootMargin: PREFETCH_MARGIN });+ useEffect(() => {+ if (nearTail && !isFetching) onLoadMore();+ }, [nearTail, isFetching, onLoadMore]);+ return PLACEHOLDER_ROWS.map((row) => <PlaceholderRow key={row} rowRef={row === 0 ? tailRef : undefined} />);+}+function EmptyRuns({ rangeEmpty, onSetUpTracing }: { rangeEmpty: boolean; onSetUpTracing: () => void }) {if (!rangeEmpty)return (@@ -98,85 +191,6 @@ function EmptyRuns({ rangeEmpty, onSetUpTracing }: { rangeEmpty: boolean; onSetU);}-function RunRow({- run,- selected,- onOpen,-}: {- run: TraceSummary;- selected: boolean;- onOpen: (run: TraceSummary) => void;-}) {- return (- <tr- data-testid="agent-trace-row"- {...PANEL_TRIGGER}- onClick={() => onOpen(run)}- aria-selected={selected}- className={cn(- "h-9 cursor-pointer border-b border-border/60 text-xs transition-colors duration-150 motion-reduce:transition-none",- selected ? "bg-trace-row-selected shadow-[inset_2px_0_0_var(--trace-brand)]" : "hover:bg-trace-row-hover",- )}- >- <td- className="px-3 font-mono text-xs whitespace-nowrap tabular-nums text-muted-foreground"- title={formatActivityTimestamp(run.start_time)}- >- {formatRunTimestamp(run.start_time)}- </td>- <AgentCell run={run} />- <td className="px-3">- <div className="flex min-w-0 items-center gap-2">- <StatusMark status={run.error_count > 0 ? "error" : "ok"} subtle />- <span className="truncate text-foreground">- {firstLine(previewText(run.input_preview)) || traceDisplayName(run)}- </span>- {run.resolution_limited && (- <span- className="shrink-0 text-xs text-muted-foreground"- title="This run is too large to calculate all totals in this view"- >- Partial totals- </span>- )}- <span className="hidden shrink-0 font-mono text-xs text-muted-foreground 2xl:inline">{run.trace_id}</span>- </div>- </td>- <td className={TD_NUM}>{run.agent_count.toLocaleString()}</td>- <td className={TD_NUM}>{run.span_count.toLocaleString()}</td>- <td className="px-3 text-right font-mono tabular-nums text-foreground">{fmtMs(run.duration_ms)}</td>- <td className="px-3 text-right font-mono tabular-nums text-foreground">- {run.spend == null ? "—" : formatCost(run.spend)}- </td>- <td className="px-3 text-right">- {run.error_count > 0 ? (- <StatusMark status="error" count={run.error_count} />- ) : (- <span className="font-mono text-xs text-muted-foreground/60">0</span>- )}- </td>- <td>- <ChevronRight className="size-3 text-muted-foreground/60" />- </td>- </tr>- );-}--function useVirtualRows(traces: TraceSummary[], scroller: HTMLDivElement | null) {- const options = {- count: traces.length,- getScrollElement: () => scroller,- estimateSize: () => ROW_HEIGHT,- overscan: OVERSCAN_ROWS,- getItemKey: (index: number) => runKey(traces[index]),- };- const virtualizer = useVirtualizer(options);- const rows = virtualizer.getVirtualItems();- const padTop = rows[0]?.start ?? 0;- const padBottom = virtualizer.getTotalSize() - (rows.at(-1)?.end ?? 0);- return { rows, padTop, padBottom };-}-/** Devtool-dense runs list: one row per agent run, newest first. */export function AgentTracesTable({traces,@@ -186,8 +200,6 @@ export function AgentTracesTable({isFetching = false,onRetry,onLoadMore,- onOpenTrace,- selectedKey = null,rangeEmpty = false,onSetUpTracing,}: AgentTracesTableProps) {@@ -195,49 +207,32 @@ export function AgentTracesTable({const isEmpty = settled && !hasMore && traces.length === 0;const canContinue = settled && hasMore;const autoContinue = canContinue && traces.length > 0;- const [scroller, setScroller] = useState<HTMLDivElement | null>(null);- const { ref: tailRef, inView: nearTail } = useInView({ root: scroller, rootMargin: PREFETCH_MARGIN });- useEffect(() => {- if (nearTail && autoContinue && !isFetching) onLoadMore();- }, [nearTail, autoContinue, isFetching, onLoadMore]);- const { rows, padTop, padBottom } = useVirtualRows(traces, scroller);+ const tableOptions: TableOptions<TraceSummary> = {+ data: traces,+ columns: RUN_COLUMNS,+ getRowId: runKey,+ autoResetAll: false,+ getCoreRowModel: getCoreRowModel(),+ };+ const table = useReactTable(tableOptions);return (- <div ref={setScroller} className="min-h-0 flex-1 overflow-auto" data-testid="runs-table">- <table- aria-label="Agent runs"- aria-busy={isFetching}- className="w-full min-w-[900px] table-fixed border-collapse text-left"- >- <thead className="sticky top-0 z-sticky bg-[color-mix(in_oklab,var(--muted)_40%,var(--card))]">- <tr className="h-8 border-b border-border text-xs tracking-wider text-muted-foreground uppercase">- <th className={`w-[170px] ${TH}`}>- <span className="inline-flex items-center gap-1 whitespace-nowrap">- Time <ArrowDown className="size-2.5" />- <span className="font-normal normal-case tracking-normal text-muted-foreground/70">- {localTimeZoneAbbreviation()}- </span>- </span>- </th>- <th className={`w-[160px] ${TH}`}>Agent</th>- <th className={TH}>Input</th>- <th className={`w-[72px] ${TH_NUM}`}>Agents</th>- <th className={`w-[74px] ${TH_NUM}`}>Steps</th>- <th className={`w-[86px] ${TH_NUM}`}>Duration</th>- <th className={`w-[80px] ${TH_NUM}`}>Cost</th>- <th className={`w-[72px] ${TH_NUM}`}>Failed</th>- <th className="w-8" />- </tr>- </thead>- <tbody>- {padTop > 0 && <tr aria-hidden style={{ height: padTop }} />}- {rows.map(({ index, key }) => (- <RunRow key={key} run={traces[index]} selected={selectedKey === key} onOpen={onOpenTrace} />- ))}- {padBottom > 0 && <tr aria-hidden style={{ height: padBottom }} />}- {autoContinue &&- PLACEHOLDER_ROWS.map((row) => <PlaceholderRow key={row} rowRef={row === 0 ? tailRef : undefined} />)}- </tbody>- </table>+ <InspectorTable.Root table={table} data-testid="runs-table">+ <InspectorTable.Grid aria-label="Agent runs" aria-busy={isFetching} className="min-w-[900px] text-xs">+ <InspectorTable.Header />+ <InspectorTable.Body<TraceSummary>+ rowHeight={() => ROW_HEIGHT}+ after={autoContinue && <LoadMoreRows isFetching={isFetching} onLoadMore={onLoadMore} />}+ >+ {(row) => (+ <InspectorTable.Row+ row={row}+ item={traceRefOf(row.original)}+ data-testid="agent-trace-row"+ className="h-9"+ />+ )}+ </InspectorTable.Body>+ </InspectorTable.Grid>{isLoading && <div className="py-16 text-center text-xs text-muted-foreground">Loading runs…</div>}{error && (<div role="alert" className="flex items-center justify-center gap-3 py-6 text-xs text-muted-foreground">@@ -260,6 +255,6 @@ export function AgentTracesTable({</div>)}{isEmpty && <EmptyRuns rangeEmpty={rangeEmpty} onSetUpTracing={onSetUpTracing} />}- </div>+ </InspectorTable.Root>);}diff --git a/ui/litellm-dashboard/src/components/lens/LensPreviewButton.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/LensPreviewButton.tsxsimilarity index 100%rename from ui/litellm-dashboard/src/components/lens/LensPreviewButton.tsxrename to ui/litellm-dashboard/src/components/view_logs/TraceView/LensPreviewButton.tsxdiff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/RunDrawer.test.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/RunDrawer.test.tsxdeleted file mode 100644index cd7de595fdf..00000000000--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/RunDrawer.test.tsx+++ /dev/null@@ -1,284 +0,0 @@-import { fireEvent, screen, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";--import { renderWithProviders } from "../../../../tests/test-utils";-import { clampDrawerWidth, PANEL_TRIGGER } from "@/components/shared/SidePanel";-import { RunDrawer } from "./RunDrawer";-import { type RunSelection, traceRefOf, useOpenTraceRouting } from "./traceRouting";-import type { TraceSummary } from "./traceTypes";--vi.mock("./TraceDrawer", () => ({- RunView: ({ traceId }: { traceId: string }) => <div data-testid="run-view">run {traceId}</div>,-}));--const run = (trace_id: string): TraceSummary => ({- trace_id,- name: trace_id,- service: "svc",- input_preview: "",- start_time: "2026-09-30T00:00:00Z",- duration_ms: 1,- status: "ok",- span_count: 1,- agent_count: 1,- agent_invocations: 1,- llm_calls: 0,- tool_calls: 0,- error_count: 0,- input_tokens: 0,- output_tokens: 0,- models: [],- spend: null,-});--const selection: RunSelection = {- spanId: null,- view: "steps",- spanTab: "content",- stepQuery: "",- errorsOnly: false,- selectSpan: vi.fn(),- setView: vi.fn(),- setSpanTab: vi.fn(),- setStepQuery: vi.fn(),- setErrorsOnly: vi.fn(),-};--function RoutedDrawer({ runs }: { runs: TraceSummary[] }) {- const { trace, openTrace, selection, fullScreen, setFullScreen } = useOpenTraceRouting();- return (- <RunDrawer- trace={trace}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={openTrace}- fullScreen={fullScreen}- onFullScreenChange={setFullScreen}- />- );-}--const lastUrl = (onUrlUpdate: ReturnType<typeof vi.fn>) =>- new URLSearchParams(String(onUrlUpdate.mock.lastCall?.[0].queryString ?? ""));--const mockReducedMotion = (reduce: boolean) =>- vi.spyOn(window, "matchMedia").mockImplementation(- (query: string) =>- ({- matches: reduce && query.includes("reduce"),- media: query,- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- }) as unknown as MediaQueryList,- );--describe("clampDrawerWidth", () => {- it("keeps at least 700px and a 100px strip of list on wide screens", () => {- expect(clampDrawerWidth(200, 1600)).toBe(700);- expect(clampDrawerWidth(5000, 1600)).toBe(1500);- expect(clampDrawerWidth(900, 1600)).toBe(900);- });-- it("never exceeds the screen on viewports narrower than the minimum width", () => {- expect(clampDrawerWidth(900, 600)).toBe(600);- expect(clampDrawerWidth(100, 600)).toBe(600);- expect(clampDrawerWidth(750, 760)).toBe(700);- });-});--describe("RunDrawer", () => {- afterEach(() => {- vi.restoreAllMocks();- window.localStorage.clear();- });-- it("fills the page across trace navigation and restores the resized drawer width", async () => {- const runs = [run("a"), run("b")];- const onUrlUpdate = vi.fn();- renderWithProviders(<RoutedDrawer runs={runs} />, { searchParams: "?trace=a", onUrlUpdate });- const drawer = screen.getByRole("complementary", { name: "Trace details" });- fireEvent.keyDown(screen.getByRole("separator", { name: "Resize trace panel" }), { key: "ArrowLeft" });- const resizedWidth = drawer.style.width;- const storedWidth = window.localStorage.getItem("litellm.agentTraces.drawerWidth");-- fireEvent.click(screen.getByRole("button", { name: "Enter full screen" }));- expect(drawer).toHaveStyle({ width: "100%" });- expect(screen.queryByRole("separator", { name: "Resize trace panel" })).not.toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Next trace (J)" }));- expect(drawer).toHaveStyle({ width: "100%" });- expect(screen.getByTestId("run-view")).toHaveTextContent("run b");- await waitFor(() => expect(lastUrl(onUrlUpdate).get("fullscreen")).toBe("true"));-- fireEvent.click(screen.getByRole("button", { name: "Exit full screen" }));- expect(drawer).toHaveStyle({ width: resizedWidth });- expect(screen.getByRole("separator", { name: "Resize trace panel" })).toBeInTheDocument();- expect(window.localStorage.getItem("litellm.agentTraces.drawerWidth")).toBe(storedWidth);- });-- it("opens full screen from a shared link and drops it from the URL on close", async () => {- const onUrlUpdate = vi.fn();- renderWithProviders(<RoutedDrawer runs={[run("a")]} />, { searchParams: "?trace=a&fullscreen=true", onUrlUpdate });- expect(screen.getByRole("complementary", { name: "Trace details" })).toHaveStyle({ width: "100%" });- fireEvent.click(screen.getByRole("button", { name: "Close trace (Esc)" }));- await waitFor(() => expect(lastUrl(onUrlUpdate).has("trace")).toBe(false));- expect(lastUrl(onUrlUpdate).has("fullscreen")).toBe(false);- });-- it.each(["Close (Esc)", "Close trace (Esc)"])("closes a full-screen trace using %s", (name) => {- const runs = [run("a")];- const onSelect = vi.fn();- renderWithProviders(- <RunDrawer- trace={traceRefOf(runs[0])}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={onSelect}- fullScreen- onFullScreenChange={vi.fn()}- />,- );- fireEvent.click(screen.getByRole("button", { name }));- expect(onSelect).toHaveBeenCalledExactlyOnceWith(null);- });-- it("keeps Escape available to close a full-screen trace", () => {- const runs = [run("a")];- const onSelect = vi.fn();- renderWithProviders(- <RunDrawer- trace={traceRefOf(runs[0])}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={onSelect}- fullScreen- onFullScreenChange={vi.fn()}- />,- );- fireEvent.keyDown(window, { key: "Escape" });- expect(onSelect).toHaveBeenCalledExactlyOnceWith(null);- });-- it("leaves J, K and Escape to an open menu or listbox instead of stepping or closing the trace", () => {- const runs = [run("a"), run("b"), run("c")];- const onSelect = vi.fn();- renderWithProviders(- <>- <div role="menu">- <button type="button">menu item</button>- </div>- <div role="listbox">- <button type="button">option</button>- </div>- <RunDrawer- trace={traceRefOf(runs[1])}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={onSelect}- fullScreen={false}- onFullScreenChange={vi.fn()}- />- </>,- );- for (const target of [screen.getByText("menu item"), screen.getByText("option")]) {- for (const key of ["j", "k", "Escape"]) fireEvent.keyDown(target, { key });- }- expect(onSelect).not.toHaveBeenCalled();- fireEvent.keyDown(window, { key: "j" });- expect(onSelect).toHaveBeenCalledExactlyOnceWith(traceRefOf(runs[2]));- });-- it("closes on a press outside the panel but not inside it, on a trigger row, or in a dialog", () => {- const runs = [run("a")];- const onSelect = vi.fn();- renderWithProviders(- <>- <button type="button">outside</button>- <table>- <tbody>- <tr {...PANEL_TRIGGER}>- <td>row</td>- </tr>- </tbody>- </table>- <div role="dialog">dialog</div>- <RunDrawer- trace={traceRefOf(runs[0])}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={onSelect}- fullScreen={false}- onFullScreenChange={vi.fn()}- />- </>,- );- fireEvent.mouseDown(screen.getByTestId("run-view"));- fireEvent.mouseDown(screen.getByText("row"));- fireEvent.mouseDown(screen.getByText("dialog"));- fireEvent.mouseDown(screen.getByText("outside"), { button: 2 });- expect(onSelect).not.toHaveBeenCalled();- fireEvent.mouseDown(screen.getByText("outside"));- expect(onSelect).toHaveBeenCalledExactlyOnceWith(null);- });-- it("unmounts right away on close when the user prefers reduced motion", () => {- mockReducedMotion(true);- const runs = [run("a")];- const { rerender } = renderWithProviders(- <RunDrawer- trace={traceRefOf(runs[0])}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={vi.fn()}- fullScreen={false}- onFullScreenChange={vi.fn()}- />,- );- expect(screen.getByRole("complementary", { name: "Trace details" })).toBeInTheDocument();- rerender(- <RunDrawer- trace={null}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={vi.fn()}- fullScreen={false}- onFullScreenChange={vi.fn()}- />,- );- expect(screen.queryByRole("complementary", { name: "Trace details" })).not.toBeInTheDocument();- });-- it("plays the exit animation before unmounting when motion is allowed", () => {- mockReducedMotion(false);- const runs = [run("a")];- const { rerender } = renderWithProviders(- <RunDrawer- trace={traceRefOf(runs[0])}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={vi.fn()}- fullScreen={false}- onFullScreenChange={vi.fn()}- />,- );- rerender(- <RunDrawer- trace={null}- runs={runs}- accessToken="sk"- selection={selection}- onSelect={vi.fn()}- fullScreen={false}- onFullScreenChange={vi.fn()}- />,- );- expect(screen.getByRole("complementary", { name: "Trace details" })).toHaveClass("animate-trace-drawer-out");- });-});diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/RunDrawer.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/RunDrawer.tsxdeleted file mode 100644index e7422fa171d..00000000000--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/RunDrawer.tsx+++ /dev/null@@ -1,66 +0,0 @@-"use client";--import { useCallback } from "react";--import { SidePanel } from "@/components/shared/SidePanel";--import { RunView } from "./TraceDrawer";-import { type RunSelection, type TraceRef, traceKey, traceRefOf } from "./traceRouting";-import type { TraceSummary } from "./traceTypes";--interface RunDrawerProps {- trace: TraceRef | null;- runs: readonly TraceSummary[];- accessToken: string;- selection: RunSelection;- onSelect: (trace: TraceRef | null) => void;- fullScreen: boolean;- onFullScreenChange: (fullScreen: boolean) => void;-}--/** Right-side drawer over the runs list: resizable, keeps the list clickable, swaps runs in place. */-export function RunDrawer({- trace,- runs,- accessToken,- selection,- onSelect,- fullScreen,- onFullScreenChange,-}: RunDrawerProps) {- const index = trace === null ? -1 : runs.findIndex((run) => traceKey(traceRefOf(run)) === traceKey(trace));- const step = useCallback(- (delta: number) => {- const next = runs[index + delta];- if (next) onSelect(traceRefOf(next));- },- [runs, index, onSelect],- );- const close = useCallback(() => onSelect(null), [onSelect]);- return (- <SidePanel- item={trace}- itemKey={traceKey}- noun="trace"- label="Trace details"- testId="run-drawer"- index={index}- total={runs.length}- onStep={step}- onClose={close}- fullScreen={fullScreen}- onFullScreenChange={onFullScreenChange}- >- {(shown) => (- <RunView- traceId={shown.traceId}- traceRef={shown.traceRef}- selection={selection}- accessToken={accessToken}- onBack={close}- embedded- />- )}- </SidePanel>- );-}diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/SpanTree.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/SpanTree.tsxindex d96e3cd24bd..69143bf1b26 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/SpanTree.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/SpanTree.tsx@@ -34,8 +34,6 @@ interface SpanTreeProps {onToggleGroup: (id: string) => void;onLoadMore: (groupId: string) => void;onOpenDetails?: () => void;- /** Inside the side drawer J/K switch runs, so spans move with the arrow keys. */- embedded?: boolean;query: string;onQueryChange: (query: string) => void;errorsOnly: boolean;@@ -275,7 +273,6 @@ export function SpanTree({onToggleGroup,onLoadMore,onOpenDetails,- embedded = false,query,onQueryChange,errorsOnly,@@ -413,36 +410,6 @@ export function SpanTree({})}</div></div>- <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-x-3 gap-y-1 border-t border-border px-3 py-1.5 text-xs text-muted-foreground">- {embedded ? (- <>- <span className="whitespace-nowrap">- <Kbd>↑</Kbd>/<Kbd>↓</Kbd> step- </span>- <span className="whitespace-nowrap">- <Kbd>J</Kbd>/<Kbd>K</Kbd> trace- </span>- </>- ) : (- <span className="whitespace-nowrap">- <Kbd>J</Kbd>/<Kbd>K</Kbd> move- </span>- )}- <span className="whitespace-nowrap">- <Kbd>←</Kbd>/<Kbd>→</Kbd> fold- </span>- <span className="whitespace-nowrap">- <Kbd>Esc</Kbd> close- </span>- </div></section>);}--function Kbd({ children }: { children: React.ReactNode }) {- return (- <kbd className="rounded-sm border border-border border-b-2 bg-muted px-[3px] font-mono text-muted-foreground">- {children}- </kbd>- );-}diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/TimeRangeControls.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/TimeRangeControls.tsxindex 0802f097d72..3ead80193c7 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/TimeRangeControls.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/TimeRangeControls.tsx@@ -1,6 +1,6 @@"use client";-import { ChevronDown, Pause, Play, RotateCcw } from "lucide-react";+import { ChevronDown, Pause, Play } from "lucide-react";import moment from "moment";import {@@ -24,83 +24,70 @@ export const RANGE_PRESETS = [const RANGE_LABEL_FORMAT = "MMM D, h:mm A";-export const rangeLabel = (range: TimeWindow): string =>+const fixedRangeLabel = (range: TimeWindow): string =>`${moment(range.startMs).format(RANGE_LABEL_FORMAT)} to ${moment(range.endMs).format(RANGE_LABEL_FORMAT)}`;+const presetLabel = (hours: number): string =>+ RANGE_PRESETS.find((preset) => preset.hours === hours)?.label ?? `Last ${hours} hours`;+const SEGMENT = "inline-flex h-7 items-center gap-1.5 px-2.5 text-sm outline-none focus-visible:bg-accent";interface TimeRangeControlsProps {- range: TimeWindow;+ fixedRange: TimeWindow | null;rangeHours: number;onRangeHoursChange: (hours: number) => void;live: boolean;showLive?: boolean;onLiveChange: (live: boolean) => void;- onRefresh: () => void;- refreshing: boolean;}-/** Joined control group: refresh, the actual time range (opens presets), and Live. */+/** Joined control group: the time range (opens presets) and Live. */export function TimeRangeControls({- range,+ fixedRange,rangeHours,onRangeHoursChange,live,showLive = true,onLiveChange,- onRefresh,- refreshing,}: TimeRangeControlsProps) {return (- <div className="flex items-center gap-1.5">- <button- type="button"- onClick={onRefresh}- aria-label="Refresh"- title="Refresh"- aria-busy={refreshing}- className="inline-flex size-7 items-center justify-center rounded-md border border-border text-muted-foreground hover:text-foreground hover:bg-muted/60"- >- <RotateCcw className={cn("size-3.5", refreshing && "animate-spin")} />- </button>- <div className="flex items-center divide-x divide-border overflow-hidden rounded-md border border-border bg-card">- <DropdownMenu>- <DropdownMenuTrigger- aria-label="Time range"- className={cn(SEGMENT, "text-foreground hover:bg-muted/60")}- data-testid="time-range-trigger"- >- <span className="tabular-nums">{rangeLabel(range)}</span>- <ChevronDown className="size-3.5 text-muted-foreground" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-auto min-w-44">- <DropdownMenuRadioGroup- value={String(rangeHours)}- onValueChange={(value: string) => onRangeHoursChange(Number(value))}- >- {RANGE_PRESETS.map((preset) => (- <DropdownMenuRadioItem key={preset.hours} value={String(preset.hours)} className="text-sm">- {preset.label}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- {showLive && (- <button- type="button"- aria-pressed={live}- onClick={() => onLiveChange(!live)}- className={cn(- SEGMENT,- live ? "bg-info/10 text-info hover:bg-info/15" : "text-muted-foreground hover:text-foreground",- )}+ <div className="flex items-center divide-x divide-border overflow-hidden rounded-lg border border-border bg-card">+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label="Time range"+ className={cn(SEGMENT, "text-foreground hover:bg-muted/60")}+ data-testid="time-range-trigger"+ >+ <span className="tabular-nums">{fixedRange ? fixedRangeLabel(fixedRange) : presetLabel(rangeHours)}</span>+ <ChevronDown className="size-3.5 text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-auto min-w-44">+ <DropdownMenuRadioGroup+ value={String(rangeHours)}+ onValueChange={(value: string) => onRangeHoursChange(Number(value))}>- {live ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}- Live- </button>- )}- </div>+ {RANGE_PRESETS.map((preset) => (+ <DropdownMenuRadioItem key={preset.hours} value={String(preset.hours)} className="text-sm">+ {preset.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ {showLive && (+ <button+ type="button"+ aria-pressed={live}+ onClick={() => onLiveChange(!live)}+ className={cn(+ SEGMENT,+ live ? "bg-info/10 text-info hover:bg-info/15" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {live ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}+ Live+ </button>+ )}</div>);}diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.test.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.test.tsxindex 7593673fa42..0eb9889f2d8 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.test.tsx@@ -7,6 +7,7 @@ import { renderWithProviders, testQueryClient } from "../../../../tests/test-utiimport researchTrace from "./__fixtures__/research_trace.json";import swarmTrace from "./__fixtures__/swarm_trace.json";import type { ComponentProps } from "react";+import { ShortcutHints } from "@/components/shared/ShortcutHints";import { initialRunSelection, RunView } from "./TraceDrawer";import { useOpenTraceRouting } from "./traceRouting";import { agentHandoffText } from "./tracesApi";@@ -42,7 +43,12 @@ const research = researchTrace as Trace;function RoutedRunView(props: Omit<ComponentProps<typeof RunView>, "selection">) {const { selection } = useOpenTraceRouting();- return <RunView {...props} selection={selection} />;+ return (+ <>+ <RunView {...props} selection={selection} />+ <ShortcutHints />+ </>+ );}const renderRun = (trace: Trace) => {@@ -131,6 +137,7 @@ describe("RunView", () => {await user.keyboard("{ArrowDown}");expect(screen.getByTestId("detail-pane").getAttribute("data-row-id")).not.toBe(root);expect(screen.queryByRole("button", { name: "Back to runs" })).not.toBeInTheDocument();+ expect(screen.getByLabelText("Keyboard shortcuts")).toHaveTextContent("↑/↓ step←/→ foldEsc close");});it("keeps the current run on screen, inert, while an unvisited run loads in the drawer", async () => {@@ -176,8 +183,10 @@ describe("RunView", () => {expect(screen.getByTestId("detail-pane").getAttribute("data-row-id")).not.toBe(root);await user.keyboard("k");expect(screen.getByTestId("detail-pane")).toHaveAttribute("data-row-id", root);+ expect(screen.getByLabelText("Keyboard shortcuts")).toHaveTextContent("↑/↓ step←/→ foldJ/K moveEsc close");await user.keyboard("{Escape}");expect(screen.queryByTestId("detail-pane")).not.toBeInTheDocument();+ expect(screen.getByLabelText("Keyboard shortcuts")).toHaveTextContent("↑/↓ step←/→ foldJ/K move");});it.each(["button", "Escape"])("reopens the selected step after closing details with %s", async (method) => {@@ -404,7 +413,8 @@ describe("initialRunSelection", () => {it("folds other agent branches while revealing the failed step", () => {const first = child({ span_id: "first", type: "agent" });const second = child({ span_id: "second", type: "agent" });- const failure = child({ span_id: "failed", parent_span_id: "second", type: "tool", status: "error" });+ const failureFields: Partial<Span> = { span_id: "failed", parent_span_id: "second", type: "tool", status: "error" };+ const failure = child(failureFields);const { selectedId, state } = initialRunSelection({ ...research, spans: [base, first, second, failure] });expect(selectedId).toBe("failed");expect(state.collapsedSpanIds.has("first")).toBe(true);diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.tsxindex e8cba149140..e93fe5dc9c0 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/TraceDrawer.tsx@@ -5,8 +5,9 @@ import { QueryErrorResetBoundary, useQueryClient, useSuspenseInfiniteQuery } froimport { ArrowLeft, Check, Copy } from "lucide-react";import { Suspense, useCallback, useDeferredValue, useEffect, useMemo, useState } from "react";import { ErrorBoundary } from "react-error-boundary";-import { useEventListener, useTimeout } from "usehooks-ts";+import { useTimeout } from "usehooks-ts";+import { useShortcut } from "@/components/shared/useShortcut";import { Button } from "@/components/ui/button";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";@@ -36,7 +37,6 @@ import {traceAgentNames,traceDisplayName,} from "./traceUtils";-import { ignoresLetterShortcut } from "../letterShortcut";const INITIAL_STATE: SpanTreeState = {hideFramework: true,@@ -174,17 +174,6 @@ function RunHeader({);}-/** Tree + detail pane for one loaded run, with J/K/arrow keyboard navigation. */-const SPAN_KEYS = { down: ["j", "J", "ArrowDown"], up: ["k", "K", "ArrowUp"] } as const;-const EMBEDDED_SPAN_KEYS = { down: ["ArrowDown"], up: ["ArrowUp"] } as const;--function ignoreStepKey(event: KeyboardEvent): boolean {- const control = (event.target as HTMLElement | null)?.closest(- "input, textarea, select, [contenteditable='true'], [role='combobox'], [role='tablist'], [role='menu'], [role='separator']",- );- return event.defaultPrevented || ignoresLetterShortcut(event) || Boolean(control);-}-interface RunBodyProps {trace: Trace;accessToken: string;@@ -193,8 +182,8 @@ interface RunBodyProps {stale: boolean;}+/** Tree + detail pane for one loaded run. Arrows move and fold steps; J/K also move unless the drawer owns them. */function RunBody({ trace, accessToken, selection, embedded, stale }: RunBodyProps) {- const spanKeys = embedded ? EMBEDDED_SPAN_KEYS : SPAN_KEYS;const { view, selectSpan, setView, stepQuery: query, setStepQuery: setQuery, errorsOnly, setErrorsOnly } = selection;const [initial] = useState(() => initialRunSelection(trace, selection.spanId ?? undefined));const [state, setState] = useState<SpanTreeState>(initial.state);@@ -252,35 +241,24 @@ function RunBody({ trace, accessToken, selection, embedded, stale }: RunBodyPropif (row.kind === "span" && row.hasChildren && row.collapsed === expand) toggleSpan(row.id);if (row.kind === "group" && row.expanded !== expand) toggleGroup(row.id);};- useEventListener(- "keydown",- (event) => {- if (stale || view !== "steps" || ignoreStepKey(event)) return;- const index = rows.findIndex((row) => row.id === selectedRow?.id);- const row = rows[index];- if (event.key === "Escape" && detailOpen) {- event.preventDefault();- event.stopPropagation();- setDetailOpen(false);- return;- }- if ((spanKeys.down as readonly string[]).includes(event.key)) {- event.preventDefault();- const next = rows[Math.min(rows.length - 1, index + 1)];- if (next) select(next.id);- } else if ((spanKeys.up as readonly string[]).includes(event.key)) {- event.preventDefault();- const next = rows[Math.max(0, index - 1)];- if (next) select(next.id);- } else if (event.key === "ArrowLeft" && row) {- setRowExpanded(row, false);- } else if (event.key === "ArrowRight" && row) {- setRowExpanded(row, true);- }- },- undefined,- true,- );+ const moveBy = (delta: number) => {+ const index = rows.findIndex((row) => row.id === selectedRow?.id);+ const next = rows[Math.min(rows.length - 1, Math.max(0, index + delta))];+ if (next) select(next.id);+ };+ const fold = (expand: boolean) => {+ const row = rows.find((candidate) => candidate.id === selectedRow?.id);+ if (row) setRowExpanded(row, expand);+ };+ const active = !stale && view === "steps";+ const pane = { layer: "pane", enabled: active } as const;+ useShortcut("down", () => moveBy(1), { ...pane, description: "step" });+ useShortcut("up", () => moveBy(-1), { ...pane, description: "step" });+ useShortcut("j", () => moveBy(1), { ...pane, enabled: active && !embedded, description: "move" });+ useShortcut("k", () => moveBy(-1), { ...pane, enabled: active && !embedded, description: "move" });+ useShortcut("left", () => fold(false), { ...pane, description: "fold" });+ useShortcut("right", () => fold(true), { ...pane, description: "fold" });+ useShortcut("escape", () => setDetailOpen(false), { ...pane, enabled: active && detailOpen, description: "close" });if (view === "conversation")return (@@ -317,7 +295,6 @@ function RunBody({ trace, accessToken, selection, embedded, stale }: RunBodyProponToggleGroup={toggleGroup}onLoadMore={loadMore}onOpenDetails={detailOpen ? undefined : () => setDetailOpen(true)}- embedded={embedded}query={query}onQueryChange={setQuery}errorsOnly={errorsOnly}diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.test.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.test.tsindex 46c69559af6..0b03c696f8f 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.test.ts+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.test.ts@@ -20,25 +20,25 @@ describe("bucketRuns", () => {expect(buckets).toHaveLength(10);expect(buckets[0].startMs).toBe(range.startMs);expect(buckets.at(-1)?.endMs).toBe(range.endMs);- const fourthBucket = { startMs: START + 3 * HOUR, endMs: START + 4 * HOUR, runs: 0, failed: 0 };+ const fourthBucket = { startMs: START + 3 * HOUR, endMs: START + 4 * HOUR, total: 0, failed: 0 };expect(buckets[3]).toMatchObject(fourthBucket);});it("puts each run in the bucket covering its start time", () => {const buckets = bucketRuns([run(0), run(30 * 60 * 1000), run(2.5 * HOUR), run(10 * HOUR - 1)], range, 10);- expect(buckets.map((b) => b.runs)).toEqual([2, 0, 1, 0, 0, 0, 0, 0, 0, 1]);+ expect(buckets.map((b) => b.total)).toEqual([2, 0, 1, 0, 0, 0, 0, 0, 0, 1]);});it("drops runs that start before or at/after the window", () => {const buckets = bucketRuns([run(-1), run(10 * HOUR), run(20 * HOUR), run(HOUR)], range, 10);- expect(buckets.reduce((sum, b) => sum + b.runs, 0)).toBe(1);- expect(buckets[1].runs).toBe(1);+ expect(buckets.reduce((sum, b) => sum + b.total, 0)).toBe(1);+ expect(buckets[1].total).toBe(1);});it("counts runs with any errors as failed", () => {const buckets = bucketRuns([run(HOUR, 3), run(HOUR + 1), run(HOUR + 2, 1), run(5 * HOUR)], range, 10);- expect(buckets[1]).toMatchObject({ runs: 3, failed: 2 });- expect(buckets[5]).toMatchObject({ runs: 1, failed: 0 });+ expect(buckets[1]).toMatchObject({ total: 3, failed: 2 });+ expect(buckets[5]).toMatchObject({ total: 1, failed: 0 });});});diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.tsxindex 0d4754b57a5..e9ca8752b63 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracesTimeline.tsx@@ -2,12 +2,13 @@import { X } from "lucide-react";import moment from "moment";-import { useEffect, useMemo, useRef, useState, type RefObject } from "react";-import { useMediaQuery, useResizeObserver } from "usehooks-ts";+import { useMemo, useRef, useState, type RefObject } from "react";+import { useResizeObserver } from "usehooks-ts";+import { DotFieldCanvas, DotFieldRoot } from "@/components/shared/dotField/DotField";+import type { DotBand, DotColumn } from "@/components/shared/dotField/dots";import { cn } from "@/lib/cva.config";-import { FIELD_COLS, FIELD_ROWS, columnDots } from "./lensField";import type { TraceSummary } from "./traceTypes";import { traceAgentNames } from "./traceUtils";@@ -23,12 +24,9 @@ export interface TimeWindow {endMs: number;}-export interface Bucket {+export interface Bucket extends DotColumn {startMs: number;endMs: number;- runs: number;- failed: number;- agents: readonly string[];}/** Run counts per equal-width time bucket across the window; runs outside it are dropped. */@@ -44,9 +42,9 @@ export function bucketRuns(runs: readonly TraceSummary[], range: TimeWindow, bucreturn {startMs: range.startMs + i * width,endMs: range.startMs + (i + 1) * width,- runs: hits.length,+ total: hits.length,failed: hits.filter((p) => p.failed).length,- agents: hits.filter((p) => !p.failed).map((p) => p.agent),+ series: hits.filter((p) => !p.failed).map((p) => p.agent),};});}@@ -80,114 +78,8 @@ interface TracesTimelineProps {onSelect: (selection: TimeWindow | null) => void;}-const FAILED_RED = "#e5484d";-const DOT_PITCH = 6;-const FIELD_HEIGHT = FIELD_ROWS * DOT_PITCH;--function fieldDotColor(lit: boolean, dot: ReturnType<typeof columnDots>[number], grid: string): string {- if (!lit) return grid;- if (dot.kind === "failed") return FAILED_RED;- return dot.kind === "run" ? dot.color : grid;-}--interface FieldFrame {- buckets: readonly Bucket[];- max: number;- band: Band | null;- hover: number | null;- progress: number;-}--function dotRadius(lit: boolean, hovered: boolean): number {- if (!lit) return 0.9;- return hovered ? 2.4 : 1.9;-}--function drawField(canvas: HTMLCanvasElement, { buckets, max, band, hover, progress }: FieldFrame) {- const context = canvas.getContext("2d");- const width = canvas.clientWidth;- if (!context || width === 0) return;- const ratio = window.devicePixelRatio || 1;- canvas.width = Math.round(width * ratio);- canvas.height = Math.round(FIELD_HEIGHT * ratio);- context.setTransform(ratio, 0, 0, ratio, 0, 0);- context.clearRect(0, 0, width, FIELD_HEIGHT);- const grid = document.documentElement.classList.contains("dark") ? "rgba(255,255,255,0.08)" : "rgba(15,23,42,0.08)";- const columnWidth = width / buckets.length;- const pitch = columnWidth / FIELD_COLS;- buckets.forEach((bucket, i) => {- const dots = columnDots(bucket, max, i * 7919 + bucket.runs);- const visible = Math.ceil(dots.length * progress);- const dimmed = band !== null && (i < band.lo || i > band.hi);- dots.forEach((dot, index) => {- const lit = dot.kind !== "grid" && index < visible;- context.globalAlpha = lit && dimmed ? 0.15 : 1;- context.fillStyle = fieldDotColor(lit, dot, grid);- context.beginPath();- context.arc(- i * columnWidth + pitch * ((index % FIELD_COLS) + 0.5),- FIELD_HEIGHT - DOT_PITCH * (Math.floor(index / FIELD_COLS) + 0.5),- dotRadius(lit, hover === i),- 0,- Math.PI * 2,- );- context.fill();- });- });- context.globalAlpha = 1;-}--function useRiseIn(): number {- const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");- const [progress, setProgress] = useState(0);- useEffect(() => {- if (reduceMotion) {- setProgress(1);- return;- }- const start = performance.now();- let frame = requestAnimationFrame(function rise(now) {- const t = Math.min(1, (now - start) / 700);- setProgress(1 - (1 - t) ** 3);- if (t < 1) frame = requestAnimationFrame(rise);- });- return () => cancelAnimationFrame(frame);- }, [reduceMotion]);- return progress;-}--function DotField({- buckets,- max,- band,- hover,-}: {- buckets: readonly Bucket[];- max: number;- band: Band | null;- hover: number | null;-}) {- const canvas = useRef<HTMLCanvasElement>(null);- const progress = useRiseIn();- const { width, height } = useResizeObserver({ ref: canvas as RefObject<HTMLCanvasElement> });- useEffect(() => {- if (canvas.current) {- const fieldFrame = { buckets, max, band, hover, progress };- drawField(canvas.current, fieldFrame);- }- }, [buckets, max, band, hover, progress, width, height]);- return (- <canvas- ref={canvas}- aria-hidden="true"- className="pointer-events-none absolute inset-x-0 bottom-0 w-full"- style={{ height: FIELD_HEIGHT }}- />- );-}-function BucketBar({ bucket }: { bucket: Bucket }) {- return <div className="pointer-events-none h-full flex-1" data-testid="timeline-bucket" data-runs={bucket.runs} />;+ return <div className="pointer-events-none h-full flex-1" data-testid="timeline-bucket" data-runs={bucket.total} />;}function NowEdge() {@@ -216,7 +108,7 @@ function BucketTooltip({ bucket, index }: { bucket: Bucket; index: number }) {{moment(bucket.startMs).format(EDGE_FORMAT)} to {moment(bucket.endMs).format("HH:mm")}</div><div>- {bucket.runs} {bucket.runs === 1 ? "run" : "runs"}+ {bucket.total} {bucket.total === 1 ? "run" : "runs"}{bucket.failed > 0 && `, ${bucket.failed} failed`}</div><div className="text-info">drag to zoom</div>@@ -226,11 +118,7 @@ function BucketTooltip({ bucket, index }: { bucket: Bucket; index: number }) {const MIN_DURATION_LABEL_PX = 120;-/** Bucket-index band [lo, hi], inclusive. */-export interface Band {- lo: number;- hi: number;-}+export type Band = DotBand;export type DragMode = "select" | "move" | "resize-lo" | "resize-hi";@@ -346,7 +234,6 @@ function TickAxis({ range }: { range: TimeWindow }) {/** Histogram of runs over the window. Drag to select; drag the bracket or its edges to adjust; Esc clears. */export function TracesTimeline({ runs, range, selection, onSelect }: TracesTimelineProps) {const buckets = useMemo(() => bucketRuns(runs, range), [runs, range]);- const max = Math.max(1, ...buckets.map((b) => b.runs));const [hover, setHover] = useState<number | null>(null);const [drag, setDrag] = useState<DragState | null>(null);const [draft, setDraft] = useState<Band | null>(null);@@ -408,12 +295,14 @@ export function TracesTimeline({ runs, range, selection, onSelect }: TracesTimeltabIndex={0}onKeyDown={onKeyDown}>- <div+ <DotFieldRootref={areaRef}+ columns={buckets}+ band={band}+ hover={hover}role="presentation"data-testid="timeline-area"- className="relative flex cursor-crosshair touch-none items-end"- style={{ height: FIELD_HEIGHT }}+ className="flex cursor-crosshair touch-none items-end"onPointerDown={(e) => begin("select", e)}onPointerMove={onMove}onPointerUp={onUp}@@ -427,7 +316,7 @@ export function TracesTimeline({ runs, range, selection, onSelect }: TracesTimeldata-testid="timeline-cursor"/>)}- <DotField buckets={buckets} max={max} band={band} hover={hover} />+ <DotFieldCanvas /><NowEdge />{buckets.map((b) => (<BucketBar key={b.startMs} bucket={b} />@@ -441,7 +330,7 @@ export function TracesTimeline({ runs, range, selection, onSelect }: TracesTimelonHandleDown={onHandleDown}/>)}- </div>+ </DotFieldRoot><div className="mt-1"><TickAxis range={range} /></div>diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.integration.test.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.integration.test.tsxindex 16efd7faa98..26e0be89104 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.integration.test.tsx@@ -3,7 +3,7 @@ import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { chooseSelectOption, renderWithProviders } from "@/../tests/test-utils";import { copyToClipboard } from "@/utils/dataUtils";-import { LensPreviewContext } from "@/components/lens/LensPreviewButton";+import { LensPreviewContext } from "./LensPreviewButton";import { agentTraceCall, apiClient, sendOtlpTraceCall } from "../../networking";import {codingAgentCommand,diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.tsxindex 26904ef49ff..dcb458fc367 100644--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/TracingSetupCard.tsx@@ -5,7 +5,7 @@ import { useState } from "react";import { useTimeout } from "usehooks-ts";import { cn } from "@/lib/cva.config";-import { LensPreviewButton } from "@/components/lens/LensPreviewButton";+import { LensPreviewButton } from "./LensPreviewButton";import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { copyToClipboard } from "@/utils/dataUtils";diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/lensField.test.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/lensField.test.tsdeleted file mode 100644index 117710f5fb9..00000000000--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/lensField.test.ts+++ /dev/null@@ -1,103 +0,0 @@-import { describe, expect, it } from "vitest";--import {- AGENT_DOT_COLORS,- FIELD_COLS,- FIELD_ROWS,- UNNAMED_AGENT_COLOR,- agoLabel,- agentDotColor,- columnDots,- columnTop,- litDots,-} from "./lensField";--const capacity = FIELD_ROWS * FIELD_COLS;-const bucket = (runs: number, failed = 0, agents: string[] = []) => ({ runs, failed, agents });-const count = (dots: ReturnType<typeof columnDots>, kind: string) => dots.filter((dot) => dot.kind === kind).length;--describe("litDots", () => {- it("lights nothing for an empty bucket and at least one full row for any runs", () => {- expect(litDots(0, 10)).toBe(0);- expect(litDots(1, 1000)).toBe(FIELD_COLS);- });-- it("fills the busiest bucket and keeps quieter buckets visible with square-root scaling", () => {- expect(litDots(4, 4)).toBe(capacity);- expect(litDots(1, 4)).toBe(capacity / 2);- });-});--describe("columnDots", () => {- it("always returns one dot per slot in the column", () => {- expect(columnDots(bucket(0), 4, 1)).toHaveLength(capacity);- expect(count(columnDots(bucket(0), 4, 1), "grid")).toBe(capacity);- });-- it("puts failures above the successful runs", () => {- const dots = columnDots(bucket(4, 1, ["a", "a", "a"]), 4, 3);- const lastRun = dots.findLastIndex((dot) => dot.kind === "run");- const firstFailed = dots.findIndex((dot) => dot.kind === "failed");- expect(firstFailed).toBeGreaterThan(lastRun);- expect(count(dots, "failed")).toBeGreaterThan(0);- });-- it("colors successful runs by agent in bands sized by each agent's share", () => {- const other = ["beta", "gamma", "delta", "omega", "zeta"].find(- (name) => agentDotColor(name) !== agentDotColor("alpha"),- );- if (!other) throw new Error("palette maps every candidate to one color");- const dots = columnDots(bucket(4, 0, ["alpha", "alpha", "alpha", other]), 4, 5);- const colors = dots.flatMap((dot) => (dot.kind === "run" ? [dot.color] : []));- const alpha = colors.filter((color) => color === agentDotColor("alpha")).length;- const beta = colors.filter((color) => color === agentDotColor(other)).length;- expect(alpha).toBeGreaterThan(beta * 2);- expect(beta).toBeGreaterThan(0);- });-- it("keeps the bottom row solid so even a single run reads as a mark", () => {- const dots = columnDots(bucket(1, 0, ["a"]), 1000, 9);- expect(dots.slice(0, FIELD_COLS).every((dot) => dot.kind === "run")).toBe(true);- });-- it("is deterministic for the same bucket and seed so the field does not flicker on re-render", () => {- expect(columnDots(bucket(3, 1, ["a", "b"]), 4, 11)).toEqual(columnDots(bucket(3, 1, ["a", "b"]), 4, 11));- });-});--describe("agentDotColor", () => {- it("gives each agent a stable color from the palette", () => {- expect(agentDotColor("claude-code")).toBe(agentDotColor("claude-code"));- expect(AGENT_DOT_COLORS).toContain(agentDotColor("claude-code"));- });-- it("keeps runs with no agent name neutral so they never look like a named agent", () => {- expect(agentDotColor("")).toBe(UNNAMED_AGENT_COLOR);- expect(AGENT_DOT_COLORS).not.toContain(agentDotColor(""));- });-});--describe("columnTop", () => {- it("reaches the top of the field only for the busiest bucket", () => {- expect(columnTop(4, 4)).toBe(1);- expect(columnTop(0, 4)).toBe(0);- expect(columnTop(1, 4)).toBeGreaterThan(0);- expect(columnTop(1, 4)).toBeLessThan(columnTop(2, 4));- });-});--describe("agoLabel", () => {- const now = Date.UTC(2026, 9, 3, 12, 0, 0);-- it("rounds down to the largest whole unit", () => {- expect(agoLabel(now - 2_000, now)).toBe("just now");- expect(agoLabel(now - 45_000, now)).toBe("45s ago");- expect(agoLabel(now - 12 * 60_000 - 59_000, now)).toBe("12m ago");- expect(agoLabel(now - 3 * 3_600_000, now)).toBe("3h ago");- expect(agoLabel(now - 2 * 86_400_000, now)).toBe("2d ago");- });-- it("treats a timestamp slightly in the future as just now instead of negative", () => {- expect(agoLabel(now + 10_000, now)).toBe("just now");- });-});diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/lensField.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/lensField.tsdeleted file mode 100644index 42499942347..00000000000--- a/ui/litellm-dashboard/src/components/view_logs/TraceView/lensField.ts+++ /dev/null@@ -1,61 +0,0 @@-export const AGENT_DOT_COLORS = ["#0011b3", "#3b5bfd", "#7c93ff", "#22b3e8"] as const;-export const FIELD_ROWS = 12;-export const FIELD_COLS = 2;--export type FieldDot = { kind: "run"; color: string } | { kind: "failed" } | { kind: "grid" };--export interface FieldBucket {- runs: number;- failed: number;- agents: readonly string[];-}--const hash = (seed: number, value: number): number => Math.imul(seed ^ Math.imul(value, 0x9e3779b1), 0x85ebca6b) >>> 0;--export const UNNAMED_AGENT_COLOR = "#94a3b8";--export function agentDotColor(agent: string): string {- if (!agent) return UNNAMED_AGENT_COLOR;- const code = Array.from(agent).reduce((total, char) => hash(total, char.charCodeAt(0)), 7);- return AGENT_DOT_COLORS[code % AGENT_DOT_COLORS.length];-}--/** Lit dot count for a bucket: square-root scaled against the busiest bucket so sparse traffic still reads. */-export function litDots(runs: number, max: number, capacity = FIELD_ROWS * FIELD_COLS): number {- if (runs === 0 || max === 0) return 0;- return Math.max(FIELD_COLS, Math.round(Math.sqrt(runs / max) * capacity));-}--/**- * Bottom-up dots for one time bucket. Successful runs fill from the bottom in agent-colored bands sized by- * each agent's share; failures sit on top. A stable sprinkle of gaps (seeded by bucket) keeps the field organic.- */-export function columnDots(bucket: FieldBucket, max: number, seed: number): readonly FieldDot[] {- const capacity = FIELD_ROWS * FIELD_COLS;- const lit = litDots(bucket.runs, max, capacity);- const failed =- bucket.failed === 0 ? 0 : Math.min(lit, Math.max(FIELD_COLS, Math.round((bucket.failed / bucket.runs) * lit)));- const ok = lit - failed;- const agents = bucket.agents.length ? bucket.agents : [""];- return Array.from({ length: capacity }, (_, index): FieldDot => {- if (index >= lit) return { kind: "grid" };- const gap = index >= FIELD_COLS && hash(seed + 1, index) % 100 < 12;- if (gap) return { kind: "grid" };- if (index >= ok) return { kind: "failed" };- return { kind: "run", color: agentDotColor(agents[Math.floor((index / ok) * agents.length)]) };- });-}--/** Top edge of a bucket's lit dots as a 0..1 fraction of the field height, for anchoring annotation leaders. */-export function columnTop(runs: number, max: number): number {- return Math.ceil(litDots(runs, max) / FIELD_COLS) / FIELD_ROWS;-}--export function agoLabel(thenMs: number, nowMs: number): string {- const seconds = Math.max(0, Math.floor((nowMs - thenMs) / 1000));- if (seconds < 5) return "just now";- if (seconds < 60) return `${seconds}s ago`;- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;- return `${Math.floor(seconds / 86400)}d ago`;-}diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunSearch.test.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunSearch.test.tsxnew file mode 100644index 00000000000..f4da4b49cdc--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunSearch.test.tsx@@ -0,0 +1,47 @@+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";++import { runs } from "./__fixtures__/runs";+import { RunSearch } from "./RunSearch";++const box = () => screen.getByRole("combobox", { name: "Search runs" });+const listbox = () => screen.getByRole("listbox", { name: "Search suggestions" });++describe("RunSearch", () => {+ it("offers the run fields, then the agents seen in the loaded runs", async () => {+ const user = userEvent.setup();+ render(<RunSearch value="" onChange={vi.fn()} runs={runs} />);+ expect(screen.getByText("Search runs, or filter like agent:researcher status:error")).toBeVisible();+ await user.click(box());+ expect(+ within(listbox())+ .getAllByRole("group")+ .map((g) => g.getAttribute("aria-label")),+ ).toEqual(["Run attributes", "Content", "Identity"]);+ await user.keyboard("agent:");+ expect(+ within(listbox())+ .getAllByRole("option")+ .map((o) => o.textContent),+ ).toEqual(["billing-agent", "cron", "researcher", "triage"]);+ await user.click(within(listbox()).getByRole("option", { name: "researcher" }));+ expect(box()).toHaveTextContent(/^agent:researcher $/, { normalizeWhitespace: false });+ });++ it("copies the filtered list as a trace query bounded to the shown range", async () => {+ const user = userEvent.setup();+ const range = { startMs: 1_700_000_000_000, endMs: 1_700_003_600_000 };+ render(<RunSearch value="" onChange={vi.fn()} runs={runs} range={range} />);+ await user.click(box());+ await user.keyboard("agent:res");+ await user.click(screen.getByRole("button", { name: "Copy as curl" }));+ const command = await navigator.clipboard.readText();+ expect(command).toContain('/v1/traces/query"');+ expect(command).toContain("fromUnixTimestamp64Milli(1700000000000)");+ expect(command).toContain("fromUnixTimestamp64Milli(1700003600000)");+ expect(command).toContain("arrayExists(x -> x ILIKE 'res', agents)");+ expect(screen.getByRole("button", { name: "Copied" })).toBeVisible();+ expect(box()).toHaveAttribute("aria-expanded", "true");+ });+});diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunSearch.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunSearch.tsxnew file mode 100644index 00000000000..9c0c850b03f--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunSearch.tsx@@ -0,0 +1,41 @@+"use client";++import { useMemo } from "react";++import type { TraceSummary } from "../traceTypes";+import type { TimeWindow } from "../TracesTimeline";++import { SearchBox } from "@/components/shared/search/SearchBox";+import { itemValues } from "@/components/shared/search/valueSource";+import { RUN_INDEX, RUN_QUERY } from "./runQuery";+import { runQueryCommand } from "./runSql";++const COPY_HINT = "Copy this list as a curl call to the trace query API, which takes full SQL over the same rows.";++interface RunSearchProps {+ value: string;+ onChange: (value: string) => void;+ /** Loaded runs, the source of value suggestions. */+ runs: readonly TraceSummary[];+ /** The range the list shows; the copied query bounds itself to it. */+ range?: TimeWindow;+}++/** The runs list query box: free text plus `key:value` filters over run fields, copyable as a trace query. */+export function RunSearch({ value, onChange, runs, range }: RunSearchProps) {+ const command = useMemo(() => runQueryCommand(range), [range]);+ return (+ <SearchBox.Root+ language={RUN_QUERY}+ values={itemValues(RUN_INDEX, runs)}+ value={value}+ onValueChange={onChange}+ label="Search runs"+ >+ <SearchBox.Input className="rounded-lg" placeholder="Search runs, or filter like agent:researcher status:error" />+ <SearchBox.Suggestions>+ <SearchBox.CopyCommand title={COPY_HINT} command={command} />+ </SearchBox.Suggestions>+ </SearchBox.Root>+ );+}diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/RunsToolbar.tsx b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunsToolbar.tsxsimilarity index 60%rename from ui/litellm-dashboard/src/components/lens/runSearch/RunsToolbar.tsxrename to ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunsToolbar.tsxindex 80e52c2f77d..cb198240960 100644--- a/ui/litellm-dashboard/src/components/lens/runSearch/RunsToolbar.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/RunsToolbar.tsx@@ -1,6 +1,7 @@"use client";-import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";+import type { TraceSummary } from "../traceTypes";+import type { TimeWindow } from "../TracesTimeline";import { RunSearch } from "./RunSearch";@@ -8,14 +9,16 @@ interface RunsToolbarProps {query: string;onQueryChange: (value: string) => void;runs: readonly TraceSummary[];+ /** The range the list shows, for the copied query. */+ range?: TimeWindow;/** Extra controls (time range, live tail) rendered on the right. */children?: React.ReactNode;}-export function RunsToolbar({ query, onQueryChange, runs, children }: RunsToolbarProps) {+export function RunsToolbar({ query, onQueryChange, runs, range, children }: RunsToolbarProps) {return (- <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-border bg-card px-3 py-2">- <RunSearch value={query} onChange={onQueryChange} runs={runs} />+ <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-border bg-card p-2">+ <RunSearch value={query} onChange={onQueryChange} runs={runs} range={range} />{children && <div className="ml-auto flex items-center gap-2">{children}</div>}</div>);diff --git a/ui/litellm-dashboard/src/components/lens/runSearch/__fixtures__/runs.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/__fixtures__/runs.tssimilarity index 92%rename from ui/litellm-dashboard/src/components/lens/runSearch/__fixtures__/runs.tsrename to ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/__fixtures__/runs.tsindex a513907e96a..71a437c087a 100644--- a/ui/litellm-dashboard/src/components/lens/runSearch/__fixtures__/runs.ts+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/__fixtures__/runs.ts@@ -1,4 +1,4 @@-import type { TraceSummary } from "@/components/view_logs/TraceView/traceTypes";+import type { TraceSummary } from "../../traceTypes";export const run = (overrides: Partial<TraceSummary>): TraceSummary => ({agent_count: 1,diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runQuery.test.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runQuery.test.tsnew file mode 100644index 00000000000..d30b8afe382--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runQuery.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";++import { fieldValues } from "@/components/shared/search/evaluate";+import { run, runs } from "./__fixtures__/runs";+import { filterRuns, RUN_INDEX } from "./runQuery";++const ids = (query: string) => filterRuns(runs, query).map((r) => r.trace_id);++describe("filterRuns", () => {+ it("matches free text against input, name and trace id, but not agents or models", () => {+ expect(ids("REFUND")).toEqual(["aaa111"]);+ expect(ids("lead")).toEqual(["bbb222"]);+ expect(ids("ccc3")).toEqual(["ccc333"]);+ expect(ids("triage")).toEqual([]);+ expect(ids("gpt-5")).toEqual([]);+ });++ it("splits runs by status, judged by recorded errors", () => {+ expect(ids("status:error")).toEqual(["bbb222"]);+ expect(ids("-status:error")).toEqual(["aaa111", "ccc333"]);+ expect(ids("status:OK")).toEqual(["aaa111", "ccc333"]);+ });++ it("reads agents from the trace, falling back to the service, and models from the run", () => {+ expect(ids("agent:triage")).toEqual(["aaa111"]);+ expect(ids("agent:cron")).toEqual(["ccc333"]);+ expect(ids("model:gpt-5")).toEqual(["aaa111"]);+ expect(ids("name:support")).toEqual(["aaa111"]);+ });++ it("searches the readable input text", () => {+ expect(ids('input:"*vector stores"')).toEqual(["bbb222"]);+ expect(ids("trace_id:bbb222")).toEqual(["bbb222"]);+ });++ it("combines field clauses with free text", () => {+ expect(ids("agent:*e* -status:error refund")).toEqual(["aaa111"]);+ });+});++describe("RUN_INDEX values", () => {+ it("lists the loaded agents and statuses for autocomplete", () => {+ expect(fieldValues(RUN_INDEX, runs, "agent")).toEqual(["billing-agent", "cron", "researcher", "triage"]);+ expect(fieldValues(RUN_INDEX, runs, "status")).toEqual(["error", "ok"]);+ expect(fieldValues(RUN_INDEX, [run({ models: [] })], "model")).toEqual([]);+ });+});diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runQuery.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runQuery.tsnew file mode 100644index 00000000000..08adfa98656--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runQuery.ts@@ -0,0 +1,36 @@+import { Bot, Box, Braces, CircleDashed, Hash, SquareChevronRight } from "lucide-react";++import type { TraceSummary } from "../traceTypes";+import { previewText, traceAgentNames } from "../traceUtils";++import { type ClientIndex, filterItems } from "@/components/shared/search/evaluate";+import type { FieldSpec, QueryLanguage } from "@/components/shared/search/language";++const RUN_FIELDS = {+ name: { group: "Run attributes", icon: SquareChevronRight, suggestValues: true },+ agent: { group: "Run attributes", icon: Bot, suggestValues: true },+ status: { group: "Run attributes", icon: CircleDashed, suggestValues: true },+ model: { group: "Run attributes", icon: Box, suggestValues: true },+ input: { group: "Content", icon: Braces, suggestValues: false },+ trace_id: { group: "Identity", icon: Hash, suggestValues: false },+} as const satisfies Record<string, FieldSpec>;++export type RunField = keyof typeof RUN_FIELDS;++export const RUN_QUERY: QueryLanguage<RunField> = { fields: RUN_FIELDS };++/** Reads the run fields off a loaded page; free text searches trace id, input and name. */+export const RUN_INDEX: ClientIndex<TraceSummary, RunField> = {+ read: {+ name: (run) => [run.name],+ agent: traceAgentNames,+ status: (run) => [run.error_count > 0 ? "error" : "ok"],+ model: (run) => run.models,+ input: (run) => [previewText(run.input_preview)],+ trace_id: (run) => [run.trace_id],+ },+ freeText: (run) => [run.trace_id, previewText(run.input_preview), run.name],+};++export const filterRuns = (runs: TraceSummary[], query: string): TraceSummary[] =>+ filterItems(RUN_QUERY, RUN_INDEX, runs, query);diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runSql.test.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runSql.test.tsnew file mode 100644index 00000000000..faae0491fbe--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runSql.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";++import { parseQuery } from "@/components/shared/search/language";+import { toSearchQuery } from "@/components/shared/search/searchQuery";+import { RUN_QUERY } from "./runQuery";+import { runPredicates, runQueryCommand, runQuerySql, traceQueryCommand } from "./runSql";++const query = (text: string) => toSearchQuery(parseQuery(RUN_QUERY, text));+const predicates = (text: string) => runPredicates(query(text));+const RANGE = { startMs: 1_700_000_000_000, endMs: 1_700_003_600_000 };++describe("runPredicates", () => {+ it("turns each run field into a predicate over the per-trace rollup columns", () => {+ expect(predicates("agent:researcher status:error model:gpt-5 name:support trace_id:aaa111")).toEqual([+ "arrayExists(x -> x ILIKE 'researcher', agents)",+ "errors > 0",+ "arrayExists(x -> x ILIKE 'gpt-5', models)",+ "name ILIKE 'support'",+ "trace_id ILIKE 'aaa111'",+ ]);+ });++ it("negates and globs like the list filter", () => {+ expect(predicates("-model:gpt* input:*vector*")).toEqual([+ "NOT (arrayExists(x -> x ILIKE 'gpt%', models))",+ "input ILIKE '%vector%'",+ ]);+ });++ it("keeps LIKE metacharacters and quotes literal", () => {+ expect(predicates(String.raw`name:"50%_off's"`)).toEqual([String.raw`name ILIKE '50\\%\\_off\'s'`]);+ expect(predicates(String.raw`input:back\slash`)).toEqual([String.raw`input ILIKE 'back\\\\slash'`]);+ });++ it("resolves a status glob statically, since status has two values", () => {+ expect(predicates("status:ok")).toEqual(["errors = 0"]);+ expect(predicates("status:*")).toEqual(["true"]);+ expect(predicates("-status:pending")).toEqual(["NOT (false)"]);+ });++ it("searches free text across trace id, input and name, and skips a key without a value", () => {+ expect(predicates("agent: refund")).toEqual([+ "(trace_id ILIKE '%refund%' OR input ILIKE '%refund%' OR name ILIKE '%refund%')",+ ]);+ expect(predicates("a*b")).toEqual(["(trace_id ILIKE '%a*b%' OR input ILIKE '%a*b%' OR name ILIKE '%a*b%')"]);+ });+});++describe("runQuerySql", () => {+ it("groups the rollup by trace, bounds the window the list shows and applies the filters", () => {+ const sql = runQuerySql(query("agent:researcher status:error"), RANGE);+ expect(sql).toBe(+ [+ "SELECT TraceId AS trace_id, any(RootName) AS name, any(RootInput) AS input, sum(ErrorCount) AS errors,",+ " groupUniqArrayArray(AgentNames) AS agents, groupUniqArrayArray(Models) AS models",+ "FROM agent_traces_by_key",+ "GROUP BY TraceId",+ `HAVING min(StartTs) >= fromUnixTimestamp64Milli(${RANGE.startMs}) AND min(StartTs) < fromUnixTimestamp64Milli(${RANGE.endMs})`,+ " AND arrayExists(x -> x ILIKE 'researcher', agents)",+ " AND errors > 0",+ "ORDER BY min(StartTs) DESC",+ "LIMIT 100",+ ].join("\n"),+ );+ });++ it("falls back to the last day without a range", () => {+ expect(runQuerySql(query(""))).toContain("HAVING min(StartTs) >= now() - INTERVAL 1 DAY\nORDER BY");+ });+});++describe("traceQueryCommand", () => {+ it("posts the SQL as JSON to the trace query endpoint through a quoted heredoc", () => {+ const sql = `SELECT 1 WHERE name ILIKE 'o\\'reilly' AND note = "q"`;+ const [curl, headers, body, terminator] = traceQueryCommand(sql).split("\n");+ expect(curl).toMatch(/^curl -s ".*\/v1\/traces\/query" \\$/);+ expect(headers).toBe(+ ` -H "Authorization: Bearer $LITELLM_API_KEY" -H "Content-Type: application/json" -d @- <<'EOF'`,+ );+ expect(JSON.parse(body)).toEqual({ sql });+ expect(terminator).toBe("EOF");+ });+});++describe("runQueryCommand", () => {+ it("wraps the bounded, filtered query in the trace query call", () => {+ const command = runQueryCommand(RANGE)(query("agent:researcher status:error"));+ expect(command).toBe(traceQueryCommand(runQuerySql(query("agent:researcher status:error"), RANGE)));+ expect(command).toContain("arrayExists(x -> x ILIKE 'researcher', agents)");+ expect(command).toContain("errors > 0");+ });+});diff --git a/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runSql.ts b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runSql.tsnew file mode 100644index 00000000000..9a3751593bd--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/TraceView/runSearch/runSql.ts@@ -0,0 +1,81 @@+import { getProxyBaseUrl } from "@/components/networking";+import type { TimeWindow } from "../TracesTimeline";++import { valueMatcher } from "@/components/shared/search/language";+import type { SearchFilter, SearchQuery } from "@/components/shared/search/searchQuery";+import type { RunField } from "./runQuery";++const RUN_ROWS = `SELECT TraceId AS trace_id, any(RootName) AS name, any(RootInput) AS input, sum(ErrorCount) AS errors,+ groupUniqArrayArray(AgentNames) AS agents, groupUniqArrayArray(Models) AS models+FROM agent_traces_by_key+GROUP BY TraceId`;++const sqlString = (value: string): string => `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;++/** LIKE's own metacharacters match literally. */+const likeLiteral = (value: string): string => value.replace(/[\\%_]/g, (char) => `\\${char}`);+/** `*` is the only glob, as in the list filter. */+const likePattern = (value: string): string => likeLiteral(value).replaceAll("*", "%");++const matches = (column: string, pattern: string): string => `${column} ILIKE ${sqlString(pattern)}`;+const anyMatches = (column: string, pattern: string): string => `arrayExists(x -> ${matches("x", pattern)}, ${column})`;++const STATUS_PREDICATES = { error: "errors > 0", ok: "errors = 0" } as const;++/** Status has two values, so a glob over it resolves statically to one, both or neither predicate. */+function statusPredicate(value: string): string {+ const hits = (["error", "ok"] as const).filter(valueMatcher(value)).map((status) => STATUS_PREDICATES[status]);+ if (hits.length === 2) return "true";+ return hits[0] ?? "false";+}++const FIELD_PREDICATES: Record<RunField, (value: string) => string> = {+ name: (value) => matches("name", likePattern(value)),+ agent: (value) => anyMatches("agents", likePattern(value)),+ status: statusPredicate,+ model: (value) => anyMatches("models", likePattern(value)),+ input: (value) => matches("input", likePattern(value)),+ trace_id: (value) => matches("trace_id", likePattern(value)),+};++const FREE_TEXT_COLUMNS = ["trace_id", "input", "name"] as const;++const textPredicate = (term: string): string => {+ const contains = `%${likeLiteral(term)}%`;+ return `(${FREE_TEXT_COLUMNS.map((column) => matches(column, contains)).join(" OR ")})`;+};++function filterPredicate(filter: SearchFilter<RunField>): string {+ const predicate = FIELD_PREDICATES[filter.field](filter.value);+ return filter.op === "neq" || filter.op === "nglob" ? `NOT (${predicate})` : predicate;+}++const timeBound = (range: TimeWindow | undefined): string =>+ range+ ? `min(StartTs) >= fromUnixTimestamp64Milli(${range.startMs}) AND min(StartTs) < fromUnixTimestamp64Milli(${range.endMs})`+ : "min(StartTs) >= now() - INTERVAL 1 DAY";++export const runPredicates = (query: SearchQuery<RunField>): string[] => [+ ...query.text.map(textPredicate),+ ...query.filters.map(filterPredicate),+];++/** The runs list as a trace query: one row per trace from the per-key rollup, filtered like the list. */+export function runQuerySql(query: SearchQuery<RunField>, range?: TimeWindow): string {+ const having = [timeBound(range), ...runPredicates(query)].join("\n AND ");+ return `${RUN_ROWS}\nHAVING ${having}\nORDER BY min(StartTs) DESC\nLIMIT 100`;+}++/** Runs `sql` through the trace query API; the quoted heredoc keeps the SQL's own quotes intact. */+export const traceQueryCommand = (sql: string): string =>+ [+ `curl -s "${getProxyBaseUrl().replace(/\/$/, "")}/v1/traces/query" \\`,+ ` -H "Authorization: Bearer $LITELLM_API_KEY" -H "Content-Type: application/json" -d @- <<'EOF'`,+ JSON.stringify({ sql }),+ "EOF",+ ].join("\n");++export const runQueryCommand =+ (range?: TimeWindow) =>+ (query: SearchQuery<RunField>): string =>+ traceQueryCommand(runQuerySql(query, range));diff --git a/ui/litellm-dashboard/src/components/view_logs/letterShortcut.ts b/ui/litellm-dashboard/src/components/view_logs/letterShortcut.tsdeleted file mode 100644index 0ddef471f74..00000000000--- a/ui/litellm-dashboard/src/components/view_logs/letterShortcut.ts+++ /dev/null@@ -1,9 +0,0 @@-const isTypingTarget = (target: EventTarget | null): boolean =>- target instanceof HTMLElement &&- target.matches("input, textarea, select, [contenteditable='true'], [role='combobox']");--const isModified = (event: KeyboardEvent): boolean => event.metaKey || event.ctrlKey || event.altKey;--/** Single-key drawer shortcuts (J, K, Esc) yield to typing and to modified presses such as Cmd+J. */-export const ignoresLetterShortcut = (event: KeyboardEvent): boolean =>- isModified(event) || isTypingTarget(event.target);diff --git a/ui/litellm-dashboard/src/contexts/HotkeysProvider.tsx b/ui/litellm-dashboard/src/contexts/HotkeysProvider.tsxnew file mode 100644index 00000000000..26155042095--- /dev/null+++ b/ui/litellm-dashboard/src/contexts/HotkeysProvider.tsx@@ -0,0 +1,7 @@+"use client";++import { HotkeysProvider as HotkeysScopeProvider } from "react-hotkeys-hook";++export default function HotkeysProvider({ children }: { children: React.ReactNode }) {+ return <HotkeysScopeProvider>{children}</HotkeysScopeProvider>;+}diff --git a/ui/litellm-dashboard/src/lib/storage.test.tsx b/ui/litellm-dashboard/src/lib/storage.test.tsxnew file mode 100644index 00000000000..e5281121519--- /dev/null+++ b/ui/litellm-dashboard/src/lib/storage.test.tsx@@ -0,0 +1,59 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it } from "vitest";+import { z } from "zod";++import { clearStorage, readStorage, storageKey, useStoredValue, writeStorage } from "./storage";++const flag = storageKey("local", "test.flag", z.boolean(), false);+const prefs = storageKey("session", "test.prefs", z.object({ theme: z.enum(["light", "dark"]) }), { theme: "light" });++beforeEach(() => {+ window.localStorage.clear();+ window.sessionStorage.clear();+});++describe("readStorage", () => {+ it("returns the fallback when the slot is empty, unparsable, or fails validation", () => {+ expect(readStorage(flag)).toBe(false);+ window.localStorage.setItem(flag.name, "{not json");+ expect(readStorage(flag)).toBe(false);+ window.localStorage.setItem(flag.name, JSON.stringify("yes"));+ expect(readStorage(flag)).toBe(false);+ window.sessionStorage.setItem(prefs.name, JSON.stringify({ theme: "sepia" }));+ expect(readStorage(prefs)).toEqual({ theme: "light" });+ });++ it("round-trips a written value through its own area only", () => {+ writeStorage(flag, true);+ writeStorage(prefs, { theme: "dark" });+ expect(readStorage(flag)).toBe(true);+ expect(readStorage(prefs)).toEqual({ theme: "dark" });+ expect(window.sessionStorage.getItem(flag.name)).toBeNull();+ expect(window.localStorage.getItem(prefs.name)).toBeNull();+ clearStorage(flag);+ expect(readStorage(flag)).toBe(false);+ });+});++describe("useStoredValue", () => {+ it("starts from what is stored and re-renders readers when the slot changes", () => {+ writeStorage(prefs, { theme: "dark" });+ const { result } = renderHook(() => useStoredValue(prefs));+ expect(result.current[0]).toEqual({ theme: "dark" });+ act(() => result.current[1]({ theme: "light" }));+ expect(result.current[0]).toEqual({ theme: "light" });+ expect(readStorage(prefs)).toEqual({ theme: "light" });+ act(() => clearStorage(prefs));+ expect(result.current[0]).toEqual(prefs.fallback);+ });++ it("follows writes made in another tab", () => {+ const { result } = renderHook(() => useStoredValue(flag));+ expect(result.current[0]).toBe(false);+ act(() => {+ window.localStorage.setItem(flag.name, "true");+ window.dispatchEvent(new StorageEvent("storage", { key: flag.name }));+ });+ expect(result.current[0]).toBe(true);+ });+});diff --git a/ui/litellm-dashboard/src/lib/storage.ts b/ui/litellm-dashboard/src/lib/storage.tsnew file mode 100644index 00000000000..ed7dbebeeae--- /dev/null+++ b/ui/litellm-dashboard/src/lib/storage.ts@@ -0,0 +1,95 @@+import { useCallback, useMemo, useSyncExternalStore } from "react";+import type { z } from "zod";++export type StorageArea = "local" | "session";++/** A web storage slot declared once: where it lives, what it is called, what shape it holds and what to use when absent. */+export interface StorageKey<T> {+ readonly area: StorageArea;+ readonly name: string;+ readonly schema: z.ZodType<T>;+ readonly fallback: T;+}++export function storageKey<T>(area: StorageArea, name: string, schema: z.ZodType<T>, fallback: T): StorageKey<T> {+ return { area, name, schema, fallback };+}++const CHANGE_EVENT = "litellm:storage-change";++function storageOf(area: StorageArea): Storage | null {+ if (typeof window === "undefined") return null;+ try {+ return area === "local" ? window.localStorage : window.sessionStorage;+ } catch {+ return null;+ }+}++function rawOf<T>(key: StorageKey<T>): string | null {+ try {+ return storageOf(key.area)?.getItem(key.name) ?? null;+ } catch {+ return null;+ }+}++function decode<T>(key: StorageKey<T>, raw: string | null): T {+ if (raw === null) return key.fallback;+ try {+ const parsed = key.schema.safeParse(JSON.parse(raw));+ return parsed.success ? parsed.data : key.fallback;+ } catch {+ return key.fallback;+ }+}++export function readStorage<T>(key: StorageKey<T>): T {+ return decode(key, rawOf(key));+}++export function writeStorage<T>(key: StorageKey<T>, value: T): void {+ try {+ storageOf(key.area)?.setItem(key.name, JSON.stringify(value));+ } catch {+ return;+ }+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT, { detail: key.name }));+}++export function clearStorage<T>(key: StorageKey<T>): void {+ try {+ storageOf(key.area)?.removeItem(key.name);+ } catch {+ return;+ }+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT, { detail: key.name }));+}++function subscribeTo(name: string, onChange: () => void): () => void {+ const onStorage = (event: StorageEvent) => {+ if (event.key === null || event.key === name) onChange();+ };+ const onLocal = (event: Event) => {+ if ((event as CustomEvent<string>).detail === name) onChange();+ };+ window.addEventListener("storage", onStorage);+ window.addEventListener(CHANGE_EVENT, onLocal);+ return () => {+ window.removeEventListener("storage", onStorage);+ window.removeEventListener(CHANGE_EVENT, onLocal);+ };+}++/** Validated web storage as React state. Server renders see the fallback; writes from any tab update every reader. */+export function useStoredValue<T>(key: StorageKey<T>): readonly [T, (value: T) => void] {+ const subscribe = useCallback((onChange: () => void) => subscribeTo(key.name, onChange), [key.name]);+ const raw = useSyncExternalStore(+ subscribe,+ () => rawOf(key),+ () => null,+ );+ const value = useMemo(() => decode(key, raw), [key, raw]);+ const write = useCallback((next: T) => writeStorage(key, next), [key]);+ return [value, write];+}diff --git a/ui/litellm-dashboard/tests/lens-test-utils.tsx b/ui/litellm-dashboard/tests/lens-test-utils.tsxnew file mode 100644index 00000000000..da539c8a9d3--- /dev/null+++ b/ui/litellm-dashboard/tests/lens-test-utils.tsx@@ -0,0 +1,39 @@+import type { ReactElement } from "react";+import { LensServicesProvider, liveLensServices } from "@/components/lens/data/LensServices";+import { OnboardingProvider, type Onboarding } from "@/components/lens/onboarding/OnboardingContext";+import { LENS_INTRO_DISMISSED } from "@/components/lens/storage";+import { writeStorage } from "@/lib/storage";+import { renderWithProviders } from "./test-utils";++/** The Lens introduction opens on a first visit; tests about anything else start with it dismissed. */+export function dismissLensIntro() {+ writeStorage(LENS_INTRO_DISMISSED, true);+}++type LensRenderOptions = Parameters<typeof renderWithProviders>[1] & {+ accessToken?: string;+ onboarding?: Partial<Onboarding>;+};++/** Lens components read their API from context, so standalone renders need the live services for a token. */+export function renderWithLens(ui: ReactElement, options?: LensRenderOptions) {+ const { accessToken = "test", onboarding: overrides, ...renderOptions } = options ?? {};+ const services = liveLensServices(accessToken);+ const onboarding: Onboarding = {+ readOnly: false,+ canViewInvestigations: true,+ canInvestigate: true,+ canMintTracingKey: true,+ connect: () => {},+ create: () => {},+ openTrace: () => {},+ ...overrides,+ };+ const wrap = (element: ReactElement) => (+ <LensServicesProvider services={services}>+ <OnboardingProvider value={onboarding}>{element}</OnboardingProvider>+ </LensServicesProvider>+ );+ const view = renderWithProviders(wrap(ui), renderOptions);+ return { ...view, rerender: (next: ReactElement) => view.rerender(wrap(next)) };+}diff --git a/ui/litellm-dashboard/tests/setupTests.ts b/ui/litellm-dashboard/tests/setupTests.tsindex e248275c054..fe637e0473a 100644--- a/ui/litellm-dashboard/tests/setupTests.ts+++ b/ui/litellm-dashboard/tests/setupTests.ts@@ -22,7 +22,7 @@ const ensureTestLocalStorage = () => {return store;};- Object.defineProperties(storagePrototype, {+ const storageMethods: PropertyDescriptorMap = {getItem: {configurable: true,writable: true,@@ -64,7 +64,8 @@ const ensureTestLocalStorage = () => {return Array.from(store.keys())[index] ?? null;},},- });+ };+ Object.defineProperties(storagePrototype, storageMethods);const localStorage = Object.create(storagePrototype);storageStores.set(localStorage, new Map<string, string>());@@ -245,12 +246,12 @@ if (typeof Range !== "undefined" && !("getClientRects" in Range.prototype)) {getBoundingClientRect: { configurable: true, value: () => new DOMRect() },});}-// The virtualized runs list renders no rows in a zero-height viewport, and jsdom reports 0 for every offsetHeight.+// Virtualized InspectorTables render no rows in a zero-height viewport, and jsdom reports 0 for every offsetHeight.if (typeof HTMLElement !== "undefined") {Object.defineProperty(HTMLElement.prototype, "offsetHeight", {configurable: true,get(this: HTMLElement) {- return this.dataset.testid === "runs-table" ? 720 : 0;+ return this.dataset.slot === "inspector-table" ? 720 : 0;},});}diff --git a/ui/litellm-dashboard/tests/test-utils.tsx b/ui/litellm-dashboard/tests/test-utils.tsxindex 553726faff0..b3cd45a15f0 100644--- a/ui/litellm-dashboard/tests/test-utils.tsx+++ b/ui/litellm-dashboard/tests/test-utils.tsx@@ -3,6 +3,7 @@ import { render, RenderOptions, screen, waitFor } from "@testing-library/react";import type userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { NuqsTestingAdapter, OnUrlUpdateFunction } from "nuqs/adapters/testing";+import { HotkeysProvider } from "react-hotkeys-hook";import { expect } from "vitest";// Create a client for testing@@ -31,7 +32,9 @@ export const renderWithProviders = (ui: React.ReactElement, options?: RenderOpticonst { searchParams, onUrlUpdate, ...renderOptions } = options ?? {};const Providers: React.FC<PropsWithChildren> = ({ children }) => (<NuqsTestingAdapter searchParams={searchParams} onUrlUpdate={onUrlUpdate} hasMemory>- <QueryClientProvider client={testQueryClient}>{children}</QueryClientProvider>+ <QueryClientProvider client={testQueryClient}>+ <HotkeysProvider>{children}</HotkeysProvider>+ </QueryClientProvider></NuqsTestingAdapter>);return render(ui, { wrapper: Providers, ...renderOptions });