From 12fb97314b70da8683f48aed329181ef470337c6 Mon Sep 17 00:00:00 2001 From: Z User Date: Sat, 24 Oct 2026 01:53:37 +0000 Subject: [PATCH] fix: comfyui mount uses HOST_PROJECT_PATH + add CivitAI download support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 1. ComfyUI mount fix ### Problem When the dashboard called `docker compose up -d comfyui`, the comfyui service's volume mounts used ${COMFY_BASE_HOST:-./gpu/comfy} and ${COMFY_RUN_HOST:-./comfyui/run}. Without explicit env overrides, compose resolved these to './gpu/comfy' relative to the CWD of the dashboard container (= /project inside the container). Docker daemon on the host tried to mount /project/gpu/comfy — but /project only exists inside the dashboard container, not on the host. The result: comfyui mounted to non-existent paths on the host, all models missing. ### Fix `startService('comfyui')` now explicitly passes the same env vars that `gpuctl start comfy` does, mirroring `ssh/scripts/comfy.sh`: - COMFY_BASE_HOST=$HOST_PROJECT_PATH/gpu/comfy - COMFY_RUN_HOST=$HOST_PROJECT_PATH/comfyui/run These are passed as extra env to `runCompose`, which forwards them to the compose subprocess. Compose then resolves the volume mounts to the real host path. ## 2. CivitAI download support ### Why CivitAI URLs are special: - `https://civitai.com/models/12345` is a model PAGE (HTML), not the file. curl would download the HTML page instead of the .gguf. - The actual file is at `https://civitai.com/api/download/models/12345` which returns a 302 redirect to a signed Cloudflare URL. - Downloads require an API token: `?token=XXX`. Without it, NSFW / gated models fail with 401. - `civitai.red` is a mirror — it doesn't accept API requests the same way. ### Fix #### Settings storage New `DashboardSettings` interface with `civitaiToken: string`. Persisted to `gpu/dashboard/settings.json` (separate from the llama config — download settings shouldn't be part of a llama preset). - `loadSettings()` / `saveSettings()` in `dashboard/src/lib/downloads.ts` - Cache like the .env loader (read once per process lifetime) #### URL transformation `prepareCivitaiUrl(rawUrl, token)` — handles all CivitAI URL shapes: 1. `https://civitai.com/models/12345` (model page) → converts to `https://civitai.com/api/download/models/12345` (preserves any `?modelVersionId=...` query param) 2. `https://civitai.com/api/download/models/12345` → appends `?token=XXX` if missing 3. `https://civitai.red/models/12345` → normalizes host to civitai.com (mirror doesn't accept API requests the same way) 4. Non-CivitAI URLs (HuggingFace, GitHub releases, etc.) → passed through unchanged Returns `{ url, note }` where note explains what we did (e.g. 'converted model page → API download URL, added API token'). #### startModelDownload integration `startModelDownload()` now: 1. Loads settings (to get the token) 2. Calls `prepareCivitaiUrl()` on the input URL 3. Uses the transformed URL for curl 4. Records `originalUrl` and `urlNote` on the job object (shown in UI) #### API routes (new) `/api/settings`: - `GET` — returns the persisted settings (civitai token etc) - `PUT` — updates settings (body: `{ civitaiToken: '...' }`) - `POST { action: 'preview-url', url: '...' }` — returns what the URL would be transformed into, without starting a download. Used by the frontend for live URL preview as the user types. #### Frontend - **Settings UI** in the Models tab: 'CivitAI token' button (with badge showing 'set' / 'empty'). Click to expand a form with password input, Save / Clear buttons, and a link to https://civitai.com/user/account to get a token. - **URL preview**: as the user types in the download URL field, a debounced call to `POST /api/settings {action:'preview-url'}` runs. If the URL will be transformed (e.g. civitai.com/models/12345 → civitai.com/api/download/models/12345?token=...), a preview card appears below the input showing the transformed URL + note. - **DownloadJobRow**: shows `originalUrl` (struck through) → `url` (the actual URL curled), plus the `urlNote` as italic text. So the user can see what happened to their pasted URL. ## Verification - `npm run build` — OK, all 26 routes (1 new /api/settings route) - `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 ``` For ComfyUI: 1. Click 'Start Comfy' (or Start button in System tab → comfyui row) 2. Check `docker inspect | grep Mounts` — should show $HOST_PROJECT_PATH/gpu/comfy and $HOST_PROJECT_PATH/comfyui/run For CivitAI: 1. Open Models tab → 'CivitAI token' button → paste your token from https://civitai.com/user/account → API Keys → Save 2. Paste any CivitAI URL (model page or API download URL) in the URL field 3. Watch the URL preview card show the transformed URL 4. Click Download — file fetches with token auth ## Files changed - dashboard/src/lib/docker.ts — added DASHBOARD_SETTINGS_PATH export, startService() now passes COMFY_BASE_HOST / COMFY_RUN_HOST for comfyui - dashboard/src/lib/downloads.ts — new DashboardSettings interface, loadSettings / saveSettings, prepareCivitaiUrl, startModelDownload integrates URL transformation - dashboard/src/app/api/settings/route.ts — new (GET/PUT/POST preview) - dashboard/src/app/page.tsx — settings state, civitai token UI, URL preview, DownloadJobRow shows originalUrl + urlNote --- dashboard/src/app/api/settings/route.ts | 78 ++++++++ dashboard/src/app/page.tsx | 227 ++++++++++++++++++++++-- dashboard/src/lib/docker.ts | 27 ++- dashboard/src/lib/downloads.ts | 158 ++++++++++++++++- 4 files changed, 477 insertions(+), 13 deletions(-) create mode 100644 dashboard/src/app/api/settings/route.ts diff --git a/dashboard/src/app/api/settings/route.ts b/dashboard/src/app/api/settings/route.ts new file mode 100644 index 0000000..5890244 --- /dev/null +++ b/dashboard/src/app/api/settings/route.ts @@ -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 — 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; + 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: "" } + * + * 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 }); +} diff --git a/dashboard/src/app/page.tsx b/dashboard/src/app/page.tsx index 9984484..49259d7 100644 --- a/dashboard/src/app/page.tsx +++ b/dashboard/src/app/page.tsx @@ -7,6 +7,7 @@ import { CpuIcon, Gauge, HardDrive, + Key as KeyIcon, Layers, MessageSquare, Moon, @@ -144,6 +145,8 @@ interface ComfyQueueEntry { interface DownloadJob { id: string; url: string; + originalUrl?: string; + urlNote?: string; filename: string; status: "queued" | "downloading" | "done" | "failed" | "cancelled"; bytesDownloaded: number; @@ -155,6 +158,17 @@ interface DownloadJob { 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, @@ -263,6 +277,12 @@ export default function DashboardPage() { const [downloadUrl, setDownloadUrl] = React.useState(""); const downloadsActiveRef = React.useRef(false); + // Settings (civitai token etc) + const [settings, setSettings] = React.useState({ + civitaiToken: "", + }); + const [urlPreview, setUrlPreview] = React.useState(null); + const llamaContainer = containers.find((c) => c.role === "llama") || null; const comfyContainer = containers.find((c) => c.role === "comfyui") || null; @@ -808,6 +828,83 @@ export default function DashboardPage() { } } + // --------------------------------------------------------------------------- + // 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 | 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"); @@ -1133,6 +1230,9 @@ export default function DashboardPage() { setDownloadUrl={setDownloadUrl} onDownload={handleDownload} onCancelDownload={handleCancelDownload} + civitaiToken={settings.civitaiToken} + onSaveCivitaiToken={handleSaveCivitaiToken} + urlPreview={urlPreview} /> @@ -1902,6 +2002,9 @@ function ModelsTab({ setDownloadUrl, onDownload, onCancelDownload, + civitaiToken, + onSaveCivitaiToken, + urlPreview, }: { models: ModelFile[]; config: DashboardConfig; @@ -1915,9 +2018,18 @@ function ModelsTab({ setDownloadUrl: (v: string) => void; onDownload: () => void; onCancelDownload: (id: string) => void; + civitaiToken: string; + onSaveCivitaiToken: (token: string) => void; + urlPreview: UrlPreview | null; }) { const fileInputRef = React.useRef(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; @@ -2003,16 +2115,83 @@ 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. -

+
+
+ + + Download from URL + +

+ 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. +

+
+
+ + {showCivitaiSettings && ( +
+ + setCivitaiTokenDraft(e.target.value)} + placeholder="Get it from https://civitai.com/user/account → API Keys" + className="font-mono text-xs" + /> +
+ + + + Get token ↗ + +
+

+ Stored locally in gpu/dashboard/settings.json. + Used to authenticate CivitAI downloads. Without it, NSFW / + gated models will fail with 401. +

+
+ )} +
@@ -2020,7 +2199,7 @@ function ModelsTab({ id="download-url" value={downloadUrl} onChange={(e) => setDownloadUrl(e.target.value)} - placeholder="https://huggingface.co/.../model.gguf" + 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) { @@ -2039,6 +2218,21 @@ function ModelsTab({
+ {/* URL preview — shows what we'll actually curl */} + {urlPreview && urlPreview.original !== urlPreview.transformed && ( +
+
+ + {urlPreview.isCivitai ? "CivitAI" : "transformed"} + + {urlPreview.note} +
+
+                {urlPreview.transformed}
+              
+
+ )} + {/* Active downloads */} {activeDownloads.length > 0 && (
@@ -2244,9 +2438,22 @@ function DownloadJobRow({
)} + {/* URL transformation note (e.g. "added CivitAI token") */} + {!compact && job.urlNote && ( +
+ {job.urlNote} +
+ )} + {/* Show source URL for reference (compact mode hides it) */} {!compact && (
+ {job.originalUrl && ( + + {job.originalUrl} + + )} + {job.originalUrl && →} = {}; + 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: diff --git a/dashboard/src/lib/downloads.ts b/dashboard/src/lib/downloads.ts index 9b7f41b..7a0f6a3 100644 --- a/dashboard/src/lib/downloads.ts +++ b/dashboard/src/lib/downloads.ts @@ -1,7 +1,144 @@ import { spawn } from "node:child_process"; import { promises as fs } from "node:fs"; import path from "node:path"; -import { LLAMA_MODELS_DIR } from "./docker"; +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 { + 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 { + 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/ (model page) → convert to /api/download/models/ + // Pattern 2: /models// (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/ — 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 @@ -16,7 +153,12 @@ import { LLAMA_MODELS_DIR } from "./docker"; 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; @@ -47,9 +189,19 @@ const MAX_HISTORY = 50; * subscribe via `subscribeToJob(id, callback)`. */ export async function startModelDownload( - url: string, + rawUrl: string, filenameOverride?: string ): Promise { + // 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 { @@ -88,6 +240,8 @@ export async function startModelDownload( const job: DownloadJob = { id, url, + originalUrl: rawUrl !== url ? rawUrl : undefined, + urlNote: urlNote || undefined, filename, status: "queued", bytesDownloaded: 0, -- 2.49.1