Library: load import folder files on demand, memoize search

The library page passed every importable folder's full file list (up to 5,000
entries each, from the worker's scan) into a client component, though it is
only used after clicking Import. With three such folders that was 84% of a
1.3 MB page, re-sent on every refresh after a job finished.

- listLocalFolders() returns path, commit and counts only; the Import button
  fetches one folder's files from GET /api/local-folders?path=…
- addModel() checks that an import folder exists without loading its files.
- LibraryView builds each model's search text once and memoizes the visible
  rows and facet counts; the facet sort uses one Intl.Collator.

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:49:18 +00:00
1 parent 76d851896e
commit 7239ba2692
9 files changed
+110 -31

No files matched your search

+6
View File
@@ -14,6 +14,12 @@ step 1 (Hugging Face downloader) is released as a minor version.
everything on the page, paused while the tab is in the background. The server also no longer
grows in memory while a tab stays open, and an idle page no longer redraws every 5 seconds.
### Changed
- **Lighter library page**: folders found in the models folder no longer bring their whole file
list (up to 5,000 entries each) into the page; **Import** loads it when you click it. Search and
filter counts are computed once per change instead of on every progress update.
## [0.16.0] - 2026-10-30
A new look, a search for everything (⌘K / Ctrl+K), removing single files, and an easier deployment
+23 -11
View File
@@ -10,7 +10,8 @@ import { formatBytes, shortSha } from "@/lib/format";
import { cn } from "@/lib/utils";
import { AddModelForm, type ImportFolder } from "./add-model-form";
type Folder = ImportFolder & { totalBytes: number };
/** A folder found by the scan, without its file list (fetched when you click Import). */
type Folder = { path: string; commit: string | null; fileCount: number; totalBytes: number };
/** The "Add model" / "Close" toggle (shown in the library hero). */
export function AddModelToggle({ open, onToggle }: { open: boolean; onToggle: () => void }) {
@@ -37,7 +38,9 @@ export function AddModelPanel({
setOpen: (open: boolean) => void;
}) {
const router = useRouter();
const [importing, setImporting] = useState<Folder | null>(null);
const [importing, setImporting] = useState<ImportFolder | null>(null);
// The folder whose file list is being fetched for Import.
const [fetching, setFetching] = useState<string | null>(null);
// Closed from outside (the toggle in the hero): forget the folder being imported.
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
@@ -51,6 +54,22 @@ export function AddModelPanel({
setImporting(null);
}
async function startImport(folder: Folder) {
setFetching(folder.path);
try {
const res = await fetch(`/api/local-folders?path=${encodeURIComponent(folder.path)}`, { cache: "no-store" });
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not load the folder (${res.status})`);
return;
}
setImporting(body as ImportFolder);
setOpen(true);
} finally {
setFetching(null);
}
}
async function rescan() {
setScanning(true);
try {
@@ -109,15 +128,8 @@ export function AddModelPanel({
{f.fileCount} file{f.fileCount === 1 ? "" : "s"} · {formatBytes(f.totalBytes)}
{f.commit && <> · hf commit {shortSha(f.commit)}</>}
</span>
<Button
size="sm"
variant="outline"
onClick={() => {
setImporting(f);
setOpen(true);
}}
>
Import
<Button size="sm" variant="outline" disabled={fetching != null} onClick={() => void startImport(f)}>
{fetching === f.path ? "Loading…" : "Import"}
</Button>
</li>
))}
+16 -3
View File
@@ -27,7 +27,9 @@ import {
type Filters,
matchesFilters,
matchesQuery,
queryTerms,
type SearchableModel,
searchText,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
@@ -45,7 +47,7 @@ const FACET_LABEL: Record<Facet, string> = {
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
function toSearchable(r: LibraryRow): SearchableModel {
return {
const m: SearchableModel = {
repoId: r.repoId,
author: r.author,
families: r.families,
@@ -64,6 +66,7 @@ function toSearchable(r: LibraryRow): SearchableModel {
? "update available"
: null,
};
return { ...m, text: searchText(m) };
}
/** Search + facet filters (kept in the URL) over the library table. */
@@ -106,9 +109,19 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
sync("", EMPTY_FILTERS);
};
// Search text and counts are computed once per change of rows, query or filters, not on every
// render (live job progress re-renders this table while downloads run).
const searchable = useMemo(() => rows.map(toSearchable), [rows]);
const tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
const visible = rows.filter((_, i) => matchesQuery(searchable[i], query) && matchesFilters(searchable[i], filters));
const terms = useMemo(() => queryTerms(query), [query]);
const visible = useMemo(
() => rows.filter((_, i) => matchesQuery(searchable[i], terms) && matchesFilters(searchable[i], filters)),
[rows, searchable, terms, filters],
);
const facetOptions = useMemo(
() => Object.fromEntries(FACETS.map((facet) => [facet, facetCounts(searchable, facet, terms, filters)])) as Record<Facet, [string, number][]>,
[searchable, terms, filters],
);
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
const pages = Math.max(1, Math.ceil(visible.length / pageSize));
const current = Math.min(page, pages - 1);
@@ -147,7 +160,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<FacetFilter
key={facet}
label={FACET_LABEL[facet]}
values={facetCounts(searchable, facet, query, filters)}
values={facetOptions[facet]}
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
+1 -4
View File
@@ -24,10 +24,7 @@ export default async function LibraryPage({ searchParams }: PageProps<"/">) {
updates: rows.filter((r) => r.updateAvailable && (r.hubState === "available" || !r.hubState)).length,
goneFromHub: rows.filter((r) => r.hubState === "repo_missing" || r.hubState === "commit_missing").length,
}}
panel={{
freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
folders: folders.map((f) => ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes })),
}}
panel={{ freeBytes: worker.online ? worker.modelsDirFreeBytes : null, folders }}
/>
{rows.length > 0 && <LibraryView rows={rows} />}
</div>
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { getLocalFolder } from "@/lib/local-folders";
export const dynamic = "force-dynamic";
/** One folder the scan found, with its files (`?path=<org>/<name>`): what the Import form needs. */
export const GET = withAuth(async (req) => {
const path = new URL(req.url).searchParams.get("path");
const folder = path ? await getLocalFolder(path) : undefined;
if (!folder) return apiError(404, "not_found", "This folder is no longer in the models folder. Rescan and try again.");
return NextResponse.json({
path: folder.path,
commit: folder.commit,
files: folder.files,
fileCount: folder.fileCount,
totalBytes: folder.totalBytes,
});
});
+13 -3
View File
@@ -4,21 +4,31 @@ import { db } from "@/lib/db/client";
import { localFolders, models, workerState } from "@/lib/db/schema";
export type LocalFolder = typeof localFolders.$inferSelect;
export type LocalFolderSummary = Pick<LocalFolder, "path" | "commit" | "fileCount" | "totalBytes">;
/** Folders in MODELS_DIR that no model uses (from the worker's last scan). */
export async function listLocalFolders(): Promise<LocalFolder[]> {
/**
* Folders in MODELS_DIR that no model uses (from the worker's last scan), without their file lists:
* those can hold thousands of entries and are only needed once you click Import (getLocalFolder).
*/
export async function listLocalFolders(): Promise<LocalFolderSummary[]> {
const d = db();
return d
.select()
.select({ path: localFolders.path, commit: localFolders.commit, fileCount: localFolders.fileCount, totalBytes: localFolders.totalBytes })
.from(localFolders)
.where(notInArray(localFolders.path, d.select({ p: models.localPath }).from(models)))
.orderBy(asc(localFolders.path));
}
/** One folder with its file list. */
export async function getLocalFolder(path: string): Promise<LocalFolder | undefined> {
return db().query.localFolders.findFirst({ where: eq(localFolders.path, path) });
}
export async function localFolderExists(path: string): Promise<boolean> {
const row = await db().query.localFolders.findFirst({ columns: { path: true }, where: eq(localFolders.path, path) });
return !!row;
}
/** Ask the worker to scan MODELS_DIR now (it picks this up with its next heartbeat). */
export async function requestFolderScan(): Promise<void> {
await db().update(workerState).set({ scanRequestedAt: new Date() }).where(eq(workerState.id, "worker"));
+2 -2
View File
@@ -7,7 +7,7 @@ import { hubMissingMessage } from "@/lib/hub/availability";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { localFolderExists, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
import { contentId } from "@/lib/update-diff";
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
@@ -39,7 +39,7 @@ export async function addModel(input: {
const info = await getRepoInfo(input.repoId, input.sha);
const repoId = info.repoId;
const localPath = input.localPath ?? repoId;
if (input.localPath && !(await getLocalFolder(input.localPath))) {
if (input.localPath && !(await localFolderExists(input.localPath))) {
throw new ModelError("not_found", `Folder ${input.localPath} was not found in the models folder. Rescan and try again.`, 404);
}
const usedBy = await db().query.models.findFirst({ columns: { repoId: true }, where: eq(models.localPath, localPath) });
+11 -1
View File
@@ -3,7 +3,7 @@ import { describe, it } from "node:test";
import { groupSplitFiles, splitInfo } from "./file-groups";
import { fileRole } from "./file-roles";
import { modelFamilies, parseRepoMetadata } from "./hub/metadata";
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, type SearchableModel } from "./search";
import { EMPTY_FILTERS, facetCounts, matchesFilters, matchesQuery, queryTerms, type SearchableModel, searchText } from "./search";
describe("parseRepoMetadata (real Hub responses, trimmed)", () => {
it("unsloth GGUF quant of Qwen", () => {
@@ -69,6 +69,16 @@ describe("matchesQuery", () => {
assert.ok(matchesQuery(m, " "));
assert.ok(!matchesQuery(m, "unsloth gemma"));
});
it("takes pre-split terms and a precomputed text with the same result", () => {
const m = model({});
const cached = { ...m, text: searchText(m) };
for (const q of ["qwen", "unsloth qwen", "ROLEPLAY", " ", "unsloth gemma"]) {
assert.equal(matchesQuery(cached, queryTerms(q)), matchesQuery(m, q), q);
}
// The stored text is what gets searched (it isn't rebuilt per call).
assert.ok(matchesQuery({ ...m, text: "only this" }, "only"));
assert.ok(!matchesQuery({ ...m, text: "only this" }, "qwen"));
});
});
describe("hub status", () => {
+18 -7
View File
@@ -14,6 +14,8 @@ export type SearchableModel = {
status: string;
/** Extra status value when the repo or commit is gone from the Hub, e.g. "deleted on Hub". */
hubStatus: string | null;
/** The text search terms are matched against (searchText), computed once per model. */
text?: string;
};
export const FACETS = ["author", "family", "quant", "tag", "status"] as const;
@@ -37,7 +39,8 @@ export function facetValues(m: SearchableModel, facet: Facet): string[] {
}
}
function haystack(m: SearchableModel): string {
/** Lowercased text of every searchable field; store it as `text` to build it only once. */
export function searchText(m: SearchableModel): string {
return [
m.repoId,
m.author,
@@ -57,11 +60,16 @@ function haystack(m: SearchableModel): string {
.toLowerCase();
}
/** The search terms of a query: lowercased, split on whitespace. */
export function queryTerms(query: string): string[] {
return query.toLowerCase().split(/\s+/).filter(Boolean);
}
/** Every whitespace-separated term must appear somewhere (case-insensitive substring). */
export function matchesQuery(m: SearchableModel, query: string): boolean {
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
export function matchesQuery(m: SearchableModel, query: string | string[]): boolean {
const terms = typeof query === "string" ? queryTerms(query) : query;
if (terms.length === 0) return true;
const text = haystack(m);
const text = m.text ?? searchText(m);
return terms.every((t) => text.includes(t));
}
@@ -75,17 +83,20 @@ export function matchesFilters(m: SearchableModel, filters: Filters, except?: Fa
});
}
const byName = new Intl.Collator(undefined, { numeric: true });
/**
* Value counts for one facet, computed over the models that match the query and all *other*
* facets, so picking e.g. an author narrows the quant counts but not the author list itself.
*/
export function facetCounts(models: SearchableModel[], facet: Facet, query: string, filters: Filters) {
export function facetCounts(models: SearchableModel[], facet: Facet, query: string | string[], filters: Filters) {
const terms = typeof query === "string" ? queryTerms(query) : query;
const counts = new Map<string, number>();
for (const m of models) {
if (!matchesQuery(m, query) || !matchesFilters(m, filters, facet)) continue;
if (!matchesQuery(m, terms) || !matchesFilters(m, filters, facet)) continue;
for (const v of new Set(facetValues(m, facet))) counts.set(v, (counts.get(v) ?? 0) + 1);
}
// Keep selected values visible even if their count dropped to 0.
for (const v of filters[facet]) if (!counts.has(v)) counts.set(v, 0);
return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], undefined, { numeric: true }));
return [...counts.entries()].sort((a, b) => b[1] - a[1] || byName.compare(a[0], b[0]));
}