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:
1 parent
276108932d
commit
c6bcb514e6
14 files changed
+1940
-12
No files matched your search
@@ -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'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>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user