diff --git a/dashboard/Dockerfile b/dashboard/Dockerfile index 647a6b7..7d589ed 100644 --- a/dashboard/Dockerfile +++ b/dashboard/Dockerfile @@ -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 diff --git a/dashboard/src/app/api/models/download/[id]/cancel/route.ts b/dashboard/src/app/api/models/download/[id]/cancel/route.ts new file mode 100644 index 0000000..6d225ad --- /dev/null +++ b/dashboard/src/app/api/models/download/[id]/cancel/route.ts @@ -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) }); +} diff --git a/dashboard/src/app/api/models/download/[id]/stream/route.ts b/dashboard/src/app/api/models/download/[id]/stream/route.ts new file mode 100644 index 0000000..957d2e3 --- /dev/null +++ b/dashboard/src/app/api/models/download/[id]/stream/route.ts @@ -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({ + 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", + }, + }); +} diff --git a/dashboard/src/app/api/models/download/route.ts b/dashboard/src/app/api/models/download/route.ts new file mode 100644 index 0000000..e9754a5 --- /dev/null +++ b/dashboard/src/app/api/models/download/route.ts @@ -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 .part + * + * 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 } + ); + } +} diff --git a/dashboard/src/app/api/models/download/status/route.ts b/dashboard/src/app/api/models/download/status/route.ts new file mode 100644 index 0000000..4e68a3b --- /dev/null +++ b/dashboard/src/app/api/models/download/status/route.ts @@ -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, + }); +} diff --git a/dashboard/src/app/page.tsx b/dashboard/src/app/page.tsx index 4aa11a1..9984484 100644 --- a/dashboard/src/app/page.tsx +++ b/dashboard/src/app/page.tsx @@ -141,6 +141,20 @@ interface ComfyQueueEntry { created_at?: string; } +interface DownloadJob { + id: string; + url: 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; +} + const DEFAULT_CONFIG: DashboardConfig = { model: "model.gguf", ctxSize: 64000, @@ -244,6 +258,11 @@ export default function DashboardPage() { percent: number; } | null>(null); + // Download state (.gguf from URL) + const [downloadJobs, setDownloadJobs] = React.useState([]); + const [downloadUrl, setDownloadUrl] = React.useState(""); + const downloadsActiveRef = React.useRef(false); + const llamaContainer = containers.find((c) => c.role === "llama") || null; const comfyContainer = containers.find((c) => c.role === "comfyui") || null; @@ -644,6 +663,151 @@ 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>(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); + } + } + async function handleSavePreset() { if (!presetName.trim()) { showToast("error", "Preset name required"); @@ -964,6 +1128,11 @@ export default function DashboardPage() { onSelectModel={(m) => update("model", m)} onUpload={handleUpload} onDelete={handleDeleteModel} + downloadJobs={downloadJobs} + downloadUrl={downloadUrl} + setDownloadUrl={setDownloadUrl} + onDownload={handleDownload} + onCancelDownload={handleCancelDownload} /> @@ -1728,6 +1897,11 @@ function ModelsTab({ onSelectModel, onUpload, onDelete, + downloadJobs, + downloadUrl, + setDownloadUrl, + onDownload, + onCancelDownload, }: { models: ModelFile[]; config: DashboardConfig; @@ -1736,6 +1910,11 @@ 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; }) { const fileInputRef = React.useRef(null); const [dragOver, setDragOver] = React.useState(false); @@ -1745,6 +1924,16 @@ function ModelsTab({ 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 ( @@ -1812,6 +2001,70 @@ function ModelsTab({ )} + {/* Download from URL */} +
+
+ + + Download from URL + +

+ Fetch a .gguf file from HuggingFace, GitHub releases, or any + direct URL. Uses curl with redirect-following and atomic rename. +

+
+
+
+ + setDownloadUrl(e.target.value)} + placeholder="https://huggingface.co/.../model.gguf" + className="font-mono text-xs" + onKeyDown={(e) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + onDownload(); + } + }} + /> +
+ +
+ + {/* Active downloads */} + {activeDownloads.length > 0 && ( +
+ {activeDownloads.map((job) => ( + onCancelDownload(job.id)} + /> + ))} +
+ )} + + {/* Recently finished downloads */} + {finishedDownloads.length > 0 && ( +
+ +
+ {finishedDownloads.map((job) => ( + + ))} +
+
+ )} +
+ {/* Models table */} {models.length === 0 ? (
@@ -1890,6 +2143,124 @@ 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 ( +
+
+ + {job.status} + + {job.filename} + {isActive && onCancel && ( + + )} +
+ + {!compact && isActive && ( + <> +
+
+
+
+ {progressText} + + {job.percent > 0 ? `${job.percent.toFixed(1)}%` : ""} + {speedText ? ` · ${speedText}` : ""} + {` · ${durationSec.toFixed(0)}s elapsed`} + +
+ + )} + + {!compact && (isFailed || isCancelled) && job.error && ( +

{job.error}

+ )} + + {compact && ( +
+ {isDone && formatBytes(job.bytesDownloaded)} + {isFailed && job.error && ` · ${job.error.slice(0, 80)}`} + {isCancelled && " · cancelled"} + {` · ${durationSec.toFixed(0)}s`} +
+ )} + + {/* Show source URL for reference (compact mode hides it) */} + {!compact && ( + + )} +
+ ); +} + // --------------------------------------------------------------------------- // Comfy Tab // --------------------------------------------------------------------------- diff --git a/dashboard/src/lib/downloads.ts b/dashboard/src/lib/downloads.ts new file mode 100644 index 0000000..9b7f41b --- /dev/null +++ b/dashboard/src/lib/downloads.ts @@ -0,0 +1,402 @@ +import { spawn } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { LLAMA_MODELS_DIR } from "./docker"; + +// --------------------------------------------------------------------------- +// 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; + url: 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; + // Subscribers notified on every progress event + _subscribers: Set<(job: DownloadJob) => void>; +} + +const _jobs = new Map(); + +// 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( + url: string, + filenameOverride?: string +): Promise { + // 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, + 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 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((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 { + // 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 = { + "": 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 { + const { _child: _c, _subscribers: _s, ...rest } = job; + void _c; + void _s; + return rest; +}