// The models-folder scan, on a temporary folder and SQLite database. // Runs with `--conditions=react-server` (see package.json). import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { after, before, describe, it } from "node:test"; const dir = mkdtempSync(join(tmpdir(), "kaname-scan-")); process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`; const modelsDir = join(dir, "models"); process.env.MODELS_DIR = modelsDir; let scan: typeof import("./scan"); let D: typeof import("@/lib/db/client"); let S: typeof import("@/lib/db/schema"); before(async () => { const { runMigrations } = await import("@/lib/db/migrate"); await runMigrations(); scan = await import("./scan"); D = await import("@/lib/db/client"); S = await import("@/lib/db/schema"); }); after(() => { try { rmSync(dir, { recursive: true, force: true }); } catch {} }); function put(path: string, bytes = 3) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, "x".repeat(bytes)); } const tick = () => new Promise((r) => setTimeout(r, 5)); async function stored() { const rows = await D.db().select().from(S.localFolders); return Object.fromEntries(rows.map((r) => [r.path, r])); } describe("models folder scan", () => { it("writes only new or changed folders and removes the ones that are gone", async () => { put(join(modelsDir, "org", "a", "model.gguf")); put(join(modelsDir, "org", "b", "shards", "x.safetensors")); assert.equal(await scan.scanModelsDir(modelsDir), 2); const first = await stored(); await tick(); assert.equal(await scan.scanModelsDir(modelsDir), 2); const second = await stored(); assert.equal(second["org/a"].scannedAt.getTime(), first["org/a"].scannedAt.getTime(), "unchanged: not written"); assert.equal(second["org/b"].scannedAt.getTime(), first["org/b"].scannedAt.getTime(), "unchanged: not written"); await tick(); put(join(modelsDir, "org", "a", "extra.json"), 10); rmSync(join(modelsDir, "org", "b"), { recursive: true }); assert.equal(await scan.scanModelsDir(modelsDir), 1); const third = await stored(); assert.deepEqual(Object.keys(third), ["org/a"]); assert.equal(third["org/a"].fileCount, 2); assert.deepEqual(third["org/a"].files.map((f) => f.path), ["extra.json", "model.gguf"]); assert.ok(third["org/a"].scannedAt.getTime() > first["org/a"].scannedAt.getTime(), "changed: written"); }); it("compares the file list, not only the counts", () => { const at = new Date(); const found = { path: "o/m", files: [{ path: "b.gguf", size: 2 }], fileCount: 1, totalBytes: 2, commit: null, scannedAt: at }; const same = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 2, commit: null, readme: null }; assert.deepEqual(scan.folderChanges([same], [found]), { insert: [], update: [], remove: [] }); const renamed = { ...same, filesJson: JSON.stringify([{ path: "a.gguf", size: 2 }]) }; assert.deepEqual(scan.folderChanges([renamed], [found]).update, [found]); }); it("writes a folder again when its README changed", () => { const at = new Date(); const found = { path: "o/m", files: [{ path: "README.md", size: 3 }], fileCount: 1, totalBytes: 3, commit: null, readme: "new", scannedAt: at }; const stored = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 3, commit: null, readme: "old" }; assert.deepEqual(scan.folderChanges([stored], [found]).update, [found]); }); it("reads README.md in any case, and only at the top level", async () => { const folder = join(dir, "readme-test"); // outside MODELS_DIR: no other test scans it put(join(folder, "sub", "README.md"), 1); assert.equal(await scan.readReadme(folder), null); 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"); }); });