Client bundles: no drizzle in the browser, lazy palette, one copy of the painting

- The enum arrays move from schema.ts to src/lib/db/enums.ts (no imports),
  which schema.ts re-exports. The endpoint form and benchmark start imported
  ENDPOINT_ENGINES/QUALITY_SECTIONS from the schema, which put drizzle-orm,
  every table definition and ulid (18 KB gzipped) on the endpoint pages. An
  ESLint rule now refuses value imports from the schema in client code.
- The ⌘K palette dialog is its own chunk, loaded on first open and preloaded
  when you hover or focus Search or press ⌘/Ctrl.
- The dot painting's brightness grid was copied into 10 page chunks (~10 KB
  gzipped each); it is now one async chunk, parsed once per tab. The canvas
  skips redraws when size, pixel ratio and theme are unchanged (the
  ResizeObserver's first callback drew everything a second time) and draws at
  most once per frame while resizing.

First-load JS per route drops by 10-29 KB gzipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
This commit is contained in:
Claude committed 2026-11-01 20:57:53 +00:00
1 parent 2e56351e96
commit d10a491042
9 files changed
+458 -339

No files matched your search

+4
View File
@@ -22,6 +22,10 @@ step 1 (Hugging Face downloader) is released as a minor version.
- **Lighter benchmark lists**: the Benchmarks and Endpoints pages, a model's sidebar and the ⌘K - **Lighter benchmark lists**: the Benchmarks and Endpoints pages, a model's sidebar and the ⌘K
search load only what they show (headline numbers, the quality score), not every run's full search load only what they show (headline numbers, the quality score), not every run's full
results; the list refreshed every 3 s during a run now sends a fraction of the data. results; the list refreshed every 3 s during a run now sends a fraction of the data.
- **Less JavaScript per page** (10–29 KB gzipped less on every page): the dot painting's data is
loaded once and cached instead of being part of each page, the ⌘K search loads when you first
reach for it, and the endpoint pages no longer include database code. The painting is drawn once
per page view instead of twice, and at most once per frame while the window is resized.
## [0.16.0] - 2026-10-30 ## [0.16.0] - 2026-10-30
+21
View File
@@ -15,6 +15,27 @@ const eslintConfig = defineConfig([
// Bundled worker output // Bundled worker output
"dist/**", "dist/**",
]), ]),
// A value import from the schema in a client component puts drizzle-orm and every table
// definition into the browser bundle. Enums are in @/lib/db/enums; types are fine. Pages, layouts
// and route handlers run on the server only.
{
files: ["src/components/**/*.{ts,tsx}", "src/hooks/**/*.{ts,tsx}", "src/app/**/*.{ts,tsx}"],
ignores: ["src/app/**/page.tsx", "src/app/**/layout.tsx", "src/app/**/route.ts"],
rules: {
"@typescript-eslint/no-restricted-imports": [
"error",
{
paths: [
{
name: "@/lib/db/schema",
allowTypeImports: true,
message: "In client code this bundles drizzle-orm and every table. Import enums from @/lib/db/enums.",
},
],
},
],
},
},
]); ]);
export default eslintConfig; export default eslintConfig;
@@ -9,7 +9,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox"; import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { NativeSelect } from "@/components/ui/native-select"; import { NativeSelect } from "@/components/ui/native-select";
import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema"; import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/enums";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view"; import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
+2 -1
View File
@@ -10,7 +10,8 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { NativeSelect } from "@/components/ui/native-select"; import { NativeSelect } from "@/components/ui/native-select";
import { ENGINE_LABEL } from "@/lib/benchmark-meta"; import { ENGINE_LABEL } from "@/lib/benchmark-meta";
import { ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe } from "@/lib/db/schema"; import { ENDPOINT_ENGINES } from "@/lib/db/enums";
import type { EndpointHardware, EndpointProbe } from "@/lib/db/schema";
import type { EndpointView } from "@/lib/endpoints"; import type { EndpointView } from "@/lib/endpoints";
type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string }; type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string };
+227
View File
@@ -0,0 +1,227 @@
"use client";
import { Dialog } from "@base-ui/react/dialog";
import {
BoxIcon,
CornerDownLeftIcon,
DownloadIcon,
GaugeIcon,
LibraryIcon,
MonitorIcon,
MoonIcon,
PlusIcon,
ScanSearchIcon,
SearchIcon,
ServerIcon,
SunIcon,
TagIcon,
TagsIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { useEffect, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/utils";
type Index = {
models: { id: string; repoId: string; quants: string[]; status: string; tags: string[] }[];
endpoints: { id: string; name: string; model: string | null; engine: string | null }[];
benchmarks: { id: string; label: string | null; kind: string; state: string; target: string; model: string; createdAt: number }[];
tags: string[];
};
type Item = {
id: string;
group: string;
title: string;
hint?: string;
icon: React.ComponentType<{ className?: string }>;
/** Extra words that match (not shown). */
keywords?: string;
run: () => void;
};
const KIND_LABEL: Record<string, string> = { run: "speed run", ab: "A/B", eval: "quality eval" };
/** Every whitespace-separated term must appear (case-insensitive); earlier and title matches rank higher. */
function score(item: Item, terms: string[]): number {
if (terms.length === 0) return 1;
const title = item.title.toLowerCase();
const all = `${title} ${item.hint ?? ""} ${item.keywords ?? ""} ${item.group}`.toLowerCase();
let s = 0;
for (const t of terms) {
const i = all.indexOf(t);
if (i < 0) return 0;
s += title.startsWith(t) ? 4 : title.includes(t) ? 2 : 1;
}
return s;
}
/** The palette itself: loaded on first use (see command-palette.tsx), then kept mounted. */
export function CommandPaletteDialog({ open, setOpen }: { open: boolean; setOpen: (open: boolean) => void }) {
const router = useRouter();
const { setTheme } = useTheme();
const [query, setQuery] = useState("");
const [index, setIndex] = useState<Index | null>(null);
const [active, setActive] = useState(0);
const list = useRef<HTMLDivElement>(null);
// Fresh data every time it opens (the library changes while you use it).
useEffect(() => {
if (!open) return;
let stop = false;
void fetch("/api/search-index", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.then((d: Index | null) => !stop && d && setIndex(d));
return () => {
stop = true;
};
}, [open]);
const go = (href: string) => () => {
setOpen(false);
router.push(href);
};
const items = useMemo<Item[]>(() => {
const out: Item[] = [
{ id: "p:library", group: "Pages", title: "Library", icon: LibraryIcon, keywords: "models home", run: go("/") },
{ id: "p:endpoints", group: "Pages", title: "Endpoints", icon: ServerIcon, keywords: "servers", run: go("/endpoints") },
{ id: "p:benchmarks", group: "Pages", title: "Benchmarks", icon: GaugeIcon, keywords: "runs compare", run: go("/benchmarks") },
{ id: "a:add-model", group: "Actions", title: "Add model", icon: PlusIcon, keywords: "download new hugging face repo", run: go("/?add=1") },
{ id: "a:new-endpoint", group: "Actions", title: "Add endpoint", icon: PlusIcon, keywords: "new server", run: go("/endpoints/new") },
{ id: "a:scan", group: "Actions", title: "Scan the models folder", icon: ScanSearchIcon, keywords: "rescan import", run: go("/settings/downloads#scan") },
{ id: "a:theme-light", group: "Actions", title: "Light theme", icon: SunIcon, keywords: "appearance", run: () => (setTheme("light"), setOpen(false)) },
{ id: "a:theme-dark", group: "Actions", title: "Dark theme", icon: MoonIcon, keywords: "appearance", run: () => (setTheme("dark"), setOpen(false)) },
{ id: "a:theme-system", group: "Actions", title: "System theme", icon: MonitorIcon, keywords: "appearance", run: () => (setTheme("system"), setOpen(false)) },
{ id: "s:labels", group: "Settings", title: "File labels", icon: TagIcon, keywords: "colors roles", run: go("/settings/labels") },
{ id: "s:tags", group: "Settings", title: "Tags", icon: TagsIcon, keywords: "rename colors", run: go("/settings/tags") },
{ id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") },
{ id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") },
{ id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") },
];
for (const m of index?.models ?? []) {
out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) });
}
for (const e of index?.endpoints ?? []) {
out.push({ id: `e:${e.id}`, group: "Endpoints", title: e.name, hint: [e.engine, e.model].filter(Boolean).join(" · "), icon: ServerIcon, run: go(`/endpoints/${e.id}`) });
}
for (const b of index?.benchmarks ?? []) {
out.push({
id: `b:${b.id}`,
group: "Benchmarks",
title: b.label ?? `${b.target} · ${b.model}`,
hint: `${KIND_LABEL[b.kind] ?? b.kind} · ${b.state} · ${new Date(b.createdAt).toLocaleDateString()}`,
icon: GaugeIcon,
keywords: `${b.target} ${b.model}`,
run: go(`/benchmarks/${b.id}`),
});
}
for (const t of index?.tags ?? []) {
out.push({ id: `t:${t}`, group: "Tags", title: t, hint: "models with this tag", icon: TagIcon, run: go(`/?tag=${encodeURIComponent(t)}`) });
}
return out;
// `go` only closes over router and setOpen (the shell's state setter), which are stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [index, setTheme]);
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
const groups = useMemo(() => {
const scored = items.map((it) => ({ it, s: score(it, terms) })).filter((x) => x.s > 0);
const order = ["Pages", "Actions", "Models", "Endpoints", "Benchmarks", "Settings", "Tags"];
// Without a query: pages, actions and settings, plus the newest few of the rest.
const per = terms.length ? 8 : 4;
return order
.map((g) => ({ g, rows: scored.filter((x) => x.it.group === g).sort((a, b) => b.s - a.s).slice(0, per).map((x) => x.it) }))
.filter((x) => x.rows.length && (terms.length || ["Pages", "Actions", "Models", "Benchmarks"].includes(x.g)));
// terms is derived from query
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, query]);
const flat = groups.flatMap((g) => g.rows);
const current = Math.min(active, Math.max(0, flat.length - 1));
useEffect(() => {
list.current?.querySelector(`[data-index="${current}"]`)?.scrollIntoView({ block: "nearest" });
}, [current]);
function onKeyDown(e: React.KeyboardEvent) {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((current + 1) % Math.max(1, flat.length));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((current - 1 + flat.length) % Math.max(1, flat.length));
} else if (e.key === "Enter") {
e.preventDefault();
flat[current]?.run();
}
}
let n = -1;
return (
<Dialog.Root
open={open}
onOpenChange={(o) => {
setOpen(o);
if (!o) {
setQuery("");
setActive(0);
}
}}
>
<Dialog.Portal>
<Dialog.Backdrop className="fixed inset-0 z-50 bg-black/50 backdrop-blur-[2px] data-ending-style:opacity-0 data-starting-style:opacity-0" />
<Dialog.Popup className="fixed top-[15vh] left-1/2 z-50 flex max-h-[70vh] w-[min(40rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-2xl bg-popover/85 text-popover-foreground shadow-2xl ring-1 ring-foreground/10 backdrop-blur-xl outline-none data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0">
<Dialog.Title className="sr-only">Search</Dialog.Title>
<div className="flex items-center gap-2 border-b px-4">
<SearchIcon className="size-4 shrink-0 text-muted-foreground" />
<input
autoFocus
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
}}
onKeyDown={onKeyDown}
placeholder="Search models, endpoints, benchmarks, settings…"
className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
aria-label="Search"
/>
<kbd className="rounded-full border px-2 text-[10px] leading-4 text-muted-foreground">Esc</kbd>
</div>
<div ref={list} className="min-h-0 flex-1 overflow-y-auto p-2" role="listbox">
{flat.length === 0 ? (
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{index ? `Nothing matches "${query}".` : "Loading…"}</p>
) : (
groups.map(({ g, rows }) => (
<div key={g} className="mb-1">
<div className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g}</div>
{rows.map((it) => {
n++;
const i = n;
return (
<button
key={it.id}
type="button"
role="option"
aria-selected={i === current}
data-index={i}
onMouseMove={() => setActive(i)}
onClick={it.run}
className={cn("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left text-sm", i === current && "bg-muted")}
>
<it.icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{it.title}</span>
{it.hint && <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{it.hint}</span>}
{i === current && <CornerDownLeftIcon className="size-3.5 shrink-0 text-muted-foreground" />}
</button>
);
})}
</div>
))
)}
</div>
</Dialog.Popup>
</Dialog.Portal>
</Dialog.Root>
);
}
+40 -237
View File
@@ -1,258 +1,61 @@
"use client"; "use client";
import { Dialog } from "@base-ui/react/dialog"; import { SearchIcon } from "lucide-react";
import { import dynamic from "next/dynamic";
BoxIcon, import { useEffect, useState, useSyncExternalStore } from "react";
CornerDownLeftIcon,
DownloadIcon,
GaugeIcon,
LibraryIcon,
MonitorIcon,
MoonIcon,
PlusIcon,
ScanSearchIcon,
SearchIcon,
ServerIcon,
SunIcon,
TagIcon,
TagsIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
type Index = { // The dialog (base-ui Dialog, all items and icons) is its own chunk, kept out of every page's first
models: { id: string; repoId: string; quants: string[]; status: string; tags: string[] }[]; // load: most page views never open it. It starts loading when you reach for it (hovering or focusing
endpoints: { id: string; name: string; model: string | null; engine: string | null }[]; // the Search button, pressing ⌘ or Ctrl) and renders on the first open.
benchmarks: { id: string; label: string | null; kind: string; state: string; target: string; model: string; createdAt: number }[]; const loadDialog = () => import("./command-palette-dialog");
tags: string[]; const CommandPaletteDialog = dynamic(() => loadDialog().then((m) => m.CommandPaletteDialog), { ssr: false });
}; const preload = () => void loadDialog();
type Item = { const OPEN_EVENT = "kaname:command-palette";
id: string;
group: string;
title: string;
hint?: string;
icon: React.ComponentType<{ className?: string }>;
/** Extra words that match (not shown). */
keywords?: string;
run: () => void;
};
const KIND_LABEL: Record<string, string> = { run: "speed run", ab: "A/B", eval: "quality eval" }; /** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */
export function CommandPalette() {
const [open, setOpen] = useState(false);
// Mounted from the first open on, so it keeps its state like before.
const [used, setUsed] = useState(false);
/** Every whitespace-separated term must appear (case-insensitive); earlier and title matches rank higher. */ useEffect(() => {
function score(item: Item, terms: string[]): number { const onKey = (e: KeyboardEvent) => {
if (terms.length === 0) return 1; if (e.key === "Meta" || e.key === "Control") preload();
const title = item.title.toLowerCase(); if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
const all = `${title} ${item.hint ?? ""} ${item.keywords ?? ""} ${item.group}`.toLowerCase(); e.preventDefault();
let s = 0; setUsed(true);
for (const t of terms) { setOpen((o) => !o);
const i = all.indexOf(t); }
if (i < 0) return 0; };
s += title.startsWith(t) ? 4 : title.includes(t) ? 2 : 1; const onOpen = () => {
} setUsed(true);
return s; setOpen(true);
};
window.addEventListener("keydown", onKey);
window.addEventListener(OPEN_EVENT, onOpen);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener(OPEN_EVENT, onOpen);
};
}, []);
return used ? <CommandPaletteDialog open={open} setOpen={setOpen} /> : null;
} }
const isMac = () => /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent); const isMac = () => /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent);
const noSubscribe = () => () => {}; const noSubscribe = () => () => {};
/** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */
export function CommandPalette() {
const router = useRouter();
const { setTheme } = useTheme();
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [index, setIndex] = useState<Index | null>(null);
const [active, setActive] = useState(0);
const list = useRef<HTMLDivElement>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
setOpen((o) => !o);
}
};
const onOpen = () => setOpen(true);
window.addEventListener("keydown", onKey);
window.addEventListener("kaname:command-palette", onOpen);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("kaname:command-palette", onOpen);
};
}, []);
// Fresh data every time it opens (the library changes while you use it).
useEffect(() => {
if (!open) return;
let stop = false;
void fetch("/api/search-index", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.then((d: Index | null) => !stop && d && setIndex(d));
return () => {
stop = true;
};
}, [open]);
const go = (href: string) => () => {
setOpen(false);
router.push(href);
};
const items = useMemo<Item[]>(() => {
const out: Item[] = [
{ id: "p:library", group: "Pages", title: "Library", icon: LibraryIcon, keywords: "models home", run: go("/") },
{ id: "p:endpoints", group: "Pages", title: "Endpoints", icon: ServerIcon, keywords: "servers", run: go("/endpoints") },
{ id: "p:benchmarks", group: "Pages", title: "Benchmarks", icon: GaugeIcon, keywords: "runs compare", run: go("/benchmarks") },
{ id: "a:add-model", group: "Actions", title: "Add model", icon: PlusIcon, keywords: "download new hugging face repo", run: go("/?add=1") },
{ id: "a:new-endpoint", group: "Actions", title: "Add endpoint", icon: PlusIcon, keywords: "new server", run: go("/endpoints/new") },
{ id: "a:scan", group: "Actions", title: "Scan the models folder", icon: ScanSearchIcon, keywords: "rescan import", run: go("/settings/downloads#scan") },
{ id: "a:theme-light", group: "Actions", title: "Light theme", icon: SunIcon, keywords: "appearance", run: () => (setTheme("light"), setOpen(false)) },
{ id: "a:theme-dark", group: "Actions", title: "Dark theme", icon: MoonIcon, keywords: "appearance", run: () => (setTheme("dark"), setOpen(false)) },
{ id: "a:theme-system", group: "Actions", title: "System theme", icon: MonitorIcon, keywords: "appearance", run: () => (setTheme("system"), setOpen(false)) },
{ id: "s:labels", group: "Settings", title: "File labels", icon: TagIcon, keywords: "colors roles", run: go("/settings/labels") },
{ id: "s:tags", group: "Settings", title: "Tags", icon: TagsIcon, keywords: "rename colors", run: go("/settings/tags") },
{ id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") },
{ id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") },
{ id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") },
];
for (const m of index?.models ?? []) {
out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) });
}
for (const e of index?.endpoints ?? []) {
out.push({ id: `e:${e.id}`, group: "Endpoints", title: e.name, hint: [e.engine, e.model].filter(Boolean).join(" · "), icon: ServerIcon, run: go(`/endpoints/${e.id}`) });
}
for (const b of index?.benchmarks ?? []) {
out.push({
id: `b:${b.id}`,
group: "Benchmarks",
title: b.label ?? `${b.target} · ${b.model}`,
hint: `${KIND_LABEL[b.kind] ?? b.kind} · ${b.state} · ${new Date(b.createdAt).toLocaleDateString()}`,
icon: GaugeIcon,
keywords: `${b.target} ${b.model}`,
run: go(`/benchmarks/${b.id}`),
});
}
for (const t of index?.tags ?? []) {
out.push({ id: `t:${t}`, group: "Tags", title: t, hint: "models with this tag", icon: TagIcon, run: go(`/?tag=${encodeURIComponent(t)}`) });
}
return out;
// `go` only closes over router and setOpen, which are stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [index, setTheme]);
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
const groups = useMemo(() => {
const scored = items.map((it) => ({ it, s: score(it, terms) })).filter((x) => x.s > 0);
const order = ["Pages", "Actions", "Models", "Endpoints", "Benchmarks", "Settings", "Tags"];
// Without a query: pages, actions and settings, plus the newest few of the rest.
const per = terms.length ? 8 : 4;
return order
.map((g) => ({ g, rows: scored.filter((x) => x.it.group === g).sort((a, b) => b.s - a.s).slice(0, per).map((x) => x.it) }))
.filter((x) => x.rows.length && (terms.length || ["Pages", "Actions", "Models", "Benchmarks"].includes(x.g)));
// terms is derived from query
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, query]);
const flat = groups.flatMap((g) => g.rows);
const current = Math.min(active, Math.max(0, flat.length - 1));
useEffect(() => {
list.current?.querySelector(`[data-index="${current}"]`)?.scrollIntoView({ block: "nearest" });
}, [current]);
function onKeyDown(e: React.KeyboardEvent) {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((current + 1) % Math.max(1, flat.length));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((current - 1 + flat.length) % Math.max(1, flat.length));
} else if (e.key === "Enter") {
e.preventDefault();
flat[current]?.run();
}
}
let n = -1;
return (
<Dialog.Root
open={open}
onOpenChange={(o) => {
setOpen(o);
if (!o) {
setQuery("");
setActive(0);
}
}}
>
<Dialog.Portal>
<Dialog.Backdrop className="fixed inset-0 z-50 bg-black/50 backdrop-blur-[2px] data-ending-style:opacity-0 data-starting-style:opacity-0" />
<Dialog.Popup className="fixed top-[15vh] left-1/2 z-50 flex max-h-[70vh] w-[min(40rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-2xl bg-popover/85 text-popover-foreground shadow-2xl ring-1 ring-foreground/10 backdrop-blur-xl outline-none data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0">
<Dialog.Title className="sr-only">Search</Dialog.Title>
<div className="flex items-center gap-2 border-b px-4">
<SearchIcon className="size-4 shrink-0 text-muted-foreground" />
<input
autoFocus
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
}}
onKeyDown={onKeyDown}
placeholder="Search models, endpoints, benchmarks, settings…"
className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
aria-label="Search"
/>
<kbd className="rounded-full border px-2 text-[10px] leading-4 text-muted-foreground">Esc</kbd>
</div>
<div ref={list} className="min-h-0 flex-1 overflow-y-auto p-2" role="listbox">
{flat.length === 0 ? (
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{index ? `Nothing matches "${query}".` : "Loading…"}</p>
) : (
groups.map(({ g, rows }) => (
<div key={g} className="mb-1">
<div className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g}</div>
{rows.map((it) => {
n++;
const i = n;
return (
<button
key={it.id}
type="button"
role="option"
aria-selected={i === current}
data-index={i}
onMouseMove={() => setActive(i)}
onClick={it.run}
className={cn("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left text-sm", i === current && "bg-muted")}
>
<it.icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{it.title}</span>
{it.hint && <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{it.hint}</span>}
{i === current && <CornerDownLeftIcon className="size-3.5 shrink-0 text-muted-foreground" />}
</button>
);
})}
</div>
))
)}
</div>
</Dialog.Popup>
</Dialog.Portal>
</Dialog.Root>
);
}
/** The menu button that opens the palette, showing its shortcut. */ /** The menu button that opens the palette, showing its shortcut. */
export function CommandPaletteButton({ className }: { className?: string }) { export function CommandPaletteButton({ className }: { className?: string }) {
const mac = useSyncExternalStore(noSubscribe, isMac, () => false); const mac = useSyncExternalStore(noSubscribe, isMac, () => false);
return ( return (
<button <button
type="button" type="button"
onClick={() => window.dispatchEvent(new Event("kaname:command-palette"))} onClick={() => window.dispatchEvent(new Event(OPEN_EVENT))}
onPointerEnter={preload}
onFocus={preload}
className={cn("flex h-8 items-center gap-2 rounded-lg px-2 text-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground", className)} className={cn("flex h-8 items-center gap-2 rounded-lg px-2 text-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground", className)}
aria-label="Search" aria-label="Search"
> >
+48 -15
View File
@@ -1,10 +1,20 @@
"use client"; "use client";
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { ADAM_DOTS, ADAM_H, ADAM_W } from "./adam-dots";
const SPACING = 6; // CSS px between dot centres const SPACING = 6; // CSS px between dot centres
const levels = Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16));
type Grid = { w: number; h: number; levels: Uint8Array };
// The brightness grid (26 KB of text) is its own chunk, shared by every page and parsed once per
// tab. Imported statically, it was copied into each page's chunk.
let grid: Promise<Grid> | null = null;
const loadGrid = () =>
(grid ??= import("./adam-dots").then(({ ADAM_DOTS, ADAM_H, ADAM_W }) => ({
w: ADAM_W,
h: ADAM_H,
levels: Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16)),
})));
/** /**
* The Creation of Adam as a dot matrix. `view` is the horizontal slice of the painting (0–1) that * The Creation of Adam as a dot matrix. `view` is the horizontal slice of the painting (0–1) that
@@ -30,30 +40,43 @@ export function DotPainting({
useEffect(() => { useEffect(() => {
const canvas = ref.current; const canvas = ref.current;
if (!canvas) return; if (!canvas) return;
let data: Grid | null = null;
let cancelled = false;
let frame = 0;
// What the canvas shows (size, pixel ratio, theme, color): a drawing takes tens of ms, so skip it
// when nothing changed, e.g. for the ResizeObserver's first callback or another class on <html>.
let drawn = "";
const draw = () => { const draw = () => {
frame = 0;
if (!data) return;
const { width, height } = canvas.getBoundingClientRect(); const { width, height } = canvas.getBoundingClientRect();
if (!width || !height) return; if (!width || !height) return;
const dpr = window.devicePixelRatio || 1; const dpr = window.devicePixelRatio || 1;
const color = getComputedStyle(canvas).color;
const dark = document.documentElement.classList.contains("dark");
const key = `${width}x${height}@${dpr} ${dark} ${color}`;
if (key === drawn) return;
drawn = key;
const { w, h, levels } = data;
canvas.width = Math.round(width * dpr); canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr); canvas.height = Math.round(height * dpr);
const g = canvas.getContext("2d")!; const g = canvas.getContext("2d")!;
g.setTransform(dpr, 0, 0, dpr, 0, 0); g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, width, height); g.clearRect(0, 0, width, height);
g.fillStyle = getComputedStyle(canvas).color; g.fillStyle = color;
const dark = document.documentElement.classList.contains("dark");
// CSS px per grid cell: `view` of the painting's width fills the box (at least covering it). // CSS px per grid cell: `view` of the painting's width fills the box (at least covering it).
const scale = Math.max(width / (view * ADAM_W), height / ADAM_H); const scale = Math.max(width / (view * w), height / h);
const offX = ax * width - fx * ADAM_W * scale; const offX = ax * width - fx * w * scale;
const offY = ay * height - fy * ADAM_H * scale; const offY = ay * height - fy * h * scale;
const clampOff = (o: number, box: number, size: number) => Math.min(0, Math.max(box - size, o)); const clampOff = (o: number, box: number, size: number) => Math.min(0, Math.max(box - size, o));
const ox = clampOff(offX, width, ADAM_W * scale); const ox = clampOff(offX, width, w * scale);
const oy = clampOff(offY, height, ADAM_H * scale); const oy = clampOff(offY, height, h * scale);
const maxR = SPACING * 0.48; const maxR = SPACING * 0.48;
for (let y = SPACING / 2; y < height; y += SPACING) { for (let y = SPACING / 2; y < height; y += SPACING) {
const iy = Math.min(ADAM_H - 1, Math.max(0, Math.floor((y - oy) / scale))); const iy = Math.min(h - 1, Math.max(0, Math.floor((y - oy) / scale)));
for (let x = SPACING / 2; x < width; x += SPACING) { for (let x = SPACING / 2; x < width; x += SPACING) {
const ix = Math.min(ADAM_W - 1, Math.max(0, Math.floor((x - ox) / scale))); const ix = Math.min(w - 1, Math.max(0, Math.floor((x - ox) / scale)));
const v = levels[iy * ADAM_W + ix] / 15; const v = levels[iy * w + ix] / 15;
const r = maxR * (dark ? v : 1 - v); const r = maxR * (dark ? v : 1 - v);
if (r < 0.35) continue; if (r < 0.35) continue;
g.beginPath(); g.beginPath();
@@ -62,13 +85,23 @@ export function DotPainting({
} }
} }
}; };
draw(); // While a window is resized, observations arrive every frame: draw at most once per frame.
const resize = new ResizeObserver(draw); const schedule = () => {
if (!frame) frame = requestAnimationFrame(draw);
};
void loadGrid().then((g) => {
if (cancelled) return;
data = g;
draw();
});
const resize = new ResizeObserver(schedule);
resize.observe(canvas); resize.observe(canvas);
// next-themes switches the class on <html>. // next-themes switches the class on <html>.
const theme = new MutationObserver(draw); const theme = new MutationObserver(schedule);
theme.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); theme.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
return () => { return () => {
cancelled = true;
cancelAnimationFrame(frame);
resize.disconnect(); resize.disconnect();
theme.disconnect(); theme.disconnect();
}; };
+93
View File
@@ -0,0 +1,93 @@
// Enum values stored in text columns (see schema.ts), with their types. No imports: client
// components may use these, unlike schema.ts, whose table definitions pull in drizzle-orm.
// Models
export const MODEL_STATUSES = [
"pending", // added, nothing downloaded yet
"downloading",
"ready", // all selected files present at pinned SHA
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
"failed", // last download failed
"deleting",
] as const;
export type ModelStatus = (typeof MODEL_STATUSES)[number];
/** Is the repo (at the pinned commit) still on the Hub? Local files are never touched either way. */
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
export type HubState = (typeof HUB_STATES)[number];
export const MODEL_FILE_STATES = [
"pending", // not downloaded yet / not checked
"present", // exists with the expected size
"missing",
"size_mismatch",
"hash_mismatch",
"verified", // deep verify: hash matches
] as const;
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
// Jobs
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
/** Download purposes; "remove" is a delete job that removes only some files (the model stays). */
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update", "remove"] as const;
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
"queued",
"downloading",
"verifying",
"completed",
"failed",
"cancelled",
"interrupted",
] as const;
export type JobState = (typeof JOB_STATES)[number];
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
export const JOB_ERROR_CODES = [
"auth", // invalid/missing token
"gated", // gated repo, access not granted
"repo_not_found",
"revision_not_found",
"disk_full",
"network",
"size_mismatch", // finished but files don't match expected sizes
"unknown",
] as const;
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
export type JobFileState = (typeof JOB_FILE_STATES)[number];
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
export type LogStream = (typeof LOG_STREAMS)[number];
// Endpoints and benchmarks
export const ENDPOINT_ENGINES = ["llama.cpp", "vllm", "sglang", "ollama", "other"] as const;
export type EndpointEngine = (typeof ENDPOINT_ENGINES)[number];
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
export type BenchmarkPhase = (typeof BENCHMARK_PHASES)[number];
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
/**
* preview: the worker runs `L80 betterbench --results … --dry-run --payload-out`; previewed: the
* exact payload is ready to inspect; publish: confirmed by a user, the worker publishes it;
* published / failed.
*/
export const PUBLICATION_STATES = ["preview", "previewed", "publish", "published", "failed"] as const;
export type PublicationState = (typeof PUBLICATION_STATES)[number];
+22 -85
View File
@@ -8,6 +8,28 @@ import {
uniqueIndex, uniqueIndex,
} from "drizzle-orm/sqlite-core"; } from "drizzle-orm/sqlite-core";
import { ulid } from "ulid"; import { ulid } from "ulid";
import {
BENCHMARK_KINDS,
type BenchmarkPhase,
BENCHMARK_STATES,
ENDPOINT_ENGINES,
type EndpointEngine,
HUB_STATES,
JOB_ERROR_CODES,
JOB_FILE_STATES,
JOB_KINDS,
JOB_PURPOSES,
JOB_STATES,
LOG_STREAMS,
MODEL_FILE_STATES,
MODEL_STATUSES,
PUBLICATION_STATES,
type QualitySection,
} from "./enums";
// The enum arrays live in ./enums (no dependencies), so client components can use them without
// pulling drizzle-orm and every table definition into the browser bundle.
export * from "./enums";
// Conventions (keep these when adding tables in later steps, they keep a Postgres port simple): // Conventions (keep these when adding tables in later steps, they keep a Postgres port simple):
// - Primary keys are ULID strings, generated in the app, never reused. // - Primary keys are ULID strings, generated in the app, never reused.
@@ -36,20 +58,6 @@ const ts = (name: string) => integer(name, { mode: "timestamp_ms" });
// Models // Models
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export const MODEL_STATUSES = [
"pending", // added, nothing downloaded yet
"downloading",
"ready", // all selected files present at pinned SHA
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
"failed", // last download failed
"deleting",
] as const;
export type ModelStatus = (typeof MODEL_STATUSES)[number];
/** Is the repo (at the pinned commit) still on the Hub? Local files are never touched either way. */
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
export type HubState = (typeof HUB_STATES)[number];
export type UpdateDiffFile = { path: string; size: number; oldSize?: number }; export type UpdateDiffFile = { path: string; size: number; oldSize?: number };
export type UpdateDiff = { export type UpdateDiff = {
/** Commit the diff was computed against (the tracked revision's head on the Hub). */ /** Commit the diff was computed against (the tracked revision's head on the Hub). */
@@ -181,16 +189,6 @@ export const modelRevisions = sqliteTable(
(t) => [index("model_revisions_model_idx").on(t.modelId)], (t) => [index("model_revisions_model_idx").on(t.modelId)],
); );
export const MODEL_FILE_STATES = [
"pending", // not downloaded yet / not checked
"present", // exists with the expected size
"missing",
"size_mismatch",
"hash_mismatch",
"verified", // deep verify: hash matches
] as const;
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
/** All files in the repo at the pinned SHA. `selected` marks what we keep locally. */ /** All files in the repo at the pinned SHA. `selected` marks what we keep locally. */
export const modelFiles = sqliteTable( export const modelFiles = sqliteTable(
"model_files", "model_files",
@@ -218,37 +216,6 @@ export const modelFiles = sqliteTable(
// Jobs (executed by the worker) // Jobs (executed by the worker)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
/** Download purposes; "remove" is a delete job that removes only some files (the model stays). */
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update", "remove"] as const;
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
"queued",
"downloading",
"verifying",
"completed",
"failed",
"cancelled",
"interrupted",
] as const;
export type JobState = (typeof JOB_STATES)[number];
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
export const JOB_ERROR_CODES = [
"auth", // invalid/missing token
"gated", // gated repo, access not granted
"repo_not_found",
"revision_not_found",
"disk_full",
"network",
"size_mismatch", // finished but files don't match expected sizes
"unknown",
] as const;
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
export const jobs = sqliteTable( export const jobs = sqliteTable(
"jobs", "jobs",
{ {
@@ -279,9 +246,6 @@ export const jobs = sqliteTable(
(t) => [index("jobs_state_idx").on(t.state), index("jobs_model_idx").on(t.modelId)], (t) => [index("jobs_state_idx").on(t.state), index("jobs_model_idx").on(t.modelId)],
); );
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
export type JobFileState = (typeof JOB_FILE_STATES)[number];
export const jobFiles = sqliteTable( export const jobFiles = sqliteTable(
"job_files", "job_files",
{ {
@@ -299,9 +263,6 @@ export const jobFiles = sqliteTable(
(t) => [primaryKey({ columns: [t.jobId, t.modelFileId] })], (t) => [primaryKey({ columns: [t.jobId, t.modelFileId] })],
); );
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
export type LogStream = (typeof LOG_STREAMS)[number];
export const jobLogs = sqliteTable( export const jobLogs = sqliteTable(
"job_logs", "job_logs",
{ {
@@ -425,9 +386,6 @@ export type DeploymentOptions = {
// Endpoints: OpenAI-compatible servers to benchmark (llama.cpp, vLLM, SGLang, …), run elsewhere // Endpoints: OpenAI-compatible servers to benchmark (llama.cpp, vLLM, SGLang, …), run elsewhere
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export const ENDPOINT_ENGINES = ["llama.cpp", "vllm", "sglang", "ollama", "other"] as const;
export type EndpointEngine = (typeof ENDPOINT_ENGINES)[number];
/** /**
* What runs behind an endpoint, as the user describes it (Kaname can't see that machine). Copied into * What runs behind an endpoint, as the user describes it (Kaname can't see that machine). Copied into
* every run; goes into BetterBench notes and launch80. Nothing here may identify the host. * every run; goes into BetterBench notes and launch80. Nothing here may identify the host.
@@ -499,12 +457,6 @@ export const endpoints = sqliteTable(
// Benchmarks (BetterBench runs against an endpoint) // Benchmarks (BetterBench runs against an endpoint)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
export type BenchmarkPhase = (typeof BENCHMARK_PHASES)[number];
/** What a run measures. `passes`/`warmup` null: BetterBench's defaults (20 / 3), or 5 / 1 with quick. */ /** What a run measures. `passes`/`warmup` null: BetterBench's defaults (20 / 3), or 5 / 1 with quick. */
export type BenchmarkSettings = { export type BenchmarkSettings = {
quick: boolean; quick: boolean;
@@ -518,9 +470,6 @@ export type BenchmarkSettings = {
evalSections?: QualitySection[]; evalSections?: QualitySection[];
}; };
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
/** A quality eval's result: pass rates per section and the overall score (their mean), 0–100. */ /** A quality eval's result: pass rates per section and the overall score (their mean), 0–100. */
export type QualityResult = { export type QualityResult = {
/** The eval set's version; only results of the same version are comparable. */ /** The eval set's version; only results of the same version are comparable. */
@@ -539,10 +488,6 @@ export type QualityResult = {
config: { temperature: number; seed: number; thinking: boolean; contextTokens: number | null }; config: { temperature: number; seed: number; thinking: boolean; contextTokens: number | null };
}; };
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
/** One side of a paired comparison, as BetterBench's paired_compare reports it. */ /** One side of a paired comparison, as BetterBench's paired_compare reports it. */
export type PairedResult = { export type PairedResult = {
metric: string; metric: string;
@@ -792,14 +737,6 @@ export const benchmarkLogs = sqliteTable(
// launch80 publications (double opt-in: a dry-run preview, then an explicit confirmation) // launch80 publications (double opt-in: a dry-run preview, then an explicit confirmation)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/**
* preview: the worker runs `L80 betterbench --results … --dry-run --payload-out`; previewed: the
* exact payload is ready to inspect; publish: confirmed by a user, the worker publishes it;
* published / failed.
*/
export const PUBLICATION_STATES = ["preview", "previewed", "publish", "published", "failed"] as const;
export type PublicationState = (typeof PUBLICATION_STATES)[number];
export const benchmarkPublications = sqliteTable( export const benchmarkPublications = sqliteTable(
"benchmark_publications", "benchmark_publications",
{ {