Compare commits
6 Commits
feature/da
...
fix/llama-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38d8d55c21 | ||
| b0e03cdb99 | |||
|
|
12fb97314b | ||
| e02b0e57a3 | |||
|
|
6c4e1c8f64 | ||
| 405c88f086 |
@@ -39,6 +39,7 @@ RUN apk add --no-cache \
|
||||
tini \
|
||||
ca-certificates \
|
||||
wget \
|
||||
curl \
|
||||
&& addgroup -g 1001 dash \
|
||||
&& adduser -D -G dash -u 1001 dash
|
||||
|
||||
|
||||
36
dashboard/src/app/api/models/download/[id]/cancel/route.ts
Normal file
36
dashboard/src/app/api/models/download/[id]/cancel/route.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cancelDownload, getJob, publicJob } from "@/lib/downloads";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* POST /api/models/download/[id]/cancel
|
||||
*
|
||||
* Cancels an active download. Sends SIGTERM to the underlying curl process
|
||||
* and deletes the partial .part file. The job's status becomes 'cancelled'.
|
||||
*/
|
||||
export async function POST(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params;
|
||||
const job = getJob(id);
|
||||
if (!job) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: `download job ${id} not found` },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
const ok = cancelDownload(id);
|
||||
if (!ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: `job ${id} is not in a cancellable state (status: ${job.status})`,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ ok: true, job: publicJob(job) });
|
||||
}
|
||||
78
dashboard/src/app/api/models/download/[id]/stream/route.ts
Normal file
78
dashboard/src/app/api/models/download/[id]/stream/route.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { subscribeToJob, publicJob, getJob } from "@/lib/downloads";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 300;
|
||||
|
||||
/**
|
||||
* GET /api/models/download/[id]/stream
|
||||
*
|
||||
* Server-Sent Events stream for a single download job. Emits a `progress`
|
||||
* event every time the job state changes (bytes downloaded, percent, status).
|
||||
*
|
||||
* Emits `end` when the job reaches a terminal state (done / failed /
|
||||
* cancelled), then closes the stream.
|
||||
*/
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params;
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const send = (event: string, data: unknown) => {
|
||||
try {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
/* stream closed */
|
||||
}
|
||||
};
|
||||
|
||||
const job = getJob(id);
|
||||
if (!job) {
|
||||
send("error", { message: `download job ${id} not found` });
|
||||
send("end", { reason: "not-found" });
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Send current state immediately
|
||||
send("progress", publicJob(job));
|
||||
|
||||
// Subscribe to updates
|
||||
const unsubscribe = subscribeToJob(id, (updated) => {
|
||||
send("progress", publicJob(updated));
|
||||
if (
|
||||
updated.status === "done" ||
|
||||
updated.status === "failed" ||
|
||||
updated.status === "cancelled"
|
||||
) {
|
||||
send("end", { status: updated.status });
|
||||
unsubscribe();
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
}
|
||||
42
dashboard/src/app/api/models/download/route.ts
Normal file
42
dashboard/src/app/api/models/download/route.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { startModelDownload, publicJob } from "@/lib/downloads";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 600;
|
||||
|
||||
/**
|
||||
* POST /api/models/download
|
||||
*
|
||||
* Body: { url: string, filename?: string }
|
||||
*
|
||||
* Starts downloading a .gguf file from the given URL into
|
||||
* gpu/llama_models/. Returns the job id immediately — caller polls
|
||||
* /api/models/download/status for progress.
|
||||
*
|
||||
* Uses curl under the hood (available in the Alpine-based runtime image):
|
||||
* curl -L -f -S --progress-bar -o <dest>.part <url>
|
||||
*
|
||||
* Redirects are followed (HuggingFace, Cloudflare R2, etc.).
|
||||
* On success, the .part suffix is stripped via atomic rename.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = (await req.json()) as { url?: string; filename?: string };
|
||||
|
||||
if (!body.url || typeof body.url !== "string") {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "url is required (must be a string)" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const job = await startModelDownload(body.url, body.filename);
|
||||
return NextResponse.json({ ok: true, job: publicJob(job) });
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: (err as Error).message },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
30
dashboard/src/app/api/models/download/status/route.ts
Normal file
30
dashboard/src/app/api/models/download/status/route.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { listJobs, publicJob } from "@/lib/downloads";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* GET /api/models/download/status
|
||||
*
|
||||
* Returns all download jobs (active + recent history). Useful for the
|
||||
* frontend to render a list of in-progress downloads.
|
||||
*
|
||||
* For SSE push on a single job, see /api/models/download/[id]/stream.
|
||||
*
|
||||
* Returns: { jobs: [...], activeCount: N }
|
||||
*/
|
||||
export async function GET(_req: NextRequest) {
|
||||
const jobs = listJobs().map(publicJob);
|
||||
// Sort: active first (by startedAt asc — oldest first), then finished (by finishedAt desc)
|
||||
const active = jobs
|
||||
.filter((j) => j.status === "downloading" || j.status === "queued")
|
||||
.sort((a, b) => a.startedAt - b.startedAt);
|
||||
const finished = jobs
|
||||
.filter((j) => j.status !== "downloading" && j.status !== "queued")
|
||||
.sort((a, b) => (b.finishedAt || 0) - (a.finishedAt || 0));
|
||||
return NextResponse.json({
|
||||
jobs: [...active, ...finished],
|
||||
activeCount: active.length,
|
||||
});
|
||||
}
|
||||
78
dashboard/src/app/api/settings/route.ts
Normal file
78
dashboard/src/app/api/settings/route.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
loadSettings,
|
||||
saveSettings,
|
||||
prepareCivitaiUrl,
|
||||
type DashboardSettings,
|
||||
} from "@/lib/downloads";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* GET /api/settings
|
||||
*
|
||||
* Returns the persisted dashboard settings (civitai token etc).
|
||||
*
|
||||
* NOTE: The civitai token is returned in plain text. The dashboard has no
|
||||
* auth and is intended for use within a trusted tailnet only (Tailscale
|
||||
* serve on port 8090). If you expose this externally, add auth first.
|
||||
*/
|
||||
export async function GET() {
|
||||
const settings = await loadSettings();
|
||||
return NextResponse.json({ settings });
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /api/settings
|
||||
*
|
||||
* Body: Partial<DashboardSettings> — only the fields you want to change.
|
||||
*
|
||||
* Common usage:
|
||||
* PUT { civitaiToken: "abc123..." }
|
||||
*/
|
||||
export async function PUT(req: NextRequest) {
|
||||
const body = (await req.json()) as Partial<DashboardSettings>;
|
||||
const current = await loadSettings();
|
||||
const next: DashboardSettings = {
|
||||
civitaiToken: body.civitaiToken ?? current.civitaiToken,
|
||||
};
|
||||
await saveSettings(next);
|
||||
return NextResponse.json({ settings: next });
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/settings
|
||||
*
|
||||
* Body: { action: "preview-url", url: "<civitai URL>" }
|
||||
*
|
||||
* Returns what we'd transform the URL into (without actually starting a
|
||||
* download). Useful for the frontend to show the user "this URL will become
|
||||
* this" before clicking Download.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = (await req.json()) as {
|
||||
action: "preview-url";
|
||||
url?: string;
|
||||
};
|
||||
|
||||
if (body.action === "preview-url") {
|
||||
if (!body.url) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "url required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const settings = await loadSettings();
|
||||
const result = prepareCivitaiUrl(body.url, settings.civitaiToken || "");
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
original: body.url,
|
||||
transformed: result.url,
|
||||
note: result.note,
|
||||
isCivitai: result.note.length > 0 || result.url !== body.url,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "unknown action" }, { status: 400 });
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
CpuIcon,
|
||||
Gauge,
|
||||
HardDrive,
|
||||
Key as KeyIcon,
|
||||
Layers,
|
||||
MessageSquare,
|
||||
Moon,
|
||||
@@ -141,6 +142,33 @@ interface ComfyQueueEntry {
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
interface DownloadJob {
|
||||
id: string;
|
||||
url: string;
|
||||
originalUrl?: string;
|
||||
urlNote?: string;
|
||||
filename: string;
|
||||
status: "queued" | "downloading" | "done" | "failed" | "cancelled";
|
||||
bytesDownloaded: number;
|
||||
bytesTotal: number | null;
|
||||
percent: number;
|
||||
speedBytesPerSec: number | null;
|
||||
startedAt: number;
|
||||
finishedAt: number | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface DashboardSettings {
|
||||
civitaiToken: string;
|
||||
}
|
||||
|
||||
interface UrlPreview {
|
||||
original: string;
|
||||
transformed: string;
|
||||
note: string;
|
||||
isCivitai: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_CONFIG: DashboardConfig = {
|
||||
model: "model.gguf",
|
||||
ctxSize: 64000,
|
||||
@@ -244,6 +272,17 @@ export default function DashboardPage() {
|
||||
percent: number;
|
||||
} | null>(null);
|
||||
|
||||
// Download state (.gguf from URL)
|
||||
const [downloadJobs, setDownloadJobs] = React.useState<DownloadJob[]>([]);
|
||||
const [downloadUrl, setDownloadUrl] = React.useState("");
|
||||
const downloadsActiveRef = React.useRef(false);
|
||||
|
||||
// Settings (civitai token etc)
|
||||
const [settings, setSettings] = React.useState<DashboardSettings>({
|
||||
civitaiToken: "",
|
||||
});
|
||||
const [urlPreview, setUrlPreview] = React.useState<UrlPreview | null>(null);
|
||||
|
||||
const llamaContainer = containers.find((c) => c.role === "llama") || null;
|
||||
const comfyContainer = containers.find((c) => c.role === "comfyui") || null;
|
||||
|
||||
@@ -644,6 +683,228 @@ export default function DashboardPage() {
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Model download (.gguf from URL) — uses SSE for live progress
|
||||
// ---------------------------------------------------------------------------
|
||||
const refreshDownloadJobs = React.useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/models/download/status", {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const jobs: DownloadJob[] = data.jobs || [];
|
||||
setDownloadJobs(jobs);
|
||||
// If any active jobs, ensure SSE subscription is running
|
||||
const hasActive = jobs.some(
|
||||
(j) => j.status === "downloading" || j.status === "queued"
|
||||
);
|
||||
if (hasActive && !downloadsActiveRef.current) {
|
||||
startDownloadSSE(jobs);
|
||||
} else if (!hasActive && downloadsActiveRef.current) {
|
||||
stopDownloadSSE();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[refreshDownloadJobs] error:", err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const downloadSSERef = React.useRef<Map<string, EventSource>>(new Map());
|
||||
|
||||
const startDownloadSSE = React.useCallback((jobs: DownloadJob[]) => {
|
||||
const active = jobs.filter(
|
||||
(j) => j.status === "downloading" || j.status === "queued"
|
||||
);
|
||||
for (const job of active) {
|
||||
if (downloadSSERef.current.has(job.id)) continue;
|
||||
const es = new EventSource(
|
||||
`/api/models/download/${job.id}/stream`
|
||||
);
|
||||
downloadSSERef.current.set(job.id, es);
|
||||
|
||||
es.addEventListener("progress", (e) => {
|
||||
try {
|
||||
const data = JSON.parse((e as MessageEvent).data) as DownloadJob;
|
||||
setDownloadJobs((prev) => {
|
||||
const next = [...prev];
|
||||
const idx = next.findIndex((j) => j.id === data.id);
|
||||
if (idx >= 0) next[idx] = data;
|
||||
else next.push(data);
|
||||
return next;
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
});
|
||||
|
||||
es.addEventListener("end", () => {
|
||||
es.close();
|
||||
downloadSSERef.current.delete(job.id);
|
||||
// Refresh models list — file may have appeared on disk
|
||||
refreshModels();
|
||||
});
|
||||
|
||||
es.addEventListener("error", () => {
|
||||
// Will auto-retry; if stream really ended, the end event will fire.
|
||||
});
|
||||
}
|
||||
if (active.length > 0) downloadsActiveRef.current = true;
|
||||
}, [refreshModels]);
|
||||
|
||||
const stopDownloadSSE = React.useCallback(() => {
|
||||
for (const es of downloadSSERef.current.values()) {
|
||||
es.close();
|
||||
}
|
||||
downloadSSERef.current.clear();
|
||||
downloadsActiveRef.current = false;
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
// On mount, fetch existing download jobs (in case page was refreshed mid-download)
|
||||
refreshDownloadJobs();
|
||||
return () => stopDownloadSSE();
|
||||
}, [refreshDownloadJobs, stopDownloadSSE]);
|
||||
|
||||
async function handleDownload() {
|
||||
if (!downloadUrl.trim()) {
|
||||
showToast("error", "URL required");
|
||||
return;
|
||||
}
|
||||
let url: string;
|
||||
try {
|
||||
url = downloadUrl.trim();
|
||||
// Validate URL
|
||||
new URL(url);
|
||||
} catch {
|
||||
showToast("error", "Invalid URL");
|
||||
return;
|
||||
}
|
||||
setBusy("download-start");
|
||||
try {
|
||||
const res = await fetch("/api/models/download", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok && data.job) {
|
||||
const job = data.job as DownloadJob;
|
||||
setDownloadJobs((prev) => [...prev, job]);
|
||||
setDownloadUrl("");
|
||||
showToast("info", `Started: ${job.filename}`);
|
||||
// Start SSE subscription for this job
|
||||
startDownloadSSE([job]);
|
||||
} else {
|
||||
showToast("error", data.error || "Failed to start download");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast("error", (err as Error).message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCancelDownload(id: string) {
|
||||
if (!confirm("Cancel this download? Partial file will be deleted.")) return;
|
||||
try {
|
||||
const res = await fetch(`/api/models/download/${id}/cancel`, {
|
||||
method: "POST",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok) {
|
||||
showToast("info", "Download cancelled");
|
||||
// Stop SSE for this job
|
||||
const es = downloadSSERef.current.get(id);
|
||||
if (es) {
|
||||
es.close();
|
||||
downloadSSERef.current.delete(id);
|
||||
}
|
||||
await refreshDownloadJobs();
|
||||
} else {
|
||||
showToast("error", data.error || "Failed to cancel");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast("error", (err as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Settings (CivitAI token etc)
|
||||
// ---------------------------------------------------------------------------
|
||||
const refreshSettings = React.useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/settings", { cache: "no-store" });
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setSettings(data.settings || { civitaiToken: "" });
|
||||
} catch (err) {
|
||||
console.error("[refreshSettings] error:", err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const previewDebounceRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const previewUrl = React.useCallback(async (url: string) => {
|
||||
if (!url.trim()) {
|
||||
setUrlPreview(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/api/settings", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "preview-url", url }),
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
if (data.ok) {
|
||||
setUrlPreview({
|
||||
original: data.original,
|
||||
transformed: data.transformed,
|
||||
note: data.note,
|
||||
isCivitai: data.isCivitai,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
/* ignore — preview is best-effort */
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Debounced URL preview — fires 400ms after the user stops typing
|
||||
React.useEffect(() => {
|
||||
if (previewDebounceRef.current) clearTimeout(previewDebounceRef.current);
|
||||
previewDebounceRef.current = setTimeout(() => {
|
||||
void previewUrl(downloadUrl);
|
||||
}, 400);
|
||||
return () => {
|
||||
if (previewDebounceRef.current) clearTimeout(previewDebounceRef.current);
|
||||
};
|
||||
}, [downloadUrl, previewUrl]);
|
||||
|
||||
React.useEffect(() => {
|
||||
refreshSettings();
|
||||
}, [refreshSettings]);
|
||||
|
||||
async function handleSaveCivitaiToken(token: string) {
|
||||
setBusy("save-settings");
|
||||
try {
|
||||
const res = await fetch("/api/settings", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ civitaiToken: token }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.settings) {
|
||||
setSettings(data.settings);
|
||||
showToast("success", "CivitAI token saved");
|
||||
} else {
|
||||
showToast("error", data.error || "Failed to save");
|
||||
}
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSavePreset() {
|
||||
if (!presetName.trim()) {
|
||||
showToast("error", "Preset name required");
|
||||
@@ -964,6 +1225,14 @@ export default function DashboardPage() {
|
||||
onSelectModel={(m) => update("model", m)}
|
||||
onUpload={handleUpload}
|
||||
onDelete={handleDeleteModel}
|
||||
downloadJobs={downloadJobs}
|
||||
downloadUrl={downloadUrl}
|
||||
setDownloadUrl={setDownloadUrl}
|
||||
onDownload={handleDownload}
|
||||
onCancelDownload={handleCancelDownload}
|
||||
civitaiToken={settings.civitaiToken}
|
||||
onSaveCivitaiToken={handleSaveCivitaiToken}
|
||||
urlPreview={urlPreview}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
@@ -1728,6 +1997,14 @@ function ModelsTab({
|
||||
onSelectModel,
|
||||
onUpload,
|
||||
onDelete,
|
||||
downloadJobs,
|
||||
downloadUrl,
|
||||
setDownloadUrl,
|
||||
onDownload,
|
||||
onCancelDownload,
|
||||
civitaiToken,
|
||||
onSaveCivitaiToken,
|
||||
urlPreview,
|
||||
}: {
|
||||
models: ModelFile[];
|
||||
config: DashboardConfig;
|
||||
@@ -1736,15 +2013,39 @@ function ModelsTab({
|
||||
onSelectModel: (m: string) => void;
|
||||
onUpload: (file: File) => void;
|
||||
onDelete: (name: string) => void;
|
||||
downloadJobs: DownloadJob[];
|
||||
downloadUrl: string;
|
||||
setDownloadUrl: (v: string) => void;
|
||||
onDownload: () => void;
|
||||
onCancelDownload: (id: string) => void;
|
||||
civitaiToken: string;
|
||||
onSaveCivitaiToken: (token: string) => void;
|
||||
urlPreview: UrlPreview | null;
|
||||
}) {
|
||||
const fileInputRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const [dragOver, setDragOver] = React.useState(false);
|
||||
const [showCivitaiSettings, setShowCivitaiSettings] = React.useState(false);
|
||||
const [civitaiTokenDraft, setCivitaiTokenDraft] = React.useState(civitaiToken);
|
||||
|
||||
React.useEffect(() => {
|
||||
setCivitaiTokenDraft(civitaiToken);
|
||||
}, [civitaiToken]);
|
||||
|
||||
function handleFiles(files: FileList | null) {
|
||||
if (!files || files.length === 0) return;
|
||||
onUpload(files[0]);
|
||||
}
|
||||
|
||||
const activeDownloads = downloadJobs.filter(
|
||||
(j) => j.status === "downloading" || j.status === "queued"
|
||||
);
|
||||
const finishedDownloads = downloadJobs
|
||||
.filter(
|
||||
(j) => j.status !== "downloading" && j.status !== "queued"
|
||||
)
|
||||
.sort((a, b) => (b.finishedAt || 0) - (a.finishedAt || 0))
|
||||
.slice(0, 5);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -1812,6 +2113,152 @@ function ModelsTab({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Download from URL */}
|
||||
<div className="rounded-md border bg-muted/20 p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<span className="text-sm font-medium flex items-center gap-2">
|
||||
<CloudDownload className="h-4 w-4" />
|
||||
Download from URL
|
||||
</span>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Fetch a .gguf file from HuggingFace, GitHub releases, or any
|
||||
direct URL. CivitAI URLs are auto-converted (model page →
|
||||
API download) and the saved token is appended.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setShowCivitaiSettings((v) => !v)}
|
||||
>
|
||||
<KeyIcon className="h-3.5 w-3.5" />
|
||||
CivitAI token
|
||||
{civitaiToken ? (
|
||||
<Badge variant="success" className="ml-1 text-[10px]">
|
||||
set
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="ml-1 text-[10px]">
|
||||
empty
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showCivitaiSettings && (
|
||||
<div className="rounded-md border bg-card p-3 space-y-2">
|
||||
<Label htmlFor="civitai-token">CivitAI API token</Label>
|
||||
<Input
|
||||
id="civitai-token"
|
||||
type="password"
|
||||
value={civitaiTokenDraft}
|
||||
onChange={(e) => setCivitaiTokenDraft(e.target.value)}
|
||||
placeholder="Get it from https://civitai.com/user/account → API Keys"
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => onSaveCivitaiToken(civitaiTokenDraft)}
|
||||
disabled={busy === "save-settings"}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setCivitaiTokenDraft("");
|
||||
onSaveCivitaiToken("");
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
<a
|
||||
href="https://civitai.com/user/account"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="ml-auto text-xs text-muted-foreground hover:underline"
|
||||
>
|
||||
Get token ↗
|
||||
</a>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
Stored locally in <code className="font-mono">gpu/dashboard/settings.json</code>.
|
||||
Used to authenticate CivitAI downloads. Without it, NSFW /
|
||||
gated models will fail with 401.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-end gap-2">
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label htmlFor="download-url">URL</Label>
|
||||
<Input
|
||||
id="download-url"
|
||||
value={downloadUrl}
|
||||
onChange={(e) => setDownloadUrl(e.target.value)}
|
||||
placeholder="https://huggingface.co/.../model.gguf or https://civitai.com/models/12345"
|
||||
className="font-mono text-xs"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
onDownload();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={onDownload}
|
||||
disabled={busy !== null || !downloadUrl.trim()}
|
||||
>
|
||||
<CloudDownload className="h-3.5 w-3.5" />
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* URL preview — shows what we'll actually curl */}
|
||||
{urlPreview && urlPreview.original !== urlPreview.transformed && (
|
||||
<div className="rounded-md border bg-card p-2.5 text-xs space-y-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Badge variant={urlPreview.isCivitai ? "default" : "secondary"} className="text-[10px]">
|
||||
{urlPreview.isCivitai ? "CivitAI" : "transformed"}
|
||||
</Badge>
|
||||
<span className="text-muted-foreground">{urlPreview.note}</span>
|
||||
</div>
|
||||
<pre className="font-mono text-[10px] text-foreground whitespace-pre-wrap break-all">
|
||||
{urlPreview.transformed}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Active downloads */}
|
||||
{activeDownloads.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{activeDownloads.map((job) => (
|
||||
<DownloadJobRow
|
||||
key={job.id}
|
||||
job={job}
|
||||
onCancel={() => onCancelDownload(job.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recently finished downloads */}
|
||||
{finishedDownloads.length > 0 && (
|
||||
<div className="space-y-1.5 pt-2 border-t">
|
||||
<Label>Recent</Label>
|
||||
<div className="space-y-1">
|
||||
{finishedDownloads.map((job) => (
|
||||
<DownloadJobRow key={job.id} job={job} compact />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Models table */}
|
||||
{models.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
@@ -1890,6 +2337,137 @@ function ModelsTab({
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadJobRow({
|
||||
job,
|
||||
onCancel,
|
||||
compact = false,
|
||||
}: {
|
||||
job: DownloadJob;
|
||||
onCancel?: () => void;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const isActive = job.status === "downloading" || job.status === "queued";
|
||||
const isDone = job.status === "done";
|
||||
const isFailed = job.status === "failed";
|
||||
const isCancelled = job.status === "cancelled";
|
||||
|
||||
const durationSec =
|
||||
job.finishedAt != null
|
||||
? (job.finishedAt - job.startedAt) / 1000
|
||||
: (Date.now() - job.startedAt) / 1000;
|
||||
|
||||
const speedText =
|
||||
job.speedBytesPerSec != null
|
||||
? `${formatBytes(job.speedBytesPerSec)}/s`
|
||||
: null;
|
||||
|
||||
const progressText =
|
||||
job.bytesTotal != null && job.bytesTotal > 0
|
||||
? `${formatBytes(job.bytesDownloaded)} / ${formatBytes(job.bytesTotal)}`
|
||||
: job.bytesDownloaded > 0
|
||||
? formatBytes(job.bytesDownloaded)
|
||||
: "starting...";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border p-2.5 space-y-1.5 bg-card",
|
||||
isFailed && "border-destructive/30",
|
||||
isCancelled && "opacity-60",
|
||||
isDone && "border-success/30"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={
|
||||
isActive
|
||||
? "default"
|
||||
: isDone
|
||||
? "success"
|
||||
: isFailed
|
||||
? "destructive"
|
||||
: "secondary"
|
||||
}
|
||||
className="text-[10px] shrink-0"
|
||||
>
|
||||
{job.status}
|
||||
</Badge>
|
||||
<span className="font-mono text-xs truncate flex-1">{job.filename}</span>
|
||||
{isActive && onCancel && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-6 text-xs hover:text-destructive"
|
||||
onClick={onCancel}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!compact && isActive && (
|
||||
<>
|
||||
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-primary transition-all"
|
||||
style={{ width: `${job.percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between text-[10px] text-muted-foreground font-mono">
|
||||
<span>{progressText}</span>
|
||||
<span>
|
||||
{job.percent > 0 ? `${job.percent.toFixed(1)}%` : ""}
|
||||
{speedText ? ` · ${speedText}` : ""}
|
||||
{` · ${durationSec.toFixed(0)}s elapsed`}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!compact && (isFailed || isCancelled) && job.error && (
|
||||
<p className="text-[10px] text-destructive font-mono">{job.error}</p>
|
||||
)}
|
||||
|
||||
{compact && (
|
||||
<div className="text-[10px] text-muted-foreground font-mono">
|
||||
{isDone && formatBytes(job.bytesDownloaded)}
|
||||
{isFailed && job.error && ` · ${job.error.slice(0, 80)}`}
|
||||
{isCancelled && " · cancelled"}
|
||||
{` · ${durationSec.toFixed(0)}s`}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* URL transformation note (e.g. "added CivitAI token") */}
|
||||
{!compact && job.urlNote && (
|
||||
<div className="text-[10px] text-muted-foreground italic">
|
||||
{job.urlNote}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Show source URL for reference (compact mode hides it) */}
|
||||
{!compact && (
|
||||
<div className="text-[10px] text-muted-foreground font-mono truncate">
|
||||
{job.originalUrl && (
|
||||
<span className="line-through opacity-60">
|
||||
{job.originalUrl}
|
||||
</span>
|
||||
)}
|
||||
{job.originalUrl && <span className="mx-1">→</span>}
|
||||
<a
|
||||
href={job.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="hover:underline"
|
||||
>
|
||||
{job.url}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Comfy Tab
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -3208,16 +3786,24 @@ function buildPreviewArgs(cfg: DashboardConfig): string {
|
||||
parts.push(`--cache-type-v ${cfg.cacheTypeV}`);
|
||||
if (cfg.defragThold >= 0 && cfg.defragThold !== 0.1)
|
||||
parts.push(`--defrag-thold ${cfg.defragThold}`);
|
||||
if (cfg.flashAttn) parts.push("--flash-attn");
|
||||
if (cfg.noMmap) parts.push("--no-mmap");
|
||||
if (cfg.mlock) parts.push("--mlock");
|
||||
if (cfg.contBatching) parts.push("--cont-batching");
|
||||
// --flash-attn takes on/off/auto in modern llama.cpp (bare flag fails)
|
||||
parts.push(`--flash-attn ${cfg.flashAttn ? "on" : "off"}`);
|
||||
// --mlock / --no-mmap → unified --load-mode in modern llama.cpp
|
||||
if (cfg.mlock && cfg.noMmap) {
|
||||
parts.push("--load-mode mlock");
|
||||
} else if (cfg.mlock) {
|
||||
parts.push("--load-mode mmap+mlock");
|
||||
} else if (cfg.noMmap) {
|
||||
parts.push("--load-mode none");
|
||||
}
|
||||
// cont-batching is enabled by default; only emit --no-cont-batching if off
|
||||
if (!cfg.contBatching) parts.push("--no-cont-batching");
|
||||
if (cfg.embeddings) parts.push("--embeddings");
|
||||
if (cfg.metrics) parts.push("--metrics");
|
||||
if (cfg.ropeFreqScale !== 1.0)
|
||||
parts.push(`--rope-freq-scale ${cfg.ropeFreqScale}`);
|
||||
if (cfg.ropeScale !== 1.0)
|
||||
parts.push(`--rope-scaling ${cfg.ropeScale}`);
|
||||
parts.push(`--rope-scale ${cfg.ropeScale}`);
|
||||
if (cfg.yarnExtFactor !== 1.0)
|
||||
parts.push(`--yarn-ext-factor ${cfg.yarnExtFactor}`);
|
||||
if (cfg.yarnAttnFactor !== 1.0)
|
||||
|
||||
@@ -143,6 +143,16 @@ export const NODE_INSTANCE =
|
||||
*/
|
||||
const COMPOSE_FILE = path.join(PROJECT_DIR, "compose.yaml");
|
||||
|
||||
/**
|
||||
* Path to the persisted dashboard settings (civitai token, etc).
|
||||
*/
|
||||
export const DASHBOARD_SETTINGS_PATH = path.join(
|
||||
PROJECT_DIR,
|
||||
"gpu",
|
||||
"dashboard",
|
||||
"settings.json"
|
||||
);
|
||||
|
||||
/**
|
||||
* Path to the persisted dashboard config (last-used + saved presets).
|
||||
*/
|
||||
@@ -358,6 +368,10 @@ export function parseLlamaExtraArgs(
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const tok = tokens[i];
|
||||
const next = tokens[i + 1];
|
||||
// Helper: check if next token is a value (not another flag)
|
||||
const isValue = (s: string | undefined) =>
|
||||
s != null && !s.startsWith("--") && !s.startsWith("-");
|
||||
|
||||
switch (tok) {
|
||||
case "--ctx-size":
|
||||
cfg.ctxSize = Number(next) || cfg.ctxSize;
|
||||
@@ -400,7 +414,32 @@ export function parseLlamaExtraArgs(
|
||||
i++;
|
||||
break;
|
||||
case "--flash-attn":
|
||||
cfg.flashAttn = true;
|
||||
case "-fa":
|
||||
// Modern: --flash-attn on|off|auto (default auto).
|
||||
// Legacy: --flash-attn (bare flag, no value).
|
||||
if (isValue(next) && /^(on|off|auto)$/i.test(next)) {
|
||||
cfg.flashAttn = next.toLowerCase() !== "off";
|
||||
i++;
|
||||
} else {
|
||||
cfg.flashAttn = true;
|
||||
}
|
||||
break;
|
||||
case "--load-mode":
|
||||
case "-lm":
|
||||
// Replaces --mlock / --no-mmap in modern llama.cpp
|
||||
if (isValue(next)) {
|
||||
const mode = next.toLowerCase();
|
||||
if (mode === "mlock") {
|
||||
cfg.mlock = true;
|
||||
cfg.noMmap = true;
|
||||
} else if (mode === "mmap+mlock") {
|
||||
cfg.mlock = true;
|
||||
cfg.noMmap = false;
|
||||
} else if (mode === "none") {
|
||||
cfg.noMmap = true;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
break;
|
||||
case "--no-mmap":
|
||||
cfg.noMmap = true;
|
||||
@@ -409,8 +448,13 @@ export function parseLlamaExtraArgs(
|
||||
cfg.mlock = true;
|
||||
break;
|
||||
case "--cont-batching":
|
||||
case "-cb":
|
||||
cfg.contBatching = true;
|
||||
break;
|
||||
case "--no-cont-batching":
|
||||
case "-nocb":
|
||||
cfg.contBatching = false;
|
||||
break;
|
||||
case "--embeddings":
|
||||
cfg.embeddings = true;
|
||||
break;
|
||||
@@ -421,10 +465,21 @@ export function parseLlamaExtraArgs(
|
||||
cfg.ropeFreqScale = Number(next) || cfg.ropeFreqScale;
|
||||
i++;
|
||||
break;
|
||||
case "--rope-scaling":
|
||||
case "--rope-scale":
|
||||
cfg.ropeScale = Number(next) || cfg.ropeScale;
|
||||
i++;
|
||||
break;
|
||||
case "--rope-scaling":
|
||||
// Modern: enum {none,linear,yarn}. Legacy: numeric factor.
|
||||
// If numeric, treat as --rope-scale (the new flag for the factor).
|
||||
if (isValue(next) && /^\d/.test(next)) {
|
||||
cfg.ropeScale = Number(next) || cfg.ropeScale;
|
||||
i++;
|
||||
} else if (isValue(next)) {
|
||||
// enum value like 'yarn' — ignore, it's the scaling method not the factor
|
||||
i++;
|
||||
}
|
||||
break;
|
||||
case "--yarn-ext-factor":
|
||||
cfg.yarnExtFactor = Number(next) || cfg.yarnExtFactor;
|
||||
i++;
|
||||
@@ -512,17 +567,33 @@ export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
|
||||
if (cfg.defragThold >= 0 && cfg.defragThold !== 0.1)
|
||||
parts.push(`--defrag-thold ${cfg.defragThold}`);
|
||||
// Performance flags
|
||||
if (cfg.flashAttn) parts.push("--flash-attn");
|
||||
if (cfg.noMmap) parts.push("--no-mmap");
|
||||
if (cfg.mlock) parts.push("--mlock");
|
||||
if (cfg.contBatching) parts.push("--cont-batching");
|
||||
// --flash-attn takes a value (on/off/auto) since llama.cpp changed the CLI
|
||||
// (https://github.com/ggml-org/llama.cpp/issues/...). Passing it as a bare
|
||||
// flag causes 'unknown value for --flash-attn: <next-flag>'.
|
||||
parts.push(`--flash-attn ${cfg.flashAttn ? "on" : "off"}`);
|
||||
// --mlock and --no-mmap were replaced by --load-mode (mlock/none/mmap+mlock)
|
||||
// in newer llama.cpp builds. We emit the unified --load-mode flag, which is
|
||||
// backwards-compatible — older builds ignore unknown values silently.
|
||||
if (cfg.mlock && cfg.noMmap) {
|
||||
// mlock the file after loading to RAM (no mmap)
|
||||
parts.push("--load-mode mlock");
|
||||
} else if (cfg.mlock) {
|
||||
// mmap + mlock (default mmap, but also keep in RAM)
|
||||
parts.push("--load-mode mmap+mlock");
|
||||
} else if (cfg.noMmap) {
|
||||
// no mmap at all
|
||||
parts.push("--load-mode none");
|
||||
}
|
||||
// --cont-batching is enabled by default in modern llama.cpp. Only emit
|
||||
// --no-cont-batching if the user explicitly disabled it.
|
||||
if (!cfg.contBatching) parts.push("--no-cont-batching");
|
||||
if (cfg.embeddings) parts.push("--embeddings");
|
||||
if (cfg.metrics) parts.push("--metrics");
|
||||
// RoPE / YaRN
|
||||
if (cfg.ropeFreqScale !== 1.0)
|
||||
parts.push(`--rope-freq-scale ${cfg.ropeFreqScale}`);
|
||||
if (cfg.ropeScale !== 1.0)
|
||||
parts.push(`--rope-scaling ${cfg.ropeScale}`);
|
||||
parts.push(`--rope-scale ${cfg.ropeScale}`);
|
||||
if (cfg.yarnExtFactor !== 1.0)
|
||||
parts.push(`--yarn-ext-factor ${cfg.yarnExtFactor}`);
|
||||
if (cfg.yarnAttnFactor !== 1.0)
|
||||
@@ -1022,7 +1093,22 @@ export async function startService(
|
||||
const profile = COMPOSE_PROFILES[role];
|
||||
const args = ["up", "-d", "--force-recreate", role];
|
||||
if (profile) args.unshift("--profile", profile);
|
||||
const res = await runCompose(args, {});
|
||||
|
||||
// Service-specific env overrides. Mirrors what gpuctl shells do — they
|
||||
// explicitly export these vars before `docker compose` so compose's
|
||||
// ${VAR:-default} syntax picks the real host path instead of the relative
|
||||
// default (which would resolve to a path inside the dashboard container,
|
||||
// not on the host).
|
||||
const extra: Record<string, string> = {};
|
||||
if (role === "comfyui") {
|
||||
// These mirror `ssh/scripts/comfy.sh`:
|
||||
// COMFY_BASE_HOST="$HOST_PROJECT_PATH/gpu/comfy"
|
||||
// COMFY_RUN_HOST="$HOST_PROJECT_PATH/comfyui/run"
|
||||
extra.COMFY_BASE_HOST = `${HOST_PROJECT_PATH}/gpu/comfy`;
|
||||
extra.COMFY_RUN_HOST = `${HOST_PROJECT_PATH}/comfyui/run`;
|
||||
}
|
||||
|
||||
const res = await runCompose(args, extra);
|
||||
return {
|
||||
ok: res.code === 0,
|
||||
message:
|
||||
|
||||
556
dashboard/src/lib/downloads.ts
Normal file
556
dashboard/src/lib/downloads.ts
Normal file
@@ -0,0 +1,556 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { LLAMA_MODELS_DIR, DASHBOARD_SETTINGS_PATH } from "./docker";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Settings (civitai token etc.)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface DashboardSettings {
|
||||
civitaiToken: string;
|
||||
// Add more settings here in the future (e.g. default download dir,
|
||||
// HF token for gated repos, etc.)
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: DashboardSettings = {
|
||||
civitaiToken: "",
|
||||
};
|
||||
|
||||
let _settingsCache: DashboardSettings | null = null;
|
||||
|
||||
export async function loadSettings(): Promise<DashboardSettings> {
|
||||
if (_settingsCache !== null) return _settingsCache;
|
||||
let result: DashboardSettings;
|
||||
try {
|
||||
const raw = await fs.readFile(DASHBOARD_SETTINGS_PATH, "utf-8");
|
||||
const parsed = JSON.parse(raw);
|
||||
result = { ...DEFAULT_SETTINGS, ...parsed };
|
||||
} catch {
|
||||
result = { ...DEFAULT_SETTINGS };
|
||||
}
|
||||
_settingsCache = result;
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function saveSettings(settings: DashboardSettings): Promise<void> {
|
||||
await fs.mkdir(path.dirname(DASHBOARD_SETTINGS_PATH), { recursive: true });
|
||||
await fs.writeFile(
|
||||
DASHBOARD_SETTINGS_PATH,
|
||||
JSON.stringify(settings, null, 2),
|
||||
"utf-8"
|
||||
);
|
||||
_settingsCache = settings;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// URL preparation — handle CivitAI's quirky URL scheme
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// CivitAI URLs come in several shapes:
|
||||
//
|
||||
// 1. https://civitai.com/models/12345
|
||||
// Model page (HTML). NOT downloadable directly — must be converted.
|
||||
//
|
||||
// 2. https://civitai.com/models/12345?modelVersionId=67890
|
||||
// Specific version. Also a model page.
|
||||
//
|
||||
// 3. https://civitai.com/api/download/models/12345
|
||||
// Direct download. Returns 302 to a signed Cloudflare URL.
|
||||
// Requires API token: ?token=XXX
|
||||
//
|
||||
// 4. https://civitai.com/api/download/models/12345?token=XXX
|
||||
// Same with token inline.
|
||||
//
|
||||
// 5. https://civitai.com/api/download/models/12345?token=XXX&modelVersionId=67890
|
||||
// Specific version with token.
|
||||
//
|
||||
// We accept ANY of the above (and the .red mirror variants) and:
|
||||
// - Convert model page URLs → API download URLs
|
||||
// - Append the saved token if not already present
|
||||
// - Preserve existing query params (modelVersionId, type, etc.)
|
||||
//
|
||||
// Returns { url, note } where note explains what we did.
|
||||
|
||||
export interface PreparedUrl {
|
||||
url: string;
|
||||
note: string;
|
||||
}
|
||||
|
||||
export function prepareCivitaiUrl(
|
||||
rawUrl: string,
|
||||
token: string
|
||||
): PreparedUrl {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
// Not a parseable URL — return as-is
|
||||
return { url: rawUrl, note: "invalid URL, passed through unchanged" };
|
||||
}
|
||||
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
const isCivitai =
|
||||
host === "civitai.com" || host === "civitai.red" || host.endsWith(".civitai.com") || host.endsWith(".civitai.red");
|
||||
|
||||
if (!isCivitai) {
|
||||
// Not CivitAI — return as-is
|
||||
return { url: rawUrl, note: "" };
|
||||
}
|
||||
|
||||
// Normalize: replace civitai.red host with civitai.com (same backend).
|
||||
// The .red domain is a mirror that doesn't accept API requests the same way.
|
||||
if (host === "civitai.red") {
|
||||
parsed.hostname = "civitai.com";
|
||||
}
|
||||
|
||||
const pathname = parsed.pathname;
|
||||
|
||||
// Pattern 1: /models/<id> (model page) → convert to /api/download/models/<id>
|
||||
// Pattern 2: /models/<id>/<slug> (also model page with slug)
|
||||
const modelMatch = pathname.match(/^\/models\/(\d+)(?:\/[^/]*)?$/);
|
||||
if (modelMatch) {
|
||||
const modelId = modelMatch[1];
|
||||
// Build the API download URL
|
||||
const apiPath = `/api/download/models/${modelId}`;
|
||||
parsed.pathname = apiPath;
|
||||
// Preserve modelVersionId from query if present
|
||||
// (other query params like 'type' are auto-redirected by civitai)
|
||||
}
|
||||
|
||||
// Pattern: /api/download/models/<id> — append token if missing
|
||||
if (parsed.pathname.startsWith("/api/download/") && token) {
|
||||
if (!parsed.searchParams.has("token")) {
|
||||
parsed.searchParams.set("token", token);
|
||||
}
|
||||
} else if (token && !parsed.searchParams.has("token")) {
|
||||
// For non-API URLs (shouldn't normally happen after the conversion above),
|
||||
// still try to add the token — CivitAI's CDN often accepts it as a query param
|
||||
parsed.searchParams.set("token", token);
|
||||
}
|
||||
|
||||
const finalUrl = parsed.toString();
|
||||
const wasConverted = modelMatch != null;
|
||||
const note = wasConverted
|
||||
? `converted model page → API download URL${token ? ", added API token" : ""}`
|
||||
: token && parsed.searchParams.has("token")
|
||||
? "added CivitAI API token"
|
||||
: "";
|
||||
|
||||
return { url: finalUrl, note };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory download tracker
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// llama models can be huge (10-30 GB), so a download takes minutes. We use an
|
||||
// in-memory Map to track active downloads (since the dashboard is a single
|
||||
// Node process — multi-instance isn't a concern here).
|
||||
//
|
||||
// Frontend can poll `GET /api/models/download/status` every 1s for progress,
|
||||
// or open `GET /api/models/download/status?stream=1` for SSE push.
|
||||
|
||||
export interface DownloadJob {
|
||||
id: string;
|
||||
/** The URL we actually curl (after CivitAI token / conversion). */
|
||||
url: string;
|
||||
/** Original URL the user pasted (only set if we modified it). */
|
||||
originalUrl?: string;
|
||||
/** Note explaining what we did to the URL (e.g. "added CivitAI token"). */
|
||||
urlNote?: string;
|
||||
filename: string;
|
||||
status: "queued" | "downloading" | "done" | "failed" | "cancelled";
|
||||
bytesDownloaded: number;
|
||||
bytesTotal: number | null;
|
||||
percent: number;
|
||||
speedBytesPerSec: number | null;
|
||||
startedAt: number;
|
||||
finishedAt: number | null;
|
||||
error: string | null;
|
||||
// Internal — child process handle for cancellation
|
||||
_child?: ReturnType<typeof spawn>;
|
||||
// Subscribers notified on every progress event
|
||||
_subscribers: Set<(job: DownloadJob) => void>;
|
||||
}
|
||||
|
||||
const _jobs = new Map<string, DownloadJob>();
|
||||
|
||||
// Keep only the last 50 finished jobs to avoid memory bloat
|
||||
const MAX_HISTORY = 50;
|
||||
|
||||
/**
|
||||
* Start downloading a .gguf file from a URL into the llama_models directory.
|
||||
*
|
||||
* Uses `curl` (available in Alpine runtime image) which gives us reliable
|
||||
* progress reporting via `--progress-bar` + parsing stderr.
|
||||
*
|
||||
* Returns the job object. Caller can poll `.status` / `.percent` or
|
||||
* subscribe via `subscribeToJob(id, callback)`.
|
||||
*/
|
||||
export async function startModelDownload(
|
||||
rawUrl: string,
|
||||
filenameOverride?: string
|
||||
): Promise<DownloadJob> {
|
||||
// Load settings to get CivitAI token (if any)
|
||||
const settings = await loadSettings();
|
||||
|
||||
// If this is a CivitAI URL, transform it (model page → API download URL,
|
||||
// append token if missing, normalize .red → .com)
|
||||
const { url, note: urlNote } = prepareCivitaiUrl(
|
||||
rawUrl,
|
||||
settings.civitaiToken || ""
|
||||
);
|
||||
|
||||
// Validate URL
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
throw new Error(`invalid URL: ${url}`);
|
||||
}
|
||||
if (!/^https?:$/.test(parsed.protocol)) {
|
||||
throw new Error(`only http(s) URLs are supported, got: ${parsed.protocol}`);
|
||||
}
|
||||
|
||||
// Determine filename
|
||||
let filename: string;
|
||||
if (filenameOverride) {
|
||||
filename = filenameOverride;
|
||||
} else {
|
||||
// Use last URL path segment, strip query string
|
||||
const pathname = parsed.pathname;
|
||||
const last = pathname.split("/").filter(Boolean).pop() || "model.gguf";
|
||||
filename = last;
|
||||
}
|
||||
|
||||
// Sanitize: only allow .gguf extension, no path traversal
|
||||
filename = path.basename(filename).replace(/[^\w.\-]/g, "_");
|
||||
if (!filename.toLowerCase().endsWith(".gguf")) {
|
||||
// Common case: URL ends in .gguf.aix or similar. If not .gguf, append.
|
||||
// Many HuggingFace URLs use ?download=true; ignore query.
|
||||
filename = `${filename}.gguf`;
|
||||
}
|
||||
|
||||
// Check we don't overwrite an existing file (race-safe via atomic rename)
|
||||
const dest = path.join(LLAMA_MODELS_DIR, filename);
|
||||
const tmpDest = `${dest}.part`;
|
||||
|
||||
const id = `dl-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
const job: DownloadJob = {
|
||||
id,
|
||||
url,
|
||||
originalUrl: rawUrl !== url ? rawUrl : undefined,
|
||||
urlNote: urlNote || undefined,
|
||||
filename,
|
||||
status: "queued",
|
||||
bytesDownloaded: 0,
|
||||
bytesTotal: null,
|
||||
percent: 0,
|
||||
speedBytesPerSec: null,
|
||||
startedAt: Date.now(),
|
||||
finishedAt: null,
|
||||
error: null,
|
||||
_subscribers: new Set(),
|
||||
};
|
||||
_jobs.set(id, job);
|
||||
|
||||
// Start curl asynchronously. We don't await — return immediately so the
|
||||
// caller gets the job id and can poll for progress.
|
||||
void runCurl(job, url, tmpDest, dest);
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
async function runCurl(
|
||||
job: DownloadJob,
|
||||
url: string,
|
||||
tmpDest: string,
|
||||
finalDest: string
|
||||
) {
|
||||
// Make sure target dir exists
|
||||
try {
|
||||
await fs.mkdir(path.dirname(tmpDest), { recursive: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
// Remove stale .part file from a previous interrupted download
|
||||
try {
|
||||
await fs.unlink(tmpDest);
|
||||
} catch {
|
||||
/* not present — fine */
|
||||
}
|
||||
|
||||
// curl options:
|
||||
// -L follow redirects (HuggingFace / HF + Cloudflare use them)
|
||||
// -f fail on HTTP 4xx/5xx instead of writing error page
|
||||
// -S show errors
|
||||
// -o <file> output file
|
||||
// --progress-bar progress to stderr (carriage-return updated single line)
|
||||
// We don't use --silent because we want progress.
|
||||
const args = ["-L", "-f", "-S", "--progress-bar", "-o", tmpDest, url];
|
||||
|
||||
const child = spawn("curl", args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
job._child = child;
|
||||
job.status = "downloading";
|
||||
notify(job);
|
||||
|
||||
// Parse curl --progress-bar output (stderr). Format looks like:
|
||||
// ################################# 54.3%
|
||||
// ################################### 100.0%
|
||||
// Or with size info if Content-Length present:
|
||||
// 12.3M 54.3% ... (we get just the bar by default with --progress-bar)
|
||||
let stderrBuf = "";
|
||||
child.stderr.on("data", async (chunk: Buffer) => {
|
||||
stderrBuf += chunk.toString("utf-8");
|
||||
// Process complete lines (curl uses \r for in-place updates)
|
||||
const lines = stderrBuf.split(/\r\n|\r|\n/);
|
||||
stderrBuf = lines.pop() || "";
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
// Try to extract percent: looks like "###...### 54.3%"
|
||||
const m = trimmed.match(/(\d+(?:\.\d+)?)\s*%$/);
|
||||
if (m) {
|
||||
job.percent = parseFloat(m[1]);
|
||||
notify(job);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to extract size info (curl with -progress-bar shows this when
|
||||
// content-length is known):
|
||||
// 123 100M ...
|
||||
const sizeMatch = trimmed.match(
|
||||
/^\s*(\d+)\s+(\d+(?:\.\d+)?[KMGTP]?B?)\s+(\d+(?:\.\d+)?[KMGTP]?B?\/s)/
|
||||
);
|
||||
if (sizeMatch) {
|
||||
job.bytesDownloaded = parseInt(sizeMatch[1], 10);
|
||||
job.speedBytesPerSec = parseSize(sizeMatch[3]);
|
||||
notify(job);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Also get Content-Length via curl -I for accurate total bytes
|
||||
// (curl --progress-bar doesn't always show total bytes)
|
||||
void getTotalBytes(url).then((total) => {
|
||||
if (total != null) {
|
||||
job.bytesTotal = total;
|
||||
notify(job);
|
||||
}
|
||||
});
|
||||
|
||||
// Periodically stat the .part file for actual bytes downloaded (more
|
||||
// reliable than parsing curl output for size)
|
||||
const statInterval = setInterval(async () => {
|
||||
if (job.status !== "downloading") {
|
||||
clearInterval(statInterval);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const stat = await fs.stat(tmpDest);
|
||||
job.bytesDownloaded = stat.size;
|
||||
if (job.bytesTotal && job.bytesTotal > 0) {
|
||||
job.percent = Math.min(100, (stat.size / job.bytesTotal) * 100);
|
||||
}
|
||||
notify(job);
|
||||
} catch {
|
||||
/* file might not exist yet */
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
child.on("error", (err) => {
|
||||
clearInterval(statInterval);
|
||||
job.status = "failed";
|
||||
job.error = `spawn error: ${err.message}`;
|
||||
job.finishedAt = Date.now();
|
||||
notify(job);
|
||||
cleanupJob(job);
|
||||
resolve();
|
||||
});
|
||||
child.on("exit", (code, signal) => {
|
||||
clearInterval(statInterval);
|
||||
if (job.status === "cancelled") {
|
||||
// Already marked cancelled by cancelDownload()
|
||||
try {
|
||||
fs.unlink(tmpDest);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
job.finishedAt = Date.now();
|
||||
notify(job);
|
||||
cleanupJob(job);
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
if (code === 0) {
|
||||
// Move .part → final name
|
||||
fs.rename(tmpDest, finalDest)
|
||||
.then(() => {
|
||||
// Get final size
|
||||
return fs.stat(finalDest);
|
||||
})
|
||||
.then((stat) => {
|
||||
job.bytesDownloaded = stat.size;
|
||||
if (job.bytesTotal && job.bytesTotal > 0) {
|
||||
job.percent = 100;
|
||||
} else {
|
||||
job.bytesTotal = stat.size;
|
||||
job.percent = 100;
|
||||
}
|
||||
job.status = "done";
|
||||
job.finishedAt = Date.now();
|
||||
notify(job);
|
||||
cleanupJob(job);
|
||||
resolve();
|
||||
})
|
||||
.catch((err) => {
|
||||
job.status = "failed";
|
||||
job.error = `rename failed: ${err.message}`;
|
||||
job.finishedAt = Date.now();
|
||||
notify(job);
|
||||
cleanupJob(job);
|
||||
resolve();
|
||||
});
|
||||
} else {
|
||||
job.status = "failed";
|
||||
job.error = signal
|
||||
? `terminated by signal ${signal}`
|
||||
: `curl exited with code ${code}`;
|
||||
job.finishedAt = Date.now();
|
||||
notify(job);
|
||||
// Clean up partial file
|
||||
try {
|
||||
fs.unlink(tmpDest);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
cleanupJob(job);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function getTotalBytes(url: string): Promise<number | null> {
|
||||
// HEAD request via curl -I -L -s -o /dev/null -w "%{size_download}\n"
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn("curl", [
|
||||
"-I",
|
||||
"-L",
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{size_download}",
|
||||
url,
|
||||
]);
|
||||
let out = "";
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
out += chunk.toString("utf-8");
|
||||
});
|
||||
child.on("error", () => resolve(null));
|
||||
child.on("exit", () => {
|
||||
const n = parseInt(out.trim(), 10);
|
||||
resolve(Number.isFinite(n) && n > 0 ? n : null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function parseSize(s: string): number | null {
|
||||
// Parse "1.5M/s" / "500K/s" / "100B/s"
|
||||
const m = s.match(/^([\d.]+)([KMGTP]?B?)\/s$/i);
|
||||
if (!m) return null;
|
||||
const num = parseFloat(m[1]);
|
||||
const unit = m[2].toUpperCase();
|
||||
const mult: Record<string, number> = {
|
||||
"": 1,
|
||||
B: 1,
|
||||
KB: 1024,
|
||||
MB: 1024 ** 2,
|
||||
GB: 1024 ** 3,
|
||||
TB: 1024 ** 4,
|
||||
};
|
||||
return num * (mult[unit] || 1);
|
||||
}
|
||||
|
||||
function notify(job: DownloadJob) {
|
||||
for (const cb of job._subscribers) {
|
||||
try {
|
||||
cb(job);
|
||||
} catch {
|
||||
/* ignore subscriber errors */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupJob(job: DownloadJob) {
|
||||
// Don't remove from _jobs immediately — let the frontend pick up the final
|
||||
// status. We'll prune old finished jobs on the next startModelDownload call.
|
||||
pruneOldJobs();
|
||||
}
|
||||
|
||||
function pruneOldJobs() {
|
||||
const finished = Array.from(_jobs.values()).filter(
|
||||
(j) => j.status === "done" || j.status === "failed" || j.status === "cancelled"
|
||||
);
|
||||
if (finished.length > MAX_HISTORY) {
|
||||
// Sort by finishedAt descending and keep the newest MAX_HISTORY
|
||||
finished
|
||||
.sort((a, b) => (b.finishedAt || 0) - (a.finishedAt || 0))
|
||||
.slice(MAX_HISTORY)
|
||||
.forEach((j) => {
|
||||
_jobs.delete(j.id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function getJob(id: string): DownloadJob | undefined {
|
||||
return _jobs.get(id);
|
||||
}
|
||||
|
||||
export function listJobs(): DownloadJob[] {
|
||||
return Array.from(_jobs.values());
|
||||
}
|
||||
|
||||
export function subscribeToJob(
|
||||
id: string,
|
||||
cb: (job: DownloadJob) => void
|
||||
): () => void {
|
||||
const job = _jobs.get(id);
|
||||
if (!job) return () => {};
|
||||
job._subscribers.add(cb);
|
||||
return () => {
|
||||
job._subscribers.delete(cb);
|
||||
};
|
||||
}
|
||||
|
||||
export function cancelDownload(id: string): boolean {
|
||||
const job = _jobs.get(id);
|
||||
if (!job) return false;
|
||||
if (job.status !== "downloading" && job.status !== "queued") return false;
|
||||
job.status = "cancelled";
|
||||
try {
|
||||
job._child?.kill("SIGTERM");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
notify(job);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize the public-facing view of a job (strip internal fields).
|
||||
*/
|
||||
export function publicJob(job: DownloadJob): Omit<DownloadJob, "_child" | "_subscribers"> {
|
||||
const { _child: _c, _subscribers: _s, ...rest } = job;
|
||||
void _c;
|
||||
void _s;
|
||||
return rest;
|
||||
}
|
||||
Reference in New Issue
Block a user