Compare commits

..

2 Commits

Author SHA1 Message Date
Z User
cb92e32bdf feat(comfy): CivitAI URL transformation + token support for comfy models
## 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.
- `<ComfyTab>` 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 <transformed-url> <type>`
6. Worker downloads the file with token auth → saves to
   `gpu/comfy/models/<type>/<filename>`
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
2026-10-24 02:35:37 +00:00
3d2bec055b Merge pull request 'fix(dashboard): chat survives tab switch, Enter to send, reasoning display, /health via fetch, n-predict + reasoning-format params' (#12) from fix/chat-improvements into master
Reviewed-on: #12
2026-10-24 02:19:06 +00:00
3 changed files with 219 additions and 20 deletions

View File

@@ -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 }
);
}

View File

@@ -288,6 +288,9 @@ export default function DashboardPage() {
civitaiToken: "",
});
const [urlPreview, setUrlPreview] = React.useState<UrlPreview | null>(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<UrlPreview | null>(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<ReturnType<typeof setTimeout> | 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}
/>
</TabsContent>
@@ -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 (
<div className="space-y-4">
{/* Download queue */}
@@ -2848,22 +2918,94 @@ function ComfyTab({
{/* Add model */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Plus className="h-4 w-4" />
Queue Download
</CardTitle>
<CardDescription>
Mirrors <code className="font-mono text-xs">gpuctl comfy models add &lt;URL&gt; &lt;type&gt;</code>
</CardDescription>
<CardHeader className="flex flex-row items-start justify-between gap-2">
<div>
<CardTitle className="text-base flex items-center gap-2">
<Plus className="h-4 w-4" />
Queue Download
</CardTitle>
<CardDescription>
Mirrors <code className="font-mono text-xs">gpuctl comfy models add &lt;URL&gt; &lt;type&gt;</code>.
{" "}CivitAI URLs auto-converted (model page → API download),
token appended.
</CardDescription>
</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>
</CardHeader>
<CardContent>
<CardContent className="space-y-3">
{showCivitaiSettings && (
<div className="rounded-md border bg-card p-3 space-y-2">
<Label htmlFor="comfy-civitai-token">CivitAI API token</Label>
<Input
id="comfy-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">
Shared with the llama-models downloader. Stored in{" "}
<code className="font-mono">gpu/dashboard/settings.json</code>.
</p>
</div>
)}
<div className="grid gap-2 sm:grid-cols-[1fr_180px_auto]">
<Input
placeholder="https://huggingface.co/.../model.safetensors"
placeholder="https://civitai.com/models/12345 or HF/GitHub URL"
value={addUrl}
onChange={(e) => 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();
}
}}
/>
<Select value={addType} onValueChange={setAddType}>
<SelectTrigger>
@@ -2883,11 +3025,29 @@ function ComfyTab({
)}
</SelectContent>
</Select>
<Button onClick={onAdd} disabled={busy !== null}>
<Button onClick={onAdd} disabled={busy !== null || !addUrl.trim()}>
<Plus className="h-3.5 w-3.5" />
Queue
</Button>
</div>
{/* URL preview — shows what we'll actually send to the worker */}
{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>
)}
</CardContent>
</Card>

View File

@@ -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(