Compare commits

...
1 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 c6bcb514e6 Release 0.15.1: schedule for the models folder scan
Release / release (push) Successful in 3m49s
Settings -> Downloads lets you scan the models folder every 2 minutes
(default, as before), hourly, daily, weekly, monthly at a chosen local
time, or only manually, with a Scan now button and the last/next scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:42:56 +01:00
14 changed files with 1940 additions and 12 deletions

No files matched your search

+11
View File
@@ -4,6 +4,17 @@ All notable changes to this project are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
step 1 (Hugging Face downloader) is released as a minor version.
## [0.15.1] - 2026-10-27
### Added
- Settings → Downloads → **Models folder scan**: choose when Kaname looks for importable folders
in the models folder: every 2 minutes (as before, the default), hourly, daily, weekly or monthly
at a time you pick (in your browser's time zone), or only manually. **Scan now** starts one right
away; the card shows the last scan, what it found and when the next one is due. A scan missed
while the worker was down runs when it is back; a restart no longer scans by itself unless one
is due.
## [0.15.0] - 2026-10-26
Kaname is back to two jobs: downloading models, and benchmarking the servers that run them. It no
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `worker_state` ADD `last_scan_at` integer;--> statement-breakpoint
ALTER TABLE `worker_state` ADD `last_scan_found` integer;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -162,6 +162,13 @@
"when": 1793045228739,
"tag": "0022_endpoints",
"breakpoints": true
},
{
"idx": 23,
"version": "6",
"when": 1793115558680,
"tag": "0023_scan_schedule",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.15.0",
"version": "0.15.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.15.0",
"version": "0.15.1",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.15.0",
"version": "0.15.1",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
+3 -1
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { getDownloadSpeedLimit, getRecommendedRoles } from "@/lib/settings";
import { getDownloadSpeedLimit, getRecommendedRoles, getScanStatus } from "@/lib/settings";
import { RecommendedSettings } from "./recommended-settings";
import { ScanSettings } from "./scan-settings";
import { SpeedLimit } from "./speed-limit";
export const dynamic = "force-dynamic";
@@ -11,6 +12,7 @@ export default async function DownloadSettingsPage() {
<div className="flex flex-col gap-4">
<SpeedLimit initial={await getDownloadSpeedLimit()} />
<RecommendedSettings initial={await getRecommendedRoles()} />
<ScanSettings initial={await getScanStatus()} />
</div>
);
}
@@ -0,0 +1,156 @@
"use client";
import { Loader2Icon, ScanSearchIcon } from "lucide-react";
import { useEffect, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
import { LocalTime } from "@/components/local-time";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import { FREQUENCY_LABEL, SCAN_FREQUENCIES, type ScanFrequency } from "@/lib/folder-scan";
import type { ScanStatus } from "@/lib/settings";
const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const browserTz = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
const noSubscribe = () => () => {};
/** When the worker looks for importable folders in the models folder, plus "Scan now". */
export function ScanSettings({ initial }: { initial: ScanStatus }) {
const [status, setStatus] = useState(initial);
const [every, setEvery] = useState<ScanFrequency>(initial.schedule.every);
const [time, setTime] = useState(initial.schedule.time);
const [weekday, setWeekday] = useState(initial.schedule.weekday);
const [monthDay, setMonthDay] = useState(initial.schedule.monthDay);
const [busy, setBusy] = useState(false);
// The browser's zone; the server renders the stored one.
const tz = useSyncExternalStore(noSubscribe, browserTz, () => initial.schedule.tz);
const s = status.schedule;
const dirty = every !== s.every || time !== s.time || weekday !== s.weekday || monthDay !== s.monthDay || (every !== "2min" && every !== "manual" && tz !== s.tz);
const timed = every === "daily" || every === "weekly" || every === "monthly";
// While a requested scan hasn't run yet, refresh until it has.
useEffect(() => {
if (!status.requested) return;
const t = setInterval(async () => {
const res = await fetch("/api/settings/downloads", { cache: "no-store" }).catch(() => null);
if (res?.ok) setStatus((await res.json()).scan);
}, 2_000);
return () => clearInterval(t);
}, [status.requested]);
async function save() {
setBusy(true);
try {
const res = await fetch("/api/settings/downloads", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scanSchedule: { every, time, weekday, monthDay, tz } }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
setStatus(body.scan);
toast.success("Scan schedule saved");
} finally {
setBusy(false);
}
}
async function scanNow() {
const res = await fetch("/api/local-folders/scan", { method: "POST" });
if (!res.ok) return toast.error(`Could not start a scan (${res.status})`);
setStatus((cur) => ({ ...cur, requested: true }));
}
return (
<Card>
<CardHeader>
<CardTitle>Models folder scan</CardTitle>
<CardDescription>
Kaname looks through the models folder for folders that aren&apos;t in the library yet, so you can import them. It only lists files and their sizes (no
hashing) and skips the models you already have; on a NAS, a rarer schedule lets the disks sleep.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
<div className="flex flex-wrap items-end gap-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="scan-every">Scan</Label>
<NativeSelect id="scan-every" value={every} onChange={(e) => setEvery(e.target.value as ScanFrequency)} className="w-64">
{SCAN_FREQUENCIES.map((f) => (
<option key={f} value={f}>
{FREQUENCY_LABEL[f]}
</option>
))}
</NativeSelect>
</div>
{every === "weekly" && (
<div className="flex flex-col gap-1.5">
<Label htmlFor="scan-weekday">On</Label>
<NativeSelect id="scan-weekday" value={weekday} onChange={(e) => setWeekday(Number(e.target.value))} className="w-36">
{WEEKDAYS.map((d, i) => (
<option key={d} value={i}>
{d}
</option>
))}
</NativeSelect>
</div>
)}
{every === "monthly" && (
<div className="flex flex-col gap-1.5">
<Label htmlFor="scan-day">On day</Label>
<NativeSelect id="scan-day" value={monthDay} onChange={(e) => setMonthDay(Number(e.target.value))} className="w-24">
{Array.from({ length: 28 }, (_, i) => i + 1).map((d) => (
<option key={d} value={d}>
{d}.
</option>
))}
</NativeSelect>
</div>
)}
{timed && (
<div className="flex flex-col gap-1.5">
<Label htmlFor="scan-time">At</Label>
<Input id="scan-time" type="time" value={time} onChange={(e) => setTime(e.target.value || "03:00")} className="w-32" />
</div>
)}
{every === "hourly" && (
<div className="flex flex-col gap-1.5">
<Label htmlFor="scan-minute">At minute</Label>
<NativeSelect id="scan-minute" value={time.slice(3)} onChange={(e) => setTime(`${time.slice(0, 2)}:${e.target.value}`)} className="w-24">
{Array.from({ length: 12 }, (_, i) => String(i * 5).padStart(2, "0")).map((m) => (
<option key={m} value={m}>
:{m}
</option>
))}
</NativeSelect>
</div>
)}
<Button onClick={save} disabled={busy || !dirty}>
Save
</Button>
<Button variant="outline" onClick={scanNow} disabled={status.requested}>
{status.requested ? <Loader2Icon className="animate-spin" /> : <ScanSearchIcon />}
{status.requested ? "Scanning…" : "Scan now"}
</Button>
</div>
{timed && <p className="text-xs text-muted-foreground">Times are in your time zone ({tz}).</p>}
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
<dt className="text-muted-foreground">Last scan</dt>
<dd>
{status.lastScanAt ? (
<>
<LocalTime value={status.lastScanAt} /> · {status.lastScanFound ?? 0} folder{status.lastScanFound === 1 ? "" : "s"} to import
</>
) : (
"not yet"
)}
</dd>
<dt className="text-muted-foreground">Next scan</dt>
<dd>{status.nextScanAt ? <LocalTime value={status.nextScanAt} /> : "only when you click Scan now"}</dd>
</dl>
</CardContent>
</Card>
);
}
+5 -3
View File
@@ -2,20 +2,21 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getDownloadSpeedLimit, getRecommendedRoles, saveDownloadSpeedLimit, saveRecommendedRoles, SettingsError } from "@/lib/settings";
import { getDownloadSpeedLimit, getRecommendedRoles, getScanStatus, saveDownloadSpeedLimit, saveRecommendedRoles, saveScanSchedule, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
async function current() {
return { recommendedRoles: await getRecommendedRoles(), maxBytesPerSecond: await getDownloadSpeedLimit() };
return { recommendedRoles: await getRecommendedRoles(), maxBytesPerSecond: await getDownloadSpeedLimit(), scan: await getScanStatus() };
}
/** Download settings: which file kinds are picked along with model weights, and the speed limit. */
/** Download settings: which file kinds are picked along with model weights, the speed limit, and the models folder scan. */
export const GET = withAuth(async () => NextResponse.json(await current()));
const Body = z.object({
recommendedRoles: z.array(z.string()).max(32).optional(),
maxBytesPerSecond: z.number().nullable().optional(),
scanSchedule: z.unknown().optional(),
});
export const PUT = withAuth(async (req) => {
@@ -23,6 +24,7 @@ export const PUT = withAuth(async (req) => {
const body = Body.parse(await req.json());
if (body.recommendedRoles) await saveRecommendedRoles(body.recommendedRoles);
if (body.maxBytesPerSecond !== undefined) await saveDownloadSpeedLimit(body.maxBytesPerSecond);
if (body.scanSchedule !== undefined) await saveScanSchedule(body.scanSchedule);
return NextResponse.json(await current());
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
+3
View File
@@ -342,6 +342,9 @@ export const workerState = sqliteTable("worker_state", {
heartbeatAt: ts("heartbeat_at").notNull(),
/** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */
scanRequestedAt: ts("scan_requested_at"),
/** The last scan of MODELS_DIR (scheduled, requested or at startup) and how many importable folders it found. */
lastScanAt: ts("last_scan_at"),
lastScanFound: integer("last_scan_found"),
});
/** A PCIe link: generation (1 = 2.5 GT/s … 6 = 64 GT/s) and lanes. */
+54
View File
@@ -0,0 +1,54 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { DEFAULT_SCAN_SCHEDULE, nextScanAt, parseScanSchedule, type ScanSchedule, scanDue, validateScanSchedule } from "./folder-scan";
const at = (iso: string) => new Date(iso);
const s = (o: Partial<ScanSchedule>): ScanSchedule => ({ ...DEFAULT_SCAN_SCHEDULE, tz: "Europe/Berlin", ...o });
describe("folder scan schedule", () => {
it("keeps the old every-2-minutes default and never schedules manual-only", () => {
assert.equal(nextScanAt(DEFAULT_SCAN_SCHEDULE, at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-10-27T10:02:00.000Z");
assert.equal(nextScanAt(s({ every: "manual" }), at("2026-10-27T10:00:00Z")), null);
assert.equal(scanDue(s({ every: "manual" }), null, at("2026-10-27T10:00:00Z")), false);
});
it("runs daily at the local time, across a DST change", () => {
const daily = s({ every: "daily", time: "03:00" });
// Berlin is UTC+1 after the switch on 25 Oct 2026.
assert.equal(nextScanAt(daily, at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-10-28T02:00:00.000Z");
assert.equal(nextScanAt(daily, at("2026-10-27T01:00:00Z"))!.toISOString(), "2026-10-27T02:00:00.000Z");
// Still summer time (UTC+2) before the switch.
assert.equal(nextScanAt(daily, at("2026-10-23T12:00:00Z"))!.toISOString(), "2026-10-24T01:00:00.000Z");
});
it("runs hourly at the given minute, weekly on the weekday, monthly on the day", () => {
assert.equal(nextScanAt(s({ every: "hourly", time: "00:15" }), at("2026-10-27T10:20:00Z"))!.toISOString(), "2026-10-27T11:15:00.000Z");
// 27 Oct 2026 is a Tuesday; next Sunday is 1 Nov.
assert.equal(nextScanAt(s({ every: "weekly", weekday: 0, time: "04:30" }), at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-11-01T03:30:00.000Z");
assert.equal(nextScanAt(s({ every: "monthly", monthDay: 1, time: "03:00" }), at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-11-01T02:00:00.000Z");
assert.equal(nextScanAt(s({ every: "monthly", monthDay: 27, time: "03:00" }), at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-11-27T02:00:00.000Z");
});
it("is due once the next slot after the last scan has passed (also after downtime)", () => {
const daily = s({ every: "daily", time: "03:00" });
assert.equal(scanDue(daily, null, at("2026-10-27T10:00:00Z")), true, "never scanned");
assert.equal(scanDue(daily, at("2026-10-27T02:00:30Z"), at("2026-10-27T10:00:00Z")), false);
assert.equal(scanDue(daily, at("2026-10-27T02:00:30Z"), at("2026-10-28T02:00:00Z")), true);
assert.equal(scanDue(daily, at("2026-10-25T02:00:30Z"), at("2026-10-27T10:00:00Z")), true, "missed while the worker was down");
});
it("validates input and falls back to the default for broken stored values", () => {
assert.deepEqual(validateScanSchedule({ every: "weekly", time: "23:59", weekday: 6, monthDay: 1, tz: "America/New_York" }), {
every: "weekly",
time: "23:59",
weekday: 6,
monthDay: 1,
tz: "America/New_York",
});
assert.throws(() => validateScanSchedule({ every: "yearly", time: "03:00" }), /Frequency/);
assert.throws(() => validateScanSchedule({ every: "daily", time: "24:00" }), /HH:MM/);
assert.throws(() => validateScanSchedule({ every: "monthly", time: "03:00", monthDay: 31 }), /1–28/);
assert.throws(() => validateScanSchedule({ every: "daily", time: "03:00", tz: "Mars/Base" }), /time zone/);
assert.deepEqual(parseScanSchedule({ every: "nope" }), DEFAULT_SCAN_SCHEDULE);
});
});
+121
View File
@@ -0,0 +1,121 @@
// When the worker scans the models folder for importable folders (Settings → Downloads). Pure;
// shared by the settings API, the settings page and the worker. Times are wall-clock times in the
// time zone the schedule was saved in (the browser's), so "03:00" means 03:00 for the user.
export const SCAN_SCHEDULE_KEY = "scan.schedule";
export const SCAN_FREQUENCIES = ["2min", "hourly", "daily", "weekly", "monthly", "manual"] as const;
export type ScanFrequency = (typeof SCAN_FREQUENCIES)[number];
export type ScanSchedule = {
every: ScanFrequency;
/** "HH:MM"; hourly uses only the minutes. */
time: string;
/** weekly: 0 = Sunday … 6 = Saturday. */
weekday: number;
/** monthly: 1–28 (every month has those). */
monthDay: number;
/** IANA time zone, e.g. "Europe/Berlin". */
tz: string;
};
/** Before this setting existed the worker scanned every 2 minutes; that stays the default. */
export const DEFAULT_SCAN_SCHEDULE: ScanSchedule = { every: "2min", time: "03:00", weekday: 1, monthDay: 1, tz: "UTC" };
export const FREQUENCY_LABEL: Record<ScanFrequency, string> = {
"2min": "Every 2 minutes",
hourly: "Hourly",
daily: "Daily",
weekly: "Weekly",
monthly: "Monthly",
manual: "Only when I click Scan now",
};
export class ScanScheduleError extends Error {}
export function validTimeZone(tz: string): boolean {
try {
new Intl.DateTimeFormat("en-US", { timeZone: tz });
return true;
} catch {
return false;
}
}
/** Validate input from the settings form; throws ScanScheduleError. */
export function validateScanSchedule(input: unknown): ScanSchedule {
const o = (input ?? {}) as Record<string, unknown>;
const every = o.every as ScanFrequency;
if (!SCAN_FREQUENCIES.includes(every)) throw new ScanScheduleError(`Frequency must be one of: ${SCAN_FREQUENCIES.join(", ")}.`);
const time = typeof o.time === "string" ? o.time.trim() : "";
const m = time.match(/^([01]\d|2[0-3]):([0-5]\d)$/);
if (!m) throw new ScanScheduleError('Time must be "HH:MM" (24 hours).');
const weekday = Number(o.weekday ?? 1);
if (!Number.isInteger(weekday) || weekday < 0 || weekday > 6) throw new ScanScheduleError("Weekday must be 0 (Sunday) to 6 (Saturday).");
const monthDay = Number(o.monthDay ?? 1);
if (!Number.isInteger(monthDay) || monthDay < 1 || monthDay > 28) throw new ScanScheduleError("Day of the month must be 1–28.");
const tz = typeof o.tz === "string" && o.tz ? o.tz : "UTC";
if (!validTimeZone(tz)) throw new ScanScheduleError(`Unknown time zone "${tz}".`);
return { every, time, weekday, monthDay, tz };
}
/** The stored schedule; anything invalid falls back to the default rather than stopping scans. */
export function parseScanSchedule(stored: unknown): ScanSchedule {
try {
return validateScanSchedule(stored);
} catch {
return DEFAULT_SCAN_SCHEDULE;
}
}
type Parts = { y: number; mo: number; d: number; h: number; mi: number; wd: number };
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
/** Wall-clock date and time of `t` in `tz`. */
function partsIn(t: number, tz: string): Parts {
const f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", weekday: "short" });
const p = Object.fromEntries(f.formatToParts(new Date(t)).map((x) => [x.type, x.value]));
return { y: Number(p.year), mo: Number(p.month), d: Number(p.day), h: Number(p.hour), mi: Number(p.minute), wd: WEEKDAYS.indexOf(p.weekday) };
}
/** The instant a wall-clock time in `tz` happens (in a DST gap: shortly after). */
function zonedToUtc(y: number, mo: number, d: number, h: number, mi: number, tz: string): number {
const wall = Date.UTC(y, mo - 1, d, h, mi);
const offsetAt = (t: number) => {
const p = partsIn(t, tz);
return Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi) - Math.floor(t / 60_000) * 60_000;
};
let t = wall - offsetAt(wall);
t = wall - offsetAt(t);
return t;
}
/** The first scheduled scan strictly after `after`; null for manual-only. */
export function nextScanAt(s: ScanSchedule, after: Date): Date | null {
const from = after.getTime();
if (s.every === "manual") return null;
if (s.every === "2min") return new Date(from + 2 * 60_000);
const [hh, mm] = s.time.split(":").map(Number);
const start = partsIn(from, s.tz);
// Walk local calendar days from `after`'s day on; 62 covers a month plus DST and edge cases.
for (let i = 0; i <= 62; i++) {
const day = new Date(Date.UTC(start.y, start.mo - 1, start.d + i));
const [y, mo, d, wd] = [day.getUTCFullYear(), day.getUTCMonth() + 1, day.getUTCDate(), day.getUTCDay()];
if (s.every === "weekly" && wd !== s.weekday) continue;
if (s.every === "monthly" && d !== s.monthDay) continue;
const hours = s.every === "hourly" ? Array.from({ length: 24 }, (_, h) => h) : [hh];
for (const h of hours) {
const t = zonedToUtc(y, mo, d, h, mm, s.tz);
if (t > from) return new Date(t);
}
}
return null;
}
/** Is a scheduled scan due? Never scanned: yes (the import list would stay empty otherwise). */
export function scanDue(s: ScanSchedule, lastScanAt: Date | null, now: Date): boolean {
if (s.every === "manual") return false;
if (!lastScanAt) return true;
const next = nextScanAt(s, lastScanAt);
return !!next && next.getTime() <= now.getTime();
}
+42 -1
View File
@@ -1,10 +1,11 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { settings, workerState } from "@/lib/db/schema";
import { isLabelColor } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
import { nextScanAt, parseScanSchedule, SCAN_SCHEDULE_KEY, type ScanSchedule, ScanScheduleError, validateScanSchedule } from "@/lib/folder-scan";
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
const FILE_ROLES_KEY = "labels.fileRoles";
@@ -99,3 +100,43 @@ export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Pro
else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond));
return getDownloadSpeedLimit();
}
/** When the worker scans the models folder for importable folders (Settings → Downloads). */
export async function getScanSchedule(): Promise<ScanSchedule> {
return parseScanSchedule(await read<unknown>(SCAN_SCHEDULE_KEY));
}
export async function saveScanSchedule(input: unknown): Promise<ScanSchedule> {
try {
await write(SCAN_SCHEDULE_KEY, validateScanSchedule(input));
} catch (err) {
if (err instanceof ScanScheduleError) throw new SettingsError(err.message);
throw err;
}
return getScanSchedule();
}
export type ScanStatus = {
schedule: ScanSchedule;
lastScanAt: number | null;
lastScanFound: number | null;
/** A "Scan now" the worker hasn't started yet. */
requested: boolean;
nextScanAt: number | null;
};
export async function getScanStatus(): Promise<ScanStatus> {
const [schedule, ws] = await Promise.all([
getScanSchedule(),
db().query.workerState.findFirst({ columns: { lastScanAt: true, lastScanFound: true, scanRequestedAt: true }, where: eq(workerState.id, "worker") }),
]);
const last = ws?.lastScanAt ?? null;
const next = schedule.every === "manual" ? null : last ? nextScanAt(schedule, last) : new Date();
return {
schedule,
lastScanAt: last?.getTime() ?? null,
lastScanFound: ws?.lastScanFound ?? null,
requested: !!ws?.scanRequestedAt && (!last || ws.scanRequestedAt > last),
nextScanAt: next?.getTime() ?? null,
};
}
+21 -4
View File
@@ -7,8 +7,9 @@ import { promisify } from "node:util";
import { and, asc, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { runMigrations } from "@/lib/db/migrate";
import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, settings, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { parseScanSchedule, SCAN_SCHEDULE_KEY, scanDue } from "@/lib/folder-scan";
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
import { backfillMetadata } from "@/lib/hub/refresh";
import { DeleteRunner } from "./delete";
@@ -29,7 +30,8 @@ const SHUTDOWN_GRACE_MS = 8_000;
/** How often to look for models whose Hub check is due (the check interval itself is configurable). */
const HUB_CHECK_SCAN_MS = 10 * 60_000;
/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */
const FOLDER_SCAN_MS = 2 * 60_000;
/** How often the worker checks whether a scheduled scan of MODELS_DIR is due (Settings → Downloads). */
const FOLDER_SCAN_CHECK_MS = 30_000;
const LOG_FLUSH_INTERVAL_MS = 1_000;
const BENCHMARK_TICK_MS = 2_000;
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
@@ -282,6 +284,7 @@ async function scanFolders() {
lastScanStartedAt = Date.now();
try {
const n = await scanModelsDir(coreEnv().MODELS_DIR);
await db().update(workerState).set({ lastScanAt: new Date(), lastScanFound: n }).where(eq(workerState.id, "worker"));
if (n > 0) log.info(`found ${n} folder(s) in the models dir that aren't in the library`);
} catch (err) {
log.error("models dir scan failed", err);
@@ -290,6 +293,20 @@ async function scanFolders() {
}
}
/** Scan when the schedule says so; the last scan is stored, so a restart doesn't scan again early. */
async function scanIfDue() {
if (scanning || stopping) return;
try {
const [row, ws] = await Promise.all([
db().query.settings.findFirst({ where: eq(settings.key, SCAN_SCHEDULE_KEY) }),
db().query.workerState.findFirst({ columns: { lastScanAt: true }, where: eq(workerState.id, "worker") }),
]);
if (scanDue(parseScanSchedule(row?.value), ws?.lastScanAt ?? null, new Date())) await scanFolders();
} catch (err) {
log.error("scan schedule check failed", err);
}
}
let checkingHub = false;
async function checkHubDue() {
const hours = coreEnv().UPDATE_CHECK_INTERVAL_HOURS;
@@ -382,7 +399,7 @@ async function main() {
timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS));
timers.push(setInterval(() => void tick(), TICK_MS));
timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS));
timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS));
timers.push(setInterval(() => void scanIfDue(), FOLDER_SCAN_CHECK_MS));
// Benchmarks: one run at a time against an endpoint.
await recoverBenchmarks();
@@ -391,7 +408,7 @@ async function main() {
timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS));
void scanFolders();
void scanIfDue();
void tick();
setTimeout(() => void checkHubDue(), 15_000);
}