Compare commits
10 Commits
fix/dashbo
...
fix/comfy-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12fb97314b | ||
| e02b0e57a3 | |||
|
|
6c4e1c8f64 | ||
| 405c88f086 | |||
|
|
ab60962d76 | ||
| 201f4266b2 | |||
|
|
93bf5cdc88 | ||
| ff180be9b5 | |||
|
|
15892cf0d1 | ||
| 41da236ee6 |
@@ -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
|
||||
|
||||
|
||||
169
dashboard/src/app/api/chat/route.ts
Normal file
169
dashboard/src/app/api/chat/route.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getLlamaContainerName } from "@/lib/docker";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 300;
|
||||
|
||||
/**
|
||||
* POST /api/chat
|
||||
*
|
||||
* Streams a chat completion from llama.cpp /v1/chat/completions (OpenAI-compatible).
|
||||
*
|
||||
* Body: {
|
||||
* messages: [{role, content}],
|
||||
* temperature?, top_p?, top_k?, min_p?, repeat_penalty?, max_tokens?, stream?
|
||||
* }
|
||||
*
|
||||
* Returns: SSE stream of OpenAI-compatible chat completion chunks.
|
||||
*/
|
||||
interface ChatMessage {
|
||||
role: "system" | "user" | "assistant";
|
||||
content: string;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = (await req.json()) as {
|
||||
messages: ChatMessage[];
|
||||
temperature?: number;
|
||||
top_p?: number;
|
||||
top_k?: number;
|
||||
min_p?: number;
|
||||
repeat_penalty?: number;
|
||||
max_tokens?: number;
|
||||
stream?: boolean;
|
||||
};
|
||||
|
||||
if (!body.messages || !Array.isArray(body.messages) || body.messages.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "messages array is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const containerName = await getLlamaContainerName();
|
||||
if (!containerName) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: "llama container not running" },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
// Build the request payload for llama.cpp /v1/chat/completions endpoint.
|
||||
// llama.cpp supports OpenAI-compatible API.
|
||||
const payload: Record<string, unknown> = {
|
||||
messages: body.messages,
|
||||
stream: body.stream !== false,
|
||||
};
|
||||
if (body.temperature != null) payload.temperature = body.temperature;
|
||||
if (body.top_p != null) payload.top_p = body.top_p;
|
||||
if (body.top_k != null) payload.top_k = body.top_k;
|
||||
if (body.min_p != null) payload.min_p = body.min_p;
|
||||
if (body.repeat_penalty != null) payload.repeat_penalty = body.repeat_penalty;
|
||||
if (body.max_tokens != null) payload.max_tokens = body.max_tokens;
|
||||
|
||||
const payloadJson = JSON.stringify(payload);
|
||||
|
||||
// Build the docker exec command to send the request to llama.cpp inside
|
||||
// the container. We use `docker exec ... wget` because we can't reach
|
||||
// the container's port from the dashboard directly (different network
|
||||
// namespace). Actually — the dashboard IS on the same Docker network,
|
||||
// so we can just fetch http://llama:8080/v1/chat/completions directly.
|
||||
// But wget is more reliable for streaming.
|
||||
|
||||
const useStream = body.stream !== false;
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
if (useStream) {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
try {
|
||||
// Use Node's fetch (available in Node 18+) to call llama.cpp
|
||||
// directly over the Docker network. The dashboard container is
|
||||
// on the same network as llama, so http://llama:8080 works.
|
||||
const res = await fetch("http://llama:8080/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: payloadJson,
|
||||
signal: req.signal,
|
||||
});
|
||||
|
||||
if (!res.ok || !res.body) {
|
||||
const text = await res.text().catch(() => "");
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${JSON.stringify({
|
||||
error: `llama returned ${res.status}: ${text.slice(0, 500)}`,
|
||||
})}\n\n`
|
||||
)
|
||||
);
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Pipe the response through — llama.cpp /v1/chat/completions with
|
||||
// stream=true returns SSE chunks (data: {...}\n\n).
|
||||
const reader = res.body.getReader();
|
||||
const pump = (): Promise<void> =>
|
||||
reader.read().then(({ done, value }) => {
|
||||
if (done) {
|
||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(value);
|
||||
return pump();
|
||||
});
|
||||
await pump();
|
||||
} catch (err) {
|
||||
try {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${JSON.stringify({
|
||||
error: (err as Error).message,
|
||||
})}\n\n`
|
||||
)
|
||||
);
|
||||
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",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Non-streaming — return JSON
|
||||
try {
|
||||
const res = await fetch("http://llama:8080/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: payloadJson,
|
||||
});
|
||||
const text = await res.text();
|
||||
return new Response(text, {
|
||||
status: res.status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: (err as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Suppress unused warning
|
||||
void spawn;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { getComfyQueue } from "@/lib/docker";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -6,12 +6,20 @@ export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* GET /api/comfy/queue
|
||||
* Returns current download queue via `docker exec model-worker python3 /app/worker.py queue`.
|
||||
*
|
||||
* Returns current download queue via `docker exec model-worker python3
|
||||
* /app/worker.py queue --json`.
|
||||
*
|
||||
* Returns 200 even when model-worker is offline (queue is empty in that
|
||||
* case) — frontend polls this every 5s, returning 500 on every poll when
|
||||
* worker isn't running would spam the browser console.
|
||||
*/
|
||||
export async function GET() {
|
||||
const result = await getComfyQueue();
|
||||
return NextResponse.json(
|
||||
{ ok: result.ok, queue: result.queue, raw: result.raw, error: result.error },
|
||||
{ status: result.ok ? 200 : 500 }
|
||||
);
|
||||
return NextResponse.json({
|
||||
ok: result.ok,
|
||||
queue: result.queue,
|
||||
raw: result.raw,
|
||||
error: result.error,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,6 +10,53 @@ import {
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* Merge a Partial<DashboardConfig> into a full DashboardConfig. All known
|
||||
* fields are copied; missing fields keep their existing values.
|
||||
*/
|
||||
function mergeConfig(
|
||||
base: DashboardConfig,
|
||||
patch: Partial<DashboardConfig> | undefined
|
||||
): DashboardConfig {
|
||||
if (!patch) return base;
|
||||
return {
|
||||
model: patch.model ?? base.model,
|
||||
ctxSize: patch.ctxSize ?? base.ctxSize,
|
||||
parallel: patch.parallel ?? base.parallel,
|
||||
nGpuLayers: patch.nGpuLayers ?? base.nGpuLayers,
|
||||
threads: patch.threads ?? base.threads,
|
||||
draftModel: patch.draftModel ?? base.draftModel,
|
||||
specType: patch.specType ?? base.specType,
|
||||
specDraftNMax: patch.specDraftNMax ?? base.specDraftNMax,
|
||||
batchSize: patch.batchSize ?? base.batchSize,
|
||||
ubatchSize: patch.ubatchSize ?? base.ubatchSize,
|
||||
contextOverflow: patch.contextOverflow ?? base.contextOverflow,
|
||||
cacheTypeK: patch.cacheTypeK ?? base.cacheTypeK,
|
||||
cacheTypeV: patch.cacheTypeV ?? base.cacheTypeV,
|
||||
defragThold: patch.defragThold ?? base.defragThold,
|
||||
flashAttn: patch.flashAttn ?? base.flashAttn,
|
||||
noMmap: patch.noMmap ?? base.noMmap,
|
||||
mlock: patch.mlock ?? base.mlock,
|
||||
contBatching: patch.contBatching ?? base.contBatching,
|
||||
embeddings: patch.embeddings ?? base.embeddings,
|
||||
metrics: patch.metrics ?? base.metrics,
|
||||
ropeFreqScale: patch.ropeFreqScale ?? base.ropeFreqScale,
|
||||
ropeScale: patch.ropeScale ?? base.ropeScale,
|
||||
yarnExtFactor: patch.yarnExtFactor ?? base.yarnExtFactor,
|
||||
yarnAttnFactor: patch.yarnAttnFactor ?? base.yarnAttnFactor,
|
||||
yarnBetaFast: patch.yarnBetaFast ?? base.yarnBetaFast,
|
||||
yarnBetaSlow: patch.yarnBetaSlow ?? base.yarnBetaSlow,
|
||||
systemPrompt: patch.systemPrompt ?? base.systemPrompt,
|
||||
topK: patch.topK ?? base.topK,
|
||||
topP: patch.topP ?? base.topP,
|
||||
minP: patch.minP ?? base.minP,
|
||||
temperature: patch.temperature ?? base.temperature,
|
||||
repeatPenalty: patch.repeatPenalty ?? base.repeatPenalty,
|
||||
extraArgs: patch.extraArgs ?? base.extraArgs,
|
||||
presets: patch.presets ?? base.presets,
|
||||
};
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const config = await loadConfig();
|
||||
return NextResponse.json({ config, defaults: DEFAULT_CONFIG });
|
||||
@@ -18,23 +65,7 @@ export async function GET() {
|
||||
export async function PUT(req: NextRequest) {
|
||||
const body = (await req.json()) as Partial<DashboardConfig>;
|
||||
const current = await loadConfig();
|
||||
|
||||
// Merge: keep existing presets unless explicitly overwritten
|
||||
const next: DashboardConfig = {
|
||||
model: body.model ?? current.model,
|
||||
ctxSize: body.ctxSize ?? current.ctxSize,
|
||||
parallel: body.parallel ?? current.parallel,
|
||||
nGpuLayers: body.nGpuLayers ?? current.nGpuLayers,
|
||||
threads: body.threads ?? current.threads,
|
||||
draftModel: body.draftModel ?? current.draftModel,
|
||||
specType: body.specType ?? current.specType,
|
||||
specDraftNMax: body.specDraftNMax ?? current.specDraftNMax,
|
||||
batchSize: body.batchSize ?? current.batchSize,
|
||||
contextOverflow: body.contextOverflow ?? current.contextOverflow,
|
||||
extraArgs: body.extraArgs ?? current.extraArgs,
|
||||
presets: body.presets ?? current.presets,
|
||||
};
|
||||
|
||||
const next = mergeConfig(current, body);
|
||||
await saveConfig(next);
|
||||
return NextResponse.json({ config: next });
|
||||
}
|
||||
@@ -46,9 +77,17 @@ export async function POST(req: NextRequest) {
|
||||
action: "save-preset" | "delete-preset" | "load-preset" | "reset";
|
||||
name?: string;
|
||||
id?: string;
|
||||
config?: Partial<DashboardConfig>;
|
||||
};
|
||||
const current = await loadConfig();
|
||||
|
||||
// If the caller passed a `config` in the body, merge it into `current`
|
||||
// before performing the action. This is critical for `save-preset`: if the
|
||||
// user has edited the form but not clicked "Apply" yet, the persisted
|
||||
// config.json still has the old values, and saving a preset would snapshot
|
||||
// the OLD config — not what's currently in the UI.
|
||||
const effective = mergeConfig(current, body.config);
|
||||
|
||||
if (body.action === "save-preset") {
|
||||
if (!body.name) {
|
||||
return NextResponse.json(
|
||||
@@ -59,12 +98,15 @@ export async function POST(req: NextRequest) {
|
||||
const preset: Preset = {
|
||||
id: `preset-${Date.now()}`,
|
||||
name: body.name,
|
||||
config: stripPresets(current),
|
||||
config: stripPresets(effective),
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
const next: DashboardConfig = {
|
||||
...current,
|
||||
presets: [...current.presets.filter((p) => p.name !== body.name), preset],
|
||||
...effective,
|
||||
presets: [
|
||||
...effective.presets.filter((p) => p.name !== body.name),
|
||||
preset,
|
||||
],
|
||||
};
|
||||
await saveConfig(next);
|
||||
return NextResponse.json({ config: next });
|
||||
|
||||
@@ -17,13 +17,17 @@ export async function POST(req: NextRequest) {
|
||||
config?: Partial<DashboardConfig>;
|
||||
};
|
||||
|
||||
console.log("[/api/llama] action:", body.action, "config.model:", body.config?.model);
|
||||
|
||||
if (body.action === "start") {
|
||||
const current = await loadConfig();
|
||||
const cfg: DashboardConfig = {
|
||||
...current,
|
||||
...(body.config || {}),
|
||||
} as DashboardConfig;
|
||||
console.log("[/api/llama] merged cfg.model:", cfg.model);
|
||||
const result = await startLlama(cfg);
|
||||
console.log("[/api/llama] startLlama result ok:", result.ok);
|
||||
return NextResponse.json(result, { status: result.ok ? 200 : 500 });
|
||||
}
|
||||
|
||||
|
||||
45
dashboard/src/app/api/metrics/route.ts
Normal file
45
dashboard/src/app/api/metrics/route.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* GET /api/metrics
|
||||
*
|
||||
* Proxies llama.cpp's /metrics (Prometheus) endpoint. The dashboard container
|
||||
* is on the same Docker network as llama, so http://llama:8080/metrics works.
|
||||
*
|
||||
* Returns plain text (Prometheus exposition format).
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
const res = await fetch("http://llama:8080/metrics", {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: `llama returned ${res.status}`,
|
||||
raw: await res.text().catch(() => ""),
|
||||
},
|
||||
{ status: res.status }
|
||||
);
|
||||
}
|
||||
const text = await res.text();
|
||||
// Return as plain text — the frontend can render it as <pre>
|
||||
return new Response(text, {
|
||||
headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" },
|
||||
});
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: (err as Error).message,
|
||||
hint: "llama container must be running and started with --metrics flag",
|
||||
},
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
}
|
||||
36
dashboard/src/app/api/models/download/[id]/cancel/route.ts
Normal file
36
dashboard/src/app/api/models/download/[id]/cancel/route.ts
Normal file
@@ -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) });
|
||||
}
|
||||
78
dashboard/src/app/api/models/download/[id]/stream/route.ts
Normal file
78
dashboard/src/app/api/models/download/[id]/stream/route.ts
Normal file
@@ -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<Uint8Array>({
|
||||
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",
|
||||
},
|
||||
});
|
||||
}
|
||||
42
dashboard/src/app/api/models/download/route.ts
Normal file
42
dashboard/src/app/api/models/download/route.ts
Normal file
@@ -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 <dest>.part <url>
|
||||
*
|
||||
* 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
30
dashboard/src/app/api/models/download/status/route.ts
Normal file
30
dashboard/src/app/api/models/download/status/route.ts
Normal file
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,17 @@ import { deleteModel, listModels } from "@/lib/docker";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* GET /api/models
|
||||
*
|
||||
* Lists all .gguf files in gpu/llama_models/. Returns:
|
||||
* { models: [{ name, sizeBytes, sizeHuman, modifiedAt }] }
|
||||
*/
|
||||
export async function GET() {
|
||||
const models = await listModels();
|
||||
return NextResponse.json({ models });
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/models?name=foo.gguf
|
||||
*
|
||||
|
||||
78
dashboard/src/app/api/settings/route.ts
Normal file
78
dashboard/src/app/api/settings/route.ts
Normal file
@@ -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<DashboardSettings> — 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<DashboardSettings>;
|
||||
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: "<civitai 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 });
|
||||
}
|
||||
51
dashboard/src/app/api/slots/route.ts
Normal file
51
dashboard/src/app/api/slots/route.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* GET /api/slots
|
||||
*
|
||||
* Returns llama.cpp slot status from /slots endpoint. Each slot is one
|
||||
* parallel processing unit (controlled by --parallel). Includes:
|
||||
* - id: slot id (0-indexed)
|
||||
* - is_processing: bool
|
||||
* - prompt: current prompt tokens
|
||||
* - n_ctx: context size
|
||||
* - n_past: tokens processed so far
|
||||
* - n_eval: total tokens generated in this slot
|
||||
* - timings: { prompt_n, prompt_ms, prompt_per_token, prompt_per_second,
|
||||
* predicted_n, predicted_ms, predicted_per_token,
|
||||
* predicted_per_second }
|
||||
*
|
||||
* From these we can compute TPS (predicted_per_second), TTFT (prompt_ms),
|
||||
* cache-hit ratio, etc.
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
const res = await fetch("http://llama:8080/slots", {
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: `llama returned ${res.status}`,
|
||||
},
|
||||
{ status: res.status }
|
||||
);
|
||||
}
|
||||
const data = await res.json();
|
||||
return NextResponse.json({ ok: true, slots: data });
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: (err as Error).message,
|
||||
slots: [],
|
||||
},
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
}
|
||||
27
dashboard/src/app/icon.svg
Normal file
27
dashboard/src/app/icon.svg
Normal file
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0" stop-color="#0a0a0a"/>
|
||||
<stop offset="1" stop-color="#525252"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="32" height="32" rx="6" fill="url(#g)"/>
|
||||
<!-- stylized "GPU" / chip icon -->
|
||||
<g fill="none" stroke="#fafafa" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="9" y="9" width="14" height="14" rx="2"/>
|
||||
<rect x="13" y="13" width="6" height="6" rx="0.5" fill="#fafafa" stroke="none"/>
|
||||
<!-- pins -->
|
||||
<line x1="12" y1="6" x2="12" y2="9"/>
|
||||
<line x1="16" y1="6" x2="16" y2="9"/>
|
||||
<line x1="20" y1="6" x2="20" y2="9"/>
|
||||
<line x1="12" y1="23" x2="12" y2="26"/>
|
||||
<line x1="16" y1="23" x2="16" y2="26"/>
|
||||
<line x1="20" y1="23" x2="20" y2="26"/>
|
||||
<line x1="6" y1="12" x2="9" y2="12"/>
|
||||
<line x1="6" y1="16" x2="9" y2="16"/>
|
||||
<line x1="6" y1="20" x2="9" y2="20"/>
|
||||
<line x1="23" y1="12" x2="26" y2="12"/>
|
||||
<line x1="23" y1="16" x2="26" y2="16"/>
|
||||
<line x1="23" y1="20" x2="26" y2="20"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
File diff suppressed because it is too large
Load Diff
@@ -124,6 +124,14 @@ export const TAILSCALE_HOSTNAME = envOrFile("TAILSCALE_HOSTNAME", "gpu-node");
|
||||
export const LLAMA_MODELS_DIR =
|
||||
process.env.LLAMA_MODELS_DIR || path.join(PROJECT_DIR, "gpu", "llama_models");
|
||||
|
||||
/**
|
||||
* Internal mount of the comfy models directory (mirrors the host path that
|
||||
* the model-worker container mounts as /models).
|
||||
*/
|
||||
export const COMFY_MODELS_DIR =
|
||||
process.env.COMFY_MODELS_DIR ||
|
||||
path.join(PROJECT_DIR, "gpu", "comfy", "models");
|
||||
|
||||
/**
|
||||
* Node instance name (used for filtering containers by label).
|
||||
*/
|
||||
@@ -135,6 +143,16 @@ export const NODE_INSTANCE =
|
||||
*/
|
||||
const COMPOSE_FILE = path.join(PROJECT_DIR, "compose.yaml");
|
||||
|
||||
/**
|
||||
* Path to the persisted dashboard settings (civitai token, etc).
|
||||
*/
|
||||
export const DASHBOARD_SETTINGS_PATH = path.join(
|
||||
PROJECT_DIR,
|
||||
"gpu",
|
||||
"dashboard",
|
||||
"settings.json"
|
||||
);
|
||||
|
||||
/**
|
||||
* Path to the persisted dashboard config (last-used + saved presets).
|
||||
*/
|
||||
@@ -186,10 +204,54 @@ export interface DashboardConfig {
|
||||
specType: "none" | "draft-mtp" | "draft-llama";
|
||||
/** Max draft tokens */
|
||||
specDraftNMax: number;
|
||||
/** Batch size */
|
||||
/** Batch size (prompt processing batch) */
|
||||
batchSize: number;
|
||||
/** Micro-batch size (physical batch on GPU) */
|
||||
ubatchSize: number;
|
||||
/** UB / KV cache size etc */
|
||||
contextOverflow: "none" | "shift" | "evict";
|
||||
/** KV cache type for K */
|
||||
cacheTypeK: "f16" | "f32" | "q8_0" | "q4_0";
|
||||
/** KV cache type for V */
|
||||
cacheTypeV: "f16" | "f32" | "q8_0" | "q4_0";
|
||||
/** KV cache defragmentation threshold (0..1) */
|
||||
defragThold: number;
|
||||
/** Enable Flash Attention */
|
||||
flashAttn: boolean;
|
||||
/** Don't mmap model (load to RAM) */
|
||||
noMmap: boolean;
|
||||
/** Lock model in RAM (prevents swap) */
|
||||
mlock: boolean;
|
||||
/** Continuous batching */
|
||||
contBatching: boolean;
|
||||
/** Enable /embeddings endpoint */
|
||||
embeddings: boolean;
|
||||
/** Enable /metrics (Prometheus) endpoint */
|
||||
metrics: boolean;
|
||||
/** RoPE frequency scale (NTK-aware, 1.0 = default) */
|
||||
ropeFreqScale: number;
|
||||
/** RoPE context scaling factor (1.0 = default) */
|
||||
ropeScale: number;
|
||||
/** YaRN extrapolation factor (1.0 = default) */
|
||||
yarnExtFactor: number;
|
||||
/** YaRN attention factor (1.0 = default) */
|
||||
yarnAttnFactor: number;
|
||||
/** YaRN beta fast (32.0 = default) */
|
||||
yarnBetaFast: number;
|
||||
/** YaRN beta slow (1.0 = default) */
|
||||
yarnBetaSlow: number;
|
||||
/** Default system prompt for chat completions (empty = none) */
|
||||
systemPrompt: string;
|
||||
/** Sampling: top-k (0 = disabled) */
|
||||
topK: number;
|
||||
/** Sampling: top-p (1.0 = disabled) */
|
||||
topP: number;
|
||||
/** Sampling: min-p (0 = disabled) */
|
||||
minP: number;
|
||||
/** Sampling: temperature (1.0 = default) */
|
||||
temperature: number;
|
||||
/** Sampling: repeat penalty (1.0 = disabled) */
|
||||
repeatPenalty: number;
|
||||
/** Free-form extra args (advanced) */
|
||||
extraArgs: string;
|
||||
/** Saved presets */
|
||||
@@ -213,7 +275,29 @@ export const DEFAULT_CONFIG: DashboardConfig = {
|
||||
specType: "none",
|
||||
specDraftNMax: 4,
|
||||
batchSize: 512,
|
||||
ubatchSize: 512,
|
||||
contextOverflow: "none",
|
||||
cacheTypeK: "f16",
|
||||
cacheTypeV: "f16",
|
||||
defragThold: 0.1,
|
||||
flashAttn: true,
|
||||
noMmap: false,
|
||||
mlock: false,
|
||||
contBatching: true,
|
||||
embeddings: false,
|
||||
metrics: false,
|
||||
ropeFreqScale: 1.0,
|
||||
ropeScale: 1.0,
|
||||
yarnExtFactor: 1.0,
|
||||
yarnAttnFactor: 1.0,
|
||||
yarnBetaFast: 32.0,
|
||||
yarnBetaSlow: 1.0,
|
||||
systemPrompt: "",
|
||||
topK: 40,
|
||||
topP: 0.95,
|
||||
minP: 0.05,
|
||||
temperature: 0.8,
|
||||
repeatPenalty: 1.1,
|
||||
extraArgs: "",
|
||||
presets: [],
|
||||
};
|
||||
@@ -308,6 +392,86 @@ export function parseLlamaExtraArgs(
|
||||
cfg.batchSize = Number(next) || cfg.batchSize;
|
||||
i++;
|
||||
break;
|
||||
case "--ubatch-size":
|
||||
case "-ub":
|
||||
cfg.ubatchSize = Number(next) || cfg.ubatchSize;
|
||||
i++;
|
||||
break;
|
||||
case "--cache-type-k":
|
||||
cfg.cacheTypeK = (next as DashboardConfig["cacheTypeK"]) || cfg.cacheTypeK;
|
||||
i++;
|
||||
break;
|
||||
case "--cache-type-v":
|
||||
cfg.cacheTypeV = (next as DashboardConfig["cacheTypeV"]) || cfg.cacheTypeV;
|
||||
i++;
|
||||
break;
|
||||
case "--defrag-thold":
|
||||
cfg.defragThold = Number(next) || cfg.defragThold;
|
||||
i++;
|
||||
break;
|
||||
case "--flash-attn":
|
||||
cfg.flashAttn = true;
|
||||
break;
|
||||
case "--no-mmap":
|
||||
cfg.noMmap = true;
|
||||
break;
|
||||
case "--mlock":
|
||||
cfg.mlock = true;
|
||||
break;
|
||||
case "--cont-batching":
|
||||
cfg.contBatching = true;
|
||||
break;
|
||||
case "--embeddings":
|
||||
cfg.embeddings = true;
|
||||
break;
|
||||
case "--metrics":
|
||||
cfg.metrics = true;
|
||||
break;
|
||||
case "--rope-freq-scale":
|
||||
cfg.ropeFreqScale = Number(next) || cfg.ropeFreqScale;
|
||||
i++;
|
||||
break;
|
||||
case "--rope-scaling":
|
||||
cfg.ropeScale = Number(next) || cfg.ropeScale;
|
||||
i++;
|
||||
break;
|
||||
case "--yarn-ext-factor":
|
||||
cfg.yarnExtFactor = Number(next) || cfg.yarnExtFactor;
|
||||
i++;
|
||||
break;
|
||||
case "--yarn-attn-factor":
|
||||
cfg.yarnAttnFactor = Number(next) || cfg.yarnAttnFactor;
|
||||
i++;
|
||||
break;
|
||||
case "--yarn-beta-fast":
|
||||
cfg.yarnBetaFast = Number(next) || cfg.yarnBetaFast;
|
||||
i++;
|
||||
break;
|
||||
case "--yarn-beta-slow":
|
||||
cfg.yarnBetaSlow = Number(next) || cfg.yarnBetaSlow;
|
||||
i++;
|
||||
break;
|
||||
case "--top-k":
|
||||
cfg.topK = Number(next);
|
||||
i++;
|
||||
break;
|
||||
case "--top-p":
|
||||
cfg.topP = Number(next);
|
||||
i++;
|
||||
break;
|
||||
case "--min-p":
|
||||
cfg.minP = Number(next);
|
||||
i++;
|
||||
break;
|
||||
case "--temp":
|
||||
case "--temperature":
|
||||
cfg.temperature = Number(next);
|
||||
i++;
|
||||
break;
|
||||
case "--repeat-penalty":
|
||||
cfg.repeatPenalty = Number(next);
|
||||
i++;
|
||||
break;
|
||||
case "--model-draft":
|
||||
cfg.draftModel = path.basename(next || "");
|
||||
i++;
|
||||
@@ -349,8 +513,35 @@ export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
|
||||
if (cfg.nGpuLayers >= 0) parts.push(`--n-gpu-layers ${cfg.nGpuLayers}`);
|
||||
if (cfg.threads > 0) parts.push(`--threads ${cfg.threads}`);
|
||||
parts.push(`--batch-size ${cfg.batchSize}`);
|
||||
parts.push(`--ubatch-size ${cfg.ubatchSize}`);
|
||||
if (cfg.contextOverflow !== "none")
|
||||
parts.push(`--context-overflow ${cfg.contextOverflow}`);
|
||||
// KV cache types
|
||||
parts.push(`--cache-type-k ${cfg.cacheTypeK}`);
|
||||
parts.push(`--cache-type-v ${cfg.cacheTypeV}`);
|
||||
if (cfg.defragThold >= 0 && cfg.defragThold !== 0.1)
|
||||
parts.push(`--defrag-thold ${cfg.defragThold}`);
|
||||
// Performance flags
|
||||
if (cfg.flashAttn) parts.push("--flash-attn");
|
||||
if (cfg.noMmap) parts.push("--no-mmap");
|
||||
if (cfg.mlock) parts.push("--mlock");
|
||||
if (cfg.contBatching) parts.push("--cont-batching");
|
||||
if (cfg.embeddings) parts.push("--embeddings");
|
||||
if (cfg.metrics) parts.push("--metrics");
|
||||
// RoPE / YaRN
|
||||
if (cfg.ropeFreqScale !== 1.0)
|
||||
parts.push(`--rope-freq-scale ${cfg.ropeFreqScale}`);
|
||||
if (cfg.ropeScale !== 1.0)
|
||||
parts.push(`--rope-scaling ${cfg.ropeScale}`);
|
||||
if (cfg.yarnExtFactor !== 1.0)
|
||||
parts.push(`--yarn-ext-factor ${cfg.yarnExtFactor}`);
|
||||
if (cfg.yarnAttnFactor !== 1.0)
|
||||
parts.push(`--yarn-attn-factor ${cfg.yarnAttnFactor}`);
|
||||
if (cfg.yarnBetaFast !== 32.0)
|
||||
parts.push(`--yarn-beta-fast ${cfg.yarnBetaFast}`);
|
||||
if (cfg.yarnBetaSlow !== 1.0)
|
||||
parts.push(`--yarn-beta-slow ${cfg.yarnBetaSlow}`);
|
||||
// Speculative decoding
|
||||
if (cfg.specType !== "none") {
|
||||
parts.push(`--spec-type ${cfg.specType}`);
|
||||
if (cfg.draftModel) {
|
||||
@@ -358,6 +549,13 @@ export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
|
||||
parts.push(`--spec-draft-n-max ${cfg.specDraftNMax}`);
|
||||
}
|
||||
}
|
||||
// Default sampling (server applies these as defaults for /completion)
|
||||
if (cfg.topK > 0) parts.push(`--top-k ${cfg.topK}`);
|
||||
if (cfg.topP < 1.0) parts.push(`--top-p ${cfg.topP}`);
|
||||
if (cfg.minP > 0) parts.push(`--min-p ${cfg.minP}`);
|
||||
if (cfg.temperature !== 1.0) parts.push(`--temp ${cfg.temperature}`);
|
||||
if (cfg.repeatPenalty > 1.0)
|
||||
parts.push(`--repeat-penalty ${cfg.repeatPenalty}`);
|
||||
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
|
||||
return parts.join(" ");
|
||||
}
|
||||
@@ -626,6 +824,12 @@ export async function startLlama(
|
||||
await saveConfig(config);
|
||||
await writeEnvLlamaConfig(config.model, extraArgs);
|
||||
|
||||
// Log what we're actually starting with — helps diagnose "model didn't
|
||||
// change" issues (the most common cause is the request body not including
|
||||
// the new model, or compose picking up an old LLAMA_MODEL from .env).
|
||||
console.log("[startLlama] model:", config.model);
|
||||
console.log("[startLlama] extraArgs:", extraArgs);
|
||||
|
||||
const res = await runCompose(
|
||||
[
|
||||
"--profile",
|
||||
@@ -642,9 +846,14 @@ export async function startLlama(
|
||||
);
|
||||
|
||||
const combined = res.stdout + (res.stderr ? `\n${res.stderr}` : "");
|
||||
console.log("[startLlama] compose exit:", res.code);
|
||||
console.log("[startLlama] compose output:\n", combined);
|
||||
|
||||
return {
|
||||
ok: res.code === 0,
|
||||
message: res.code === 0 ? "Llama instance started" : "Failed to start",
|
||||
message: res.code === 0
|
||||
? `Llama started (model: ${config.model})`
|
||||
: `Failed to start (exit ${res.code})`,
|
||||
logs: combined,
|
||||
};
|
||||
}
|
||||
@@ -823,7 +1032,22 @@ export async function startService(
|
||||
const profile = COMPOSE_PROFILES[role];
|
||||
const args = ["up", "-d", "--force-recreate", role];
|
||||
if (profile) args.unshift("--profile", profile);
|
||||
const res = await runCompose(args, {});
|
||||
|
||||
// Service-specific env overrides. Mirrors what gpuctl shells do — they
|
||||
// explicitly export these vars before `docker compose` so compose's
|
||||
// ${VAR:-default} syntax picks the real host path instead of the relative
|
||||
// default (which would resolve to a path inside the dashboard container,
|
||||
// not on the host).
|
||||
const extra: Record<string, string> = {};
|
||||
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:
|
||||
@@ -937,10 +1161,10 @@ async function modelWorkerExec(
|
||||
}
|
||||
try {
|
||||
const quoted = args.map((a) => `'${a.replace(/'/g, "'\\''")}'`).join(" ");
|
||||
const { stdout, stderr } = await execAsync(
|
||||
`docker exec ${container} python3 /app/worker.py ${quoted}`,
|
||||
{ maxBuffer: 8 * 1024 * 1024 }
|
||||
);
|
||||
const cmd = `docker exec ${container} python3 /app/worker.py ${quoted}`;
|
||||
const { stdout, stderr } = await execAsync(cmd, {
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
output: String(stdout),
|
||||
@@ -951,7 +1175,12 @@ async function modelWorkerExec(
|
||||
stdout?: string | Buffer;
|
||||
stderr?: string | Buffer;
|
||||
message: string;
|
||||
code?: number;
|
||||
};
|
||||
// Log the failure so it's visible in dashboard container logs
|
||||
console.error(
|
||||
`[modelWorkerExec] args=${JSON.stringify(args)} container=${container} exitCode=${e.code} stderr=${e.stderr ? String(e.stderr).slice(0, 500) : "(empty)"} message=${e.message}`
|
||||
);
|
||||
return {
|
||||
ok: false,
|
||||
output: e.stdout ? String(e.stdout) : "",
|
||||
@@ -967,43 +1196,127 @@ export interface ComfyModelEntry {
|
||||
sizeHuman?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read comfy model types directly from the filesystem (subdirs of
|
||||
* /project/gpu/comfy/models). Used as a fallback when the model-worker
|
||||
* container isn't running.
|
||||
*
|
||||
* Returns the same shape as `worker.py types`.
|
||||
*/
|
||||
async function listComfyTypesFromFs(): Promise<string[]> {
|
||||
try {
|
||||
const entries = await fs.readdir(COMFY_MODELS_DIR, { withFileTypes: true });
|
||||
return entries
|
||||
.filter((e) => e.isDirectory() && !e.isSymbolicLink())
|
||||
.map((e) => e.name)
|
||||
.sort();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read comfy models directly from the filesystem. Walks each subdirectory
|
||||
* (one per model type) and lists all files inside. Used as a fallback when
|
||||
* the model-worker container isn't running.
|
||||
*
|
||||
* Returns the same shape as `worker.py list --json`.
|
||||
*/
|
||||
async function listComfyModelsFromFs(
|
||||
type?: string
|
||||
): Promise<ComfyModelEntry[]> {
|
||||
const out: ComfyModelEntry[] = [];
|
||||
try {
|
||||
if (type) {
|
||||
// Single type — list its contents
|
||||
const typeDir = path.join(COMFY_MODELS_DIR, type);
|
||||
const stat = await fs.stat(typeDir).catch(() => null);
|
||||
if (!stat || !stat.isDirectory()) return [];
|
||||
const entries = await fs.readdir(typeDir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
if (entry.name.startsWith(".")) continue;
|
||||
const full = path.join(typeDir, entry.name);
|
||||
const size = await fs.stat(full).then((s) => s.size).catch(() => 0);
|
||||
out.push({
|
||||
type,
|
||||
filename: entry.name,
|
||||
sizeBytes: size,
|
||||
sizeHuman: size > 0 ? humanSize(size) : undefined,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// All types — walk each subdir
|
||||
const types = await listComfyTypesFromFs();
|
||||
for (const t of types) {
|
||||
const typeDir = path.join(COMFY_MODELS_DIR, t);
|
||||
const entries = await fs.readdir(typeDir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile()) continue;
|
||||
if (entry.name.startsWith(".")) continue;
|
||||
const full = path.join(typeDir, entry.name);
|
||||
const size = await fs.stat(full).then((s) => s.size).catch(() => 0);
|
||||
out.push({
|
||||
type: t,
|
||||
filename: entry.name,
|
||||
sizeBytes: size,
|
||||
sizeHuman: size > 0 ? humanSize(size) : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function listComfyModels(
|
||||
type?: string
|
||||
): Promise<{ ok: boolean; models: ComfyModelEntry[]; raw: string; error?: string }> {
|
||||
// Use the new --json flag so we get structured output instead of having to
|
||||
// parse the human-readable table.
|
||||
// Try the model-worker first — it knows which files are real models vs
|
||||
// metadata files (.txt etc.) and follows ComfyUI's naming conventions.
|
||||
const args = ["list"];
|
||||
if (type) args.push(type);
|
||||
args.push("--json");
|
||||
const res = await modelWorkerExec(...args);
|
||||
if (!res.ok) {
|
||||
return { ok: false, models: [], raw: res.output, error: res.error };
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(res.output);
|
||||
// worker.py outputs {"models": [...], "total": N, "totalBytes": N}
|
||||
// or {"error": "...", "available_types": [...]} on type-not-found
|
||||
if (parsed.error) {
|
||||
return {
|
||||
ok: false,
|
||||
models: [],
|
||||
raw: res.output,
|
||||
error: parsed.error,
|
||||
};
|
||||
|
||||
if (res.ok) {
|
||||
try {
|
||||
const parsed = JSON.parse(res.output);
|
||||
if (parsed.error) {
|
||||
return {
|
||||
ok: false,
|
||||
models: [],
|
||||
raw: res.output,
|
||||
error: parsed.error,
|
||||
};
|
||||
}
|
||||
const arr: ComfyModelEntry[] = (parsed.models || []).map(
|
||||
(m: { type: string; filename: string; sizeBytes?: number }) => ({
|
||||
type: m.type,
|
||||
filename: m.filename,
|
||||
sizeBytes: m.sizeBytes,
|
||||
sizeHuman: m.sizeBytes ? humanSize(m.sizeBytes) : undefined,
|
||||
})
|
||||
);
|
||||
return { ok: true, models: arr, raw: res.output };
|
||||
} catch {
|
||||
// Fall through to fs fallback
|
||||
}
|
||||
const arr: ComfyModelEntry[] = (parsed.models || []).map(
|
||||
(m: { type: string; filename: string; sizeBytes?: number }) => ({
|
||||
type: m.type,
|
||||
filename: m.filename,
|
||||
sizeBytes: m.sizeBytes,
|
||||
sizeHuman: m.sizeBytes ? humanSize(m.sizeBytes) : undefined,
|
||||
})
|
||||
);
|
||||
return { ok: true, models: arr, raw: res.output };
|
||||
} catch {
|
||||
// Probably worker.py without --json support (older version)
|
||||
return { ok: true, models: [], raw: res.output };
|
||||
}
|
||||
|
||||
// Fallback: read directly from the filesystem. Useful when:
|
||||
// - model-worker container isn't running (e.g. during sleep mode)
|
||||
// - worker.py doesn't support --json flag (older version)
|
||||
// - docker exec fails for any reason
|
||||
const models = await listComfyModelsFromFs(type);
|
||||
return {
|
||||
ok: true,
|
||||
models,
|
||||
raw: res.output || "",
|
||||
error: res.ok ? undefined : res.error,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getComfyTypes(): Promise<{
|
||||
@@ -1012,17 +1325,30 @@ export async function getComfyTypes(): Promise<{
|
||||
raw: string;
|
||||
error?: string;
|
||||
}> {
|
||||
// Uses the new `worker.py types` command — outputs JSON array of strings.
|
||||
// Falls back to an empty list if the worker version doesn't support it yet.
|
||||
// Try the model-worker first.
|
||||
const res = await modelWorkerExec("types");
|
||||
if (!res.ok) return { ok: false, types: [], raw: res.output, error: res.error };
|
||||
try {
|
||||
const parsed = JSON.parse(res.output);
|
||||
const arr: string[] = Array.isArray(parsed) ? parsed : [];
|
||||
return { ok: true, types: arr, raw: res.output };
|
||||
} catch {
|
||||
return { ok: true, types: [], raw: res.output };
|
||||
if (res.ok) {
|
||||
try {
|
||||
const parsed = JSON.parse(res.output);
|
||||
const arr: string[] = Array.isArray(parsed) ? parsed : [];
|
||||
if (arr.length > 0) {
|
||||
return { ok: true, types: arr, raw: res.output };
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: read subdirectories of gpu/comfy/models directly.
|
||||
// The model-worker container might not be running (sleep mode), but the
|
||||
// directory is mounted into the dashboard container at /project/gpu/comfy.
|
||||
const types = await listComfyTypesFromFs();
|
||||
return {
|
||||
ok: types.length > 0,
|
||||
types,
|
||||
raw: res.output || "",
|
||||
error: types.length > 0 ? undefined : res.error || "no types found",
|
||||
};
|
||||
}
|
||||
|
||||
export interface ComfyQueueEntry {
|
||||
|
||||
556
dashboard/src/lib/downloads.ts
Normal file
556
dashboard/src/lib/downloads.ts
Normal file
@@ -0,0 +1,556 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
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<DashboardSettings> {
|
||||
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<void> {
|
||||
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/<id> (model page) → convert to /api/download/models/<id>
|
||||
// Pattern 2: /models/<id>/<slug> (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/<id> — 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
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// 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;
|
||||
/** 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;
|
||||
bytesTotal: number | null;
|
||||
percent: number;
|
||||
speedBytesPerSec: number | null;
|
||||
startedAt: number;
|
||||
finishedAt: number | null;
|
||||
error: string | null;
|
||||
// Internal — child process handle for cancellation
|
||||
_child?: ReturnType<typeof spawn>;
|
||||
// Subscribers notified on every progress event
|
||||
_subscribers: Set<(job: DownloadJob) => void>;
|
||||
}
|
||||
|
||||
const _jobs = new Map<string, DownloadJob>();
|
||||
|
||||
// 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(
|
||||
rawUrl: string,
|
||||
filenameOverride?: string
|
||||
): Promise<DownloadJob> {
|
||||
// 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 {
|
||||
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,
|
||||
originalUrl: rawUrl !== url ? rawUrl : undefined,
|
||||
urlNote: urlNote || undefined,
|
||||
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 <file> 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<void>((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<number | null> {
|
||||
// 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<string, number> = {
|
||||
"": 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<DownloadJob, "_child" | "_subscribers"> {
|
||||
const { _child: _c, _subscribers: _s, ...rest } = job;
|
||||
void _c;
|
||||
void _s;
|
||||
return rest;
|
||||
}
|
||||
Reference in New Issue
Block a user