From 7239ba2692b7e692294e821aa70659597ae740d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 20:49:18 +0000 Subject: [PATCH] Library: load import folder files on demand, memoize search MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5 --- CHANGELOG.md | 6 ++++++ src/app/(app)/add-model-panel.tsx | 34 ++++++++++++++++++++---------- src/app/(app)/library-view.tsx | 19 ++++++++++++++--- src/app/(app)/page.tsx | 5 +---- src/app/api/local-folders/route.ts | 20 ++++++++++++++++++ src/lib/local-folders.ts | 16 +++++++++++--- src/lib/models.ts | 4 ++-- src/lib/search.test.ts | 12 ++++++++++- src/lib/search.ts | 25 ++++++++++++++++------ 9 files changed, 110 insertions(+), 31 deletions(-) create mode 100644 src/app/api/local-folders/route.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9270807..dfc9a24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/app/(app)/add-model-panel.tsx b/src/app/(app)/add-model-panel.tsx index 0183806..ef269d5 100644 --- a/src/app/(app)/add-model-panel.tsx +++ b/src/app/(app)/add-model-panel.tsx @@ -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(null); + const [importing, setImporting] = useState(null); + // The folder whose file list is being fetched for Import. + const [fetching, setFetching] = useState(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)}} - ))} diff --git a/src/app/(app)/library-view.tsx b/src/app/(app)/library-view.tsx index fb3abfd..20bd094 100644 --- a/src/app/(app)/library-view.tsx +++ b/src/app/(app)/library-view.tsx @@ -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 = { 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, + [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[] }) { updateFilter(facet, v)} format={facet === "status" ? statusLabel : undefined} diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index 1cfb644..ea7cd90 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -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 && } diff --git a/src/app/api/local-folders/route.ts b/src/app/api/local-folders/route.ts new file mode 100644 index 0000000..7a24c9a --- /dev/null +++ b/src/app/api/local-folders/route.ts @@ -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=/`): 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, + }); +}); diff --git a/src/lib/local-folders.ts b/src/lib/local-folders.ts index 3265a0d..5ea39b4 100644 --- a/src/lib/local-folders.ts +++ b/src/lib/local-folders.ts @@ -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; -/** Folders in MODELS_DIR that no model uses (from the worker's last scan). */ -export async function listLocalFolders(): Promise { +/** + * 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 { 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 { return db().query.localFolders.findFirst({ where: eq(localFolders.path, path) }); } +export async function localFolderExists(path: string): Promise { + 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 { await db().update(workerState).set({ scanRequestedAt: new Date() }).where(eq(workerState.id, "worker")); diff --git a/src/lib/models.ts b/src/lib/models.ts index c0c7dc0..247ae88 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -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) }); diff --git a/src/lib/search.test.ts b/src/lib/search.test.ts index baf08c7..9b3aecd 100644 --- a/src/lib/search.test.ts +++ b/src/lib/search.test.ts @@ -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", () => { diff --git a/src/lib/search.ts b/src/lib/search.ts index 881211d..4abbda1 100644 --- a/src/lib/search.ts +++ b/src/lib/search.ts @@ -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(); 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])); }