diff --git a/CHANGELOG.md b/CHANGELOG.md index e899722..0b940d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ step 1 (Hugging Face downloader) is released as a minor version. ## [Unreleased] +### Added + +- **Reload a local model** (Files tab → **Reload**): reads the folder again, so files you added, + changed or removed and README.md edits show up right away. Every scan of the models folder (on its + schedule, or Rescan) now also brings local models' file lists up to date, not only their README. + ## [0.20.0] - 2026-11-08 ### Added diff --git a/src/app/(app)/[org]/[repo]/download-more.tsx b/src/app/(app)/[org]/[repo]/download-more.tsx index 1e84ff9..100f43f 100644 --- a/src/app/(app)/[org]/[repo]/download-more.tsx +++ b/src/app/(app)/[org]/[repo]/download-more.tsx @@ -13,6 +13,7 @@ import { useRecommended } from "@/hooks/use-recommended"; import { groupSplitFiles } from "@/lib/file-groups"; import { formatBytes, percent, shortSha } from "@/lib/format"; import { quantGroup } from "@/lib/selection"; +import { ReloadButton } from "./reload-button"; type Candidate = { path: string; size: number }; @@ -32,6 +33,7 @@ export function FilesHeader({ freeBytes, busy, hubMissing, + local = false, }: { modelId: string; sha: string; @@ -47,6 +49,8 @@ export function FilesHeader({ busy: boolean; /** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */ hubMissing: boolean; + /** A local model: "Reload" reads the folder again instead of "Download more". */ + local?: boolean; }) { const router = useRouter(); const [open, setOpen] = useState(false); @@ -128,7 +132,8 @@ export function FilesHeader({ {localCount} of {selectedCount} on disk · {formatBytes(localBytes)} - {candidates.length > 0 && !hubMissing && ( + {local && } + {!local && candidates.length > 0 && !hubMissing && ( + ); +} diff --git a/src/app/api/local-folders/scan/route.ts b/src/app/api/local-folders/scan/route.ts index 7645ddc..7816bb9 100644 --- a/src/app/api/local-folders/scan/route.ts +++ b/src/app/api/local-folders/scan/route.ts @@ -1,9 +1,16 @@ import { NextResponse } from "next/server"; import { withAuth } from "@/lib/api-auth"; -import { requestFolderScan } from "@/lib/local-folders"; +import { getScanState, requestFolderScan } from "@/lib/local-folders"; -/** Ask the worker to rescan the models folder for importable folders. */ +export const dynamic = "force-dynamic"; + +/** Ask the worker to rescan the models folder (importable folders, and local models' files). */ export const POST = withAuth(async () => { - await requestFolderScan(); - return new NextResponse(null, { status: 202 }); + const requestedAt = await requestFolderScan(); + return NextResponse.json({ requestedAt: requestedAt.getTime() }, { status: 202 }); +}); + +/** When the worker last finished a scan, so a client can wait for the one it asked for. */ +export const GET = withAuth(async () => { + return NextResponse.json(await getScanState()); }); diff --git a/src/lib/local-folders.ts b/src/lib/local-folders.ts index 5ea39b4..e9882c9 100644 --- a/src/lib/local-folders.ts +++ b/src/lib/local-folders.ts @@ -30,6 +30,14 @@ export async function localFolderExists(path: string): Promise { } /** 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")); +export async function requestFolderScan(): Promise { + const now = new Date(); + await db().update(workerState).set({ scanRequestedAt: now }).where(eq(workerState.id, "worker")); + return now; +} + +/** When the last scan finished (ms since epoch), or null if the worker never scanned. */ +export async function getScanState(): Promise<{ lastScanAt: number | null }> { + const row = await db().query.workerState.findFirst({ columns: { lastScanAt: true }, where: eq(workerState.id, "worker") }); + return { lastScanAt: row?.lastScanAt?.getTime() ?? null }; } diff --git a/src/worker/scan.test.ts b/src/worker/scan.test.ts index d37f041..876da61 100644 --- a/src/worker/scan.test.ts +++ b/src/worker/scan.test.ts @@ -89,4 +89,60 @@ describe("models folder scan", () => { writeFileSync(join(folder, "ReadMe.md"), "# Hello\n"); assert.equal(await scan.readReadme(folder), "# Hello\n"); }); + + it("diffs a local model's files against its folder", () => { + const stored = [ + { id: "1", path: "keep.gguf", size: 5, state: "present" }, + { id: "2", path: "grown.gguf", size: 5, state: "present" }, + { id: "3", path: "back.json", size: 2, state: "missing" }, + { id: "4", path: "gone.json", size: 2, state: "present" }, + ]; + const found = [ + { path: "keep.gguf", size: 5 }, + { path: "grown.gguf", size: 9 }, + { path: "back.json", size: 2 }, + { path: "new.md", size: 1 }, + ]; + assert.deepEqual(scan.localFileChanges(stored, found), { + insert: [{ path: "new.md", size: 1 }], + update: [ + { id: "2", size: 9 }, + { id: "3", size: 2 }, + ], + remove: ["4"], + }); + }); + + it("keeps a local model in step with its folder", async () => { + const { eq } = await import("drizzle-orm"); + const d = D.db(); + const folder = join(modelsDir, "mine", "local"); + put(join(folder, "model.gguf"), 4); + put(join(folder, "old.json"), 2); + await d.insert(S.models).values({ id: "local1", repoId: "mine/local", source: "local", trackedRevision: "", pinnedSha: "", localPath: "mine/local", status: "ready" }); + await d.insert(S.modelFiles).values([ + { modelId: "local1", path: "model.gguf", size: 4, selected: true, state: "present" }, + { modelId: "local1", path: "old.json", size: 2, selected: true, state: "present" }, + ]); + + rmSync(join(folder, "old.json")); + put(join(folder, "model.gguf"), 6); + put(join(folder, "extra", "new.bin"), 3); + writeFileSync(join(folder, "README.md"), "# Mine\n"); + await scan.scanModelsDir(modelsDir); + + const files = await d.select().from(S.modelFiles).where(eq(S.modelFiles.modelId, "local1")); + assert.deepEqual( + files.map((f) => [f.path, f.size, f.state, f.selected]).sort(), + [ + ["README.md", 7, "present", true], + ["extra/new.bin", 3, "present", true], + ["model.gguf", 6, "present", true], + ], + ); + const model = await d.query.models.findFirst({ where: eq(S.models.id, "local1") }); + assert.equal(model?.localReadme, "# Mine\n"); + assert.equal(model?.status, "ready"); + assert.equal((await stored())["mine/local"], undefined, "a model's folder is no import candidate"); + }); }); diff --git a/src/worker/scan.ts b/src/worker/scan.ts index 1e6d7e5..17427f5 100644 --- a/src/worker/scan.ts +++ b/src/worker/scan.ts @@ -1,13 +1,16 @@ -// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported. +// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported, and keeps +// local models (folders without a Hub repo) in step with their folder: files and README. // Only the `/` layout is recognized (what Kaname and `hf download --local-dir` write). // Read-only: nothing on disk is changed. import { readdir, readFile, stat } from "node:fs/promises"; import { join, relative, sep } from "node:path"; -import { eq, inArray, sql } from "drizzle-orm"; +import { and, eq, inArray, sql } from "drizzle-orm"; import { db } from "@/lib/db/client"; -import { localFolders, models } from "@/lib/db/schema"; +import { ACTIVE_JOB_STATES, jobFiles, jobs, localFolders, modelFiles, models } from "@/lib/db/schema"; import { HF_CACHE_DIR } from "./hf-layout"; +import { log } from "./log"; +import { settleModelStatus } from "./model-status"; /** Longer READMEs are cut off here (it's stored in the database). */ const MAX_README_BYTES = 512 * 1024; @@ -86,6 +89,69 @@ export async function readReadme(folder: string): Promise { return buf.length > MAX_README_BYTES ? text.slice(0, text.lastIndexOf("\n") + 1) : text; } +type StoredFile = { id: string; path: string; size: number; state: string }; + +/** + * What to write so a local model's files match its folder: new files, files whose size changed or + * that were missing and are back (`update`), and the ids of files that are gone. + */ +export function localFileChanges(stored: StoredFile[], found: { path: string; size: number }[]) { + const before = new Map(stored.map((s) => [s.path, s])); + const insert: { path: string; size: number }[] = []; + const update: { id: string; size: number }[] = []; + for (const f of found) { + const s = before.get(f.path); + if (!s) insert.push(f); + else if (s.size !== f.size || (s.state !== "present" && s.state !== "verified")) update.push({ id: s.id, size: f.size }); + } + const seen = new Set(found.map((f) => f.path)); + const remove = stored.filter((s) => !seen.has(s.path)).map((s) => s.id); + return { insert, update, remove }; +} + +/** + * Bring a local model's file list and README in line with its folder. Skipped while a job runs for + * it, and for a folder that is gone or lists more files than are kept (nothing is dropped then). + */ +async function syncLocalModel(modelsDir: string, m: { id: string; p: string; readme: string | null }): Promise { + const d = db(); + const folder = join(modelsDir, m.p); + const readme = await readReadme(folder); + if (readme !== m.readme) await d.update(models).set({ localReadme: readme }).where(eq(models.id, m.id)); + + const open = await d.query.jobs.findFirst({ + columns: { id: true }, + where: and(eq(jobs.modelId, m.id), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES])), + }); + if (open) return; + const files: { path: string; size: number }[] = []; + const totals = { count: 0, bytes: 0 }; + await walk(folder, folder, files, totals); + if (totals.count === 0 || totals.count > files.length) return; + + const stored = await d + .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size, state: modelFiles.state }) + .from(modelFiles) + .where(eq(modelFiles.modelId, m.id)); + const { insert, update, remove } = localFileChanges(stored, files); + if (insert.length + update.length + remove.length === 0) return; + const now = new Date(); + const writes = [ + ...(remove.length + ? [d.delete(jobFiles).where(inArray(jobFiles.modelFileId, remove)), d.delete(modelFiles).where(inArray(modelFiles.id, remove))] + : []), + ...update.map((u) => d.update(modelFiles).set({ size: u.size, state: "present", checkedAt: now }).where(eq(modelFiles.id, u.id))), + // In chunks: SQLite caps the number of values in one statement. + ...Array.from({ length: Math.ceil(insert.length / 500) }, (_, i) => + d.insert(modelFiles).values( + insert.slice(i * 500, (i + 1) * 500).map((f) => ({ modelId: m.id, path: f.path, size: f.size, selected: true, state: "present" as const, checkedAt: now })), + ), + ), + ]; + await d.batch(writes as [(typeof writes)[number], ...typeof writes]); + await settleModelStatus(m.id); +} + /** A stored folder, its file list as the JSON text it is stored as (compared, never parsed). */ export type StoredFolder = { path: string; filesJson: string; fileCount: number; totalBytes: number; commit: string | null; readme: string | null }; @@ -109,15 +175,15 @@ export function folderChanges(stored: StoredFolder[], found: FoundFolder[]) { } /** - * Scan MODELS_DIR and update the `local_folders` table to the folders no model uses. Also refreshes - * the README of local models (their model card). + * Scan MODELS_DIR and update the `local_folders` table to the folders no model uses. Also brings + * local models in line with their folders (files and README). */ export async function scanModelsDir(modelsDir: string): Promise { const inLibrary = await db().select({ id: models.id, p: models.localPath, source: models.source, readme: models.localReadme }).from(models); const used = new Set(inLibrary.map((m) => m.p)); for (const m of inLibrary.filter((x) => x.source === "local")) { - const readme = await readReadme(join(modelsDir, m.p)); - if (readme !== m.readme) await db().update(models).set({ localReadme: readme }).where(eq(models.id, m.id)); + // One model's problem doesn't stop the scan of the others. + await syncLocalModel(modelsDir, m).catch((err) => log.error(`syncing local model ${m.p} failed`, err)); } const found: FoundFolder[] = []; const now = new Date();