Archived
radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads each when a request names it, parks it in host memory or restores it from its container, and shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP). Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5, Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B, the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0 serves all of them. Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill reworked, and a reworked adaptive draft window. Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server, each accelerator's memory by model, model states over time. Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410); eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi (#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon (#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and multi-model serving as asked for in #367 and #109. Plugin ABI 39: out-of-tree plugins need to be rebuilt. Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
1 parent
b4c04b6042
commit
ddcb9c69bb
696 files changed
+120770
-56596
No files matched your search
@@ -0,0 +1,139 @@
|
||||
// The shell: the models down the side, the chosen view beside them, and the controls that apply
|
||||
// to every view (the charts' window, the theme, the key of a server that asks for one).
|
||||
import { useEffect, useState } from "react"
|
||||
import { KeyRound, LayoutDashboard, Moon, Sun } from "lucide-react"
|
||||
import { Logo } from "@/components/logo"
|
||||
import { StateDot, stateOf } from "@/components/bits"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInset, SidebarMenu, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
|
||||
import { TooltipProvider } from "@/components/ui/tooltip"
|
||||
import { auth, type FleetModel } from "@/lib/api"
|
||||
import { useFetched } from "@/lib/fetched"
|
||||
import { fDur } from "@/lib/format"
|
||||
import { fleet, useScope } from "@/lib/store"
|
||||
import { RANGES, hrefOf, setRange, setTheme, useRange, useRoute, useTheme } from "@/lib/ui"
|
||||
import { ModelPage } from "@/pages/model"
|
||||
import { Overview } from "@/pages/overview"
|
||||
|
||||
export default function App() {
|
||||
const scope = useScope(fleet)
|
||||
const route = useRoute()
|
||||
const range = useRange()
|
||||
const theme = useTheme()
|
||||
const f = scope.live
|
||||
// A server without a key shows its fleet to its own machine only. From elsewhere the page is
|
||||
// the model the server answers with by default, as /server_info names it.
|
||||
const { data: info, error: infoError } = useFetched<ServerInfo>(scope.refused ? "server_info" : null)
|
||||
const solo: FleetModel | null = scope.refused && info?.server?.model
|
||||
? { id: info.server.model, state: "resident", file: (info.engine?.container ?? "").split("/").pop() || undefined, capabilities: info.capabilities,
|
||||
tp: info.engine?.tensor_parallel, cards: info.engine?.devices?.map((d) => d.device) }
|
||||
: null
|
||||
const models = scope.refused ? (solo ? [solo] : []) : (f?.models ?? [])
|
||||
const shown = scope.refused ? (solo?.id ?? null) : route.model
|
||||
const model = models.find((m) => m.id === shown)
|
||||
const stale = scope.loaded && scope.error !== null
|
||||
useEffect(() => { document.title = shown ? shown + " · radiance" : "radiance" }, [shown])
|
||||
|
||||
return (
|
||||
<TooltipProvider delay={150}>
|
||||
<SidebarProvider>
|
||||
<Sidebar>
|
||||
<SidebarHeader>
|
||||
<a href={hrefOf(null)} className="flex items-center gap-2.5 px-2 py-1.5">
|
||||
<Logo className="size-7 text-primary" />
|
||||
<span className="text-[15px] font-semibold tracking-tight">radiance</span>
|
||||
</a>
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
{!scope.refused && (
|
||||
<SidebarGroup>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton isActive={route.model === null} render={<a href={hrefOf(null)} />}><LayoutDashboard />Overview</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
)}
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel>Models</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{models.map((m) => (
|
||||
<SidebarMenuItem key={m.id}>
|
||||
<SidebarMenuButton isActive={shown === m.id} tooltip={m.error ?? stateOf(m.state).label} render={<a href={hrefOf(m.id, route.model ? route.tab : "performance")} />}>
|
||||
<span className="grid size-4 place-items-center"><StateDot state={m.state} busy={(m.in_flight ?? 0) > 0} /></span>
|
||||
<span className="truncate">{m.id}</span>
|
||||
</SidebarMenuButton>
|
||||
{(m.in_flight ?? 0) > 0 && <SidebarMenuBadge className="num">{m.in_flight}</SidebarMenuBadge>}
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
<SidebarFooter>
|
||||
<div className="num flex items-center justify-between px-2 pb-1 text-xs text-muted-foreground">
|
||||
<span>{f ? `${f.version} · up ${fDur(f.uptime_s)}` : info?.server?.version ? info.server.version : "Connecting…"}</span>
|
||||
{stale && <span className="text-warn">no answer</span>}
|
||||
</div>
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
<SidebarInset className="min-w-0">
|
||||
<header className="sticky top-0 z-20 flex h-13 shrink-0 items-center gap-2 border-b bg-background/85 px-3 backdrop-blur md:px-5">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<span className="truncate text-sm font-medium">{shown ?? "Overview"}</span>
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
<ToggleGroup value={[String(range)]} onValueChange={(v) => { if (v.length) setRange(Number(v[v.length - 1])) }} variant="outline" size="sm" aria-label="Time range">
|
||||
{RANGES.map(([s, label]) => <ToggleGroupItem key={s} value={String(s)} className="num px-2.5 text-xs">{label}</ToggleGroupItem>)}
|
||||
</ToggleGroup>
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Switch theme" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>{theme === "dark" ? <Sun /> : <Moon />}</Button>
|
||||
</div>
|
||||
</header>
|
||||
<main className="min-w-0">
|
||||
{shown !== null ? <ModelPage key={shown} id={shown} tab={route.tab} model={model} />
|
||||
: scope.refused ? (
|
||||
// A server of several models without a key names no model to show from elsewhere.
|
||||
<div className="max-w-prose p-6 text-sm text-muted-foreground">
|
||||
{infoError ? "This server has no API key, so its dashboard is only available on the machine it runs on. Start it with an API key to open it from other devices." : "Connecting…"}
|
||||
</div>
|
||||
)
|
||||
: <Overview />}
|
||||
</main>
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
<KeyDialog />
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
interface ServerInfo {
|
||||
server?: { model?: string; version?: string }
|
||||
capabilities?: Record<string, unknown>
|
||||
engine?: { container?: string; tensor_parallel?: number; devices?: { device: number }[] }
|
||||
}
|
||||
|
||||
/** Asked once a request comes back refused: the server was started with an API key. */
|
||||
function KeyDialog() {
|
||||
const [, bump] = useState(0)
|
||||
const [value, setValue] = useState("")
|
||||
useEffect(() => auth.subscribe(() => bump((n) => n + 1)), [])
|
||||
return (
|
||||
<Dialog open={auth.needed}>
|
||||
<DialogContent showCloseButton={false}>
|
||||
<form onSubmit={(e) => { e.preventDefault(); auth.set(value.trim()) }} className="contents">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2"><KeyRound className="size-4" />Enter API key</DialogTitle>
|
||||
<DialogDescription>This server requires an API key. It is saved in this browser only.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Input type="password" autoFocus value={value} onChange={(e) => setValue(e.target.value)} placeholder="API key" autoComplete="off" />
|
||||
<DialogFooter><Button type="submit" disabled={!value.trim()}>Save</Button></DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// Small pieces every view uses: a figure tile, a model's state, a bar of parts, a row of bars.
|
||||
import type { ReactNode } from "react"
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardAction, CardDescription } from "@/components/ui/card"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export function Kpi({ label, value, unit, detail, className }: { label: string; value: ReactNode; unit?: string; detail?: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={cn("flex min-w-0 flex-col gap-1 rounded-xl border bg-card px-4 py-3.5", className)}>
|
||||
<span className="truncate text-xs font-medium text-muted-foreground">{label}</span>
|
||||
<span className="num flex items-baseline gap-1 text-2xl leading-none font-semibold tracking-tight">
|
||||
<span className="truncate">{value}</span>
|
||||
{unit && <span className="text-sm font-normal text-muted-foreground">{unit}</span>}
|
||||
</span>
|
||||
<span className="min-h-4 truncate text-xs text-muted-foreground">{detail}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Panel({ title, description, action, children, className, flush }: { title?: ReactNode; description?: ReactNode; action?: ReactNode; children: ReactNode; className?: string; flush?: boolean }) {
|
||||
return (
|
||||
<Card className={cn("min-w-0 gap-3 py-4 shadow-none", className)}>
|
||||
{(title || action) && (
|
||||
<CardHeader className="px-4">
|
||||
<CardTitle className="text-sm font-medium">{title}</CardTitle>
|
||||
{description && <CardDescription className="text-xs">{description}</CardDescription>}
|
||||
{action && <CardAction>{action}</CardAction>}
|
||||
</CardHeader>
|
||||
)}
|
||||
<CardContent className={flush ? "px-0" : "px-4"}>{children}</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
const STATES: Record<string, { label: string; tone: string }> = {
|
||||
resident: { label: "Loaded", tone: "var(--ok)" },
|
||||
loading: { label: "Loading", tone: "var(--warn)" },
|
||||
waiting: { label: "Waiting for room", tone: "var(--series-4)" },
|
||||
restoring: { label: "Restoring", tone: "var(--warn)" },
|
||||
closing: { label: "Unloading", tone: "var(--warn)" },
|
||||
parked: { label: "Parked", tone: "var(--series-1)" },
|
||||
cold: { label: "Not loaded", tone: "var(--idle)" },
|
||||
failed: { label: "Failed", tone: "var(--bad)" },
|
||||
}
|
||||
export const stateOf = (s: string | undefined) => STATES[s ?? ""] ?? { label: s || "Unknown", tone: "var(--idle)" }
|
||||
/** The state behind a history value of an `s:<id>` column. */
|
||||
export const STATE_OF_CODE: Record<number, string> = { 0: "cold", 1: "parked", 2: "loading", 3: "resident", 4: "failed", 5: "waiting" }
|
||||
|
||||
export function StateDot({ state, busy, className }: { state?: string; busy?: boolean; className?: string }) {
|
||||
const s = stateOf(state)
|
||||
return (
|
||||
<span className={cn("relative inline-flex size-2 shrink-0", className)} aria-label={s.label}>
|
||||
{busy && <span className="absolute inline-flex size-full animate-ping rounded-full opacity-60" style={{ background: s.tone }} />}
|
||||
<span className="relative inline-flex size-2 rounded-full" style={{ background: s.tone }} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
export function StateBadge({ state, doing }: { state?: string; doing?: string }) {
|
||||
const s = stateOf(state)
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium whitespace-nowrap" style={{ borderColor: `color-mix(in oklab, ${s.tone} 35%, transparent)`, background: `color-mix(in oklab, ${s.tone} 10%, transparent)` }}>
|
||||
<span className="size-1.5 rounded-full" style={{ background: s.tone }} />
|
||||
{state === "waiting" ? s.label : doing || s.label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export interface Part { key: string; label: string; value: number; color: string; text?: string }
|
||||
/** One bar divided among parts, in proportion, with what is left of `total` shown empty. */
|
||||
export function PartBar({ parts, total, className }: { parts: Part[]; total?: number; className?: string }) {
|
||||
const sum = parts.reduce((a, p) => a + Math.max(0, p.value), 0)
|
||||
const whole = Math.max(total ?? sum, sum, 1)
|
||||
return (
|
||||
<div className={cn("flex h-2.5 w-full overflow-hidden rounded-full bg-muted", className)}>
|
||||
{parts.filter((p) => p.value > 0).map((p) => (
|
||||
<Tooltip key={p.key}>
|
||||
<TooltipTrigger render={<div className="h-full min-w-[3px] border-r border-background/60 last:border-r-0 transition-[width] duration-500" style={{ width: (100 * p.value) / whole + "%", background: p.color }} />} />
|
||||
<TooltipContent>{p.label}{p.text ? " · " + p.text : ""}</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export function PartLegend({ parts, className }: { parts: Part[]; className?: string }) {
|
||||
return (
|
||||
<div className={cn("flex flex-wrap gap-x-4 gap-y-1 text-xs", className)}>
|
||||
{parts.filter((p) => p.value > 0).map((p) => (
|
||||
<span key={p.key} className="inline-flex items-center gap-1.5">
|
||||
<i className="size-2 rounded-full" style={{ background: p.color }} />
|
||||
<span className="text-muted-foreground">{p.label}</span>
|
||||
{p.text && <span className="num">{p.text}</span>}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Upright bars of equal width, one a value, against `max`. */
|
||||
export function Bars({ values, max, color = "var(--series-1)", height = 120, tip, labels }: { values: number[]; max?: number; color?: string; height?: number; tip?: (i: number, v: number) => string; labels?: (i: number) => string | null }) {
|
||||
const top = Math.max(max ?? 0, ...values, 1e-9)
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-end justify-center gap-[3px]" style={{ height }}>
|
||||
{values.map((v, i) => (
|
||||
<Tooltip key={i}>
|
||||
<TooltipTrigger render={<div className="flex h-full max-w-14 min-w-0 flex-1 items-end rounded-sm bg-muted/60"><div className="w-full rounded-sm transition-[height] duration-500" style={{ height: Math.max(v > 0 ? 2 : 0, (100 * v) / top) + "%", background: color }} /></div>} />
|
||||
{tip && <TooltipContent className="whitespace-pre-line">{tip(i, v)}</TooltipContent>}
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
{labels && (
|
||||
<div className="num mt-1.5 flex justify-center gap-[3px] text-[10px] text-muted-foreground">
|
||||
{values.map((_, i) => <span key={i} className="max-w-14 min-w-0 flex-1 truncate text-center">{labels(i)}</span>)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Empty({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cn("grid min-h-28 place-items-center rounded-lg border border-dashed px-4 py-8 text-center text-sm text-muted-foreground", className)}>{children}</div>
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// A time chart over one scope's samples. The x axis is always the chosen window ending at the
|
||||
// latest sample, so a model that started a minute ago draws a minute of line in an hour of axis
|
||||
// instead of stretching it. A sample without a value is a gap in the line, never a zero.
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
|
||||
import uPlot from "uplot"
|
||||
import "uplot/dist/uPlot.min.css"
|
||||
import type { Series } from "@/lib/store"
|
||||
import { fClock, fin } from "@/lib/format"
|
||||
import { useTheme } from "@/lib/ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export interface Line { key: string; label: string; color?: number; dash?: boolean }
|
||||
export interface ChartProps {
|
||||
data: Series
|
||||
version: number
|
||||
lines: Line[]
|
||||
range: number
|
||||
fmt: (v: number) => string
|
||||
height?: number
|
||||
stack?: boolean
|
||||
max?: number // a fixed upper bound (1 for a ratio)
|
||||
tight?: boolean // the y range follows the data instead of starting at zero
|
||||
integer?: boolean // counts: whole ticks only
|
||||
bytes?: boolean // sizes: ticks at binary multiples
|
||||
join?: boolean // sparse events: join the values across the gaps between them
|
||||
className?: string
|
||||
}
|
||||
|
||||
const cssVar = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim()
|
||||
let probe: CanvasRenderingContext2D | null = null
|
||||
/** A CSS colour as rgba() with the given alpha, whatever notation the stylesheet used. */
|
||||
export function withAlpha(color: string, a: number): string {
|
||||
if (!probe) { const c = document.createElement("canvas"); c.width = c.height = 1; probe = c.getContext("2d", { willReadFrequently: true }) }
|
||||
if (!probe) return color
|
||||
probe.clearRect(0, 0, 1, 1)
|
||||
probe.fillStyle = color
|
||||
probe.fillRect(0, 0, 1, 1)
|
||||
const [r, g, b] = probe.getImageData(0, 0, 1, 1).data
|
||||
return `rgba(${r},${g},${b},${a})`
|
||||
}
|
||||
export const seriesColor = (i: number) => cssVar("--series-" + (((i - 1) % 8) + 1))
|
||||
|
||||
const INT_STEPS = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000]
|
||||
const BYTE_STEPS = Array.from({ length: 50 }, (_, i) => 2 ** i)
|
||||
function niceMax(v: number): number {
|
||||
if (!(v > 0)) return 1
|
||||
const p = Math.pow(10, Math.floor(Math.log10(v)))
|
||||
for (const m of [1, 1.5, 2, 3, 4, 5, 6, 8, 10]) if (m * p >= v) return m * p
|
||||
return 10 * p
|
||||
}
|
||||
|
||||
export function Chart({ data, version, lines, range, fmt, height = 220, stack, max, tight, integer, bytes, join, className }: ChartProps) {
|
||||
const host = useRef<HTMLDivElement>(null)
|
||||
const tip = useRef<HTMLDivElement>(null)
|
||||
const plot = useRef<uPlot | null>(null)
|
||||
const raw = useRef<(number | null)[][]>([])
|
||||
const theme = useTheme()
|
||||
const [empty, setEmpty] = useState(true)
|
||||
const shape = lines.map((l) => l.key + ":" + (l.color ?? 0) + (l.dash ? "d" : "")).join(",")
|
||||
const fmtRef = useRef(fmt)
|
||||
fmtRef.current = fmt
|
||||
const linesRef = useRef(lines)
|
||||
linesRef.current = lines
|
||||
|
||||
// The window's arrays: time, then one array a line (cumulative when stacked).
|
||||
const frame = useMemo(() => {
|
||||
const end = data.end
|
||||
const lo = data.firstAfter(end - range)
|
||||
const t = data.t.slice(lo)
|
||||
const cols = lines.map((l) => (data.col(l.key) ?? []).slice(lo))
|
||||
for (const c of cols) while (c.length < t.length) c.push(null)
|
||||
let any = false
|
||||
for (const c of cols) for (const v of c) if (v !== null) { any = true; break }
|
||||
let drawn: (number | null)[][] = cols
|
||||
if (stack) {
|
||||
const acc = new Array<number>(t.length).fill(0)
|
||||
drawn = cols.map((c) => c.map((v, i) => {
|
||||
const some = cols.some((q) => q[i] !== null)
|
||||
if (!some) return null
|
||||
acc[i] += v ?? 0
|
||||
return acc[i]
|
||||
}))
|
||||
}
|
||||
return { t, cols, drawn, end, any }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data, version, range, shape, stack])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = host.current
|
||||
if (!el) return
|
||||
const ink = cssVar("--muted-foreground"), grid = cssVar("--grid")
|
||||
const font = "11px 'Geist Variable', ui-sans-serif, system-ui, sans-serif"
|
||||
const colors = linesRef.current.map((l, i) => (l.dash ? cssVar("--idle") : seriesColor(l.color ?? i + 1)))
|
||||
const n = linesRef.current.length
|
||||
const opts: uPlot.Options = {
|
||||
width: Math.max(120, el.clientWidth), height,
|
||||
padding: [10, 22, 0, 0],
|
||||
legend: { show: false },
|
||||
cursor: { y: false, points: { size: 7, width: 2 }, drag: { x: false, y: false } },
|
||||
scales: {
|
||||
x: { time: true },
|
||||
y: {
|
||||
range: (_u, lo, hi) => {
|
||||
if (fin(max)) return [0, max]
|
||||
if (!fin(lo) || !fin(hi)) return [0, 1]
|
||||
if (tight && hi > 0) { const pad = Math.max((hi - lo) * 0.15, hi * 0.01); return [Math.max(0, lo - pad), hi + pad] }
|
||||
if (bytes) return [0, Math.max(1024, 2 ** Math.ceil(Math.log2(Math.max(1, hi * 1.02))))]
|
||||
return [0, integer ? Math.max(1, Math.ceil(hi)) : niceMax(hi * 1.05)]
|
||||
},
|
||||
},
|
||||
},
|
||||
axes: [
|
||||
{ stroke: ink, font, grid: { show: false }, ticks: { stroke: grid, size: 4 }, space: 58, size: 26, gap: 4,
|
||||
values: (u, splits) => { const span = (u.scales.x.max ?? 0) - (u.scales.x.min ?? 0); return splits.map((s) => fClock(s, span <= 600)) } },
|
||||
{ stroke: ink, font, grid: { stroke: grid, width: 1 }, ticks: { show: false }, gap: 6, space: 28,
|
||||
incrs: integer ? INT_STEPS : bytes ? BYTE_STEPS : undefined,
|
||||
values: (_u, splits) => splits.map((s) => fmtRef.current(s).replace(/\.0+(?=$|[^\d])/, "")),
|
||||
size(self, values, axisIdx, cycle) {
|
||||
const axis = self.axes[axisIdx] as uPlot.Axis & { _size?: number }
|
||||
if (cycle > 1) return axis._size ?? 40
|
||||
let w = 10
|
||||
const longest = (values ?? []).reduce((a, v) => (v.length > a.length ? v : a), "")
|
||||
if (longest) { self.ctx.font = font; w += self.ctx.measureText(longest).width / devicePixelRatio }
|
||||
return Math.ceil(Math.max(34, w))
|
||||
} },
|
||||
],
|
||||
series: [{}, ...linesRef.current.map((l, i): uPlot.Series => ({
|
||||
label: l.label, stroke: colors[i], width: l.dash ? 1.25 : 1.75, dash: l.dash ? [5, 4] : undefined,
|
||||
spanGaps: !!join,
|
||||
fill: l.dash ? undefined : stack ? withAlpha(colors[i], 0.34) : n === 1 ? withAlpha(colors[i], 0.12) : undefined,
|
||||
points: { show: !!join, size: 5, fill: colors[i] },
|
||||
}))],
|
||||
bands: stack ? linesRef.current.slice(1).map((_, i) => ({ series: [i + 2, i + 1] as [number, number], fill: withAlpha(colors[i + 1], 0.34) })) : undefined,
|
||||
hooks: {
|
||||
setCursor: [(u) => {
|
||||
const box = tip.current
|
||||
if (!box) return
|
||||
const i = u.cursor.idx
|
||||
if (i == null || u.cursor.left == null || u.cursor.left < 0) { box.style.opacity = "0"; return }
|
||||
// A chart of many lines (one a model) lists the ones with something at the cursor,
|
||||
// largest first, and says how many it left out; a chart of a few lists them all.
|
||||
const all = linesRef.current.map((l, k) => ({ l, k, v: raw.current[k]?.[i] ?? null }))
|
||||
const many = all.length > 4
|
||||
const shown = many ? all.filter((x) => x.v !== null && x.v !== 0).sort((p, q) => (q.v as number) - (p.v as number)).slice(0, 8) : all
|
||||
const row = (color: string, label: string, text: string) =>
|
||||
`<div class="flex items-center gap-2"><i style="background:${color}" class="size-2 rounded-full shrink-0"></i><span class="text-muted-foreground">${label}</span><b class="ml-auto pl-3 font-medium num">${text}</b></div>`
|
||||
const rows = shown.map((x) => row(colors[x.k], x.l.label, x.v == null ? "–" : fmtRef.current(x.v)))
|
||||
if (many && stack && shown.length > 1)
|
||||
rows.push(`<div class="mt-1 flex border-t pt-1"><span class="text-muted-foreground">Total</span><b class="ml-auto pl-3 font-medium num">${fmtRef.current(shown.reduce((a, x) => a + (x.v as number), 0))}</b></div>`)
|
||||
if (many && shown.length === 0) rows.push(`<div class="text-muted-foreground">Nothing at this time</div>`)
|
||||
box.innerHTML = `<div class="mb-1 text-muted-foreground num">${fClock(u.data[0][i], true)}</div>` + rows.join("")
|
||||
const left = u.cursor.left + (u.bbox.left / devicePixelRatio)
|
||||
const flip = left > el.clientWidth * 0.62
|
||||
box.style.left = flip ? "" : left + 14 + "px"
|
||||
box.style.right = flip ? el.clientWidth - left + 14 + "px" : ""
|
||||
box.style.opacity = "1"
|
||||
}],
|
||||
},
|
||||
}
|
||||
const u = new uPlot(opts, [[], ...linesRef.current.map(() => [])] as unknown as uPlot.AlignedData, el)
|
||||
plot.current = u
|
||||
const ro = new ResizeObserver(() => { if (el.clientWidth > 0) u.setSize({ width: el.clientWidth, height }) })
|
||||
ro.observe(el)
|
||||
return () => { ro.disconnect(); u.destroy(); plot.current = null }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [shape, stack, max, tight, integer, bytes, join, height, theme])
|
||||
|
||||
useEffect(() => {
|
||||
const u = plot.current
|
||||
if (!u) return
|
||||
raw.current = frame.cols
|
||||
u.batch(() => {
|
||||
u.setData([frame.t, ...frame.drawn] as unknown as uPlot.AlignedData, false)
|
||||
u.setScale("x", { min: frame.end - range, max: frame.end })
|
||||
})
|
||||
setEmpty(!frame.any)
|
||||
}, [frame, range, theme, shape, stack, max, tight, integer, bytes, join, height])
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)} style={{ height }}>
|
||||
<div ref={host} className="absolute inset-0" />
|
||||
{empty && <div className="pointer-events-none absolute inset-0 grid place-items-center text-xs text-muted-foreground">No data in this time range</div>}
|
||||
<div ref={tip} className="pointer-events-none absolute top-2 z-10 min-w-36 rounded-md border bg-popover px-2.5 py-2 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** A line's colour chips with their names, for a chart of more than one line. */
|
||||
export function Legend({ lines }: { lines: Line[] }) {
|
||||
useTheme()
|
||||
return (
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
{lines.map((l, i) => (
|
||||
<span key={l.key} className="inline-flex items-center gap-1.5">
|
||||
<i className="size-2 rounded-full" style={{ background: l.dash ? "var(--idle)" : `var(--series-${((((l.color ?? i + 1) - 1) % 8) + 1)})` }} />
|
||||
{l.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// The mark: an R in three solid pieces, its stem, its bowl and its leg. It takes the current text
|
||||
// colour.
|
||||
export function Logo({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 64 64" className={className} role="img" aria-label="radiance" fill="currentColor">
|
||||
<rect x="17" y="11" width="8" height="42" />
|
||||
<path d="M29 11h7a12.5 12.5 0 0 1 0 25h-7v-8h7a4.5 4.5 0 0 0 0-9h-7z" />
|
||||
<path d="M33 40h9l8 13h-9z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Button as ButtonPrimitive } from "@base-ui/react/button"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "cn"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
outline:
|
||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
icon: "size-8",
|
||||
"icon-xs":
|
||||
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm":
|
||||
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
|
||||
"icon-lg": "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
|
||||
return (
|
||||
<ButtonPrimitive
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,102 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Card({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn(
|
||||
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-(--card-spacing)", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn(
|
||||
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
|
||||
import { cn } from "cn"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Backdrop
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: DialogPrimitive.Popup.Props & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Popup
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-2 right-2"
|
||||
size="icon-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon
|
||||
/>
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Popup>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close render={<Button variant="outline" />}>
|
||||
Close
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn(
|
||||
"font-heading text-base leading-none font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Description.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
import { Input as InputPrimitive } from "@base-ui/react/input"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<InputPrimitive
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: SeparatorPrimitive.Props) {
|
||||
return (
|
||||
<SeparatorPrimitive
|
||||
data-slot="separator"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,136 @@
|
||||
import * as React from "react"
|
||||
import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"
|
||||
import { cn } from "cn"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
function Sheet({ ...props }: SheetPrimitive.Root.Props) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
||||
}
|
||||
|
||||
function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
||||
}
|
||||
|
||||
function SheetClose({ ...props }: SheetPrimitive.Close.Props) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
||||
}
|
||||
|
||||
function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
||||
}
|
||||
|
||||
function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<SheetPrimitive.Backdrop
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/10 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: SheetPrimitive.Popup.Props & {
|
||||
side?: "top" | "right" | "bottom" | "left"
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Popup
|
||||
data-slot="sheet-content"
|
||||
data-side={side}
|
||||
className={cn(
|
||||
"fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0 data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem] data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem] data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem] data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem] data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<SheetPrimitive.Close
|
||||
data-slot="sheet-close"
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-3 right-3"
|
||||
size="icon-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon
|
||||
/>
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
)}
|
||||
</SheetPrimitive.Popup>
|
||||
</SheetPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-0.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn(
|
||||
"font-heading text-base font-medium text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: SheetPrimitive.Description.Props) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { mergeProps } from "@base-ui/react/merge-props"
|
||||
import { useRender } from "@base-ui/react/use-render"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "cn"
|
||||
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<div
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
dir,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
dir={dir}
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar"
|
||||
data-mobile="true"
|
||||
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Sidebar</SheetTitle>
|
||||
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
data-slot="sidebar"
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
data-slot="sidebar-gap"
|
||||
className={cn(
|
||||
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
data-slot="sidebar-container"
|
||||
data-side={side}
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
data-slot="sidebar-inner"
|
||||
className="flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={cn(className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
data-sidebar="rail"
|
||||
data-slot="sidebar-rail"
|
||||
aria-label="Toggle Sidebar"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Toggle Sidebar"
|
||||
className={cn(
|
||||
"absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
|
||||
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
return (
|
||||
<main
|
||||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Input>) {
|
||||
return (
|
||||
<Input
|
||||
data-slot="sidebar-input"
|
||||
data-sidebar="input"
|
||||
className={cn("h-8 w-full bg-background shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-header"
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-footer"
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
data-slot="sidebar-separator"
|
||||
data-sidebar="separator"
|
||||
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-content"
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group"
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"div"> & React.ComponentProps<"div">) {
|
||||
return useRender({
|
||||
defaultTagName: "div",
|
||||
props: mergeProps<"div">(
|
||||
{
|
||||
className: cn(
|
||||
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-group-label",
|
||||
sidebar: "group-label",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
className,
|
||||
render,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> & React.ComponentProps<"button">) {
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(
|
||||
{
|
||||
className: cn(
|
||||
"absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-group-action",
|
||||
sidebar: "group-action",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-group-content"
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu"
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-item"
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button group/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:font-medium data-active:text-sidebar-accent-foreground [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function SidebarMenuButton({
|
||||
render,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> &
|
||||
React.ComponentProps<"button"> & {
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const { isMobile, state } = useSidebar()
|
||||
const comp = useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(
|
||||
{
|
||||
className: cn(sidebarMenuButtonVariants({ variant, size }), className),
|
||||
},
|
||||
props
|
||||
),
|
||||
render: !tooltip ? render : <TooltipTrigger render={render} />,
|
||||
state: {
|
||||
slot: "sidebar-menu-button",
|
||||
sidebar: "menu-button",
|
||||
size,
|
||||
active: isActive,
|
||||
},
|
||||
})
|
||||
|
||||
if (!tooltip) {
|
||||
return comp
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
{comp}
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
className,
|
||||
render,
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: useRender.ComponentProps<"button"> &
|
||||
React.ComponentProps<"button"> & {
|
||||
showOnHover?: boolean
|
||||
}) {
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(
|
||||
{
|
||||
className: cn(
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 after:absolute after:-inset-2 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 md:after:hidden [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
showOnHover &&
|
||||
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-active/menu-button:text-sidebar-accent-foreground aria-expanded:opacity-100 md:opacity-0",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-menu-action",
|
||||
sidebar: "menu-action",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-badge"
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none group-data-[collapsible=icon]:hidden peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 peer-data-active/menu-button:text-sidebar-accent-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
className,
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const [width] = React.useState(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="sidebar-menu-skeleton"
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-(--skeleton-width) flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="sidebar-menu-sub"
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="sidebar-menu-sub-item"
|
||||
data-sidebar="menu-sub-item"
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
render,
|
||||
size = "md",
|
||||
isActive = false,
|
||||
className,
|
||||
...props
|
||||
}: useRender.ComponentProps<"a"> &
|
||||
React.ComponentProps<"a"> & {
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}) {
|
||||
return useRender({
|
||||
defaultTagName: "a",
|
||||
props: mergeProps<"a">(
|
||||
{
|
||||
className: cn(
|
||||
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-sm data-[size=sm]:text-xs data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
className
|
||||
),
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
slot: "sidebar-menu-sub-button",
|
||||
sidebar: "menu-sub-button",
|
||||
size,
|
||||
active: isActive,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { cn } from "cn"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: SwitchPrimitive.Root.Props & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
@@ -0,0 +1,115 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50 has-aria-expanded:bg-muted/50 data-[state=selected]:bg-muted",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: TabsPrimitive.Root.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
data-orientation={orientation}
|
||||
className={cn(
|
||||
"group/tabs flex gap-2 data-horizontal:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const tabsListVariants = cva(
|
||||
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-muted",
|
||||
line: "gap-1 bg-transparent",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: TabsPrimitive.List.Props & VariantProps<typeof tabsListVariants>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
data-variant={variant}
|
||||
className={cn(tabsListVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Tab
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent",
|
||||
"data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
|
||||
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) {
|
||||
return (
|
||||
<TabsPrimitive.Panel
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 text-sm outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
|
||||
@@ -0,0 +1,87 @@
|
||||
import * as React from "react"
|
||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "cn"
|
||||
|
||||
import { toggleVariants } from "@/components/ui/toggle"
|
||||
|
||||
const ToggleGroupContext = React.createContext<
|
||||
VariantProps<typeof toggleVariants> & {
|
||||
spacing?: number
|
||||
orientation?: "horizontal" | "vertical"
|
||||
}
|
||||
>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
spacing: 2,
|
||||
orientation: "horizontal",
|
||||
})
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
spacing = 2,
|
||||
orientation = "horizontal",
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props &
|
||||
VariantProps<typeof toggleVariants> & {
|
||||
spacing?: number
|
||||
orientation?: "horizontal" | "vertical"
|
||||
}) {
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
data-spacing={spacing}
|
||||
data-orientation={orientation}
|
||||
style={{ "--gap": spacing } as React.CSSProperties}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-lg data-[size=sm]:rounded-[min(var(--radius-md),10px)] data-vertical:flex-col data-vertical:items-stretch",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider
|
||||
value={{ variant, size, spacing, orientation }}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
)
|
||||
}
|
||||
|
||||
function ToggleGroupItem({
|
||||
className,
|
||||
children,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext)
|
||||
|
||||
return (
|
||||
<TogglePrimitive
|
||||
data-slot="toggle-group-item"
|
||||
data-variant={context.variant || variant}
|
||||
data-size={context.size || size}
|
||||
data-spacing={context.spacing}
|
||||
className={cn(
|
||||
"shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-2 focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-1.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-1.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-lg group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-lg group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-lg group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-lg group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",
|
||||
toggleVariants({
|
||||
variant: context.variant || variant,
|
||||
size: context.size || size,
|
||||
}),
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</TogglePrimitive>
|
||||
)
|
||||
}
|
||||
|
||||
export { ToggleGroup, ToggleGroupItem }
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client"
|
||||
|
||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "cn"
|
||||
|
||||
const toggleVariants = cva(
|
||||
"group/toggle inline-flex items-center justify-center gap-1 rounded-lg text-sm font-medium whitespace-nowrap transition-all outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline: "border border-input bg-transparent hover:bg-muted",
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
sm: "h-7 min-w-7 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||
lg: "h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants }
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
|
||||
import { cn } from "cn"
|
||||
|
||||
function TooltipProvider({
|
||||
delay = 0,
|
||||
...props
|
||||
}: TooltipPrimitive.Provider.Props) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delay={delay}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({ ...props }: TooltipPrimitive.Root.Props) {
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
}
|
||||
|
||||
function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
side = "top",
|
||||
sideOffset = 4,
|
||||
align = "center",
|
||||
alignOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: TooltipPrimitive.Popup.Props &
|
||||
Pick<
|
||||
TooltipPrimitive.Positioner.Props,
|
||||
"align" | "alignOffset" | "side" | "sideOffset"
|
||||
>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Positioner
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
className="isolate z-50"
|
||||
>
|
||||
<TooltipPrimitive.Popup
|
||||
data-slot="tooltip-content"
|
||||
className={cn(
|
||||
"z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />
|
||||
</TooltipPrimitive.Popup>
|
||||
</TooltipPrimitive.Positioner>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
/* The page carries its own type, since the engine runs where no font server is reachable: the
|
||||
* Latin subset of each family only, which is what the interface is written in. */
|
||||
@font-face {
|
||||
font-family: 'Geist Variable';
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-weight: 100 900;
|
||||
src: url(@fontsource-variable/geist/files/geist-latin-wght-normal.woff2) format('woff2-variations');
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Geist Mono Variable';
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-weight: 100 900;
|
||||
src: url(@fontsource-variable/geist-mono/files/geist-mono-latin-wght-normal.woff2) format('woff2-variations');
|
||||
}
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--font-heading: var(--font-sans);
|
||||
--font-sans: 'Geist Variable', ui-sans-serif, system-ui, sans-serif;
|
||||
--font-mono: 'Geist Mono Variable', ui-monospace, 'SF Mono', Menlo, monospace;
|
||||
--color-ok: var(--ok);
|
||||
--color-warn: var(--warn);
|
||||
--color-bad: var(--bad);
|
||||
--color-idle: var(--idle);
|
||||
--color-grid: var(--grid);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-background: var(--background);
|
||||
--radius-sm: calc(var(--radius) * 0.6);
|
||||
--radius-md: calc(var(--radius) * 0.8);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.4);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
--radius-3xl: calc(var(--radius) * 2.2);
|
||||
--radius-4xl: calc(var(--radius) * 2.6);
|
||||
}
|
||||
|
||||
:root {
|
||||
/* Cool neutrals with a slight blue cast, one blue accent, semantic hues kept apart from it. */
|
||||
--background: oklch(0.985 0.002 255);
|
||||
--foreground: oklch(0.19 0.012 260);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.19 0.012 260);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.19 0.012 260);
|
||||
--primary: oklch(0.52 0.17 262);
|
||||
--primary-foreground: oklch(0.985 0.002 255);
|
||||
--secondary: oklch(0.955 0.005 255);
|
||||
--secondary-foreground: oklch(0.25 0.012 260);
|
||||
--muted: oklch(0.955 0.005 255);
|
||||
--muted-foreground: oklch(0.5 0.015 260);
|
||||
--accent: oklch(0.945 0.008 255);
|
||||
--accent-foreground: oklch(0.22 0.012 260);
|
||||
--destructive: oklch(0.58 0.22 27);
|
||||
--border: oklch(0.91 0.006 255);
|
||||
--input: oklch(0.91 0.006 255);
|
||||
--ring: oklch(0.62 0.14 262);
|
||||
--radius: 0.625rem;
|
||||
--sidebar: oklch(0.972 0.003 255);
|
||||
--sidebar-foreground: oklch(0.19 0.012 260);
|
||||
--sidebar-primary: oklch(0.52 0.17 262);
|
||||
--sidebar-primary-foreground: oklch(0.985 0.002 255);
|
||||
--sidebar-accent: oklch(0.935 0.008 255);
|
||||
--sidebar-accent-foreground: oklch(0.22 0.012 260);
|
||||
--sidebar-border: oklch(0.91 0.006 255);
|
||||
--sidebar-ring: oklch(0.62 0.14 262);
|
||||
/* What a mark wears: a series keeps its hue while others come and go. */
|
||||
--series-1: oklch(0.56 0.17 262);
|
||||
--series-2: oklch(0.62 0.17 35);
|
||||
--series-3: oklch(0.6 0.12 175);
|
||||
--series-4: oklch(0.58 0.16 305);
|
||||
--series-5: oklch(0.66 0.14 85);
|
||||
--series-6: oklch(0.6 0.16 350);
|
||||
--series-7: oklch(0.62 0.13 225);
|
||||
--series-8: oklch(0.6 0.14 145);
|
||||
--ok: oklch(0.6 0.15 150);
|
||||
--warn: oklch(0.7 0.15 75);
|
||||
--bad: oklch(0.6 0.2 25);
|
||||
--idle: oklch(0.62 0.02 260);
|
||||
--grid: oklch(0.92 0.005 255);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.155 0.008 262);
|
||||
--foreground: oklch(0.95 0.005 255);
|
||||
--card: oklch(0.19 0.009 262);
|
||||
--card-foreground: oklch(0.95 0.005 255);
|
||||
--popover: oklch(0.21 0.01 262);
|
||||
--popover-foreground: oklch(0.95 0.005 255);
|
||||
--primary: oklch(0.7 0.14 262);
|
||||
--primary-foreground: oklch(0.16 0.01 262);
|
||||
--secondary: oklch(0.245 0.01 262);
|
||||
--secondary-foreground: oklch(0.95 0.005 255);
|
||||
--muted: oklch(0.235 0.01 262);
|
||||
--muted-foreground: oklch(0.68 0.015 260);
|
||||
--accent: oklch(0.255 0.012 262);
|
||||
--accent-foreground: oklch(0.97 0.004 255);
|
||||
--destructive: oklch(0.68 0.19 24);
|
||||
--border: oklch(1 0.01 262 / 9%);
|
||||
--input: oklch(1 0.01 262 / 13%);
|
||||
--ring: oklch(0.6 0.13 262);
|
||||
--sidebar: oklch(0.135 0.008 262);
|
||||
--sidebar-foreground: oklch(0.92 0.006 255);
|
||||
--sidebar-primary: oklch(0.7 0.14 262);
|
||||
--sidebar-primary-foreground: oklch(0.16 0.01 262);
|
||||
--sidebar-accent: oklch(0.225 0.011 262);
|
||||
--sidebar-accent-foreground: oklch(0.97 0.004 255);
|
||||
--sidebar-border: oklch(1 0.01 262 / 8%);
|
||||
--sidebar-ring: oklch(0.6 0.13 262);
|
||||
--series-1: oklch(0.7 0.14 262);
|
||||
--series-2: oklch(0.72 0.15 38);
|
||||
--series-3: oklch(0.74 0.12 175);
|
||||
--series-4: oklch(0.72 0.14 305);
|
||||
--series-5: oklch(0.78 0.13 88);
|
||||
--series-6: oklch(0.72 0.15 350);
|
||||
--series-7: oklch(0.74 0.12 225);
|
||||
--series-8: oklch(0.74 0.14 148);
|
||||
--ok: oklch(0.76 0.15 152);
|
||||
--warn: oklch(0.8 0.14 80);
|
||||
--bad: oklch(0.7 0.18 24);
|
||||
--idle: oklch(0.6 0.02 260);
|
||||
--grid: oklch(1 0.01 262 / 7%);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
html {
|
||||
@apply font-sans;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
font-feature-settings: "ss01", "cv11";
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// What the page asks the engine for. Everything it draws every second comes from /history, which
|
||||
// the process answers from its sampler's last read: an open page reads nothing of a running model.
|
||||
// /sessions, /graph and /server_info are asked for once, when their view is opened.
|
||||
|
||||
export interface Columns { [name: string]: (number | null)[] }
|
||||
export interface FinishedRequest {
|
||||
id: string; prompt: number; out: number; ctx: number
|
||||
ttft: number | null; pf: number | null; tps: number | null; at: number
|
||||
}
|
||||
export interface HistoryBody<Live> {
|
||||
keep_s: number
|
||||
t: number[]
|
||||
c: Columns
|
||||
requests?: FinishedRequest[]
|
||||
live: Live | null
|
||||
}
|
||||
|
||||
export interface FleetModel {
|
||||
id: string; state: string; file?: string; aliases?: string[]
|
||||
priority?: number; pinned?: boolean; tp?: number; ttl_ms?: number
|
||||
parks?: number; restores?: number; loads?: number; unloads?: number
|
||||
in_flight?: number; waiting?: number
|
||||
cards?: number[]; vram_bytes_per_card?: number; parked_bytes_per_card?: number
|
||||
/** What the model holds on each accelerator now, in any state (loading and partly parked too). */
|
||||
vram_bytes_by_card?: Record<string, number>
|
||||
host_bytes?: number; host_pinned_bytes?: number; drive_bytes?: number; last_restore_s?: number; load_s?: number
|
||||
doing?: string; waiting_for?: string; error?: string; warm?: boolean; in_place?: boolean
|
||||
park?: { ram?: string; restore?: string; vram?: string }
|
||||
capabilities?: Record<string, unknown>
|
||||
[k: string]: unknown
|
||||
}
|
||||
export interface FleetCard { card: number; name?: string; vram_bytes?: number; free_bytes?: number; busy?: number; power_w?: number; temp_c?: number; queues?: number; queues_idle?: number; queue_bytes?: number }
|
||||
export interface Fleet {
|
||||
version: string; uptime_s: number
|
||||
models: FleetModel[]; cards: FleetCard[]
|
||||
groups: { name: string; kind: string; members: string[] }[]
|
||||
host: { budget_bytes?: number; copies_bytes?: number; held_bytes?: number; disk_tier?: string }
|
||||
warm_up: { queued?: number; loading?: string | null; drive_only_bytes?: number }
|
||||
}
|
||||
|
||||
// What the page reads of each route's object. Every field read is declared here (the compiler
|
||||
// refuses any other), and the engine's tests check that the routes emit each one
|
||||
// (tools/dashboard_embed.py copies these names into the compiled-in header).
|
||||
export interface RunningRequest {
|
||||
id: string | number; state: string; prompt: number; computed: number; cached: number; output: number
|
||||
max: number; age_s: number; tps: number
|
||||
}
|
||||
export interface DraftPosition { reached: number; rate: number }
|
||||
export interface ExpertTier { name: string; units: number; bytes: number }
|
||||
export interface Experts { n_units: number; tiers: ExpertTier[]; layer_units?: number[]; layer_resident?: number[] }
|
||||
export interface Stats {
|
||||
model: string; uptime_s: number
|
||||
in_flight: number; max_num_seqs?: number
|
||||
jobs: { running: number; done: number; failed: number; total_ms: number; last_ms: number }
|
||||
running?: number; waiting?: number
|
||||
kv_bytes_used?: number; kv_bytes_total?: number
|
||||
prefix_hit_rate?: number; prefill_tps?: number; decode_tps?: number
|
||||
total_requests?: number; preemptions?: number
|
||||
step_ns_decode_best?: number
|
||||
draft_positions?: DraftPosition[]
|
||||
requests?: RunningRequest[]
|
||||
experts?: Experts
|
||||
}
|
||||
export interface Session { id: number | string; label?: string; tokens: number; bytes: number; idle_s: number; on_device: number; on_host: number; moving: boolean; snapshots: number; resume_tokens: number }
|
||||
export interface Sessions {
|
||||
sessions: Session[]; enabled?: boolean
|
||||
pool?: { tokens_used: number; tokens_total: number; bytes_used: number; bytes_total: number }
|
||||
occupancy?: { host_bytes: number; host_cap_bytes: number }
|
||||
linear?: { checkpoints_written: number }
|
||||
prefix_hit_rate?: number
|
||||
}
|
||||
|
||||
let apiKey: string | null = null
|
||||
try { apiKey = localStorage.getItem("radiance.key") } catch { /* storage may be blocked */ }
|
||||
const listeners = new Set<() => void>()
|
||||
let needKey = false
|
||||
export const auth = {
|
||||
get needed() { return needKey },
|
||||
get key() { return apiKey },
|
||||
set(k: string) {
|
||||
apiKey = k || null
|
||||
try { if (k) localStorage.setItem("radiance.key", k); else localStorage.removeItem("radiance.key") } catch { /* as above */ }
|
||||
needKey = false
|
||||
listeners.forEach((f) => f())
|
||||
},
|
||||
subscribe(f: () => void) { listeners.add(f); return () => { listeners.delete(f) } },
|
||||
}
|
||||
|
||||
export class HttpError extends Error {
|
||||
status: number
|
||||
constructor(status: number, message: string) { super(message); this.status = status }
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const headers: Record<string, string> = { ...(init?.headers as Record<string, string> | undefined) }
|
||||
if (apiKey) headers.Authorization = "Bearer " + apiKey
|
||||
const r = await fetch("/" + path, { cache: "no-store", ...init, headers })
|
||||
if (r.status === 401) {
|
||||
if (!needKey) { needKey = true; listeners.forEach((f) => f()) }
|
||||
throw new HttpError(401, "an API key is required")
|
||||
}
|
||||
if (!r.ok) {
|
||||
let msg = r.statusText
|
||||
try { const j = await r.json(); msg = j?.error?.message ?? msg } catch { /* not JSON */ }
|
||||
throw new HttpError(r.status, msg)
|
||||
}
|
||||
return (await r.json()) as T
|
||||
}
|
||||
export const withModel = (path: string, model: string) => path + (path.includes("?") ? "&" : "?") + "model=" + encodeURIComponent(model)
|
||||
@@ -0,0 +1,23 @@
|
||||
// A body asked for when a view opens, and again every `refreshMs` while the view stays open and
|
||||
// the tab is visible. Kept per path, so coming back to a view shows the last answer at once.
|
||||
import { useEffect, useState } from "react"
|
||||
import { api } from "./api"
|
||||
|
||||
const cache = new Map<string, unknown>()
|
||||
export function useFetched<T>(path: string | null, refreshMs = 0): { data: T | null; error: string | null } {
|
||||
const [, bump] = useState(0)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (!path) return
|
||||
let alive = true
|
||||
const load = () => {
|
||||
if (document.hidden) return
|
||||
api<T>(path).then((d) => { if (alive) { cache.set(path, d); setError(null); bump((n) => n + 1) } })
|
||||
.catch((e: unknown) => { if (alive) setError(e instanceof Error ? e.message : String(e)) })
|
||||
}
|
||||
load()
|
||||
const timer = refreshMs ? window.setInterval(load, refreshMs) : undefined
|
||||
return () => { alive = false; window.clearInterval(timer) }
|
||||
}, [path, refreshMs])
|
||||
return { data: path ? ((cache.get(path) as T | undefined) ?? null) : null, error }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Number formats shared by every view. A value that is missing prints as a dash, never as zero.
|
||||
export const DASH = "–"
|
||||
export const fin = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v)
|
||||
|
||||
export function fBytes(b: number | null | undefined): string {
|
||||
if (!fin(b)) return DASH
|
||||
const u = ["B", "KiB", "MiB", "GiB", "TiB"]
|
||||
let i = 0
|
||||
let v = Math.abs(b)
|
||||
while (v >= 1024 && i < u.length - 1) { v /= 1024; ++i }
|
||||
const s = v >= 100 || i === 0 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)
|
||||
return (b < 0 ? "-" : "") + s + " " + u[i]
|
||||
}
|
||||
/** [value, unit] for a tile that sets the unit apart. */
|
||||
export function bytesParts(b: number | null | undefined): [string, string] {
|
||||
const s = fBytes(b)
|
||||
if (s === DASH) return [DASH, ""]
|
||||
const k = s.lastIndexOf(" ")
|
||||
return [s.slice(0, k), s.slice(k + 1)]
|
||||
}
|
||||
export const fRate = (b: number | null | undefined) => (fin(b) ? fBytes(b) + "/s" : DASH)
|
||||
export function fNum(v: number | null | undefined, digits = 0): string {
|
||||
if (!fin(v)) return DASH
|
||||
return v.toLocaleString("en-US", { minimumFractionDigits: digits, maximumFractionDigits: digits })
|
||||
}
|
||||
/** Three significant figures without trailing noise: 1,234 · 176 · 22.0 · 2.00 · 0.33 */
|
||||
export function fSig(v: number | null | undefined): string {
|
||||
if (!fin(v)) return DASH
|
||||
const a = Math.abs(v)
|
||||
if (a >= 100) return fNum(v, 0)
|
||||
if (a >= 10) return fNum(v, 1)
|
||||
return fNum(v, 2)
|
||||
}
|
||||
export const fPct = (v: number | null | undefined, digits = 1) => (fin(v) ? (v * 100).toFixed(digits) : DASH)
|
||||
export function fDur(s: number | null | undefined): string {
|
||||
if (!fin(s)) return DASH
|
||||
if (s < 1) return Math.round(s * 1000) + " ms"
|
||||
if (s < 60) return (s < 10 ? s.toFixed(1) : s.toFixed(0)) + " s"
|
||||
if (s < 3600) return Math.floor(s / 60) + " m " + String(Math.floor(s % 60)).padStart(2, "0") + " s"
|
||||
if (s < 86400) return Math.floor(s / 3600) + " h " + String(Math.floor((s % 3600) / 60)).padStart(2, "0") + " m"
|
||||
return Math.floor(s / 86400) + " d " + Math.floor((s % 86400) / 3600) + " h"
|
||||
}
|
||||
export function fClock(t: number, withSeconds = false): string {
|
||||
const d = new Date(t * 1000)
|
||||
const p = (n: number) => String(n).padStart(2, "0")
|
||||
return p(d.getHours()) + ":" + p(d.getMinutes()) + (withSeconds ? ":" + p(d.getSeconds()) : "")
|
||||
}
|
||||
export function fAgo(ms: number, now: number): string {
|
||||
return fDur(Math.max(0, (now - ms) / 1000)) + " ago"
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// The page's copy of what the process remembers. One Scope per subject (the fleet, or a model):
|
||||
// it loads the server's hour once, then asks five times a second for what came after its last sample and
|
||||
// appends it. Views read a scope through useScope and redraw when its version moves.
|
||||
import { useSyncExternalStore } from "react"
|
||||
import { HttpError, api, withModel, type FinishedRequest, type Fleet, type HistoryBody, type Stats } from "./api"
|
||||
|
||||
const KEEP_S = 3600
|
||||
// The server samples five times a second while a page asks (once a second otherwise), so each
|
||||
// answer carries the rows since the last one and the live object.
|
||||
const POLL_MS = 200
|
||||
|
||||
export class Series {
|
||||
t: number[] = []
|
||||
c = new Map<string, (number | null)[]>()
|
||||
|
||||
append(t: number[], cols: Record<string, (number | null)[]>) {
|
||||
// Only what is later than everything held: a sample the server sent before is not kept twice.
|
||||
let from = 0
|
||||
while (from < t.length && t[from] <= this.end) ++from
|
||||
if (from === t.length) return
|
||||
const n0 = this.t.length
|
||||
for (let i = from; i < t.length; ++i) this.t.push(t[i])
|
||||
const n = this.t.length
|
||||
for (const [k, a] of Object.entries(cols)) {
|
||||
let col = this.c.get(k)
|
||||
if (!col) { col = new Array(n0).fill(null); this.c.set(k, col) }
|
||||
for (let i = from; i < a.length; ++i) col.push(a[i])
|
||||
}
|
||||
for (const col of this.c.values()) while (col.length < n) col.push(null)
|
||||
const cut = this.firstAfter(this.t[n - 1] - KEEP_S)
|
||||
if (cut > 64) { this.t.splice(0, cut); for (const col of this.c.values()) col.splice(0, cut) }
|
||||
}
|
||||
/** The first index whose time is later than `t`. */
|
||||
firstAfter(t: number): number {
|
||||
let lo = 0, hi = this.t.length
|
||||
while (lo < hi) { const m = (lo + hi) >> 1; if (this.t[m] <= t) lo = m + 1; else hi = m }
|
||||
return lo
|
||||
}
|
||||
col(k: string): (number | null)[] | undefined { return this.c.get(k) }
|
||||
has(k: string): boolean { const a = this.c.get(k); return !!a && a.some((v) => v !== null) }
|
||||
/** The latest value of a column among the last `within` samples (five minutes of them). */
|
||||
last(k: string, within = 300): number | null {
|
||||
const a = this.c.get(k)
|
||||
if (a) for (let i = a.length - 1; i >= 0 && i >= a.length - within; --i) if (a[i] !== null) return a[i]
|
||||
return null
|
||||
}
|
||||
get end(): number { return this.t.length ? this.t[this.t.length - 1] : 0 }
|
||||
}
|
||||
|
||||
type Listener = () => void
|
||||
|
||||
export class Scope<Live> {
|
||||
series = new Series()
|
||||
live: Live | null = null
|
||||
finished: FinishedRequest[] = []
|
||||
loaded = false
|
||||
error: string | null = null
|
||||
/** True once the server said this subject is not for this client (403): asking again is pointless. */
|
||||
refused = false
|
||||
version = 0
|
||||
private path: string
|
||||
private subs = new Set<Listener>()
|
||||
private timer: number | undefined
|
||||
private busy = false
|
||||
private users = 0
|
||||
|
||||
constructor(path: string) { this.path = path }
|
||||
|
||||
subscribe = (f: Listener) => {
|
||||
this.subs.add(f)
|
||||
if (++this.users === 1) this.start()
|
||||
return () => { this.subs.delete(f); if (--this.users === 0) this.stop() }
|
||||
}
|
||||
getVersion = () => this.version
|
||||
|
||||
private start() {
|
||||
void this.poll()
|
||||
this.timer = window.setInterval(() => { if (!document.hidden) void this.poll() }, POLL_MS)
|
||||
document.addEventListener("visibilitychange", this.onVisible)
|
||||
}
|
||||
private stop() {
|
||||
window.clearInterval(this.timer)
|
||||
document.removeEventListener("visibilitychange", this.onVisible)
|
||||
}
|
||||
private onVisible = () => { if (!document.hidden) void this.poll() }
|
||||
|
||||
private async poll() {
|
||||
if (this.busy || this.refused) return
|
||||
this.busy = true
|
||||
try {
|
||||
const since = this.series.end
|
||||
const sep = this.path.includes("?") ? "&" : "?"
|
||||
const b = await api<HistoryBody<Live>>(this.path + (since ? sep + "since=" + since : ""))
|
||||
this.series.append(b.t, b.c)
|
||||
if (b.requests?.length) {
|
||||
const have = new Set(this.finished.slice(-64).map((r) => r.id + ":" + r.at))
|
||||
for (const r of b.requests) if (!have.has(r.id + ":" + r.at)) this.finished.push(r)
|
||||
if (this.finished.length > 500) this.finished.splice(0, this.finished.length - 500)
|
||||
}
|
||||
this.live = b.live
|
||||
this.loaded = true
|
||||
this.error = null
|
||||
} catch (e) {
|
||||
this.error = e instanceof Error ? e.message : String(e)
|
||||
if (e instanceof HttpError && e.status === 403) this.refused = true
|
||||
} finally {
|
||||
this.busy = false
|
||||
++this.version
|
||||
this.subs.forEach((f) => f())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const fleet = new Scope<Fleet>("history")
|
||||
const models = new Map<string, Scope<Stats>>()
|
||||
export function modelScope(id: string): Scope<Stats> {
|
||||
let s = models.get(id)
|
||||
if (!s) { s = new Scope<Stats>(withModel("history", id)); models.set(id, s) }
|
||||
return s
|
||||
}
|
||||
|
||||
/** Subscribes the component to a scope; the scope polls while anything is subscribed. */
|
||||
export function useScope<L>(s: Scope<L>): Scope<L> {
|
||||
useSyncExternalStore(s.subscribe, s.getVersion)
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// What the viewer chose, kept across reloads where the browser lets the page keep anything: the
|
||||
// theme, the charts' time window, and the view named by the address's fragment.
|
||||
import { useSyncExternalStore } from "react"
|
||||
|
||||
function store<T>(initial: T) {
|
||||
let value = initial
|
||||
const subs = new Set<() => void>()
|
||||
return {
|
||||
get: () => value,
|
||||
set(v: T) { if (v !== value) { value = v; subs.forEach((f) => f()) } },
|
||||
subscribe(f: () => void) { subs.add(f); return () => { subs.delete(f) } },
|
||||
}
|
||||
}
|
||||
const read = (k: string): string | null => { try { return localStorage.getItem(k) } catch { return null } }
|
||||
const write = (k: string, v: string) => { try { localStorage.setItem(k, v) } catch { /* storage may be blocked */ } }
|
||||
|
||||
export type Theme = "dark" | "light"
|
||||
const theme = store<Theme>(document.documentElement.classList.contains("dark") ? "dark" : "light")
|
||||
export function setTheme(t: Theme) {
|
||||
document.documentElement.classList.toggle("dark", t === "dark")
|
||||
write("radiance.theme", t)
|
||||
theme.set(t)
|
||||
}
|
||||
export const useTheme = () => useSyncExternalStore(theme.subscribe, theme.get)
|
||||
|
||||
export const RANGES = [[60, "1m"], [300, "5m"], [900, "15m"], [3600, "1h"]] as const
|
||||
const stored = Number(read("radiance.range"))
|
||||
const range = store<number>(RANGES.some(([s]) => s === stored) ? stored : 300)
|
||||
export function setRange(s: number) { write("radiance.range", String(s)); range.set(s) }
|
||||
export const useRange = () => useSyncExternalStore(range.subscribe, range.get)
|
||||
|
||||
export type Tab = "performance" | "requests" | "sessions" | "details"
|
||||
export interface Route { model: string | null; tab: Tab }
|
||||
const TABS: Tab[] = ["performance", "requests", "sessions", "details"]
|
||||
function parse(): Route {
|
||||
const m = /^#\/m\/([^/]+)(?:\/([a-z]+))?/.exec(location.hash)
|
||||
if (!m) return { model: null, tab: "performance" }
|
||||
const tab = TABS.includes(m[2] as Tab) ? (m[2] as Tab) : "performance"
|
||||
return { model: decodeURIComponent(m[1]), tab }
|
||||
}
|
||||
let current = parse()
|
||||
const routeSubs = new Set<() => void>()
|
||||
window.addEventListener("hashchange", () => { current = parse(); routeSubs.forEach((f) => f()) })
|
||||
export const useRoute = () => useSyncExternalStore((f) => { routeSubs.add(f); return () => { routeSubs.delete(f) } }, () => current)
|
||||
export const hrefOf = (model: string | null, tab: Tab = "performance") => (model === null ? "#/" : "#/m/" + encodeURIComponent(model) + "/" + tab)
|
||||
@@ -0,0 +1 @@
|
||||
export { cn } from "cn"
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,253 @@
|
||||
// What a model is and what the engine built for it: its shape, where its bytes are, the kernels
|
||||
// its program runs, and every op with the kernel chosen for it.
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { Empty, Panel, PartBar, type Part } from "@/components/bits"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { api, withModel, type Stats } from "@/lib/api"
|
||||
import { fBytes, fNum } from "@/lib/format"
|
||||
import { useFetched } from "@/lib/fetched"
|
||||
|
||||
interface Kernel { kernel: string; plugin: string; family?: string; computes?: string; shape?: string; dtypes?: string; geometry?: string; constraints?: string[] }
|
||||
interface Weight { name: string; bytes: number; dtype: string; shape: string; tier?: string; access?: string }
|
||||
interface Op {
|
||||
op: string; index: number; geometry: string; count?: number; ranged?: string; range_lo?: number; range_hi?: number
|
||||
schema?: { doc?: string }
|
||||
weights?: Weight[]
|
||||
bands?: { span: string; device?: Kernel; host?: Kernel }[]
|
||||
}
|
||||
interface Graph {
|
||||
model?: { arch?: string; quant?: string; n_layers?: number; n_embd?: number; n_vocab?: number; world?: number; max_seqs?: number }
|
||||
counts?: { ops?: number; weights?: number; weight_bytes?: number; arena_bytes?: number; host_arena_bytes?: number; scratch_bytes?: number }
|
||||
plugins?: { name: string; version?: string; kernels?: number; build_target?: string; description?: string }[]
|
||||
ops: Op[]; order?: number[]
|
||||
drafter?: { name?: string; kind?: string; depth?: number }
|
||||
notes?: string[]
|
||||
}
|
||||
interface Info { server?: { max_model_len?: number; max_num_seqs?: number }; engine?: Record<string, unknown>; endpoints?: string[]; request_defaults?: Record<string, unknown> }
|
||||
|
||||
const kernelOf = (o: Op): Kernel | null => { for (const b of o.bands ?? []) { const k = b.device ?? b.host; if (k?.kernel) return k } return null }
|
||||
const familyOf = (o: Op) => kernelOf(o)?.family || o.op
|
||||
|
||||
export function Details({ model, stats }: { model: string; stats: Stats | null }) {
|
||||
const { data: g, error } = useFetched<Graph>(withModel("graph", model))
|
||||
const { data: info } = useFetched<Info>(withModel("server_info", model))
|
||||
const [query, setQuery] = useState("")
|
||||
const [open, setOpen] = useState<Op | null>(null)
|
||||
const fam = useMemo(() => {
|
||||
const n = new Map<string, number>()
|
||||
for (const o of g?.ops ?? []) n.set(familyOf(o), (n.get(familyOf(o)) ?? 0) + (o.count ?? 1))
|
||||
const ranked = [...n.entries()].sort((a, b) => b[1] - a[1])
|
||||
return { ranked, hue: new Map(ranked.map(([f], i) => [f, i < 7 ? `var(--series-${i + 1})` : "var(--idle)"])) }
|
||||
}, [g])
|
||||
if (!g) return <Empty>{error ? "Details are available once the model is loaded" : "Loading"}</Empty>
|
||||
const m = g.model ?? {}, c = g.counts ?? {}, e = (info?.engine ?? {}) as Record<string, any>
|
||||
const facts: [string, string][] = [
|
||||
["Architecture", m.arch ?? e.arch ?? "–"], ["Quantization", m.quant ?? "none"], ["Layers", fNum(m.n_layers)], ["Width", fNum(m.n_embd)],
|
||||
["Vocabulary", fNum(m.n_vocab)], ["Context", fNum(info?.server?.max_model_len)], ["Sequences", fNum(m.max_seqs)], ["Accelerators", String(m.world && m.world > 1 ? m.world : 1)],
|
||||
["Ops", fNum(c.ops)], ["Weights", fNum(c.weights)],
|
||||
]
|
||||
if (g.drafter?.name) facts.push(["Drafter", g.drafter.name], ["Draft depth", String(g.drafter.depth ?? "–")])
|
||||
if (e.tp_wire && (m.world ?? 1) > 1) facts.push(["Link between accelerators", String(e.tp_wire)])
|
||||
const mem: Part[] = ([["Weights", c.weight_bytes, 1], ["Activations", c.arena_bytes, 3], ["Host arena", c.host_arena_bytes, 5], ["Scratch", c.scratch_bytes, 6], ["KV cache", stats?.kv_bytes_total, 4]] as [string, number | undefined, number][])
|
||||
.filter(([, v]) => (v ?? 0) > 0).map(([label, v, i]) => ({ key: label, label, value: v!, color: `var(--series-${i})`, text: fBytes(v) }))
|
||||
const byIndex = new Map(g.ops.map((o) => [o.index, o]))
|
||||
const q = query.trim().toLowerCase()
|
||||
const ops = g.ops.filter((o) => !q || o.op.toLowerCase().includes(q) || (kernelOf(o)?.kernel ?? "").toLowerCase().includes(q) || o.geometry.toLowerCase().includes(q))
|
||||
const top = fam.ranked.slice(0, 7), most = top[0]?.[1] ?? 1
|
||||
const strip = (g.order ?? []).slice(0, 2400)
|
||||
const libs = (g.plugins ?? []).filter((p) => (p.kernels ?? 0) > 0)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="overflow-hidden rounded-xl border bg-card">
|
||||
<div className="-mr-px -mb-px grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6">
|
||||
{facts.map(([k, v]) => (
|
||||
<div key={k} className="min-w-0 border-r border-b px-4 py-3">
|
||||
<div className="truncate text-xs text-muted-foreground">{k}</div>
|
||||
<div className="num truncate text-sm font-medium" title={v}>{v}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ControlVector model={model} />
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Panel title="Memory" description="Per accelerator, by use">
|
||||
<div className="flex flex-col gap-4">
|
||||
<PartBar parts={mem} className="h-3" />
|
||||
<div className="grid grid-cols-[auto_1fr_auto] items-center gap-x-3 gap-y-1.5 text-xs">
|
||||
{mem.map((p) => (
|
||||
<div key={p.key} className="contents">
|
||||
<span className="inline-flex items-center gap-1.5"><i className="size-2 rounded-full" style={{ background: p.color }} />{p.label}</span>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full rounded-full" style={{ width: (100 * p.value) / Math.max(...mem.map((q) => q.value), 1) + "%", background: p.color }} /></div>
|
||||
<span className="num text-right text-muted-foreground">{p.text}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel title="Kernels in use" description="Launches per pass, by kernel type">
|
||||
<div className="grid grid-cols-[auto_1fr_auto] items-center gap-x-3 gap-y-1.5 text-xs">
|
||||
{top.map(([f, n]) => (
|
||||
<div key={f} className="contents">
|
||||
<span className="truncate">{f}</span>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-muted"><div className="h-full rounded-full" style={{ width: (100 * n) / most + "%", background: fam.hue.get(f) }} /></div>
|
||||
<span className="num text-right text-muted-foreground">{fNum(n)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
{strip.length > 0 && (
|
||||
<Panel title="Program" description={`The ${fNum(g.order?.length)} launches of one pass, in order, colored by kernel type`}>
|
||||
<div className="flex flex-wrap gap-px">
|
||||
{strip.map((idx, i) => {
|
||||
const o = byIndex.get(idx)
|
||||
return o ? <button key={i} title={o.op} onClick={() => setOpen(o)} className="h-3.5 w-[3px] rounded-[1px] opacity-85 hover:opacity-100 hover:outline hover:outline-foreground" style={{ background: fam.hue.get(familyOf(o)) }} /> : null
|
||||
})}
|
||||
</div>
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
<Panel title="Ops" description={`${fNum(ops.length)} of ${fNum(g.ops.length)} distinct`} flush
|
||||
action={<Input value={query} onChange={(ev) => setQuery(ev.target.value)} placeholder="Filter by op, kernel or geometry" className="h-8 w-64 max-w-[50vw]" />}>
|
||||
<div className="max-h-[28rem] overflow-auto">
|
||||
<Table>
|
||||
<TableHeader className="sticky top-0 z-10 bg-card">
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className="pl-4">Op</TableHead><TableHead>Kernel</TableHead><TableHead>Library</TableHead>
|
||||
<TableHead className="text-right">Launches</TableHead><TableHead className="pr-4">Geometry</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{ops.map((o) => {
|
||||
const k = kernelOf(o)
|
||||
return (
|
||||
<TableRow key={o.index} className="cursor-pointer" onClick={() => setOpen(o)}>
|
||||
<TableCell className="pl-4 font-medium"><span className="inline-flex items-center gap-2"><i className="size-2 rounded-full" style={{ background: fam.hue.get(familyOf(o)) }} />{o.op}</span></TableCell>
|
||||
<TableCell className="font-mono text-xs">{k?.kernel ?? "–"}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{k?.plugin ?? "–"}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(o.count ?? 1)}</TableCell>
|
||||
<TableCell className="max-w-[28rem] truncate pr-4 font-mono text-xs text-muted-foreground">{o.geometry}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
{libs.length > 0 && (
|
||||
<Panel title="Kernel libraries" description="In lookup order" flush>
|
||||
<Table>
|
||||
<TableHeader><TableRow className="hover:bg-transparent"><TableHead className="pl-4">Library</TableHead><TableHead>Version</TableHead><TableHead className="text-right">Kernels</TableHead><TableHead className="pr-4">Built for</TableHead></TableRow></TableHeader>
|
||||
<TableBody>
|
||||
{libs.map((p) => (
|
||||
<TableRow key={p.name}>
|
||||
<TableCell className="pl-4 font-medium">
|
||||
<Tooltip><TooltipTrigger render={<span>{p.name}</span>} /><TooltipContent className="max-w-80">{p.description}</TooltipContent></Tooltip>
|
||||
</TableCell>
|
||||
<TableCell className="num text-muted-foreground">{p.version ?? "–"}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(p.kernels)}</TableCell>
|
||||
<TableCell className="pr-4 text-muted-foreground">{p.build_target ?? "–"}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Panel>
|
||||
)}
|
||||
{(g.notes?.length ?? 0) > 0 && (
|
||||
<Panel title="Notes" description="Messages from the model plugin during setup">
|
||||
<ul className="flex flex-col gap-2 text-sm text-muted-foreground">
|
||||
{g.notes!.map((n, i) => <li key={i} className="border-l-2 pl-3 leading-snug">{n}</li>)}
|
||||
</ul>
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Sheet open={!!open} onOpenChange={(v) => { if (!v) setOpen(null) }}>
|
||||
<SheetContent className="w-full gap-0 overflow-y-auto sm:max-w-xl">
|
||||
{open && <OpDetail op={open} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The switch of a model that carries a control vector: whether requests get it unless they say. */
|
||||
function ControlVector({ model }: { model: string }) {
|
||||
const [cv, setCv] = useState<{ default?: boolean; name?: string } | null>(null)
|
||||
const load = () => { api<{ default?: boolean; name?: string }>(withModel("admin/control-vector", model)).then(setCv).catch(() => setCv(null)) }
|
||||
useEffect(load, [model]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
if (!cv) return null
|
||||
const set = (on: boolean) => {
|
||||
setCv({ ...cv, default: on })
|
||||
api(withModel("admin/control-vector", model), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled: on }) }).catch(() => undefined).finally(load)
|
||||
}
|
||||
return (
|
||||
<label className="flex items-center gap-3 rounded-xl border bg-card px-4 py-3">
|
||||
<span className="text-sm font-medium">Control vector</span>
|
||||
<span className="min-w-0 flex-1 truncate text-sm text-muted-foreground">{cv.name ?? ""}</span>
|
||||
<Switch checked={!!cv.default} onCheckedChange={set} />
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
function OpDetail({ op }: { op: Op }) {
|
||||
const k = kernelOf(op)
|
||||
const rows: [string, string | undefined][] = [
|
||||
["Geometry", op.geometry], ["Launches per pass", fNum(op.count ?? 1)],
|
||||
["Range", op.ranged ? `${op.ranged} from ${op.range_lo} to ${op.range_hi}` : undefined],
|
||||
["Kernel", k?.kernel], ["Library", k?.plugin], ["Computes", k?.computes], ["Shapes", k?.shape], ["Types", k?.dtypes],
|
||||
["Requires", k?.constraints?.length ? k.constraints.join("; ") : undefined],
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<SheetHeader>
|
||||
<SheetTitle>{op.op}</SheetTitle>
|
||||
<SheetDescription>{op.schema?.doc ?? "Op " + op.index}</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex flex-col gap-4 px-4 pb-6">
|
||||
<dl className="grid grid-cols-[8rem_1fr] gap-x-3 gap-y-2 text-sm">
|
||||
{rows.filter(([, v]) => v).map(([l, v]) => (
|
||||
<div key={l} className="contents"><dt className="text-muted-foreground">{l}</dt><dd className="min-w-0 break-words font-mono text-xs leading-5">{v}</dd></div>
|
||||
))}
|
||||
</dl>
|
||||
{(op.weights?.length ?? 0) > 0 && (
|
||||
<div>
|
||||
<div className="mb-1.5 text-xs font-medium text-muted-foreground">Weights</div>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
{op.weights!.slice(0, 24).map((w) => (
|
||||
<div key={w.name} className="flex items-baseline gap-3 border-b px-3 py-1.5 text-xs last:border-b-0">
|
||||
<span className="min-w-0 flex-1 truncate font-mono">{w.name}</span>
|
||||
<span className="text-muted-foreground">{w.dtype} · {w.shape}</span>
|
||||
<span className="num w-20 text-right">{fBytes(w.bytes)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{(op.bands?.length ?? 0) > 1 && (
|
||||
<div>
|
||||
<div className="mb-1.5 text-xs font-medium text-muted-foreground">By size</div>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
{op.bands!.map((b) => (
|
||||
<div key={b.span} className="flex items-baseline gap-3 border-b px-3 py-1.5 text-xs last:border-b-0">
|
||||
<span className="num w-28 text-muted-foreground">{b.span}</span>
|
||||
<span className="min-w-0 flex-1 truncate font-mono">{(b.device ?? b.host)?.kernel ?? "–"}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// One model: what it is and how it is doing, in four views.
|
||||
import { Empty, StateBadge } from "@/components/bits"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import type { FleetModel } from "@/lib/api"
|
||||
import { fBytes, fDur } from "@/lib/format"
|
||||
import { modelScope, useScope } from "@/lib/store"
|
||||
import { hrefOf, type Tab } from "@/lib/ui"
|
||||
import { Details } from "./details"
|
||||
import { Performance, type Kind } from "./performance"
|
||||
import { Requests } from "./requests"
|
||||
import { SessionsView } from "./sessions"
|
||||
|
||||
const NOUN: Record<string, string> = { image_generation: "Images generated", shape_generation: "Meshes generated", audio_generation: "Clips generated", video_generation: "Videos generated" }
|
||||
function kindOf(c: Record<string, unknown> | undefined): [Kind, string] {
|
||||
for (const k of Object.keys(NOUN)) if (c?.[k]) return ["gen", NOUN[k]]
|
||||
if (c?.chat) return ["chat", ""]
|
||||
if (c?.embedding) return ["embed", ""]
|
||||
return ["chat", ""]
|
||||
}
|
||||
const DOES: [string, string][] = [["chat", "Chat"], ["tools", "Tools"], ["reasoning", "Reasoning"], ["image", "Reads images"], ["video", "Reads video"], ["audio", "Reads audio"], ["embedding", "Embeddings"],
|
||||
["image_generation", "Makes images"], ["image_edit", "Edits images"], ["audio_generation", "Makes audio"], ["video_generation", "Makes video"], ["shape_generation", "Makes meshes"]]
|
||||
|
||||
export function ModelPage({ id, tab, model }: { id: string; tab: Tab; model: FleetModel | undefined }) {
|
||||
const scope = useScope(modelScope(id))
|
||||
const [kind, noun] = kindOf(model?.capabilities)
|
||||
const tabs: [Tab, string][] = kind === "chat" ? [["performance", "Performance"], ["requests", "Requests"], ["sessions", "Sessions"], ["details", "Details"]] : [["performance", "Performance"], ["details", "Details"]]
|
||||
const shown = tabs.some(([t]) => t === tab) ? tab : "performance"
|
||||
const s = scope.live
|
||||
const serving = model?.state === "resident" && !!s
|
||||
const slots = typeof s?.max_num_seqs === "number" ? s.max_num_seqs : undefined
|
||||
const where = model?.cards?.length ? `accelerator${model.cards.length > 1 ? "s" : ""} ${model.cards.join(" and ")}` : null
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4 md:p-6">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||
<h1 className="text-xl font-semibold tracking-tight">{id}</h1>
|
||||
<StateBadge state={model?.state} doing={model?.doing} />
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{[model?.file, where, model?.state === "resident" && model.vram_bytes_per_card ? fBytes(model.vram_bytes_per_card) + " per accelerator" : null, s?.uptime_s ? "up " + fDur(s.uptime_s) : null].filter(Boolean).join(" · ")}
|
||||
</span>
|
||||
</div>
|
||||
{model?.error && <div className="rounded-lg border border-bad/40 bg-bad/10 px-3 py-2 text-sm">{model.error}</div>}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<Tabs value={shown} onValueChange={(v) => { location.hash = hrefOf(id, v as Tab) }}>
|
||||
<TabsList>{tabs.map(([t, label]) => <TabsTrigger key={t} value={t} className="px-3">{label}</TabsTrigger>)}</TabsList>
|
||||
</Tabs>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{DOES.filter(([k]) => model?.capabilities?.[k]).map(([k, label]) => <span key={k} className="rounded-md border px-1.5 py-0.5 text-xs text-muted-foreground">{label}</span>)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{!model ? <Empty>This process serves no model named {id}</Empty>
|
||||
: shown === "performance" ? (
|
||||
<>
|
||||
{!serving && scope.series.t.length > 0 && <div className="text-sm text-muted-foreground">This model is not loaded right now. The charts show its earlier activity.</div>}
|
||||
{scope.series.t.length === 0 && !serving ? <Empty>{model.state === "failed" ? "The model failed to start, so there is no data" : model.state === "cold" ? "This model has not been loaded yet. It loads when a request asks for it." : "No data yet. Charts appear once the model has been loaded."}</Empty>
|
||||
: <Performance scope={scope} kind={kind} slots={slots} noun={noun} />}
|
||||
</>
|
||||
) : shown === "requests" ? <Requests scope={scope} />
|
||||
: shown === "sessions" ? (serving ? <SessionsView model={id} /> : <Empty>Conversations are listed while the model is loaded</Empty>)
|
||||
: <Details model={id} stats={s} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// The fleet: what is on each card, what every model is doing, and how that moved over the window.
|
||||
import { useMemo } from "react"
|
||||
import { Chart, Legend, type Line } from "@/components/chart"
|
||||
import { Empty, Kpi, Panel, PartBar, PartLegend, StateBadge, StateDot, STATE_OF_CODE, stateOf, type Part } from "@/components/bits"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
||||
import type { Fleet, FleetModel } from "@/lib/api"
|
||||
import { bytesParts, fBytes, fClock, fDur, fin, fNum } from "@/lib/format"
|
||||
import { fleet as fleetScope, useScope, type Series } from "@/lib/store"
|
||||
import { hrefOf, useRange } from "@/lib/ui"
|
||||
|
||||
const hue = (i: number) => `var(--series-${(i % 8) + 1})`
|
||||
// What a model holds on one accelerator: the server's figure for it in any state, so a model that
|
||||
// is loading or partly parked is counted as itself; from a server that sends none, its claim
|
||||
// while it is loaded.
|
||||
const onCard = (m: FleetModel, card: number) =>
|
||||
m.vram_bytes_by_card ? (m.vram_bytes_by_card[String(card)] ?? 0)
|
||||
: m.state === "resident" && m.cards?.includes(card) ? (m.vram_bytes_per_card ?? 0) : 0
|
||||
const held = (m: FleetModel) =>
|
||||
m.vram_bytes_by_card ? Object.values(m.vram_bytes_by_card).reduce((a, b) => a + b, 0)
|
||||
: m.state === "resident" ? (m.vram_bytes_per_card ?? 0) * (m.cards?.length ?? 0) : 0
|
||||
|
||||
export function Overview() {
|
||||
const scope = useScope(fleetScope)
|
||||
const range = useRange()
|
||||
const f = scope.live
|
||||
if (!f) return <Empty className="m-6">{scope.error ?? "Waiting for data…"}</Empty>
|
||||
const hueOf = new Map(f.models.map((m, i) => [m.id, hue(i)]))
|
||||
const resident = f.models.filter((m) => m.state === "resident")
|
||||
const parked = f.models.filter((m) => m.state === "parked")
|
||||
const cold = f.models.filter((m) => m.state === "cold")
|
||||
const failed = f.models.filter((m) => m.state === "failed")
|
||||
const onCards = f.models.reduce((a, m) => a + held(m), 0)
|
||||
const vram = f.cards.reduce((a, c) => a + (c.vram_bytes ?? 0), 0)
|
||||
// All the process pins in host memory: the models' pools, tables and cache tiers as well as
|
||||
// the copies of parked ones. A server that does not say counts the copies alone.
|
||||
const copies = f.models.reduce((a, m) => a + (m.host_bytes ?? 0), 0)
|
||||
const hostBytes = f.host?.held_bytes ?? copies
|
||||
const flight = f.models.reduce((a, m) => a + (m.in_flight ?? 0), 0)
|
||||
const waiting = f.models.reduce((a, m) => a + (m.waiting ?? 0), 0)
|
||||
const returns = f.models.reduce((a, m) => a + (m.restores ?? 0), 0)
|
||||
const power = f.cards.reduce((a, c) => a + (fin(c.power_w) ? c.power_w : 0), 0)
|
||||
const [cv, cu] = bytesParts(onCards)
|
||||
const [hv, hu] = bytesParts(hostBytes)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4 md:p-6">
|
||||
{failed.map((m) => (
|
||||
<a key={m.id} href={hrefOf(m.id)} className="flex flex-wrap items-baseline gap-x-2 rounded-lg border border-bad/40 bg-bad/10 px-3 py-2 text-sm">
|
||||
<span className="font-medium">{m.id} did not start</span>
|
||||
<span className="min-w-0 text-muted-foreground">{m.error ?? "no reason was given"}</span>
|
||||
</a>
|
||||
))}
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6">
|
||||
<Kpi label="VRAM in use" value={cv} unit={cu} detail={`${resident.length} of ${f.models.length} models · ${fBytes(vram)} in all`} />
|
||||
<Kpi label="Active requests" value={fNum(flight)} detail={waiting ? `${waiting} waiting` : "being served now"} />
|
||||
<Kpi label="Parked" value={fNum(parked.length)} detail={parked.length ? parked.map((m) => m.id).join(", ") : "none"} />
|
||||
<Kpi label="Host memory in use" value={hv} unit={hu} detail={(fin(f.host?.budget_bytes) ? `of ${fBytes(f.host.budget_bytes)} allowed` : "") + (copies > 0 ? ` · ${fBytes(copies)} parked copies` : "")} />
|
||||
<Kpi label="Restores" value={fNum(returns)} detail={cold.length ? `${cold.length} not loaded` : "from parked to loaded"} />
|
||||
<Kpi label="Power draw" value={power > 0 ? fNum(power) : "–"} unit={power > 0 ? "W" : undefined} detail={`across ${f.cards.length} accelerator${f.cards.length === 1 ? "" : "s"}`} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 xl:grid-cols-2">
|
||||
{f.cards.map((c) => <CardPanel key={c.card} fleet={f} card={c.card} hueOf={hueOf} data={scope.series} version={scope.version} range={range} />)}
|
||||
</div>
|
||||
|
||||
<Panel title="State over time" description="Each model's state across the time range">
|
||||
<StateStrip models={f.models} data={scope.series} version={scope.version} range={range} />
|
||||
</Panel>
|
||||
|
||||
<Panel title="Models" flush>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className="pl-4">Model</TableHead>
|
||||
<TableHead>State</TableHead>
|
||||
<TableHead className="text-right">Priority</TableHead>
|
||||
<TableHead>Accelerators</TableHead>
|
||||
<TableHead className="text-right">VRAM</TableHead>
|
||||
<TableHead className="text-right">Host</TableHead>
|
||||
<TableHead className="text-right">Active</TableHead>
|
||||
<TableHead className="text-right">Loads</TableHead>
|
||||
<TableHead className="text-right">Parks</TableHead>
|
||||
<TableHead className="pr-4 text-right">Last load</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{f.models.map((m) => (
|
||||
<TableRow key={m.id} className="cursor-pointer" onClick={() => { location.hash = hrefOf(m.id) }}>
|
||||
<TableCell className="pl-4">
|
||||
<a href={hrefOf(m.id)} className="flex items-center gap-2 font-medium" onClick={(e) => e.stopPropagation()}>
|
||||
<i className="size-2 rounded-full" style={{ background: hueOf.get(m.id) }} />
|
||||
{m.id}
|
||||
</a>
|
||||
<div className="mt-0.5 max-w-72 truncate pl-4 text-xs text-muted-foreground">{m.error ?? m.file}</div>
|
||||
</TableCell>
|
||||
<TableCell><StateBadge state={m.state} doing={m.doing} /></TableCell>
|
||||
<TableCell className="num text-right">{fNum(m.priority)}{m.pinned ? " · pinned" : ""}</TableCell>
|
||||
<TableCell className="num text-muted-foreground">{m.cards?.length ? m.cards.join(", ") : "–"}</TableCell>
|
||||
<TableCell className="num text-right">{held(m) > 0 ? fBytes(held(m)) : "–"}</TableCell>
|
||||
<TableCell className="num text-right">{(m.host_bytes ?? 0) + (m.host_pinned_bytes ?? 0) > 0 ? fBytes((m.host_bytes ?? 0) + (m.host_pinned_bytes ?? 0)) : "–"}</TableCell>
|
||||
<TableCell className="num text-right">{m.in_flight ? fNum(m.in_flight) : "–"}{m.waiting ? ` +${m.waiting}` : ""}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(m.loads)}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(m.parks)}</TableCell>
|
||||
<TableCell className="num pr-4 text-right">{fin(m.load_seconds as number) ? fDur(m.load_seconds as number) : "–"}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Panel>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CardPanel({ fleet: f, card, hueOf, data, version, range }: { fleet: Fleet; card: number; hueOf: Map<string, string>; data: Series; version: number; range: number }) {
|
||||
const c = f.cards.find((x) => x.card === card)!
|
||||
const parts: Part[] = f.models.map((m) => ({ key: m.id, label: m.id, value: onCard(m, card), color: hueOf.get(m.id)!, text: fBytes(onCard(m, card)) }))
|
||||
const used = (c.vram_bytes ?? 0) - (c.free_bytes ?? 0)
|
||||
const named = parts.reduce((a, p) => a + p.value, 0)
|
||||
// What no model's ledger names: the open hardware queues, by the server's count, and the
|
||||
// rest, which is buffers the loaded models' kernels allocate themselves and the driver's own.
|
||||
const queues = Math.max(Math.min(c.queue_bytes ?? 0, used - named), 0)
|
||||
const rest = used - named - queues
|
||||
if (queues > 0) parts.push({ key: "~queues", label: `Queues (${c.queues ?? 0} open)`, value: queues, color: "var(--idle)", text: fBytes(queues) })
|
||||
if (rest > 64 << 20) parts.push({ key: "~other", label: "Model buffers and driver", value: rest, color: "var(--muted-foreground)", text: fBytes(rest) })
|
||||
const lines: Line[] = f.models.map((m, i) => ({ key: `c${card}:${m.id}`, label: m.id, color: i + 1 }))
|
||||
return (
|
||||
<Panel title={<span className="flex items-baseline gap-2">Accelerator {card}<span className="text-xs font-normal text-muted-foreground">{c.name}</span></span>}
|
||||
action={<span className="num text-xs text-muted-foreground">{fBytes(c.free_bytes)} free of {fBytes(c.vram_bytes)}</span>}>
|
||||
<div className="flex flex-col gap-3">
|
||||
<PartBar parts={parts} total={c.vram_bytes} className="h-3" />
|
||||
<PartLegend parts={parts} className="content-start xl:min-h-10" />
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<Gauge label="Busy" value={fin(c.busy) ? Math.round(c.busy * 100) + "%" : "–"} data={data} k={`busy${card}`} max={1} />
|
||||
<Gauge label="Power" value={fin(c.power_w) ? Math.round(c.power_w) + " W" : "–"} data={data} k={`power${card}`} />
|
||||
<Gauge label="Temperature" value={fin(c.temp_c) ? Math.round(c.temp_c) + " °C" : "–"} data={data} k={`temp${card}`} />
|
||||
</div>
|
||||
<Chart data={data} version={version} lines={lines} range={range} fmt={fBytes} stack bytes height={170} max={c.vram_bytes} />
|
||||
</div>
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
|
||||
/** A figure with its last five minutes drawn beside it. */
|
||||
function Gauge({ label, value, data, k, max }: { label: string; value: string; data: Series; k: string; max?: number }) {
|
||||
const col = data.col(k) ?? []
|
||||
const lo = data.firstAfter(data.end - 300)
|
||||
const pts = col.slice(lo)
|
||||
const vals = pts.filter((v): v is number => v !== null)
|
||||
const top = max ?? Math.max(1, ...vals) * 1.05
|
||||
const base = max !== undefined ? 0 : Math.min(...vals, top) * 0.9
|
||||
const n = pts.length
|
||||
let d = ""
|
||||
let open = false
|
||||
pts.forEach((v, i) => {
|
||||
if (v === null) { open = false; return }
|
||||
d += (open ? "L" : "M") + ((100 * i) / Math.max(1, n - 1)).toFixed(2) + " " + (27 - (24 * (Math.min(v, top) - base)) / Math.max(1e-9, top - base)).toFixed(2)
|
||||
open = true
|
||||
})
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-lg border bg-background/40 px-3 py-2">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-xs text-muted-foreground">{label}</div>
|
||||
<div className="num text-base font-semibold whitespace-nowrap">{value}</div>
|
||||
</div>
|
||||
<svg viewBox="0 0 100 30" preserveAspectRatio="none" className="h-8 min-w-0 flex-1 text-primary">
|
||||
<path d={d} fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One row a model: its state as coloured runs along the window. */
|
||||
function StateStrip({ models, data, version, range }: { models: FleetModel[]; data: Series; version: number; range: number }) {
|
||||
const rows = useMemo(() => {
|
||||
const end = data.end, start = end - range, lo = data.firstAfter(start)
|
||||
return models.map((m) => {
|
||||
const col = data.col("s:" + m.id) ?? []
|
||||
const runs: { a: number; b: number; s: string }[] = []
|
||||
for (let i = lo; i < data.t.length; ++i) {
|
||||
const v = col[i]
|
||||
if (v == null) continue
|
||||
const s = STATE_OF_CODE[v] ?? "cold"
|
||||
const a = i === lo ? Math.max(start, data.t[i] - 1) : data.t[i - 1], b = data.t[i]
|
||||
const last = runs[runs.length - 1]
|
||||
if (last && last.s === s && a - last.b < 2.5) last.b = b
|
||||
else runs.push({ a, b, s })
|
||||
}
|
||||
return { id: m.id, runs }
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [models.map((m) => m.id).join("|"), data, version, range])
|
||||
const end = data.end, start = end - range
|
||||
const ticks = [0, 0.25, 0.5, 0.75, 1]
|
||||
const seen = new Set(rows.flatMap((r) => r.runs.map((x) => x.s)))
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="grid grid-cols-[minmax(6rem,10rem)_1fr] items-center gap-x-3 gap-y-1.5">
|
||||
{rows.map((r) => (
|
||||
<div key={r.id} className="contents">
|
||||
<a href={hrefOf(r.id)} className="truncate text-sm">{r.id}</a>
|
||||
<div className="relative h-5 overflow-hidden rounded bg-muted/50">
|
||||
{r.runs.map((x, i) => (
|
||||
<Tooltip key={i}>
|
||||
<TooltipTrigger render={<div className="absolute inset-y-0" style={{ left: (100 * (x.a - start)) / range + "%", width: Math.max(0.3, (100 * (x.b - x.a)) / range) + "%", background: stateOf(x.s).tone, opacity: x.s === "cold" ? 0.35 : 0.9 }} />} />
|
||||
<TooltipContent>{stateOf(x.s).label} · {fClock(x.a, true)} to {fClock(x.b, true)} · {fDur(x.b - x.a)}</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div />
|
||||
<div className="num relative h-4 text-[11px] text-muted-foreground">
|
||||
{ticks.map((p) => (
|
||||
<span key={p} className={"absolute top-0 whitespace-nowrap" + (p === 0.25 || p === 0.75 ? " hidden lg:inline" : "")} style={p === 0 ? { left: 0 } : p === 1 ? { right: 0 } : { left: p * 100 + "%", transform: "translateX(-50%)" }}>
|
||||
{end ? fClock(start + p * range, range <= 600) : ""}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
{["resident", "loading", "waiting", "parked", "cold", "failed"].filter((s) => seen.has(s)).map((s) => (
|
||||
<span key={s} className="inline-flex items-center gap-1.5"><StateDot state={s} />{stateOf(s).label}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export { Legend }
|
||||
@@ -0,0 +1,139 @@
|
||||
// A model's figures: a row of tiles, each a figure now, and the chosen one drawn large over the
|
||||
// window. A figure the model has never produced (acceptance without a drafter) has no tile.
|
||||
import { useState } from "react"
|
||||
import { Bars, Empty, Panel, PartBar, PartLegend, type Part } from "@/components/bits"
|
||||
import { Chart, Legend, type Line } from "@/components/chart"
|
||||
import type { Experts, Stats } from "@/lib/api"
|
||||
import { DASH, bytesParts, fBytes, fDur, fNum, fPct, fRate, fSig, fin } from "@/lib/format"
|
||||
import type { Scope, Series } from "@/lib/store"
|
||||
import { useRange } from "@/lib/ui"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export type Kind = "chat" | "embed" | "gen"
|
||||
const fMs = (v: number) => (v >= 100 ? v.toFixed(0) : v.toFixed(2)) + " ms"
|
||||
const fPc = (v: number) => fPct(v, v >= 0.9995 ? 0 : 1) + "%"
|
||||
const fTps = (v: number) => (v === 0 ? "0" : fSig(v))
|
||||
|
||||
interface Metric {
|
||||
id: string; kinds: Kind; label: string; unit?: string; draft?: boolean; always?: boolean
|
||||
show: (s: Stats, h: Series, slots: number | undefined, noun: string) => [string, string?, string?]
|
||||
lines: Line[]; fmt: (v: number) => string
|
||||
stack?: boolean; max?: number; tight?: boolean; integer?: boolean; bytes?: boolean; join?: boolean
|
||||
}
|
||||
const one = (key: string, label: string): Line[] => [{ key, label, color: 1 }]
|
||||
const METRICS: Metric[] = [
|
||||
{ id: "decode", kinds: "chat", label: "Decode", unit: "tok/s", show: (s) => [fin(s.decode_tps) ? fTps(s.decode_tps) : DASH], lines: one("decode", "tokens a second"), fmt: fTps },
|
||||
{ id: "step", kinds: "chat", label: "Step", unit: "ms",
|
||||
show: (s, h) => { const v = h.last("step"); return [fin(v) ? (v >= 100 ? v.toFixed(0) : v.toFixed(2)) : DASH, (s.step_ns_decode_best ?? 0) > 0 ? "best " + fMs(s.step_ns_decode_best! / 1e6) : ""] },
|
||||
lines: [{ key: "step", label: "step", color: 1 }, { key: "stepBest", label: "best", dash: true }], fmt: fMs, tight: true },
|
||||
{ id: "prefill", kinds: "chat", label: "Prefill", unit: "tok/s", show: (_s, h) => { const v = h.last("prefillRate"); return [fin(v) ? fTps(v) : DASH] }, lines: one("prefillRate", "tokens a second"), fmt: fTps, join: true },
|
||||
{ id: "reqs", kinds: "chat", always: true, label: "Requests",
|
||||
show: (s, _h, slots) => [String(s.running ?? 0), (slots ? "of " + slots + " slots" : "") + (s.waiting ? " · " + s.waiting + " waiting" : "")],
|
||||
lines: [{ key: "running", label: "running", color: 1 }, { key: "waiting", label: "waiting", color: 5 }, { key: "preempted", label: "preempted", color: 2 }], fmt: (v) => fNum(v), stack: true, integer: true },
|
||||
{ id: "kv", kinds: "chat", label: "KV cache",
|
||||
show: (s) => { const [v, u] = bytesParts(s.kv_bytes_used); return [v, "of " + fBytes(s.kv_bytes_total), u] },
|
||||
lines: [{ key: "kvRead", label: "in use", color: 1 }, { key: "kvKept", label: "cached for the next turn", color: 4 }], fmt: fBytes, stack: true, bytes: true },
|
||||
{ id: "hit", kinds: "chat", label: "Prefix cache hits", unit: "%", show: (s) => [fin(s.prefix_hit_rate) ? fPct(s.prefix_hit_rate) : DASH], lines: one("hit", "of prompt tokens"), fmt: fPc, max: 1 },
|
||||
{ id: "accept", kinds: "chat", label: "Acceptance", unit: "%", draft: true, show: (_s, h) => [fPct(h.last("accept"))], lines: one("accept", "of drafted tokens"), fmt: fPc, max: 1 },
|
||||
{ id: "tok", kinds: "chat", label: "Tokens per step", draft: true, show: (_s, h) => { const v = h.last("tokStep"); return [fin(v) ? v.toFixed(2) : DASH] }, lines: one("tokStep", "tokens"), fmt: (v) => v.toFixed(2), tight: true },
|
||||
{ id: "ethru", kinds: "embed", always: true, label: "Throughput", unit: "tok/s", show: (s) => [fin(s.prefill_tps) ? fTps(s.prefill_tps) : DASH], lines: one("prefill", "tokens a second"), fmt: fTps },
|
||||
{ id: "erate", kinds: "embed", always: true, label: "Inputs", unit: "/s", show: (_s, h) => { const v = h.last("reqRate"); return [fin(v) ? fTps(v) : DASH] }, lines: one("reqRate", "inputs a second"), fmt: fTps },
|
||||
{ id: "estep", kinds: "embed", always: true, label: "Step", unit: "ms", show: (_s, h) => { const v = h.last("stepAny"); return [fin(v) ? v.toFixed(2) : DASH] }, lines: one("stepAny", "step"), fmt: fMs, tight: true },
|
||||
{ id: "eflight", kinds: "embed", always: true, label: "Active requests", show: (s) => [String(s.in_flight ?? 0)], lines: one("flight", "in flight"), fmt: (v) => fNum(v), integer: true },
|
||||
{ id: "jrun", kinds: "gen", always: true, label: "Running", show: (s) => [String(s.jobs?.running ?? 0)], lines: one("jobRun", "running"), fmt: (v) => fNum(v), integer: true },
|
||||
{ id: "jdone", kinds: "gen", always: true, label: "Completed", show: (s) => [fNum(s.jobs?.done), s.jobs?.failed ? s.jobs.failed + " failed" : ""], lines: one("jobDone", "made"), fmt: (v) => fNum(v), integer: true },
|
||||
{ id: "jlast", kinds: "gen", always: true, label: "Last duration", show: (s) => [s.jobs?.done ? fDur(s.jobs.last_ms / 1000) : DASH], lines: one("jobTime", "took"), fmt: (v) => fDur(v), join: true },
|
||||
{ id: "jmean", kinds: "gen", always: true, label: "Mean", show: (s) => [s.jobs?.done ? fDur(s.jobs.total_ms / s.jobs.done / 1000) : DASH], lines: one("jobTime", "took"), fmt: (v) => fDur(v), join: true },
|
||||
]
|
||||
const TRAFFIC: Line[] = [["lkAr", "between accelerators"], ["lkUp", "host to accelerator"], ["lkDn", "accelerator to host"], ["lkSsd", "drive"], ["lkStream", "streaming"]].map(([key, label], i) => ({ key, label, color: i + 1 }))
|
||||
|
||||
export function Performance({ scope, kind, slots, noun }: { scope: Scope<Stats>; kind: Kind; slots?: number; noun: string }) {
|
||||
const range = useRange()
|
||||
const [chosen, setChosen] = useState<string | null>(null)
|
||||
const s = scope.live, h = scope.series
|
||||
const hasDraft = (s?.draft_positions?.length ?? 0) > 0
|
||||
const produced = (m: Metric) => m.always || m.lines.some((l) => !l.dash && (h.col(l.key) ?? []).some((v) => (v ?? 0) > 0))
|
||||
const tiles = METRICS.filter((m) => m.kinds === kind && (!m.draft || hasDraft || h.has(m.lines[0].key)) && (s ? produced(m) : !m.draft))
|
||||
const metric = tiles.find((m) => m.id === chosen) ?? tiles[0]
|
||||
if (!metric) return <Empty>No data for this model yet</Empty>
|
||||
const moved = TRAFFIC.filter((l) => (h.col(l.key) ?? []).some((v) => (v ?? 0) > 0))
|
||||
const ex = s?.experts
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="overflow-hidden rounded-xl border bg-card">
|
||||
<div role="tablist" className="grid grid-cols-2 border-b sm:grid-cols-4 xl:grid-flow-col xl:auto-cols-fr xl:grid-cols-none">
|
||||
{tiles.map((m) => {
|
||||
const [v, det, unit] = s ? m.show(s, h, slots, noun) : [DASH]
|
||||
const on = m === metric
|
||||
return (
|
||||
<button key={m.id} role="tab" aria-selected={on} onClick={() => setChosen(m.id)}
|
||||
className={cn("relative -mb-px flex min-w-0 flex-col gap-1 border-r border-b px-4 py-3 text-left transition-colors outline-none last:border-r-0 hover:bg-accent/50 focus-visible:bg-accent/60", on && "bg-accent/40")}>
|
||||
<span className="truncate text-xs font-medium text-muted-foreground">{m.id === "jdone" && noun ? noun : m.label}</span>
|
||||
<span className="num flex items-baseline gap-1 text-xl leading-none font-semibold tracking-tight">
|
||||
<span className="truncate">{v}</span>
|
||||
{(unit ?? m.unit) && <span className="text-xs font-normal text-muted-foreground">{unit ?? m.unit}</span>}
|
||||
</span>
|
||||
<span className="min-h-4 truncate text-xs text-muted-foreground">{det}</span>
|
||||
{on && <span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary" />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 p-4">
|
||||
{metric.lines.length > 1 && <Legend lines={metric.lines} />}
|
||||
<Chart key={metric.id} data={h} version={scope.version} lines={metric.lines} range={range} fmt={metric.fmt} height={300}
|
||||
stack={metric.stack} max={metric.max} tight={metric.tight} integer={metric.integer} bytes={metric.bytes} join={metric.join} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(moved.length > 0 || hasDraft) && (
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
{moved.length > 0 && (
|
||||
<Panel title="Traffic" description="Bytes per second, by destination" className={hasDraft ? "lg:col-span-2" : "lg:col-span-3"}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Legend lines={moved} />
|
||||
<Chart data={h} version={scope.version} lines={moved} range={range} fmt={fRate} stack bytes height={190} />
|
||||
</div>
|
||||
</Panel>
|
||||
)}
|
||||
{hasDraft && s?.draft_positions && (
|
||||
<Panel title="Acceptance by position" description="Share of drafted tokens accepted, by position" className={moved.length ? "" : "lg:col-span-3"}>
|
||||
<Bars values={s.draft_positions.map((p) => p.rate || 0)} max={1} height={150}
|
||||
tip={(i, v) => `Position ${i + 1}\n${fPc(v)} accepted\n${fNum(s.draft_positions![i].reached)} reached`} labels={(i) => String(i + 1)} />
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{ex && <ExpertsPanel ex={ex} h={h} version={scope.version} range={range} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const TIER: Record<string, string> = { active: "var(--series-1)", resident: "var(--series-1)", staged: "var(--series-4)", warm: "var(--series-3)", host: "var(--series-5)", ram: "var(--series-5)" }
|
||||
function ExpertsPanel({ ex, h, version, range }: { ex: Experts; h: Series; version: number; range: number }) {
|
||||
const parts: Part[] = (ex.tiers ?? []).filter((t) => t.units > 0).map((t) => ({ key: t.name, label: t.name, value: t.bytes || t.units, color: TIER[t.name.toLowerCase()] ?? "var(--idle)", text: `${fNum(t.units)} units · ${fBytes(t.bytes)}` }))
|
||||
return (
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
<Panel title="Experts" description={`${fNum(ex.n_units)} units by where they are`}>
|
||||
<div className="flex flex-col gap-3">
|
||||
<PartBar parts={parts} className="h-3" />
|
||||
<PartLegend parts={parts} />
|
||||
{ex.layer_units && ex.layer_resident && (
|
||||
<Bars values={ex.layer_resident} max={Math.max(...ex.layer_units, 1)} height={70}
|
||||
tip={(i, v) => `Layer ${i}\n${fNum(v)} of ${fNum(ex.layer_units![i])} on the accelerator`} />
|
||||
)}
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel title="Expert hit rate" description="Share of routed experts already on the accelerator">
|
||||
<Chart data={h} version={version} lines={[{ key: "expHit", label: "hits", color: 1 }]} range={range} fmt={fPc} max={1} height={170} />
|
||||
</Panel>
|
||||
<Panel title="Expert moves" description="Units per second">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Legend lines={[{ key: "expIn", label: "onto the accelerator", color: 1 }, { key: "expOut", label: "off the accelerator", color: 2 }]} />
|
||||
<Chart data={h} version={version} lines={[{ key: "expIn", label: "onto the accelerator", color: 1 }, { key: "expOut", label: "off the accelerator", color: 2 }]} range={range} fmt={(v) => fTps(v) + "/s"} stack height={150} />
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// A model's requests: the ones running now, and the ones that finished within the hour the
|
||||
// process remembers.
|
||||
import { useMemo, useState } from "react"
|
||||
import { Empty, Kpi, Panel } from "@/components/bits"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
||||
import type { FinishedRequest, Stats } from "@/lib/api"
|
||||
import { DASH, fAgo, fDur, fNum, fSig, fin } from "@/lib/format"
|
||||
import type { Scope } from "@/lib/store"
|
||||
import { Download } from "lucide-react"
|
||||
|
||||
const median = (a: number[]) => { if (!a.length) return null; const s = a.slice().sort((x, y) => x - y); return s[s.length >> 1] }
|
||||
const STATE: Record<string, string> = { prefill: "Processing prompt", decode: "Generating", waiting: "Waiting", preempted: "Paused", done: "Done" }
|
||||
|
||||
export function Requests({ scope }: { scope: Scope<Stats> }) {
|
||||
const s = scope.live
|
||||
const done = scope.finished
|
||||
const [shown, setShown] = useState(50)
|
||||
const now = scope.series.end * 1000
|
||||
const speeds = done.map((r) => r.tps).filter((v): v is number => fin(v) && v > 0)
|
||||
const ttfts = done.map((r) => r.ttft).filter((v): v is number => fin(v))
|
||||
const mean = speeds.length ? speeds.reduce((a, b) => a + b, 0) / speeds.length : null
|
||||
const running = (s?.requests ?? []).filter((r) => r.state !== "done")
|
||||
const latest = useMemo(() => done.slice().reverse(), [done, scope.version]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
function save() {
|
||||
const blob = new Blob([JSON.stringify(done, null, 1)], { type: "application/json" })
|
||||
const a = document.createElement("a")
|
||||
a.href = URL.createObjectURL(blob)
|
||||
a.download = `${s?.model ?? "model"}-requests.json`
|
||||
a.click()
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 1000)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
<Kpi label="Served" value={fNum(s?.total_requests)} detail="since the model started" />
|
||||
<Kpi label="Preempted" value={fNum(s?.preemptions)} detail="requests paused for another and resumed" />
|
||||
<Kpi label="Mean speed" value={fin(mean) ? fSig(mean) : DASH} unit="tok/s" detail={`over ${fNum(speeds.length)} finished`} />
|
||||
<Kpi label="Median time to first token" value={ttfts.length ? fDur(median(ttfts)) : DASH} detail={`over ${fNum(ttfts.length)} finished`} />
|
||||
</div>
|
||||
|
||||
<Panel title="Running" description={running.length ? undefined : "No active requests"} flush={running.length > 0}>
|
||||
{running.length > 0 && (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className="pl-4">Request</TableHead><TableHead>Status</TableHead>
|
||||
<TableHead className="w-[28%]">Progress</TableHead>
|
||||
<TableHead className="text-right">Prompt</TableHead><TableHead className="text-right">Reused</TableHead>
|
||||
<TableHead className="text-right">Written</TableHead><TableHead className="text-right">Speed</TableHead>
|
||||
<TableHead className="pr-4 text-right">Age</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{running.map((r) => {
|
||||
const reading = r.state === "prefill"
|
||||
const of = reading ? Math.max(1, r.prompt - r.cached) : Math.max(1, r.max)
|
||||
const at = reading ? Math.max(0, r.computed - r.cached) : r.output
|
||||
return (
|
||||
<TableRow key={String(r.id)}>
|
||||
<TableCell className="num pl-4 font-medium">{String(r.id)}</TableCell>
|
||||
<TableCell>{STATE[r.state] ?? r.state}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-1.5 min-w-12 flex-1 overflow-hidden rounded-full bg-muted"><div className="h-full rounded-full bg-primary transition-[width] duration-700" style={{ width: Math.min(100, (100 * at) / of) + "%", opacity: reading ? 0.55 : 1 }} /></div>
|
||||
<span className="num w-24 shrink-0 text-right text-xs text-muted-foreground">{fNum(at)} / {fNum(of)}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="num text-right">{fNum(r.prompt)}</TableCell>
|
||||
<TableCell className="num text-right text-muted-foreground">{r.cached ? fNum(r.cached) : DASH}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(r.output)}</TableCell>
|
||||
<TableCell className="num text-right">{r.tps > 0 ? fSig(r.tps) : DASH}</TableCell>
|
||||
<TableCell className="num pr-4 text-right text-muted-foreground">{fDur(r.age_s)}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Panel title="Speed by context" description="Tokens per second vs. final context length, per finished request">
|
||||
<Scatter pts={done.filter((r) => fin(r.tps) && r.tps! > 0 && r.ctx > 0).map((r) => ({ x: r.ctx, y: r.tps!, r }))} />
|
||||
</Panel>
|
||||
<Panel title="Time to first token" description="Distribution across finished requests">
|
||||
<Histogram values={ttfts} />
|
||||
</Panel>
|
||||
</div>
|
||||
|
||||
<Panel title="Finished" description={done.length ? `${fNum(done.length)} in the last hour, latest first` : "No requests in the last hour"} flush={done.length > 0}
|
||||
action={done.length > 0 && <Button variant="outline" size="sm" onClick={save}><Download />Export</Button>}>
|
||||
{done.length > 0 && (
|
||||
<>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className="pl-4">Request</TableHead><TableHead className="text-right">Prompt</TableHead>
|
||||
<TableHead className="text-right">Written</TableHead><TableHead className="text-right">Context</TableHead>
|
||||
<TableHead className="text-right">First token</TableHead><TableHead className="text-right">Prefill</TableHead>
|
||||
<TableHead className="text-right">Speed</TableHead><TableHead className="pr-4 text-right">Finished</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{latest.slice(0, shown).map((r) => (
|
||||
<TableRow key={r.id + ":" + r.at}>
|
||||
<TableCell className="num pl-4 font-medium">{r.id}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(r.prompt)}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(r.out)}</TableCell>
|
||||
<TableCell className="num text-right text-muted-foreground">{fNum(r.ctx)}</TableCell>
|
||||
<TableCell className="num text-right">{fin(r.ttft) ? fDur(r.ttft) : DASH}</TableCell>
|
||||
<TableCell className="num text-right">{fin(r.pf) ? fSig(r.pf) + " tok/s" : DASH}</TableCell>
|
||||
<TableCell className="num text-right">{fin(r.tps) && r.tps > 0 ? fSig(r.tps) + " tok/s" : DASH}</TableCell>
|
||||
<TableCell className="num pr-4 text-right text-muted-foreground">{fAgo(r.at, now)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{latest.length > shown && <div className="border-t p-2 text-center"><Button variant="ghost" size="sm" onClick={() => setShown(shown + 100)}>Show {Math.min(100, latest.length - shown)} more</Button></div>}
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const tick = (v: number) => (v >= 1000 ? fSig(v / 1000) + "k" : fSig(v))
|
||||
function Scatter({ pts }: { pts: { x: number; y: number; r: FinishedRequest }[] }) {
|
||||
if (pts.length < 2) return <Empty>Available after two finished requests</Empty>
|
||||
const xs = pts.map((p) => p.x), ys = pts.map((p) => p.y)
|
||||
const x0 = Math.min(...xs), x1 = Math.max(...xs), y1 = Math.max(...ys) * 1.08
|
||||
const lx = (v: number) => (x1 > x0 ? (Math.log(v) - Math.log(x0)) / (Math.log(x1) - Math.log(x0)) : 0.5)
|
||||
return (
|
||||
<div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-1">
|
||||
<div className="num flex flex-col justify-between text-right text-[11px] text-muted-foreground"><span>{fSig(y1)}</span><span>{fSig(y1 / 2)}</span><span>0</span></div>
|
||||
<div className="relative h-44 rounded-md border bg-background/40">
|
||||
<div className="absolute inset-x-0 top-1/2 border-t border-dashed border-grid" />
|
||||
{pts.map((p, i) => (
|
||||
<Tooltip key={i}>
|
||||
<TooltipTrigger render={<i className="absolute size-2 -translate-x-1/2 translate-y-1/2 rounded-full bg-primary/70 ring-1 ring-background hover:bg-primary" style={{ left: 2 + 96 * lx(p.x) + "%", bottom: (96 * p.y) / y1 + "%" }} />} />
|
||||
<TooltipContent>{p.r.id} · {fNum(p.x)} tokens of context · {fSig(p.y)} tok/s</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
<div />
|
||||
<div className="num flex justify-between text-[11px] text-muted-foreground"><span>{tick(x0)}</span><span>tokens of context</span><span>{tick(x1)}</span></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Histogram({ values }: { values: number[] }) {
|
||||
if (values.length < 2) return <Empty>Available after two finished requests</Empty>
|
||||
const edges = [0, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, Infinity]
|
||||
const used = edges.findIndex((e) => e > Math.max(...values))
|
||||
const bins = edges.slice(0, Math.max(6, used + 1))
|
||||
const counts = bins.slice(0, -1).map((lo, i) => values.filter((v) => v >= lo && v < bins[i + 1]).length)
|
||||
const top = Math.max(...counts, 1)
|
||||
const name = (i: number) => (bins[i + 1] === Infinity ? "over " + fDur(bins[i]) : "under " + fDur(bins[i + 1]))
|
||||
return (
|
||||
<div className="flex h-[12.25rem] flex-col justify-end gap-1.5">
|
||||
<div className="flex flex-1 items-end justify-center gap-1.5">
|
||||
{counts.map((c, i) => (
|
||||
<Tooltip key={i}>
|
||||
<TooltipTrigger render={<div className="flex h-full max-w-24 flex-1 flex-col justify-end"><span className="num mb-1 text-center text-[11px] text-muted-foreground">{c || ""}</span><div className="rounded-sm bg-primary/80" style={{ height: Math.max(c ? 3 : 0, (82 * c) / top) + "%" }} /></div>} />
|
||||
<TooltipContent>{c} {c === 1 ? "request" : "requests"} {name(i)}</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
<div className="num flex justify-center gap-1.5 border-t pt-1 text-[11px] text-muted-foreground">
|
||||
{counts.map((_, i) => <span key={i} className="max-w-24 flex-1 truncate text-center">{bins[i + 1] === Infinity ? "> " + fDur(bins[i]) : "< " + fDur(bins[i + 1])}</span>)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// The conversations a model keeps so their next turn need not read the prompt again: how many,
|
||||
// how much of the cache they hold, and which would resume and which would start over.
|
||||
import { Empty, Kpi, Panel, PartBar, type Part } from "@/components/bits"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { withModel, type Session, type Sessions } from "@/lib/api"
|
||||
import { bytesParts, fBytes, fDur, fNum } from "@/lib/format"
|
||||
import { useFetched } from "@/lib/fetched"
|
||||
|
||||
export function SessionsView({ model }: { model: string }) {
|
||||
const { data: s, error } = useFetched<Sessions>(withModel("sessions", model), 5000)
|
||||
if (!s) return <Empty>{error ?? "Loading"}</Empty>
|
||||
const list = (s.sessions ?? []).slice().sort((a, b) => a.idle_s - b.idle_s)
|
||||
const linear = (s.linear?.checkpoints_written ?? 0) > 0 || list.some((r) => r.snapshots > 0)
|
||||
const live = list.filter((r) => !linear || r.resume_tokens > 0 || r.snapshots > 0)
|
||||
const cold = list.filter((r) => !live.includes(r))
|
||||
const reuse = (r: Session) => (linear ? Math.min(r.resume_tokens || 0, r.tokens) : r.tokens)
|
||||
const [pv, pu] = bytesParts(s.pool?.bytes_used)
|
||||
const [hv, hu] = bytesParts(s.occupancy?.host_bytes)
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
<Kpi label="Resumable" value={fNum(live.length)} detail={cold.length ? `${cold.length} will restart` : "cached conversations"} />
|
||||
<Kpi label="Tokens cached" value={fNum(s.pool?.tokens_used)} detail={s.pool ? `of ${fNum(s.pool.tokens_total)}` : ""} />
|
||||
<Kpi label="VRAM in use" value={pv} unit={pu} detail={s.pool ? `of ${fBytes(s.pool.bytes_total)}` : ""} />
|
||||
{s.enabled
|
||||
? <Kpi label="Host memory in use" value={hv} unit={hu} detail={s.occupancy?.host_cap_bytes ? `of ${fBytes(s.occupancy.host_cap_bytes)}` : ""} />
|
||||
: <Kpi label="Prefix cache hits" value={s.prefix_hit_rate != null ? (s.prefix_hit_rate * 100).toFixed(1) : "–"} unit="%" detail="of prompt tokens reused" />}
|
||||
</div>
|
||||
<Panel title="Will resume" description={live.length ? "Conversations whose next turn can reuse cached tokens, most recent first" : undefined} flush={live.length > 0}>
|
||||
{live.length ? <SessionTable rows={live} reuse={reuse} /> : <Empty>No cached conversations</Empty>}
|
||||
</Panel>
|
||||
{cold.length > 0 && (
|
||||
<Panel title={`${fNum(cold.length)} will restart`} description="Cached, but with no prefix the next turn can reuse" flush>
|
||||
<SessionTable rows={cold} />
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SessionTable({ rows, reuse }: { rows: Session[]; reuse?: (r: Session) => number }) {
|
||||
const shown = rows.slice(0, 200)
|
||||
return (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className="pl-4">Conversation</TableHead>
|
||||
<TableHead className="text-right">Tokens</TableHead>
|
||||
{reuse && <TableHead className="text-right">Reusable</TableHead>}
|
||||
<TableHead className="text-right">Idle</TableHead>
|
||||
<TableHead className="w-[30%] pr-4">Where</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{shown.map((r) => {
|
||||
const blocks = r.on_device + r.on_host, unit = blocks > 0 ? r.bytes / blocks : 0
|
||||
const parts: Part[] = [
|
||||
{ key: "d", label: "On accelerators", value: r.on_device, color: "var(--series-1)", text: fBytes(r.on_device * unit) },
|
||||
{ key: "h", label: "Host memory", value: r.on_host, color: "var(--series-5)", text: fBytes(r.on_host * unit) },
|
||||
]
|
||||
return (
|
||||
<TableRow key={String(r.id)}>
|
||||
<TableCell className="num pl-4 font-medium">{r.label || "#" + r.id}</TableCell>
|
||||
<TableCell className="num text-right">{fNum(r.tokens)}</TableCell>
|
||||
{reuse && <TableCell className="num text-right">{fNum(reuse(r))}</TableCell>}
|
||||
<TableCell className="num text-right text-muted-foreground">{fDur(r.idle_s)}</TableCell>
|
||||
<TableCell className="pr-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<PartBar parts={parts} className="h-1.5 flex-1" />
|
||||
<span className="num w-28 shrink-0 text-right text-xs text-muted-foreground">{fBytes(r.bytes)}{r.moving ? " · moving" : ""}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user