feat(dashboard): download .gguf models from URL with live progress

## What

Adds a 'Download from URL' section to the Models tab. Paste a HuggingFace
URL (or any direct .gguf URL) and the dashboard fetches it into
gpu/llama_models/ with live progress, speed, ETA, and cancel support.

## Backend

### `dashboard/src/lib/downloads.ts` (new)

In-memory download tracker. Single Node process, so no DB needed.

- `startModelDownload(url, filenameOverride?)` — validates URL (http/https
  only), sanitizes filename (.gguf only, no path traversal), spawns curl:
    curl -L -f -S --progress-bar -o <dest>.part <url>

  curl follows redirects (HuggingFace, Cloudflare R2), fails on HTTP 4xx/5xx,
  writes to <dest>.part for atomic rename on success.

- `subscribeToJob(id, cb)` — pub/sub for progress updates
- `cancelDownload(id)` — sends SIGTERM to curl, deletes .part file
- `listJobs()` / `getJob(id)` — read access
- `publicJob(job)` — strips internal fields (_child, _subscribers) before
  returning to API caller

Progress tracking:
- Parses curl --progress-bar stderr for percent (looks like '####  54.3%')
- Periodically stats the .part file for actual bytes downloaded (more
  reliable than parsing curl output)
- Does HEAD request via curl -I to get Content-Length for total bytes

History: keeps last 50 finished jobs to avoid memory bloat.

### API routes (all under /api/models/download/)

- `POST /api/models/download` — body: {url, filename?}, returns job
- `GET /api/models/download/status` — returns all jobs (active + recent)
- `GET /api/models/download/[id]/stream` — SSE push of progress events:
    event: progress
    data: {id, status, percent, bytesDownloaded, bytesTotal, ...}

  Plus 'end' event when job reaches terminal state.
- `POST /api/models/download/[id]/cancel` — SIGTERMs curl, deletes .part

### Dockerfile

Added `curl` to the apk add list — needed for the actual download.
`wget` was already present (kept for compatibility with the rest of the
codebase that uses it for health checks).

## Frontend

### ModelsTab additions

- URL input + Download button — Enter to submit
- 'Active downloads' list with progress bars, bytes downloaded / total,
  speed (e.g. '1.5 MB/s'), elapsed time, Cancel button
- 'Recent' list (last 5 finished) — shows final size + duration

### DownloadJobRow component

Reusable row for both active and finished jobs. Two modes:
- Full (default): badge + filename + progress bar + stats + source URL link
- Compact: smaller, just badge + filename + final size/duration

### Main component state

- `downloadJobs: DownloadJob[]` — full job list
- `downloadUrl: string` — URL input state
- `downloadsActiveRef` — guards SSE subscription lifecycle
- `downloadSSERef` — Map<jobId, EventSource> for cleanup

On mount, fetches existing download jobs (in case page was refreshed
mid-download). For each active job, opens an EventSource subscription.
On 'end' event, closes the SSE and refreshes the models list (file
should now be on disk).

### Handlers

- `handleDownload()` — POST /api/models/download, then start SSE
- `handleCancelDownload(id)` — POST /api/models/download/[id]/cancel,
  closes SSE, refreshes job list
- `refreshDownloadJobs()` — GET /api/models/download/status, manages
  SSE subscriptions based on which jobs are active

## Verification

- `npm run build` — OK, 25 routes (4 new download routes)
- `bash dashboard/validate-build.sh` — all 8 COPY sources ✓, standalone ✓

## After deploy

```sh
git pull && sh build.sh
docker compose up -d --force-recreate dashboard
```

Open Models tab, paste a URL like
'https://huggingface.co/bartowski/Qwen2.5-7B-Instruct-Q8_0.gguf' (or any
direct .gguf link), click Download. Watch progress live, cancel if needed.

File appears in the models list automatically when download completes.

## Files changed

- dashboard/src/lib/downloads.ts — new (download tracker + curl wrapper)
- dashboard/src/app/api/models/download/route.ts — new (POST start)
- dashboard/src/app/api/models/download/status/route.ts — new (GET list)
- dashboard/src/app/api/models/download/[id]/stream/route.ts — new (SSE)
- dashboard/src/app/api/models/download/[id]/cancel/route.ts — new (POST cancel)
- dashboard/Dockerfile — added curl to apk add
- dashboard/src/app/page.tsx — ModelsTab gets Download section,
  DownloadJobRow component, DownloadJob type, SSE-based handlers
This commit is contained in:
Z User
2026-10-24 01:34:06 +00:00
parent 405c88f086
commit 6c4e1c8f64
7 changed files with 960 additions and 0 deletions

View File

@@ -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<DownloadJob[]>([]);
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<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);
}
}
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}
/>
</TabsContent>
@@ -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<HTMLInputElement | null>(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 (
<Card>
<CardHeader>
@@ -1812,6 +2001,70 @@ function ModelsTab({
)}
</div>
{/* Download from URL */}
<div className="rounded-md border bg-muted/20 p-4 space-y-3">
<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. Uses curl with redirect-following and atomic rename.
</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"
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>
{/* 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 +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 (
<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>
)}
{/* Show source URL for reference (compact mode hides it) */}
{!compact && (
<div className="text-[10px] text-muted-foreground font-mono truncate">
<a
href={job.url}
target="_blank"
rel="noopener noreferrer"
className="hover:underline"
>
{job.url}
</a>
</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Comfy Tab
// ---------------------------------------------------------------------------