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>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-27 16:42:56 +01:00
1 parent 276108932d
commit c6bcb514e6
14 files changed
+1940 -12

No files matched your search

+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,
};
}