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:
9 files changed
+110
-31
No files matched your search
@@ -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
@@ -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
@@ -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
@@ -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]));
|
||||
}
|
||||
Reference in new issue
Block a user