From cb92e32bdfc7d1738beed096808c9357233ee17a Mon Sep 17 00:00:00 2001 From: Z User Date: Sat, 24 Oct 2026 02:35:37 +0000 Subject: [PATCH] feat(comfy): CivitAI URL transformation + token support for comfy models MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem 'цивитай в comfy models нужен скорее' — the CivitAI URL transformation (model page → API download URL, token append) was only applied to llama model downloads via `/api/models/download`. ComfyUI model downloads via `/api/comfy/models/add` just passed the raw URL straight to model-worker, so CivitAI model page URLs would download HTML instead of the actual file, and gated/NSFW models would 401 without a token. ## Fix ### Backend #### `dashboard/src/lib/docker.ts` — addComfyModel() Now applies the same `prepareCivitaiUrl()` transformation as `startModelDownload()`: 1. Loads settings (to get the saved civitaiToken) 2. Calls `prepareCivitaiUrl(rawUrl, token)`: - civitai.com/models/12345 → civitai.com/api/download/models/12345 - civitai.red/... → normalize host to civitai.com - append ?token=XXX if missing 3. Passes the transformed URL to `modelWorkerExec('add', url, type)` 4. Returns `originalUrl`, `transformedUrl`, `urlNote` in the response so the frontend can show what happened Uses lazy `await import('./downloads')` to avoid a circular import between docker.ts (which exports paths) and downloads.ts (which imports them). #### `dashboard/src/app/api/comfy/models/add/route.ts` Returns the transformation metadata (`originalUrl`, `transformedUrl`, `urlNote`) in the JSON response. ### Frontend #### `dashboard/src/app/page.tsx` - New state: `comfyUrlPreview` — separate from `urlPreview` (which is for the llama Models tab) so switching tabs doesn't mix them up. - New debounced effect: watches `comfyAddUrl` and calls `POST /api/settings {action:'preview-url'}` to get the transformed URL. - `handleComfyAddModel()` now reads `urlNote` and `transformedUrl` from the response and includes them in the toast message (multi-line) so the user sees what happened to their pasted URL. - `` now accepts `civitaiToken`, `onSaveCivitaiToken`, and `urlPreview` props. - ComfyTab 'Queue Download' section: - 'CivitAI token' button (with badge 'set' / 'empty') in the header — opens a settings panel with password input, Save/Clear buttons, and a link to https://civitai.com/user/account. - The settings panel notes that the token is shared with the llama-models downloader (same settings.json). - URL input placeholder updated to show CivitAI URLs are accepted. - Enter key in the URL field queues the download (no need to click Queue button). - URL preview card appears below the input when the URL will be transformed (e.g. civitai.com/models/12345 → civitai.com/api/download/models/12345?token=...), showing the transformed URL + note. ## How it works end-to-end 1. User opens Comfy tab → 'CivitAI token' button → pastes token → Save (stored in `gpu/dashboard/settings.json`, shared with llama downloader) 2. User pastes `https://civitai.com/models/12345` in URL field 3. URL preview card shows: ``` [CivitAI] converted model page → API download URL, added API token https://civitai.com/api/download/models/12345?token=XXX... ``` 4. User selects type (checkpoints/loras/etc) and clicks Queue (or Enter) 5. Backend `addComfyModel()` transforms URL → calls `docker exec model-worker python3 /app/worker.py add ` 6. Worker downloads the file with token auth → saves to `gpu/comfy/models//` 7. Toast shows: 'Queued: checkpoints\nconverted model page → API download URL, added API token\n→ https://civitai.com/api/download/models/...' ## Verification - `npm run build` — OK, 26 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 Comfy tab → 'CivitAI token' button → paste token → Save. Paste any CivitAI URL (model page or API download URL) → see preview → Queue. The model fetches with token auth and lands in the right type subdirectory. ## Files changed - dashboard/src/lib/docker.ts — addComfyModel() applies prepareCivitaiUrl - dashboard/src/app/api/comfy/models/add/route.ts — returns transformation metadata - dashboard/src/app/page.tsx — comfyUrlPreview state, debounced preview effect, handleComfyAddModel shows transformation in toast, ComfyTab gets civitai token UI + URL preview + Enter-to-queue --- .../src/app/api/comfy/models/add/route.ts | 21 +- dashboard/src/app/page.tsx | 190 ++++++++++++++++-- dashboard/src/lib/docker.ts | 28 ++- 3 files changed, 219 insertions(+), 20 deletions(-) diff --git a/dashboard/src/app/api/comfy/models/add/route.ts b/dashboard/src/app/api/comfy/models/add/route.ts index 7a6f50d..a190482 100644 --- a/dashboard/src/app/api/comfy/models/add/route.ts +++ b/dashboard/src/app/api/comfy/models/add/route.ts @@ -7,7 +7,17 @@ export const runtime = "nodejs"; /** * POST /api/comfy/models/add * Body: { url: string, type: string } - * Queues a model download via model-worker. + * + * Queues a ComfyUI model download via model-worker. CivitAI URLs are + * automatically transformed (model page → API download URL) and the saved + * CivitAI token is appended. + * + * Returns: + * { ok, output, error?, originalUrl?, transformedUrl?, urlNote? } + * + * The originalUrl/transformedUrl/urlNote fields are only present when we + * actually modified the URL (e.g. user pasted a civitai.com/models/12345 + * page URL and we converted it to /api/download/models/12345?token=...). */ export async function POST(req: NextRequest) { const body = (await req.json()) as { url?: string; type?: string }; @@ -19,7 +29,14 @@ export async function POST(req: NextRequest) { } const result = await addComfyModel(body.url, body.type); return NextResponse.json( - { ok: result.ok, output: result.output, error: result.error }, + { + ok: result.ok, + output: result.output, + error: result.error, + originalUrl: result.originalUrl, + transformedUrl: result.transformedUrl, + urlNote: result.urlNote, + }, { status: result.ok ? 200 : 500 } ); } diff --git a/dashboard/src/app/page.tsx b/dashboard/src/app/page.tsx index 421cf7d..05366fd 100644 --- a/dashboard/src/app/page.tsx +++ b/dashboard/src/app/page.tsx @@ -288,6 +288,9 @@ export default function DashboardPage() { civitaiToken: "", }); const [urlPreview, setUrlPreview] = React.useState(null); + // Separate preview state for the Comfy tab's URL field (same logic as urlPreview, + // just tracks a different input) + const [comfyUrlPreview, setComfyUrlPreview] = React.useState(null); // Chat state — kept at top level so switching tabs doesn't reset the // conversation. ChatTab is mounted/unmounted when the user clicks the tab. @@ -896,6 +899,45 @@ export default function DashboardPage() { }; }, [downloadUrl, previewUrl]); + // Same debounced preview, but for the Comfy tab's URL field + const comfyPreviewDebounceRef = React.useRef | null>(null); + React.useEffect(() => { + if (comfyPreviewDebounceRef.current) + clearTimeout(comfyPreviewDebounceRef.current); + comfyPreviewDebounceRef.current = setTimeout(() => { + void (async () => { + if (!comfyAddUrl.trim()) { + setComfyUrlPreview(null); + return; + } + try { + const res = await fetch("/api/settings", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: "preview-url", url: comfyAddUrl }), + }); + if (!res.ok) return; + const data = await res.json(); + if (data.ok) { + setComfyUrlPreview({ + original: data.original, + transformed: data.transformed, + note: data.note, + isCivitai: data.isCivitai, + }); + } + } catch { + /* ignore */ + } + })(); + }, 400); + return () => { + if (comfyPreviewDebounceRef.current) + clearTimeout(comfyPreviewDebounceRef.current); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [comfyAddUrl]); + React.useEffect(() => { refreshSettings(); }, [refreshSettings]); @@ -1206,10 +1248,22 @@ export default function DashboardPage() { const data = await res.json(); setComfyAddUrl(""); await refreshComfyQueue(); - return { - ok: data.ok, - message: data.ok ? `Queued: ${comfyAddType}` : data.error || "Failed", - }; + // Build a helpful message — if the URL was transformed (CivitAI + // model page → API download URL with token), include the note so the + // user can see what happened. + let message: string; + if (data.ok) { + message = `Queued: ${comfyAddType}`; + if (data.urlNote) { + message += `\n${data.urlNote}`; + } + if (data.transformedUrl) { + message += `\n→ ${data.transformedUrl}`; + } + } else { + message = data.error || "Failed"; + } + return { ok: data.ok, message }; }, false); } @@ -1457,6 +1511,9 @@ export default function DashboardPage() { setAddType={setComfyAddType} onRemove={handleComfyRemoveModel} busy={busy} + civitaiToken={settings.civitaiToken} + onSaveCivitaiToken={handleSaveCivitaiToken} + urlPreview={comfyUrlPreview} /> @@ -2747,6 +2804,9 @@ function ComfyTab({ setAddType, onRemove, busy, + civitaiToken, + onSaveCivitaiToken, + urlPreview, }: { models: ComfyModelEntry[]; queue: ComfyQueueEntry[]; @@ -2763,7 +2823,17 @@ function ComfyTab({ setAddType: (v: string) => void; onRemove: (filename: string, type?: string) => void; busy: string | null; + civitaiToken: string; + onSaveCivitaiToken: (token: string) => void; + urlPreview: UrlPreview | null; }) { + const [showCivitaiSettings, setShowCivitaiSettings] = React.useState(false); + const [civitaiTokenDraft, setCivitaiTokenDraft] = React.useState(civitaiToken); + + React.useEffect(() => { + setCivitaiTokenDraft(civitaiToken); + }, [civitaiToken]); + return (
{/* Download queue */} @@ -2848,22 +2918,94 @@ function ComfyTab({ {/* Add model */} - - - - Queue Download - - - Mirrors gpuctl comfy models add <URL> <type> - + +
+ + + Queue Download + + + Mirrors gpuctl comfy models add <URL> <type>. + {" "}CivitAI URLs auto-converted (model page → API download), + token appended. + +
+
- + + {showCivitaiSettings && ( +
+ + setCivitaiTokenDraft(e.target.value)} + placeholder="Get it from https://civitai.com/user/account → API Keys" + className="font-mono text-xs" + /> +
+ + + + Get token ↗ + +
+

+ Shared with the llama-models downloader. Stored in{" "} + gpu/dashboard/settings.json. +

+
+ )} +
setAddUrl(e.target.value)} className="font-mono text-xs" + onKeyDown={(e) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + if (addUrl.trim() && busy === null) onAdd(); + } + }} /> -
+ + {/* URL preview — shows what we'll actually send to the worker */} + {urlPreview && urlPreview.original !== urlPreview.transformed && ( +
+
+ + {urlPreview.isCivitai ? "CivitAI" : "transformed"} + + {urlPreview.note} +
+
+                {urlPreview.transformed}
+              
+
+ )}
diff --git a/dashboard/src/lib/docker.ts b/dashboard/src/lib/docker.ts index ce0c62c..26d1cb6 100644 --- a/dashboard/src/lib/docker.ts +++ b/dashboard/src/lib/docker.ts @@ -1499,11 +1499,33 @@ export async function getComfyQueue(): Promise<{ } export async function addComfyModel( - url: string, + rawUrl: string, type: string -): Promise<{ ok: boolean; output: string; error?: string }> { +): Promise<{ + ok: boolean; + output: string; + error?: string; + originalUrl?: string; + transformedUrl?: string; + urlNote?: string; +}> { + // Apply CivitAI URL transformation (model page → API download URL, append token). + // We lazy-load the imports here so docker.ts doesn't pull in downloads.ts at + // module-load time (avoids circular import concerns). + const { prepareCivitaiUrl, loadSettings } = await import("./downloads"); + const settings = await loadSettings(); + const { url, note } = prepareCivitaiUrl(rawUrl, settings.civitaiToken || ""); + const res = await modelWorkerExec("add", url, type); - return { ok: res.ok, output: res.output, error: res.error }; + return { + ok: res.ok, + output: res.output, + error: res.error, + // Only include transformation metadata if we actually changed something + originalUrl: rawUrl !== url ? rawUrl : undefined, + transformedUrl: rawUrl !== url ? url : undefined, + urlNote: note || undefined, + }; } export async function removeComfyModel( -- 2.49.1