feat: Llama Dashboard — web UI for managing launch parameters #1

Merged
mikan merged 1 commits from feature/llama-dashboard into master 2026-10-23 22:26:29 +00:00
35 changed files with 10832 additions and 2 deletions

View File

@@ -3,4 +3,5 @@ TS_AUTHKEY=
WEBDAV_USER=operator
WEBDAV_PASS=
HOST_PROJECT_PATH=
LLAMA_MODEL=model.gguf
LLAMA_MODEL=model.gguf
LLAMA_EXTRA_ARGS=

4
.gitignore vendored
View File

@@ -29,6 +29,10 @@ comfyui/run/
# Model worker
gpu/model-worker/*
# Dashboard persisted config (created at runtime)
gpu/dashboard/*
!gpu/dashboard/.gitkeep
# Environment / secrets
.env
*.env

View File

@@ -4,6 +4,7 @@ set -eu
IMAGE_SSH="gpu-node-ssh"
IMAGE_MODEL_WORKER="gpu-node-model-worker"
IMAGE_GPU_TEST="gpu-node-gpu-test"
IMAGE_DASHBOARD="gpu-node-dashboard"
echo "==> Building SSH image..."
docker build -t "$IMAGE_SSH" ./ssh
@@ -11,6 +12,9 @@ docker build -t "$IMAGE_SSH" ./ssh
echo "==> Building Model Worker image..."
docker build -t "$IMAGE_MODEL_WORKER" ./model-worker
echo "==> Building Dashboard image..."
docker build -t "$IMAGE_DASHBOARD" ./dashboard
echo "==> Building GPU Test image..."
if [ -f "./gpu-test/Dockerfile" ]; then
docker build -t "$IMAGE_GPU_TEST" ./gpu-test

View File

@@ -156,6 +156,24 @@ services:
- "node.role=comfyui"
- "node.instance=${TAILSCALE_HOSTNAME:-gpu-node}"
dashboard:
image: gpu-node-dashboard
container_name: ${TAILSCALE_HOSTNAME:-gpu-node}-dashboard
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ${HOST_PROJECT_PATH:-./}:/project
environment:
HOST_PROJECT_PATH: ${HOST_PROJECT_PATH}
PROJECT_DIR: /project
LLAMA_MODELS_DIR: /project/gpu/llama_models
NODE_INSTANCE: ${TAILSCALE_HOSTNAME:-gpu-node}
networks:
- gpu-node
restart: always
labels:
- "node.role=dashboard"
- "node.instance=${TAILSCALE_HOSTNAME:-gpu-node}"
networks:
gpu-node:
name: ${TAILSCALE_HOSTNAME:-gpu-node}

3
dashboard/.eslintrc.json Normal file
View File

@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}

33
dashboard/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
# dependencies
/node_modules
/.pnp
.pnp.*
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files
.env
.env*.local
# typescript
*.tsbuildinfo
next-env.d.ts
# editor
.idea/
.vscode/

68
dashboard/Dockerfile Normal file
View File

@@ -0,0 +1,68 @@
# syntax=docker/dockerfile:1.7
# ---------------------------------------------------------------------------
# Stage 1: Install deps & build Next.js standalone output
# ---------------------------------------------------------------------------
FROM node:20-alpine AS builder
WORKDIR /app
# Install dependencies (use yarn or npm — package-lock.json optional)
COPY package.json ./
COPY package-lock.json* ./
COPY yarn.lock* ./
RUN if [ -f yarn.lock ]; then \
yarn install --frozen-lockfile; \
elif [ -f package-lock.json ]; then \
npm ci; \
else \
npm install; \
fi
# Copy sources and build
COPY tsconfig.json next.config.ts next-env.d.ts postcss.config.mjs .eslintrc.json ./
COPY src ./src
COPY public ./public
ENV NEXT_TELEMETRY_DISABLED=1
RUN if [ -f yarn.lock ]; then \
yarn build; \
else \
npm run build; \
fi
# ---------------------------------------------------------------------------
# Stage 2: Runtime — Alpine + Node + docker-cli + docker compose plugin
# ---------------------------------------------------------------------------
FROM node:20-alpine AS runtime
# docker-cli + compose plugin + tini for proper signal handling
RUN apk add --no-cache \
docker \
docker-cli-compose \
tini \
ca-certificates \
wget \
&& addgroup -g 1001 dash \
&& adduser -D -G dash -u 1001 dash
WORKDIR /app
# Copy standalone Next.js build output
COPY --from=builder --chown=dash:dash /app/.next/standalone ./
COPY --from=builder --chown=dash:dash /app/.next/static ./.next/static
COPY --from=builder --chown=dash:dash /app/public ./public
USER dash
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
ENV NEXT_TELEMETRY_DISABLED=1
EXPOSE 3000
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "server.js"]

75
dashboard/README.md Normal file
View File

@@ -0,0 +1,75 @@
# GPU-Node Dashboard
A small Next.js web dashboard for managing the llama.cpp instance running on the
GPU node. Replaces the need to manually edit `.env` and call `gpuctl` over SSH.
## Features
- **Status overview** — live view of all containers (llama, ssh, comfyui, etc.)
for the current node instance, with health check + auto-refresh.
- **Models list** — scans `gpu/llama_models/*.gguf` and shows sizes / modified
time; click "Use" to switch the active model in the launch config.
- **Launch config** — structured form for `--ctx-size`, `--parallel`,
`--n-gpu-layers`, `--threads`, `--batch-size`, `--context-overflow`,
speculative decoding (`--spec-type`, `--model-draft`, `--spec-draft-n-max`),
and a free-form extra args textarea for anything else.
- **Presets** — save named configurations and reload them with one click.
- **Start / Restart / Stop / Remove** llama container via docker compose.
- **Live logs** — streaming `docker logs -f` with color-coded output.
- **GPU status** — runs `nvidia-smi` via `docker exec` on the llama container
(or falls back to `docker compose run --rm gpu-test nvidia-smi ...`).
- **Auto-writes `.env`** — every "Apply / Start" persists the current
`LLAMA_MODEL` and `LLAMA_EXTRA_ARGS` back to `.env`, so the existing
workflow keeps working.
## How it integrates
The dashboard runs as a new `dashboard` service in `compose.yaml`. It mounts:
- `/var/run/docker.sock` → can run `docker compose` and `docker ps` commands
- The host project path (read/write so it can edit `.env` and save presets)
On every "Start / Apply" action, the dashboard:
1. Persists the structured config to `gpu/dashboard-config.json`.
2. Writes `LLAMA_MODEL` and `LLAMA_EXTRA_ARGS` to `.env` (preserving other vars).
3. Runs `docker compose --profile llama up -d --force-recreate llama` with the
same env vars inlined — identical to `gpuctl start llama <model> <args>`.
The dashboard is exposed via Tailscale serve on port **8090**.
## Local development
```sh
cd dashboard
npm install
npm run dev
```
You will need to set the same env vars the container would set:
```sh
export HOST_PROJECT_PATH=/path/to/GPU-Node # absolute path on host
export PROJECT_DIR=/path/to/GPU-Node # path mounted inside the dev shell
export NODE_INSTANCE=gpu-node
```
You also need `docker` and `docker compose` available on your `$PATH`, and the
current user must be in a group that can access `/var/run/docker.sock`.
## Building the image
```sh
docker build -t gpu-node-dashboard ./dashboard
```
Or via the project's `build.sh` after this PR merges — that script will be
extended to build the dashboard image as well.
## Tech stack
- Next.js 16 (standalone output, App Router)
- React 19 + TypeScript 5
- Tailwind CSS 4 + shadcn-style components
- Radix UI primitives (select, tabs, switch, label)
- lucide-react icons

15
dashboard/next.config.ts Normal file
View File

@@ -0,0 +1,15 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
reactStrictMode: true,
// Allow the dashboard to call docker compose via spawned subprocesses.
// Server-side API routes use Node fs/exec — that's fine in standalone.
experimental: {
serverActions: {
bodySizeLimit: "2mb",
},
},
};
export default nextConfig;

7706
dashboard/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
dashboard/package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "gpu-node-dashboard",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3000",
"build": "next build",
"start": "next start -p 3000",
"lint": "next lint"
},
"dependencies": {
"next": "16.0.0",
"react": "19.0.0",
"react-dom": "19.0.0",
"lucide-react": "^0.456.0",
"clsx": "^2.1.1",
"tailwind-merge": "^2.5.4",
"class-variance-authority": "^0.7.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-tabs": "^1.1.1",
"@radix-ui/react-switch": "^1.1.1",
"@radix-ui/react-toast": "^1.2.2"
},
"devDependencies": {
"@types/node": "^22.9.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"typescript": "^5.6.3",
"tailwindcss": "^4.0.0-beta.3",
"@tailwindcss/postcss": "^4.0.0-beta.3",
"postcss": "^8.4.49",
"eslint": "^9.14.0",
"eslint-config-next": "16.0.0"
}
}

View File

@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

View File

@@ -0,0 +1,112 @@
import { NextRequest, NextResponse } from "next/server";
import {
loadConfig,
saveConfig,
DEFAULT_CONFIG,
type DashboardConfig,
type Preset,
} from "@/lib/docker";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export async function GET() {
const config = await loadConfig();
return NextResponse.json({ config, defaults: DEFAULT_CONFIG });
}
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,
};
await saveConfig(next);
return NextResponse.json({ config: next });
}
// ----- Presets -------------------------------------------------------------
export async function POST(req: NextRequest) {
const body = (await req.json()) as {
action: "save-preset" | "delete-preset" | "load-preset" | "reset";
name?: string;
id?: string;
};
const current = await loadConfig();
if (body.action === "save-preset") {
if (!body.name) {
return NextResponse.json(
{ error: "name is required" },
{ status: 400 }
);
}
const preset: Preset = {
id: `preset-${Date.now()}`,
name: body.name,
config: stripPresets(current),
createdAt: new Date().toISOString(),
};
const next: DashboardConfig = {
...current,
presets: [...current.presets.filter((p) => p.name !== body.name), preset],
};
await saveConfig(next);
return NextResponse.json({ config: next });
}
if (body.action === "delete-preset") {
if (!body.id) {
return NextResponse.json({ error: "id is required" }, { status: 400 });
}
const next: DashboardConfig = {
...current,
presets: current.presets.filter((p) => p.id !== body.id),
};
await saveConfig(next);
return NextResponse.json({ config: next });
}
if (body.action === "load-preset") {
if (!body.id) {
return NextResponse.json({ error: "id is required" }, { status: 400 });
}
const preset = current.presets.find((p) => p.id === body.id);
if (!preset) {
return NextResponse.json({ error: "preset not found" }, { status: 404 });
}
const next: DashboardConfig = {
...preset.config,
presets: current.presets,
};
await saveConfig(next);
return NextResponse.json({ config: next });
}
if (body.action === "reset") {
await saveConfig({ ...DEFAULT_CONFIG, presets: current.presets });
return NextResponse.json({ config: { ...DEFAULT_CONFIG, presets: current.presets } });
}
return NextResponse.json({ error: "unknown action" }, { status: 400 });
}
function stripPresets(cfg: DashboardConfig): Omit<DashboardConfig, "presets"> {
const { presets: _presets, ...rest } = cfg;
return rest;
}

View File

@@ -0,0 +1,11 @@
import { NextRequest, NextResponse } from "next/server";
import { getGpuStatus } from "@/lib/docker";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export const maxDuration = 60;
export async function GET(_req: NextRequest) {
const status = await getGpuStatus();
return NextResponse.json(status, { status: status.ok ? 200 : 500 });
}

View File

@@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from "next/server";
import {
loadConfig,
startLlama,
stopLlama,
restartLlama,
removeLlama,
type DashboardConfig,
} from "@/lib/docker";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export async function POST(req: NextRequest) {
const body = (await req.json()) as {
action: "start" | "stop" | "restart" | "remove";
config?: Partial<DashboardConfig>;
};
if (body.action === "start") {
const current = await loadConfig();
const cfg: DashboardConfig = {
...current,
...(body.config || {}),
} as DashboardConfig;
const result = await startLlama(cfg);
return NextResponse.json(result, { status: result.ok ? 200 : 500 });
}
if (body.action === "stop") {
const result = await stopLlama();
return NextResponse.json(result, { status: result.ok ? 200 : 500 });
}
if (body.action === "restart") {
const result = await restartLlama();
return NextResponse.json(result, { status: result.ok ? 200 : 500 });
}
if (body.action === "remove") {
const result = await removeLlama();
return NextResponse.json(result, { status: result.ok ? 200 : 500 });
}
return NextResponse.json({ error: "unknown action" }, { status: 400 });
}

View File

@@ -0,0 +1,76 @@
import { NextRequest } from "next/server";
import { getLlamaContainerName } from "@/lib/docker";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export const maxDuration = 300;
export async function GET(req: NextRequest) {
const name = await getLlamaContainerName();
if (!name) {
return new Response("[llama container not found]", {
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
},
});
}
const tail = Number(req.nextUrl.searchParams.get("tail") || 500);
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
controller.enqueue(
encoder.encode(
`=== Streaming logs for ${name} (tail=${tail}) ===\n`
)
);
const { spawn } = await import("node:child_process");
const child = spawn("docker", ["logs", "-f", "--tail", String(tail), "--timestamps", name]);
const enqueue = (chunk: Buffer | string) => {
try {
controller.enqueue(encoder.encode(chunk.toString()));
} catch {
/* stream closed */
}
};
child.stdout.on("data", enqueue);
child.stderr.on("data", enqueue);
child.on("error", (err) => {
controller.enqueue(encoder.encode(`[stream error: ${err.message}]\n`));
controller.close();
});
child.on("exit", () => {
try {
controller.close();
} catch {
/* already closed */
}
});
// Abort signal from client disconnect
req.signal.addEventListener("abort", () => {
try {
child.kill("SIGTERM");
} catch {
/* noop */
}
});
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
Connection: "keep-alive",
},
});
}

View File

@@ -0,0 +1,10 @@
import { NextResponse } from "next/server";
import { listModels } from "@/lib/docker";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export async function GET() {
const models = await listModels();
return NextResponse.json({ models });
}

View File

@@ -0,0 +1,18 @@
import { NextResponse } from "next/server";
import { listContainers, getLlamaHealth, NODE_INSTANCE } from "@/lib/docker";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export async function GET() {
const [containers, llamaHealth] = await Promise.all([
listContainers(),
getLlamaHealth(),
]);
return NextResponse.json({
instance: NODE_INSTANCE,
containers,
llamaHealth,
timestamp: new Date().toISOString(),
});
}

View File

@@ -0,0 +1,119 @@
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 240 5.9% 10%;
--primary-foreground: 0 0% 98%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--success: 142 71% 45%;
--success-foreground: 0 0% 98%;
--warning: 38 92% 50%;
--warning-foreground: 0 0% 98%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 240 5.9% 10%;
--radius: 0.5rem;
}
.dark {
--background: 240 10% 3.9%;
--foreground: 0 0% 98%;
--card: 240 10% 5.9%;
--card-foreground: 0 0% 98%;
--popover: 240 10% 5.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 240 5.9% 10%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 240 3.7% 15.9%;
--muted-foreground: 240 5% 64.9%;
--accent: 240 3.7% 15.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--success: 142 71% 45%;
--success-foreground: 0 0% 98%;
--warning: 38 92% 50%;
--warning-foreground: 0 0% 98%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 240 4.9% 83.9%;
}
@theme inline {
--color-background: hsl(var(--background));
--color-foreground: hsl(var(--foreground));
--color-card: hsl(var(--card));
--color-card-foreground: hsl(var(--card-foreground));
--color-popover: hsl(var(--popover));
--color-popover-foreground: hsl(var(--popover-foreground));
--color-primary: hsl(var(--primary));
--color-primary-foreground: hsl(var(--primary-foreground));
--color-secondary: hsl(var(--secondary));
--color-secondary-foreground: hsl(var(--secondary-foreground));
--color-muted: hsl(var(--muted));
--color-muted-foreground: hsl(var(--muted-foreground));
--color-accent: hsl(var(--accent));
--color-accent-foreground: hsl(var(--accent-foreground));
--color-destructive: hsl(var(--destructive));
--color-destructive-foreground: hsl(var(--destructive-foreground));
--color-success: hsl(var(--success));
--color-success-foreground: hsl(var(--success-foreground));
--color-warning: hsl(var(--warning));
--color-warning-foreground: hsl(var(--warning-foreground));
--color-border: hsl(var(--border));
--color-input: hsl(var(--input));
--color-ring: hsl(var(--ring));
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
* {
border-color: hsl(var(--border));
}
body {
background-color: hsl(var(--background));
color: hsl(var(--foreground));
font-feature-settings: "rlig" 1, "calt" 1;
}
/* Custom scrollbar for log viewers and lists */
.scrollbar-thin::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.scrollbar-thin::-webkit-scrollbar-track {
background: transparent;
}
.scrollbar-thin::-webkit-scrollbar-thumb {
background-color: hsl(var(--muted-foreground) / 0.3);
border-radius: 4px;
}
.scrollbar-thin::-webkit-scrollbar-thumb:hover {
background-color: hsl(var(--muted-foreground) / 0.5);
}
/* Logs terminal-style */
.logs-terminal {
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
font-size: 12px;
line-height: 1.5;
}

View File

@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "GPU Node · Llama Dashboard",
description: "Manage llama.cpp instance, models, and launch parameters",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className="dark" suppressHydrationWarning>
<body className="min-h-screen bg-background text-foreground antialiased">
{children}
</body>
</html>
);
}

1336
dashboard/src/app/page.tsx Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium transition-colors focus:outline-none focus:ring-1 focus:ring-ring",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground",
secondary:
"border-transparent bg-secondary text-secondary-foreground",
success:
"border-transparent bg-success/15 text-success",
warning:
"border-transparent bg-warning/15 text-warning",
destructive:
"border-transparent bg-destructive/15 text-destructive",
outline: "text-foreground",
},
},
defaultVariants: { variant: "default" },
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,53 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
success: "bg-success text-success-foreground hover:bg-success/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-6",
icon: "h-9 w-9",
},
},
defaultVariants: { variant: "default", size: "default" },
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
ref={ref}
className={cn(buttonVariants({ variant, size }), className)}
{...props}
/>
);
}
);
Button.displayName = "Button";
export { Button, buttonVariants };

View File

@@ -0,0 +1,82 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className
)}
{...props}
/>
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-4", className)}
{...props}
/>
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-xs text-muted-foreground", className)}
{...props}
/>
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-4 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-4 pt-0", className)}
{...props}
/>
));
CardFooter.displayName = "CardFooter";
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};

View File

@@ -0,0 +1,20 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<
HTMLInputElement,
React.InputHTMLAttributes<HTMLInputElement>
>(({ className, type, ...props }, ref) => (
<input
type={type}
ref={ref}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
));
Input.displayName = "Input";
export { Input };

View File

@@ -0,0 +1,22 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "@/lib/utils";
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(
"text-xs font-medium leading-none text-muted-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
className
)}
{...props}
/>
));
Label.displayName = "Label";
export { Label };

View File

@@ -0,0 +1,91 @@
"use client";
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectItem,
};

View File

@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import * as SwitchPrimitives from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };

View File

@@ -0,0 +1,54 @@
"use client";
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "@/lib/utils";
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
className
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -0,0 +1,19 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.TextareaHTMLAttributes<HTMLTextAreaElement>
>(({ className, ...props }, ref) => (
<textarea
ref={ref}
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
));
Textarea.displayName = "Textarea";
export { Textarea };

620
dashboard/src/lib/docker.ts Normal file
View File

@@ -0,0 +1,620 @@
import { exec, spawn, type ExecOptions } from "node:child_process";
import { promisify } from "node:util";
import { promises as fs } from "node:fs";
import path from "node:path";
const execAsync = promisify(exec);
// ---------------------------------------------------------------------------
// Environment / paths
// ---------------------------------------------------------------------------
/**
* Internal mount of the GPU-Node project (compose.yaml lives here).
*/
export const PROJECT_DIR = process.env.PROJECT_DIR || "/project";
/**
* Host-side absolute path of the GPU-Node project. Required so that when the
* dashboard spawns `docker compose`, the compose file's relative volume mounts
* resolve correctly on the host (where Docker daemon actually runs).
*/
export const HOST_PROJECT_PATH =
process.env.HOST_PROJECT_PATH || "/project";
/**
* Internal mount of the llama_models directory.
*/
export const LLAMA_MODELS_DIR =
process.env.LLAMA_MODELS_DIR || path.join(PROJECT_DIR, "gpu", "llama_models");
/**
* Node instance name (used for filtering containers by label).
*/
export const NODE_INSTANCE =
process.env.NODE_INSTANCE || process.env.TAILSCALE_HOSTNAME || "gpu-node";
/**
* Compose file path (relative to PROJECT_DIR).
*/
const COMPOSE_FILE = path.join(PROJECT_DIR, "compose.yaml");
/**
* Path to the persisted dashboard config (last-used + saved presets).
*/
export const DASHBOARD_CONFIG_PATH = path.join(
PROJECT_DIR,
"gpu",
"dashboard",
"config.json"
);
/**
* Path to the project's .env file (used to persist LLAMA_MODEL/LLAMA_EXTRA_ARGS
* so users can still inspect the .env if they prefer).
*/
export const ENV_FILE_PATH = path.join(PROJECT_DIR, ".env");
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface ContainerInfo {
name: string;
status: string;
state: string;
running: boolean;
ports: string;
image: string;
role: string | null;
createdAt: string;
/** Formatted "Up X minutes" or "Exited N minutes ago" */
statusText: string;
}
export interface ModelFile {
name: string;
sizeBytes: number;
sizeHuman: string;
modifiedAt: string;
}
export interface DashboardConfig {
/** Currently-selected model file (e.g., "model.gguf") */
model: string;
/** ctx-size parameter */
ctxSize: number;
/** parallel slots */
parallel: number;
/** Number of GPU layers, -1 = all */
nGpuLayers: number;
/** Number of threads, -1 = default */
threads: number;
/** Optional draft model file */
draftModel: string;
/** Speculative decoding type */
specType: "none" | "draft-mtp" | "draft-llama";
/** Max draft tokens */
specDraftNMax: number;
/** Batch size */
batchSize: number;
/** UB / KV cache size etc */
contextOverflow: "none" | "shift" | "evict";
/** Free-form extra args (advanced) */
extraArgs: string;
/** Saved presets */
presets: Preset[];
}
export interface Preset {
id: string;
name: string;
config: Omit<DashboardConfig, "presets">;
createdAt: string;
}
export const DEFAULT_CONFIG: DashboardConfig = {
model: "model.gguf",
ctxSize: 64000,
parallel: 1,
nGpuLayers: -1,
threads: -1,
draftModel: "",
specType: "none",
specDraftNMax: 4,
batchSize: 512,
contextOverflow: "none",
extraArgs: "",
presets: [],
};
// ---------------------------------------------------------------------------
// Config persistence
// ---------------------------------------------------------------------------
export async function loadConfig(): Promise<DashboardConfig> {
try {
const raw = await fs.readFile(DASHBOARD_CONFIG_PATH, "utf-8");
const parsed = JSON.parse(raw);
return { ...DEFAULT_CONFIG, ...parsed, presets: parsed.presets ?? [] };
} catch {
// Try to seed from .env if present
const envConfig = await readConfigFromEnv();
if (envConfig) return envConfig;
return DEFAULT_CONFIG;
}
}
export async function saveConfig(config: DashboardConfig): Promise<void> {
await fs.mkdir(path.dirname(DASHBOARD_CONFIG_PATH), { recursive: true });
await fs.writeFile(
DASHBOARD_CONFIG_PATH,
JSON.stringify(config, null, 2),
"utf-8"
);
}
async function readConfigFromEnv(): Promise<DashboardConfig | null> {
try {
const raw = await fs.readFile(ENV_FILE_PATH, "utf-8");
const env: Record<string, string> = {};
for (const line of raw.split("\n")) {
const m = line.match(/^([A-Z_]+)=(.*)$/);
if (m) env[m[1]] = m[2];
}
if (env.LLAMA_MODEL || env.LLAMA_EXTRA_ARGS) {
const cfg = parseLlamaExtraArgs(
env.LLAMA_EXTRA_ARGS || "",
env.LLAMA_MODEL || DEFAULT_CONFIG.model
);
return { ...DEFAULT_CONFIG, ...cfg };
}
} catch {
/* ignore */
}
return null;
}
/**
* Parse LLAMA_EXTRA_ARGS string into structured config fields.
* Anything we can't recognize lands in extraArgs.
*/
export function parseLlamaExtraArgs(
raw: string,
model: string
): Omit<DashboardConfig, "presets"> {
const cfg: Omit<DashboardConfig, "presets"> = { ...DEFAULT_CONFIG, model };
const remaining: string[] = [];
// Split respecting quoted args
const tokens = (raw.match(/(?:[^\s"]+|"[^"]*")+/g) || []).map((t) =>
t.replace(/^"|"$/g, "")
);
for (let i = 0; i < tokens.length; i++) {
const tok = tokens[i];
const next = tokens[i + 1];
switch (tok) {
case "--ctx-size":
cfg.ctxSize = Number(next) || cfg.ctxSize;
i++;
break;
case "--parallel":
cfg.parallel = Number(next) || cfg.parallel;
i++;
break;
case "--n-gpu-layers":
case "-ngl":
cfg.nGpuLayers = Number(next);
i++;
break;
case "--threads":
case "-t":
cfg.threads = Number(next);
i++;
break;
case "--batch-size":
case "-b":
cfg.batchSize = Number(next) || cfg.batchSize;
i++;
break;
case "--model-draft":
cfg.draftModel = path.basename(next || "");
i++;
break;
case "--spec-type":
cfg.specType = (next as DashboardConfig["specType"]) || cfg.specType;
i++;
break;
case "--spec-draft-n-max":
cfg.specDraftNMax = Number(next) || cfg.specDraftNMax;
i++;
break;
case "--context-overflow":
cfg.contextOverflow =
(next as DashboardConfig["contextOverflow"]) || cfg.contextOverflow;
i++;
break;
default:
if (tok.startsWith("--") && next && !next.startsWith("--")) {
remaining.push(`${tok} ${next}`);
i++;
} else {
remaining.push(tok);
}
}
}
cfg.extraArgs = remaining.join(" ").trim();
return cfg;
}
/**
* Convert structured config into LLAMA_EXTRA_ARGS string.
*/
export function buildLlamaExtraArgs(cfg: DashboardConfig): string {
const parts: string[] = [];
parts.push(`--ctx-size ${cfg.ctxSize}`);
parts.push(`--parallel ${cfg.parallel}`);
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}`);
if (cfg.contextOverflow !== "none")
parts.push(`--context-overflow ${cfg.contextOverflow}`);
if (cfg.specType !== "none") {
parts.push(`--spec-type ${cfg.specType}`);
if (cfg.draftModel) {
parts.push(`--model-draft /models/${cfg.draftModel}`);
parts.push(`--spec-draft-n-max ${cfg.specDraftNMax}`);
}
}
if (cfg.extraArgs.trim()) parts.push(cfg.extraArgs.trim());
return parts.join(" ");
}
/**
* Persist LLAMA_MODEL and LLAMA_EXTRA_ARGS to the .env file so the existing
* workflow (and anyone reading .env) still sees the active configuration.
* Other env keys are preserved.
*/
export async function writeEnvLlamaConfig(
model: string,
extraArgs: string
): Promise<void> {
let lines: string[] = [];
try {
const raw = await fs.readFile(ENV_FILE_PATH, "utf-8");
lines = raw.split("\n");
} catch {
/* no .env yet */
}
let hasModel = false;
let hasExtra = false;
const out: string[] = [];
for (const line of lines) {
if (/^LLAMA_MODEL=/.test(line)) {
out.push(`LLAMA_MODEL=${model}`);
hasModel = true;
} else if (/^LLAMA_EXTRA_ARGS=/.test(line)) {
out.push(`LLAMA_EXTRA_ARGS=${extraArgs}`);
hasExtra = true;
} else {
out.push(line);
}
}
if (!hasModel) out.push(`LLAMA_MODEL=${model}`);
if (!hasExtra) out.push(`LLAMA_EXTRA_ARGS=${extraArgs}`);
await fs.writeFile(ENV_FILE_PATH, out.join("\n").replace(/\n+$/, "\n"), "utf-8");
}
// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------
export async function listModels(): Promise<ModelFile[]> {
try {
const entries = await fs.readdir(LLAMA_MODELS_DIR, { withFileTypes: true });
const models: ModelFile[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
if (entry.name.startsWith(".")) continue;
if (!entry.name.toLowerCase().endsWith(".gguf")) continue;
const full = path.join(LLAMA_MODELS_DIR, entry.name);
const stat = await fs.stat(full);
models.push({
name: entry.name,
sizeBytes: stat.size,
sizeHuman: humanSize(stat.size),
modifiedAt: stat.mtime.toISOString(),
});
}
models.sort((a, b) => b.sizeBytes - a.sizeBytes);
return models;
} catch {
return [];
}
}
function humanSize(bytes: number): string {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
const v = bytes / Math.pow(1024, i);
return `${v.toFixed(v >= 100 ? 0 : v >= 10 ? 1 : 2)} ${units[i]}`;
}
// ---------------------------------------------------------------------------
// Docker / Compose control
// ---------------------------------------------------------------------------
function composeEnv(extra: Record<string, string> = {}): NodeJS.ProcessEnv {
return {
...process.env,
HOST_PROJECT_PATH,
NODE_INSTANCE,
...extra,
};
}
async function runCompose(
args: string[],
env: Record<string, string> = {}
): Promise<{ stdout: string; stderr: string; code: number }> {
const opts: ExecOptions = {
cwd: PROJECT_DIR,
env: composeEnv(env),
maxBuffer: 16 * 1024 * 1024,
};
try {
const { stdout, stderr } = await execAsync(
`docker compose -f "${COMPOSE_FILE}" ${args.join(" ")}`,
opts
);
return {
stdout: String(stdout),
stderr: String(stderr),
code: 0,
};
} catch (err: unknown) {
const e = err as {
stdout?: string | Buffer;
stderr?: string | Buffer;
code?: number;
message: string;
};
return {
stdout: e.stdout ? String(e.stdout) : "",
stderr: e.stderr ? String(e.stderr) : e.message,
code: e.code ?? 1,
};
}
}
export async function listContainers(): Promise<ContainerInfo[]> {
const filter = `--filter label=node.instance=${NODE_INSTANCE}`;
const cmd = `docker ps -a ${filter} --format json`;
try {
const { stdout } = await execAsync(cmd, {
maxBuffer: 16 * 1024 * 1024,
});
const text = String(stdout);
const lines = text.split("\n").filter(Boolean);
const containers: ContainerInfo[] = [];
for (const line of lines) {
try {
const c = JSON.parse(line);
const labels: Record<string, string> = Object.fromEntries(
(c.Labels || "").split(",").map((kv: string) => {
const [k, v] = kv.split("=");
return [k, v ?? ""];
})
);
containers.push({
name: c.Names || c.Name,
status: c.Status,
state: c.State,
running: c.State === "running",
ports: c.Ports || "",
image: c.Image,
role: labels["node.role"] || null,
createdAt: c.CreatedAt || c.Created,
statusText: c.Status,
});
} catch {
/* skip malformed line */
}
}
return containers.sort((a, b) => a.name.localeCompare(b.name));
} catch {
return [];
}
}
export async function getLlamaContainer(): Promise<ContainerInfo | null> {
const list = await listContainers();
return list.find((c) => c.role === "llama") || null;
}
export interface StartResult {
ok: boolean;
message: string;
logs: string;
}
/**
* Start (or force-recreate) the llama service with the given config.
* Mirrors what `gpuctl start llama <model> <args>` does.
*/
export async function startLlama(
config: DashboardConfig
): Promise<StartResult> {
const extraArgs = buildLlamaExtraArgs(config);
// Persist current config so reloads restore it.
await saveConfig(config);
await writeEnvLlamaConfig(config.model, extraArgs);
const res = await runCompose(
[
"--profile",
"llama",
"up",
"-d",
"--force-recreate",
"llama",
],
{
LLAMA_MODEL: config.model,
LLAMA_EXTRA_ARGS: extraArgs,
}
);
const combined = res.stdout + (res.stderr ? `\n${res.stderr}` : "");
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama instance started" : "Failed to start",
logs: combined,
};
}
export async function stopLlama(): Promise<StartResult> {
const res = await runCompose(["stop", "llama"], {});
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama stopped" : "Failed to stop",
logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""),
};
}
export async function restartLlama(): Promise<StartResult> {
const res = await runCompose(["restart", "llama"], {});
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama restarted" : "Failed to restart",
logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""),
};
}
export async function removeLlama(): Promise<StartResult> {
// Equivalent to `gpuctl stop llama` followed by `docker rm -f` semantics.
const res = await runCompose(["rm", "-sf", "llama"], {});
return {
ok: res.code === 0,
message: res.code === 0 ? "Llama instance removed" : "Failed to remove",
logs: res.stdout + (res.stderr ? `\n${res.stderr}` : ""),
};
}
// ---------------------------------------------------------------------------
// Logs
// ---------------------------------------------------------------------------
/**
* Returns a Node ReadableStream of `docker logs -f <container>`.
* Caller pipes it to a Response stream.
*/
export function streamLlamaLogs(tail: number = 200) {
const child = spawn("docker", [
"logs",
"-f",
"--tail",
String(tail),
"--timestamps",
`--filter=label=node.role=llama`,
`--filter=label=node.instance=${NODE_INSTANCE}`,
]);
return child;
}
/**
* Get the actual llama container name (so we can `docker logs -f <name>`).
*/
export async function getLlamaContainerName(): Promise<string | null> {
try {
const { stdout } = await execAsync(
`docker ps -a --filter label=node.role=llama --filter label=node.instance=${NODE_INSTANCE} --format {{.Names}}`,
{ maxBuffer: 1 * 1024 * 1024 }
);
return String(stdout).trim().split("\n")[0] || null;
} catch {
return null;
}
}
export async function getLlamaLogsSnapshot(tail: number = 500): Promise<string> {
const name = await getLlamaContainerName();
if (!name) return "[llama container not found]";
try {
const { stdout } = await execAsync(
`docker logs --tail ${tail} ${name}`,
{ maxBuffer: 8 * 1024 * 1024 }
);
return String(stdout);
} catch (err) {
return `[failed to read logs: ${(err as Error).message}]`;
}
}
// ---------------------------------------------------------------------------
// GPU
// ---------------------------------------------------------------------------
export async function getGpuStatus(): Promise<{
ok: boolean;
output: string;
}> {
// Try to exec nvidia-smi on the llama container first; if not running,
// fall back to running `docker compose run --rm gpu-test nvidia-smi ...`
const name = await getLlamaContainerName();
if (name) {
try {
const { stdout } = await execAsync(
`docker exec ${name} nvidia-smi --query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw --format=csv`,
{ maxBuffer: 4 * 1024 * 1024 }
);
return { ok: true, output: String(stdout) };
} catch {
/* fall through */
}
}
const res = await runCompose(
[
"--profile",
"test",
"run",
"--rm",
"gpu-test",
"nvidia-smi",
"--query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw",
"--format=csv",
],
{}
);
return { ok: res.code === 0, output: res.stdout + res.stderr };
}
// ---------------------------------------------------------------------------
// Llama server health
// ---------------------------------------------------------------------------
export async function getLlamaHealth(): Promise<{
reachable: boolean;
detail: string;
}> {
// Llama.cpp /completion endpoint returns 405 on GET /, but /health works.
try {
const { stdout } = await execAsync(
`docker exec $(docker ps --filter label=node.role=llama --filter label=node.instance=${NODE_INSTANCE} --format {{.Names}} | head -n1) wget -qO- http://127.0.0.1:8080/health || true`,
{ maxBuffer: 1 * 1024 * 1024, timeout: 5000 }
);
const text = String(stdout);
if (text.includes("ok")) return { reachable: true, detail: text.trim() };
return { reachable: false, detail: text || "no response" };
} catch (err) {
return {
reachable: false,
detail: (err as Error).message,
};
}
}

View File

@@ -0,0 +1,41 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatBytes(bytes: number | null | undefined): string {
if (bytes == null || Number.isNaN(bytes)) return "—";
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
const value = bytes / Math.pow(1024, i);
return `${value.toFixed(value >= 100 ? 0 : value >= 10 ? 1 : 2)} ${units[i]}`;
}
export function formatDuration(seconds: number): string {
if (!seconds || seconds < 0) return "—";
const d = Math.floor(seconds / 86400);
const h = Math.floor((seconds % 86400) / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
const parts: string[] = [];
if (d > 0) parts.push(`${d}d`);
if (h > 0) parts.push(`${h}h`);
if (m > 0) parts.push(`${m}m`);
if (s > 0 || parts.length === 0) parts.push(`${s}s`);
return parts.join(" ");
}
export function timeAgo(iso: string | null | undefined): string {
if (!iso) return "—";
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return "—";
const diff = Date.now() - date.getTime();
const sec = Math.floor(diff / 1000);
if (sec < 60) return `${sec}s ago`;
if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;
return `${Math.floor(sec / 86400)}d ago`;
}

41
dashboard/tsconfig.json Normal file
View File

@@ -0,0 +1,41 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}

2
gpu/dashboard/.gitkeep Normal file
View File

@@ -0,0 +1,2 @@
# Placeholder for persisted dashboard config (config.json + presets).
# Files in this directory are gitignored; created at runtime by the dashboard.

View File

@@ -14,6 +14,9 @@
},
"8188": {
"TCPForward": "comfyui:8188"
},
"8090": {
"TCPForward": "dashboard:3000"
}
}
}
}