Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29e6893a17 | ||
|
|
80d71a1bc9 |
No files matched your search
@@ -6,6 +6,14 @@ step 1 (Hugging Face downloader) is released as a minor version.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.21.0] - 2026-11-08
|
||||||
|
|
||||||
|
### 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
|
## [0.20.0] - 2026-11-08
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "kaname",
|
"name": "kaname",
|
||||||
"version": "0.20.0",
|
"version": "0.21.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "kaname",
|
"name": "kaname",
|
||||||
"version": "0.20.0",
|
"version": "0.21.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.8.0",
|
"@base-ui/react": "^1.8.0",
|
||||||
"@libsql/client": "^0.18.0",
|
"@libsql/client": "^0.18.0",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "kaname",
|
"name": "kaname",
|
||||||
"version": "0.20.0",
|
"version": "0.21.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { useRecommended } from "@/hooks/use-recommended";
|
|||||||
import { groupSplitFiles } from "@/lib/file-groups";
|
import { groupSplitFiles } from "@/lib/file-groups";
|
||||||
import { formatBytes, percent, shortSha } from "@/lib/format";
|
import { formatBytes, percent, shortSha } from "@/lib/format";
|
||||||
import { quantGroup } from "@/lib/selection";
|
import { quantGroup } from "@/lib/selection";
|
||||||
|
import { ReloadButton } from "./reload-button";
|
||||||
|
|
||||||
type Candidate = { path: string; size: number };
|
type Candidate = { path: string; size: number };
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ export function FilesHeader({
|
|||||||
freeBytes,
|
freeBytes,
|
||||||
busy,
|
busy,
|
||||||
hubMissing,
|
hubMissing,
|
||||||
|
local = false,
|
||||||
}: {
|
}: {
|
||||||
modelId: string;
|
modelId: string;
|
||||||
sha: string;
|
sha: string;
|
||||||
@@ -47,6 +49,8 @@ export function FilesHeader({
|
|||||||
busy: boolean;
|
busy: boolean;
|
||||||
/** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */
|
/** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */
|
||||||
hubMissing: boolean;
|
hubMissing: boolean;
|
||||||
|
/** A local model: "Reload" reads the folder again instead of "Download more". */
|
||||||
|
local?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
@@ -128,7 +132,8 @@ export function FilesHeader({
|
|||||||
<span className="text-muted-foreground">
|
<span className="text-muted-foreground">
|
||||||
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
|
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
|
||||||
</span>
|
</span>
|
||||||
{candidates.length > 0 && !hubMissing && (
|
{local && <ReloadButton />}
|
||||||
|
{!local && candidates.length > 0 && !hubMissing && (
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant={open ? "outline" : "default"}
|
variant={open ? "outline" : "default"}
|
||||||
|
|||||||
@@ -165,6 +165,7 @@ export function FilesTab({
|
|||||||
freeBytes={freeBytes}
|
freeBytes={freeBytes}
|
||||||
busy={busy}
|
busy={busy}
|
||||||
hubMissing={hubMissing}
|
hubMissing={hubMissing}
|
||||||
|
local={local}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ul className="divide-y">
|
<ul className="divide-y">
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export function LocalModelCardSection({ markdown, localPath }: { markdown: strin
|
|||||||
return (
|
return (
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
This folder has no README.md. Add one to <code className="font-mono">{localPath}</code> and it shows up here after the
|
This folder has no README.md. Add one to <code className="font-mono">{localPath}</code> and it shows up here after the
|
||||||
next scan of the models folder.
|
next scan of the models folder, or right away with Reload on the Files tab.
|
||||||
</p>
|
</p>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
/** The worker picks a scan request up with its next heartbeat (every 5 s); a big models folder takes longer. */
|
||||||
|
const TIMEOUT_MS = 90_000;
|
||||||
|
const POLL_MS = 1_500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Local models: read the folder again (files and README). Asks the worker for a scan of the models
|
||||||
|
* folder and waits until it has finished, then reloads the page.
|
||||||
|
*/
|
||||||
|
export function ReloadButton() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
async function reload() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/local-folders/scan", { method: "POST" });
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok || typeof body.requestedAt !== "number") {
|
||||||
|
toast.error(body.error?.message ?? `Could not start a scan (${res.status})`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const deadline = Date.now() + TIMEOUT_MS;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
await new Promise((r) => setTimeout(r, POLL_MS));
|
||||||
|
const state = await fetch("/api/local-folders/scan", { cache: "no-store" })
|
||||||
|
.then((r) => (r.ok ? r.json() : null))
|
||||||
|
.catch(() => null);
|
||||||
|
if (state?.lastScanAt != null && state.lastScanAt >= body.requestedAt) {
|
||||||
|
router.refresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toast.error("The worker hasn't scanned the folder yet. Is it running?");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button size="sm" variant="outline" onClick={() => void reload()} disabled={busy} title="Read the folder again: files and README.md">
|
||||||
|
<RefreshCwIcon className={cn(busy && "animate-spin")} />
|
||||||
|
{busy ? "Reloading…" : "Reload"}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withAuth } from "@/lib/api-auth";
|
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 () => {
|
export const POST = withAuth(async () => {
|
||||||
await requestFolderScan();
|
const requestedAt = await requestFolderScan();
|
||||||
return new NextResponse(null, { status: 202 });
|
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());
|
||||||
});
|
});
|
||||||
@@ -30,6 +30,14 @@ export async function localFolderExists(path: string): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Ask the worker to scan MODELS_DIR now (it picks this up with its next heartbeat). */
|
/** Ask the worker to scan MODELS_DIR now (it picks this up with its next heartbeat). */
|
||||||
export async function requestFolderScan(): Promise<void> {
|
export async function requestFolderScan(): Promise<Date> {
|
||||||
await db().update(workerState).set({ scanRequestedAt: new Date() }).where(eq(workerState.id, "worker"));
|
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 };
|
||||||
}
|
}
|
||||||
@@ -89,4 +89,60 @@ describe("models folder scan", () => {
|
|||||||
writeFileSync(join(folder, "ReadMe.md"), "# Hello\n");
|
writeFileSync(join(folder, "ReadMe.md"), "# Hello\n");
|
||||||
assert.equal(await scan.readReadme(folder), "# 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");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
+73
-7
@@ -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 `<org>/<name>` layout is recognized (what Kaname and `hf download --local-dir` write).
|
// Only the `<org>/<name>` layout is recognized (what Kaname and `hf download --local-dir` write).
|
||||||
// Read-only: nothing on disk is changed.
|
// Read-only: nothing on disk is changed.
|
||||||
|
|
||||||
import { readdir, readFile, stat } from "node:fs/promises";
|
import { readdir, readFile, stat } from "node:fs/promises";
|
||||||
import { join, relative, sep } from "node:path";
|
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 { 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 { 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). */
|
/** Longer READMEs are cut off here (it's stored in the database). */
|
||||||
const MAX_README_BYTES = 512 * 1024;
|
const MAX_README_BYTES = 512 * 1024;
|
||||||
@@ -86,6 +89,69 @@ export async function readReadme(folder: string): Promise<string | null> {
|
|||||||
return buf.length > MAX_README_BYTES ? text.slice(0, text.lastIndexOf("\n") + 1) : text;
|
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<void> {
|
||||||
|
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). */
|
/** 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 };
|
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
|
* Scan MODELS_DIR and update the `local_folders` table to the folders no model uses. Also brings
|
||||||
* the README of local models (their model card).
|
* local models in line with their folders (files and README).
|
||||||
*/
|
*/
|
||||||
export async function scanModelsDir(modelsDir: string): Promise<number> {
|
export async function scanModelsDir(modelsDir: string): Promise<number> {
|
||||||
const inLibrary = await db().select({ id: models.id, p: models.localPath, source: models.source, readme: models.localReadme }).from(models);
|
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));
|
const used = new Set(inLibrary.map((m) => m.p));
|
||||||
for (const m of inLibrary.filter((x) => x.source === "local")) {
|
for (const m of inLibrary.filter((x) => x.source === "local")) {
|
||||||
const readme = await readReadme(join(modelsDir, m.p));
|
// One model's problem doesn't stop the scan of the others.
|
||||||
if (readme !== m.readme) await db().update(models).set({ localReadme: readme }).where(eq(models.id, m.id));
|
await syncLocalModel(modelsDir, m).catch((err) => log.error(`syncing local model ${m.p} failed`, err));
|
||||||
}
|
}
|
||||||
const found: FoundFolder[] = [];
|
const found: FoundFolder[] = [];
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
|||||||
Reference in new issue
Block a user