diff --git a/CHANGELOG.md b/CHANGELOG.md index 33f69e0..2090c1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,10 @@ step 1 (Hugging Face downloader) is released as a minor version. every found folder's file list each time, every 2 minutes by default), and download progress no longer re-checks files that are already complete, which matters on network shares. A benchmark's current step is written when it changes, not for every line BetterBench prints. +- **Fewer and smaller Hugging Face requests**: adding a model right after looking it up reuses the + file list it just fetched (a commit's files never change), the author's avatar loads alongside, + and the regular Hub check asks only for the commit SHA instead of the full model info. +- The **Model card** tab shows the page at once and the card when it arrives from the Hub. ## [0.16.0] - 2026-10-30 diff --git a/src/app/(app)/[org]/[repo]/model-card.tsx b/src/app/(app)/[org]/[repo]/model-card.tsx index a67c606..8b6f535 100644 --- a/src/app/(app)/[org]/[repo]/model-card.tsx +++ b/src/app/(app)/[org]/[repo]/model-card.tsx @@ -1,7 +1,12 @@ +import "server-only"; +import { ExternalLinkIcon } from "lucide-react"; import ReactMarkdown, { defaultUrlTransform } from "react-markdown"; import rehypeRaw from "rehype-raw"; import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; import remarkGfm from "remark-gfm"; +import { Skeleton } from "@/components/ui/skeleton"; +import { shortSha } from "@/lib/format"; +import { fetchModelCard } from "@/lib/hub/client"; // Model cards mix Markdown and raw HTML. Parse the HTML (rehype-raw), then sanitize it: no scripts, // styles or event handlers, only the tags/attributes GitHub-style READMEs normally use. @@ -17,6 +22,55 @@ const schema = { }, }; +/** + * The Model card tab: the README at the pinned commit, fetched from the Hub (cached per commit). + * Rendered inside a Suspense boundary, so the rest of the page doesn't wait for the Hub. + */ +export async function ModelCardSection({ repoId, sha }: { repoId: string; sha: string }) { + const hub = `https://huggingface.co/${repoId}`; + const card = await fetchModelCard(repoId, sha).catch(() => undefined); + if (!card) { + return ( +

+ {card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "} + + Open on Hugging Face + +

+ ); + } + return ( + <> + +
+ + README.md @ {shortSha(sha)} + + +
+ + ); +} + +export function ModelCardSkeleton() { + return ( +
+ + + + + + + +
+ ); +} + /** Renders a repo's README like the Hub: relative links/images point at the pinned commit. */ export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) { const base = `https://huggingface.co/${repoId}`; diff --git a/src/app/(app)/[org]/[repo]/page.tsx b/src/app/(app)/[org]/[repo]/page.tsx index 8e5f432..5d656b0 100644 --- a/src/app/(app)/[org]/[repo]/page.tsx +++ b/src/app/(app)/[org]/[repo]/page.tsx @@ -2,7 +2,6 @@ import { ArrowDownIcon, BoxIcon, CpuIcon, - ExternalLinkIcon, FileTextIcon, FolderIcon, HistoryIcon, @@ -17,6 +16,7 @@ import { import type { Metadata } from "next"; import Link from "next/link"; import { notFound, redirect } from "next/navigation"; +import { Suspense } from "react"; import { CopyButton } from "@/components/copy-button"; import { BenchmarkStateBadge } from "@/components/benchmark-state"; import { PageHero } from "@/components/hero/page-hero"; @@ -27,7 +27,6 @@ import { cn } from "@/lib/utils"; import { formatBytes, shortSha } from "@/lib/format"; import { listBenchmarks } from "@/lib/benchmarks"; import { targetName } from "@/lib/benchmark-view"; -import { fetchModelCard } from "@/lib/hub/client"; import { modelFamilies } from "@/lib/hub/metadata"; import { listModelJobs } from "@/lib/jobs"; import { getModelByRepo, relatedModels } from "@/lib/library"; @@ -39,7 +38,7 @@ import { DownloadCard } from "./download-card"; import { FilesTab } from "./files-tab"; import { HubCheckButton } from "./hub-check"; import { JobsTab } from "./jobs-tab"; -import { ModelCard } from "./model-card"; +import { ModelCardSection, ModelCardSkeleton } from "./model-card"; import { DeleteModelButton } from "./delete-model-button"; import { TagEditor } from "./tag-editor"; import { UpdateBanner } from "./update-banner"; @@ -101,10 +100,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o const hubTags = model.hubTags ?? []; const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing"; - const [tags, related, card, worker, recentJobs, runs] = await Promise.all([ + // The model card (a Hub request) isn't awaited here: it streams in behind its Suspense boundary. + const [tags, related, worker, recentJobs, runs] = await Promise.all([ modelTagList(model.id), relatedModels(model.id, baseModels), - tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined), getWorkerStatus(), listModelJobs(model.id, 1), listBenchmarks({ modelId: model.id }, { limit: 5 }), // the sidebar shows 5 and links to all @@ -253,29 +252,9 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o {tab === "card" && (
- {card ? ( - <> - -
- - README.md @ {shortSha(model.pinnedSha)} - - -
- - ) : ( -

- {card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "} - - Open on Hugging Face - -

- )} + }> + +
)} {tab === "files" && ( diff --git a/src/lib/hub/availability.ts b/src/lib/hub/availability.ts index 8473f96..d799fbd 100644 --- a/src/lib/hub/availability.ts +++ b/src/lib/hub/availability.ts @@ -6,7 +6,7 @@ import { and, asc, eq, isNull, lt, or } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema"; import { computeUpdateDiff } from "@/lib/update-diff"; -import { getRepoInfo, HubError, listFiles, SHA_RE } from "./client"; +import { HubError, listFiles, resolveRevision, SHA_RE } from "./client"; type CheckedModel = Pick< typeof models.$inferSelect, @@ -45,7 +45,7 @@ const isGated = (err: unknown) => err instanceof HubError && (err.code === "gate /** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */ async function resolve(repoId: string, revision: string): Promise { try { - return (await getRepoInfo(repoId, revision)).sha; + return await resolveRevision(repoId, revision); } catch (err) { if (err instanceof HubError && err.code === "revision_not_found") return null; throw err; diff --git a/src/lib/hub/client.test.ts b/src/lib/hub/client.test.ts new file mode 100644 index 0000000..dc99bf3 --- /dev/null +++ b/src/lib/hub/client.test.ts @@ -0,0 +1,74 @@ +// Hub client: the per-commit tree cache and the SHA-only revision lookup, against a stubbed fetch. + +import assert from "node:assert/strict"; +import { after, beforeEach, describe, it } from "node:test"; +import { HubError, listFiles, resolveRevision } from "./client"; + +const realFetch = globalThis.fetch; +let requests: string[] = []; +let respond: (url: string) => Response; + +const json = (body: unknown, status = 200, headers: Record = {}) => + new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } }); + +beforeEach(() => { + requests = []; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input instanceof Request ? input.url : input); + requests.push(url); + return respond(url); + }) as typeof fetch; +}); + +after(() => { + globalThis.fetch = realFetch; +}); + +const SHA = "a".repeat(40); +const tree = [ + { type: "file", path: "b.gguf", size: 2, oid: "o2" }, + { type: "directory", path: "sub", size: 0, oid: "d" }, + { type: "file", path: "a.gguf", size: 1, oid: "o1", lfs: { oid: "f".repeat(64), size: 1 } }, +]; + +describe("listFiles", () => { + it("downloads a commit's tree once and hands out copies", async () => { + respond = () => json(tree); + const first = await listFiles("org/cached", SHA); + assert.deepEqual(first.map((f) => f.path), ["a.gguf", "b.gguf"]); + first.pop(); + const second = await listFiles("org/cached", SHA); + assert.equal(second.length, 2, "the cached list isn't changed by callers"); + assert.equal(requests.length, 1); + }); + + it("doesn't cache a branch name (it can move)", async () => { + respond = () => json(tree); + await listFiles("org/branch", "main"); + await listFiles("org/branch", "main"); + assert.equal(requests.length, 2); + }); +}); + +describe("resolveRevision", () => { + it("asks only for the SHA", async () => { + respond = () => json({ _id: "x", id: "org/repo", sha: SHA }); + assert.equal(await resolveRevision("org/repo", "main"), SHA); + assert.deepEqual(requests, ["https://huggingface.co/api/models/org/repo/revision/main?expand=sha"]); + }); + + it("falls back to the full model info when the answer has no SHA", async () => { + respond = (url) => (url.endsWith("?expand=sha") ? json({ id: "org/repo" }) : json({ id: "org/repo", sha: SHA })); + assert.equal(await resolveRevision("org/repo", "main"), SHA); + assert.deepEqual(requests, [ + "https://huggingface.co/api/models/org/repo/revision/main?expand=sha", + "https://huggingface.co/api/models/org/repo/revision/main", + ]); + }); + + it("reports a missing repo or revision like the full lookup", async () => { + respond = () => json({ error: "nope" }, 404, { "x-error-code": "RevisionNotFound" }); + await assert.rejects(resolveRevision("org/repo", "gone"), (err) => err instanceof HubError && err.code === "revision_not_found"); + assert.equal(requests.length, 1); + }); +}); diff --git a/src/lib/hub/client.ts b/src/lib/hub/client.ts index c000cbd..f585f40 100644 --- a/src/lib/hub/client.ts +++ b/src/lib/hub/client.ts @@ -160,9 +160,50 @@ type TreeEntry = { xetHash?: string; }; -/** All files (recursive) at a commit. Follows the Link header for pagination. */ +/** + * The commit a revision points to. Asks the Hub for just the SHA (`expand=sha`, as huggingface_hub's + * model_info does): the full model info can be large (file list, card data, the Spaces using it). + * Falls back to the full info if an answer comes without a SHA. + */ +export async function resolveRevision(repoId: string, revision: string): Promise { + assertRepoId(repoId); + const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}?expand=sha`); + if (res.ok) { + const j = (await res.json().catch(() => null)) as { sha?: unknown } | null; + if (typeof j?.sha === "string" && SHA_RE.test(j.sha)) return j.sha; + } else if (res.status !== 400) { + throw await toHubError(res, repoId, revision); + } + return (await getRepoInfo(repoId, revision)).sha; +} + +// A commit's file list never changes, so the last few are kept: adding a model right after looking +// it up doesn't download its tree again. Capped by the number of files held. +const treeCache = new Map(); +const TREE_CACHE_MAX_FILES = 50_000; +let treeCacheFiles = 0; + +function rememberTree(key: string, files: HubFile[]) { + if (files.length > TREE_CACHE_MAX_FILES) return; + treeCache.set(key, files); + treeCacheFiles += files.length; + for (const [k, v] of treeCache) { + if (treeCacheFiles <= TREE_CACHE_MAX_FILES) break; + treeCache.delete(k); + treeCacheFiles -= v.length; + } +} + +/** All files (recursive) at a commit, sorted by path. Follows the Link header for pagination. */ export async function listFiles(repoId: string, sha: string): Promise { assertRepoId(repoId); + const key = `${repoId}@${sha}`; + const cached = treeCache.get(key); + if (cached) { + treeCache.delete(key); // most recently used last + treeCache.set(key, cached); + return [...cached]; + } const files: HubFile[] = []; let url: string | null = `${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`; @@ -181,7 +222,9 @@ export async function listFiles(repoId: string, sha: string): Promise } url = nextLink(res.headers.get("link")); } - return files.sort((a, b) => a.path.localeCompare(b.path)); + files.sort((a, b) => a.path.localeCompare(b.path)); + if (SHA_RE.test(sha)) rememberTree(key, files); + return [...files]; } function nextLink(link: string | null): string | null { diff --git a/src/lib/models.ts b/src/lib/models.ts index 247ae88..371f5bd 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -51,7 +51,8 @@ export async function addModel(input: { }); if (existing) throw new ModelError("already_exists", `${repoId} is already in the library.`, 409); - const files = await listFiles(repoId, info.sha); + // Independent: the author's avatar loads while the file list does (usually cached from the lookup). + const [files, avatar] = await Promise.all([listFiles(repoId, info.sha), getAuthorAvatar(repoId.split("/")[0])]); const selectedFiles = files.filter((f) => isSelected(f.path, input.rule)); if (selectedFiles.length === 0) { throw new ModelError("empty_selection", "No files selected.", 400); @@ -81,7 +82,7 @@ export async function addModel(input: { localPath, includePatterns: input.rule.include, excludePatterns: input.rule.exclude, - ...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])), + ...metadataColumns(info.metadata, avatar), }), d.insert(modelRevisions).values({ modelId, sha: info.sha }), ...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),