Milestone (b): repo lookup and file selection

- Hub API client: resolve revision to SHA, paginated recursive file tree,
  gated-access probe, readable error mapping
- Add-model page with quant quick-select, fnmatch-compatible include/exclude
  globs, selection summary and free-space hint
- Models stored pinned to the reviewed SHA with full file list and selection rule
- Library list, model detail page, remove (never-downloaded models only)
- Worker reports MODELS_DIR free space; unit tests for selection logic

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 15:39:45 +02:00
1 parent 891e496157
commit 8f7ac60ccf
35 files changed
+2567 -19

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import "server-only";
import { NextResponse } from "next/server";
import { z } from "zod";
import { HubError } from "@/lib/hub/client";
export type ApiError = { error: { code: string; message: string } };
export function apiError(status: number, code: string, message: string) {
return NextResponse.json<ApiError>({ error: { code, message } }, { status });
}
const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
invalid_repo_id: 400,
repo_not_found: 404,
revision_not_found: 404,
gated_no_token: 403,
gated_no_access: 403,
rate_limited: 429,
network: 502,
};
/** Turn known errors into JSON responses; rethrow anything unexpected. */
export function handleApiError(err: unknown) {
if (err instanceof HubError) return apiError(HUB_STATUS[err.code] ?? 502, err.code, err.message);
if (err instanceof z.ZodError) {
return apiError(400, "invalid_request", err.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));
}
throw err;
}
+3
View File
@@ -241,6 +241,9 @@ export const workerState = sqliteTable("worker_state", {
id: text("id").primaryKey(), // "worker"
pid: integer("pid"),
hfVersion: text("hf_version"),
/** Free/total bytes on the filesystem holding MODELS_DIR (the web app has no access to it). */
modelsDirFreeBytes: integer("models_dir_free_bytes"),
modelsDirTotalBytes: integer("models_dir_total_bytes"),
startedAt: ts("started_at").notNull(),
heartbeatAt: ts("heartbeat_at").notNull(),
});
+23
View File
@@ -0,0 +1,23 @@
const UNITS = ["B", "KB", "MB", "GB", "TB", "PB"];
/** Decimal units (like the Hub UI): 4_793_624_384 -> "4.79 GB". */
export function formatBytes(bytes: number | null | undefined): string {
if (bytes == null || !Number.isFinite(bytes)) return "–";
if (bytes < 1000) return `${bytes} B`;
let v = bytes;
let i = 0;
while (v >= 1000 && i < UNITS.length - 1) {
v /= 1000;
i++;
}
return `${v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)} ${UNITS[i]}`;
}
export function shortSha(sha: string | null | undefined): string {
return sha ? sha.slice(0, 7) : "–";
}
export function formatDate(d: Date | string | number | null | undefined): string {
if (d == null) return "–";
return new Date(d).toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short" });
}
+202
View File
@@ -0,0 +1,202 @@
// Minimal Hugging Face Hub API client (metadata only; downloads go through the `hf` CLI).
// Server-side only: it reads HF_TOKEN from the environment. Never import from client components.
import { coreEnv } from "@/lib/env";
const HUB = "https://huggingface.co";
const TIMEOUT_MS = 20_000;
const USER_AGENT = "kaname-model-manager";
export const REPO_ID_RE = /^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/;
export const SHA_RE = /^[0-9a-f]{40}$/;
export type HubErrorCode =
| "invalid_repo_id"
| "invalid_token"
| "repo_not_found" // or private without access
| "revision_not_found"
| "gated_no_token"
| "gated_no_access"
| "rate_limited"
| "network"
| "unknown";
export class HubError extends Error {
constructor(
public code: HubErrorCode,
message: string,
public status?: number,
) {
super(message);
this.name = "HubError";
}
}
export type HubFile = {
path: string;
size: number;
/** Git blob SHA-1. */
blobOid: string;
/** SHA-256 of the content, for LFS/Xet files. */
lfsSha256: string | null;
xetHash: string | null;
};
export type RepoInfo = {
repoId: string;
sha: string;
gated: false | "auto" | "manual";
private: boolean;
lastModified: string | null;
};
function headers(): HeadersInit {
const h: Record<string, string> = { "User-Agent": USER_AGENT };
const token = coreEnv().HF_TOKEN;
if (token) h.Authorization = `Bearer ${token}`;
return h;
}
async function hubFetch(url: string, init: RequestInit = {}): Promise<Response> {
try {
return await fetch(url, {
...init,
headers: { ...headers(), ...init.headers },
cache: "no-store",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
throw new HubError("network", `Could not reach huggingface.co (${reason}).`);
}
}
/** Is the configured token valid? Only called after a 401, to tell a bad token from a missing repo. */
async function tokenIsValid(): Promise<boolean> {
const res = await hubFetch(`${HUB}/api/whoami-v2`);
return res.ok;
}
async function toHubError(res: Response, repoId: string, revision?: string): Promise<HubError> {
const code = res.headers.get("x-error-code");
const hasToken = Boolean(coreEnv().HF_TOKEN);
if (code === "RevisionNotFound") {
return new HubError("revision_not_found", `Revision "${revision}" not found in ${repoId}.`, res.status);
}
if (code === "GatedRepo") {
return hasToken
? new HubError(
"gated_no_access",
`${repoId} is gated and this token's account has not been granted access. Request access at ${HUB}/${repoId}.`,
res.status,
)
: new HubError(
"gated_no_token",
`${repoId} is gated. Set HF_TOKEN for an account that has accepted the terms at ${HUB}/${repoId}.`,
res.status,
);
}
if (res.status === 429) {
return new HubError("rate_limited", "Hugging Face rate limit hit. Try again in a minute.", res.status);
}
// The Hub answers 401 (without an error code) for missing repos when unauthenticated,
// and 401 for any request when the token is invalid.
if (res.status === 401 || res.status === 404 || code === "RepoNotFound") {
if (res.status === 401 && hasToken && !(await tokenIsValid())) {
return new HubError("invalid_token", "HF_TOKEN is invalid or expired.", res.status);
}
return new HubError(
"repo_not_found",
hasToken
? `Repository ${repoId} not found, or this token has no access to it.`
: `Repository ${repoId} not found. If it is private, set HF_TOKEN.`,
res.status,
);
}
const msg = res.headers.get("x-error-message") ?? res.statusText;
return new HubError("unknown", `Hugging Face API error ${res.status}: ${msg}`, res.status);
}
function assertRepoId(repoId: string) {
if (!REPO_ID_RE.test(repoId) || repoId.split("/").some((p) => p === "." || p === "..")) {
throw new HubError("invalid_repo_id", `"${repoId}" is not a valid repo ID (expected "org/name").`);
}
}
const enc = (s: string) => encodeURIComponent(s);
const repoPath = (repoId: string) => repoId.split("/").map(enc).join("/");
/** Resolve a branch, tag or commit to its full commit SHA, plus basic repo info. */
export async function getRepoInfo(repoId: string, revision: string): Promise<RepoInfo> {
assertRepoId(repoId);
const res = await hubFetch(`${HUB}/api/models/${repoPath(repoId)}/revision/${enc(revision)}`);
if (!res.ok) throw await toHubError(res, repoId, revision);
const j = (await res.json()) as {
id: string;
sha: string;
gated?: false | "auto" | "manual";
private?: boolean;
lastModified?: string;
};
return {
repoId: j.id ?? repoId,
sha: j.sha,
gated: j.gated ?? false,
private: j.private ?? false,
lastModified: j.lastModified ?? null,
};
}
type TreeEntry = {
type: "file" | "directory";
path: string;
size: number;
oid: string;
lfs?: { oid: string; size: number };
xetHash?: string;
};
/** All files (recursive) at a commit. Follows the Link header for pagination. */
export async function listFiles(repoId: string, sha: string): Promise<HubFile[]> {
assertRepoId(repoId);
const files: HubFile[] = [];
let url: string | null =
`${HUB}/api/models/${repoPath(repoId)}/tree/${enc(sha)}?recursive=true&expand=false&limit=1000`;
while (url) {
const res = await hubFetch(url);
if (!res.ok) throw await toHubError(res, repoId, sha);
for (const e of (await res.json()) as TreeEntry[]) {
if (e.type !== "file") continue;
files.push({
path: e.path,
size: e.size,
blobOid: e.oid,
lfsSha256: e.lfs?.oid ?? null,
xetHash: e.xetHash ?? null,
});
}
url = nextLink(res.headers.get("link"));
}
return files.sort((a, b) => a.path.localeCompare(b.path));
}
function nextLink(link: string | null): string | null {
if (!link) return null;
for (const part of link.split(",")) {
const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/);
if (m) return m[1];
}
return null;
}
/**
* For gated repos the file list is public, but downloads need accepted terms.
* Probe one file with a HEAD request (no body is downloaded) to find out early.
*/
export async function checkFileAccess(repoId: string, sha: string, path: string): Promise<void> {
const url = `${HUB}/${repoPath(repoId)}/resolve/${enc(sha)}/${path.split("/").map(enc).join("/")}`;
const res = await hubFetch(url, { method: "HEAD", redirect: "manual" });
if (res.ok || (res.status >= 300 && res.status < 400)) return;
throw await toHubError(res, repoId, sha);
}
+57
View File
@@ -0,0 +1,57 @@
import "server-only";
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
import { checkFileAccess, getRepoInfo, type HubFile, listFiles, type RepoInfo } from "./client";
export type LookupResult = {
repoId: string;
revision: string;
sha: string;
gated: RepoInfo["gated"];
lastModified: string | null;
files: HubFile[];
/** Set when this repo is already in the library. */
existingModelId: string | null;
};
/**
* Accept "org/name", or a pasted Hub URL like https://huggingface.co/org/name/tree/main.
* Returns the repo id and, if the URL contained one, the revision.
*/
export function normalizeRepoInput(input: string): { repoId: string; revision?: string } {
let s = input.trim();
const url = s.match(/^https?:\/\/(?:www\.)?huggingface\.co\/(.+)$/i);
if (url) s = url[1];
s = s.replace(/[?#].*$/, "").replace(/\/+$/, "");
const parts = s.split("/");
const repoId = parts.slice(0, 2).join("/");
const revision = parts[2] === "tree" || parts[2] === "blob" ? parts[3] : undefined;
return { repoId, revision };
}
/** Repo metadata + file list at the resolved commit, with an early access check for gated repos. */
export async function lookupRepo(repoId: string, revision: string): Promise<LookupResult> {
const info = await getRepoInfo(repoId, revision);
const files = await listFiles(info.repoId, info.sha);
if (info.gated && files.length > 0) {
const smallest = files.reduce((a, b) => (b.size < a.size ? b : a));
await checkFileAccess(info.repoId, info.sha, smallest.path);
}
const existing = await db().query.models.findFirst({
columns: { id: true },
where: and(eq(models.repoType, "model"), eq(models.repoId, info.repoId)),
});
return {
repoId: info.repoId,
revision,
sha: info.sha,
gated: info.gated,
lastModified: info.lastModified,
files,
existingModelId: existing?.id ?? null,
};
}
+58
View File
@@ -0,0 +1,58 @@
import "server-only";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { modelFiles, models } from "@/lib/db/schema";
import { quantGroup } from "@/lib/selection";
export type LibraryRow = Awaited<ReturnType<typeof listLibrary>>[number];
/** Models with their selected-file totals and a short "which quant" label. */
export async function listLibrary() {
const d = db();
const rows = await d
.select({
id: models.id,
repoId: models.repoId,
trackedRevision: models.trackedRevision,
pinnedSha: models.pinnedSha,
remoteSha: models.remoteSha,
status: models.status,
createdAt: models.createdAt,
downloadedAt: models.downloadedAt,
fileCount: sql<number>`count(${modelFiles.id})`,
totalBytes: sql<number>`coalesce(sum(${modelFiles.size}), 0)`,
})
.from(models)
.leftJoin(modelFiles, and(eq(modelFiles.modelId, models.id), eq(modelFiles.selected, true)))
.groupBy(models.id)
.orderBy(desc(models.createdAt));
const selected = await d
.select({ modelId: modelFiles.modelId, path: modelFiles.path })
.from(modelFiles)
.where(eq(modelFiles.selected, true));
const quants = new Map<string, Set<string>>();
for (const f of selected) {
const g = quantGroup(f.path);
if (!g) continue;
if (!quants.has(f.modelId)) quants.set(f.modelId, new Set());
quants.get(f.modelId)!.add(g);
}
return rows.map((r) => ({
...r,
quants: [...(quants.get(r.id) ?? [])].sort(),
}));
}
export async function getModel(id: string) {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) return null;
const files = await d
.select()
.from(modelFiles)
.where(eq(modelFiles.modelId, id))
.orderBy(asc(modelFiles.path));
return { model, files };
}
+104
View File
@@ -0,0 +1,104 @@
import "server-only";
import { and, eq, sql } from "drizzle-orm";
import { ulid } from "ulid";
import { db } from "@/lib/db/client";
import { jobs, modelFiles, modelRevisions, models } from "@/lib/db/schema";
import { checkFileAccess, getRepoInfo, listFiles } from "@/lib/hub/client";
import { isSelected, type SelectionRule } from "@/lib/selection";
export class ModelError extends Error {
constructor(
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable",
message: string,
public status: number,
) {
super(message);
}
}
const INSERT_CHUNK = 500;
/**
* Add a model pinned to `sha`. The file list is re-fetched from the Hub at that commit
* (the client's copy isn't trusted) and the selection rule is applied server-side.
*/
export async function addModel(input: {
repoId: string;
revision: string;
sha: string;
rule: SelectionRule;
}): Promise<{ id: string }> {
const info = await getRepoInfo(input.repoId, input.sha);
const repoId = info.repoId;
const existing = await db().query.models.findFirst({
columns: { id: true },
where: and(eq(models.repoType, "model"), eq(models.repoId, repoId)),
});
if (existing) throw new ModelError("already_exists", `${repoId} is already in the library.`, 409);
const files = await listFiles(repoId, info.sha);
const selectedFiles = files.filter((f) => isSelected(f.path, input.rule));
if (selectedFiles.length === 0) {
throw new ModelError("empty_selection", "No files selected.", 400);
}
if (info.gated) {
const smallest = selectedFiles.reduce((a, b) => (b.size < a.size ? b : a));
await checkFileAccess(repoId, info.sha, smallest.path);
}
const d = db();
const modelId = ulid();
const fileRows = files.map((f) => ({
modelId,
path: f.path,
size: f.size,
blobOid: f.blobOid,
lfsSha256: f.lfsSha256,
selected: isSelected(f.path, input.rule),
}));
// One atomic batch: model, its first pinned revision and the full file list.
await d.batch([
d.insert(models).values({
id: modelId,
repoId,
trackedRevision: input.revision,
pinnedSha: info.sha,
localPath: repoId,
includePatterns: input.rule.include,
excludePatterns: input.rule.exclude,
}),
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)),
]);
return { id: modelId };
}
/** Remove a model from the library. Only allowed before anything was downloaded (for now). */
export async function removeModel(id: string): Promise<void> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
const [{ n }] = await d
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(eq(jobs.modelId, id));
if (model.status !== "pending" || n > 0) {
throw new ModelError(
"not_removable",
"Only models that were never downloaded can be removed yet. Deleting downloaded models comes in a later milestone.",
409,
);
}
await d.batch([
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
d.delete(models).where(eq(models.id, id)),
]);
}
function chunk<T>(items: T[], size: number): T[][] {
const out: T[][] = [];
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
return out;
}
+86
View File
@@ -0,0 +1,86 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { escapeGlob, isSelected, matchesAny, parsePatternList, quantGroup } from "./selection";
describe("matchesAny (Python fnmatch semantics)", () => {
it("* matches across folders", () => {
assert.ok(matchesAny("Q4_K_M/model-00001-of-00003.gguf", ["*.gguf"]));
assert.ok(matchesAny("a/b/c.json", ["*c.json"]));
});
it("is anchored and case-sensitive", () => {
assert.ok(!matchesAny("model.gguf.bak", ["*.gguf"]));
assert.ok(!matchesAny("Model-Q4_K_M.GGUF", ["*.gguf"]));
});
it("? and character classes", () => {
assert.ok(matchesAny("Q4_0.gguf", ["Q?_0.gguf"]));
assert.ok(matchesAny("Q5_0.gguf", ["Q[45]_0.gguf"]));
assert.ok(!matchesAny("Q6_0.gguf", ["Q[45]_0.gguf"]));
assert.ok(matchesAny("Q6_0.gguf", ["Q[!45]_0.gguf"]));
});
it("trailing slash selects a folder", () => {
assert.ok(matchesAny("Q4_K_M/x-00001-of-00002.gguf", ["Q4_K_M/"]));
assert.ok(!matchesAny("Q4_K_S/x-00001-of-00002.gguf", ["Q4_K_M/"]));
});
it("unclosed [ is literal", () => {
assert.ok(matchesAny("a[b", ["a[b"]));
});
it("regex metacharacters in paths are literal", () => {
assert.ok(matchesAny("model (v2)+.gguf", ["model (v2)+.gguf"]));
assert.ok(!matchesAny("modelXgguf", ["model.gguf"]));
});
});
describe("escapeGlob", () => {
it("matches exactly the literal path", () => {
const weird = "dir/file[1]*?.gguf";
assert.ok(matchesAny(weird, [escapeGlob(weird)]));
assert.ok(!matchesAny("dir/file1xx.gguf", [escapeGlob(weird)]));
assert.equal(escapeGlob("plain/path.gguf"), "plain/path.gguf");
});
});
describe("isSelected", () => {
it("include minus exclude, empty include selects nothing", () => {
const rule = { include: ["*Q4_K_M*", "*.json"], exclude: ["*mmproj*"] };
assert.ok(isSelected("Qwen3-8B-Q4_K_M.gguf", rule));
assert.ok(isSelected("config.json", rule));
assert.ok(!isSelected("mmproj-Q4_K_M.gguf", rule));
assert.ok(!isSelected("README.md", rule));
assert.ok(!isSelected("anything", { include: [], exclude: [] }));
});
});
describe("parsePatternList", () => {
it("splits on commas and newlines, trims", () => {
assert.deepEqual(parsePatternList(" *.gguf, *.json\nREADME.md ,, "), ["*.gguf", "*.json", "README.md"]);
});
});
describe("quantGroup", () => {
it("flat GGUF repos", () => {
assert.equal(quantGroup("Qwen3-8B-Q4_K_M.gguf"), "Q4_K_M");
assert.equal(quantGroup("Qwen3-8B-UD-Q4_K_XL.gguf"), "UD-Q4_K_XL");
assert.equal(quantGroup("Qwen3-8B-UD-IQ1_S.gguf"), "UD-IQ1_S");
assert.equal(quantGroup("Qwen3-8B-IQ4_NL.gguf"), "IQ4_NL");
assert.equal(quantGroup("Qwen3-8B-BF16.gguf"), "BF16");
assert.equal(quantGroup("Qwen_Qwen3-8B-bf16.gguf"), "bf16");
assert.equal(quantGroup("Qwen3-8B-Q8_0.gguf"), "Q8_0");
});
it("split files group together", () => {
assert.equal(quantGroup("Model-Q4_K_M-00001-of-00002.gguf"), "Q4_K_M");
assert.equal(quantGroup("Model-Q4_K_M-00002-of-00002.gguf"), "Q4_K_M");
});
it("folder-per-quant repos use the folder", () => {
assert.equal(quantGroup("Q4_K_M/Qwen3-235B-A22B-Q4_K_M-00001-of-00003.gguf"), "Q4_K_M");
assert.equal(quantGroup("UD-Q2_K_XL/x-00001-of-00002.gguf"), "UD-Q2_K_XL");
});
it("mmproj is its own group", () => {
assert.equal(quantGroup("mmproj-F16.gguf"), "mmproj-F16");
assert.equal(quantGroup("mmproj-model-f16.gguf"), "mmproj-f16");
});
it("non-GGUF files have no group", () => {
assert.equal(quantGroup("README.md"), null);
assert.equal(quantGroup("Qwen_Qwen3-8B.imatrix"), null);
assert.equal(quantGroup("docs/notes.txt"), null);
});
});
+99
View File
@@ -0,0 +1,99 @@
// File selection rules, shared by the UI, the API and the worker.
//
// Matching follows huggingface_hub's `filter_repo_objects` (what `hf download --include/--exclude`
// uses): Python `fnmatch` against the full repo path, where `*` also matches "/", and a pattern
// ending in "/" matches everything below that folder.
const regexCache = new Map<string, RegExp>();
/** Translate a Python fnmatch pattern to a RegExp (same semantics as fnmatch.translate). */
export function fnmatchToRegExp(pattern: string): RegExp {
const cached = regexCache.get(pattern);
if (cached) return cached;
let re = "";
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
if (c === "*") {
re += ".*";
} else if (c === "?") {
re += ".";
} else if (c === "[") {
let j = i + 1;
if (pattern[j] === "!") j++;
if (pattern[j] === "]") j++;
while (j < pattern.length && pattern[j] !== "]") j++;
if (j >= pattern.length) {
re += "\\[";
} else {
let body = pattern.slice(i + 1, j).replace(/\\/g, "\\\\");
if (body.startsWith("!")) body = "^" + body.slice(1);
else if (body.startsWith("^")) body = "\\" + body;
re += `[${body}]`;
i = j;
}
} else {
re += c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
}
}
const compiled = new RegExp(`^(?:${re})$`, "s");
regexCache.set(pattern, compiled);
return compiled;
}
function normalizePattern(p: string): string {
return p.endsWith("/") ? p + "*" : p;
}
export function matchesAny(path: string, patterns: readonly string[]): boolean {
return patterns.some((p) => fnmatchToRegExp(normalizePattern(p)).test(path));
}
/** Escape a literal path so fnmatch matches exactly that path (glob chars become [x] classes). */
export function escapeGlob(path: string): string {
return path.replace(/[*?[]/g, (c) => `[${c}]`);
}
export type SelectionRule = { include: string[]; exclude: string[] };
/**
* A file is selected if it matches an include pattern and no exclude pattern.
* Unlike the CLI, an empty include list selects nothing (selection is always explicit).
*/
export function isSelected(path: string, rule: SelectionRule): boolean {
return matchesAny(path, rule.include) && !matchesAny(path, rule.exclude);
}
/** Parse a user-entered pattern field: comma or newline separated. */
export function parsePatternList(input: string): string[] {
return input
.split(/[,\n]/)
.map((s) => s.trim())
.filter(Boolean);
}
// ---------------------------------------------------------------------------
// Quant grouping for GGUF repos
// ---------------------------------------------------------------------------
const QUANT_SUFFIX =
/[-_.]((?:UD-)?(?:I?Q\d(?:_[A-Z0-9]+)*|BF16|F16|F32|MXFP4(?:_MOE)?|TQ\d_\d))$/i;
const SPLIT_SUFFIX = /-\d{5}-of-\d{5}$/;
/**
* Group key for quick-selecting one quant: the top-level folder for folder-per-quant repos
* ("Q4_K_M/...-00001-of-00003.gguf"), otherwise the quant tag parsed from a .gguf file name
* ("Qwen3-8B-UD-Q4_K_XL.gguf" -> "UD-Q4_K_XL"). Returns null for files that aren't quants.
*/
export function quantGroup(path: string): string | null {
const slash = path.indexOf("/");
if (slash > 0) {
const dir = path.slice(0, slash);
return path.toLowerCase().endsWith(".gguf") ? dir : null;
}
if (!path.toLowerCase().endsWith(".gguf")) return null;
const base = path.slice(0, -".gguf".length).replace(SPLIT_SUFFIX, "");
const m = base.match(QUANT_SUFFIX);
const tag = m ? m[1] : base;
return base.toLowerCase().startsWith("mmproj") ? `mmproj-${tag}` : tag;
}
+14 -2
View File
@@ -10,19 +10,31 @@ export type WorkerStatus = {
online: boolean;
heartbeatAt: string | null;
hfVersion: string | null;
modelsDirFreeBytes: number | null;
modelsDirTotalBytes: number | null;
};
const OFFLINE: WorkerStatus = {
online: false,
heartbeatAt: null,
hfVersion: null,
modelsDirFreeBytes: null,
modelsDirTotalBytes: null,
};
export async function getWorkerStatus(): Promise<WorkerStatus> {
try {
const row = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") });
if (!row) return { online: false, heartbeatAt: null, hfVersion: null };
if (!row) return OFFLINE;
return {
online: Date.now() - row.heartbeatAt.getTime() < OFFLINE_AFTER_MS,
heartbeatAt: row.heartbeatAt.toISOString(),
hfVersion: row.hfVersion,
modelsDirFreeBytes: row.modelsDirFreeBytes,
modelsDirTotalBytes: row.modelsDirTotalBytes,
};
} catch {
// Table missing (worker never ran migrations yet) or DB unavailable.
return { online: false, heartbeatAt: null, hfVersion: null };
return OFFLINE;
}
}