feat: add llama dashboard for managing launch config via web UI
Adds a small Next.js dashboard as a new Docker service () that replaces the need to manually edit and call over SSH every time you want to tweak llama launch parameters. Features: - Live status panel for all GPU-node containers (auto-refresh) - Models list with file sizes, click-to-select active model - Structured launch config form: * Model, ctx-size, parallel, batch-size, n-gpu-layers, threads * Context overflow (none / shift / evict) * Speculative decoding (spec-type, draft model, spec-draft-n-max) * Free-form extra args textarea for anything else - Named presets (save / load / delete) - Start / Restart / Stop / Remove llama actions - Live streaming logs viewer (docker logs -f) - GPU status (nvidia-smi via docker exec on llama) - Auto-writes LLAMA_MODEL and LLAMA_EXTRA_ARGS back to .env so the existing workflow keeps working, and persists full structured config to gpu/dashboard/config.json for reload on next visit Integration: - New service in compose.yaml (no profile, runs always) - Mounts /var/run/docker.sock + HOST_PROJECT_PATH - Tailscale serve exposes port 8090 -> dashboard:3000 - build.sh extended to build the dashboard image Tech: Next.js 16 standalone, React 19, TypeScript 5, Tailwind 4, shadcn-style components, Radix UI primitives.
This commit is contained in:
112
dashboard/src/app/api/config/route.ts
Normal file
112
dashboard/src/app/api/config/route.ts
Normal 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;
|
||||
}
|
||||
11
dashboard/src/app/api/gpu/route.ts
Normal file
11
dashboard/src/app/api/gpu/route.ts
Normal 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 });
|
||||
}
|
||||
46
dashboard/src/app/api/llama/route.ts
Normal file
46
dashboard/src/app/api/llama/route.ts
Normal 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 });
|
||||
}
|
||||
76
dashboard/src/app/api/logs/route.ts
Normal file
76
dashboard/src/app/api/logs/route.ts
Normal 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",
|
||||
},
|
||||
});
|
||||
}
|
||||
10
dashboard/src/app/api/models/route.ts
Normal file
10
dashboard/src/app/api/models/route.ts
Normal 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 });
|
||||
}
|
||||
18
dashboard/src/app/api/status/route.ts
Normal file
18
dashboard/src/app/api/status/route.ts
Normal 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(),
|
||||
});
|
||||
}
|
||||
119
dashboard/src/app/globals.css
Normal file
119
dashboard/src/app/globals.css
Normal 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;
|
||||
}
|
||||
21
dashboard/src/app/layout.tsx
Normal file
21
dashboard/src/app/layout.tsx
Normal 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
1336
dashboard/src/app/page.tsx
Normal file
File diff suppressed because it is too large
Load Diff
36
dashboard/src/components/ui/badge.tsx
Normal file
36
dashboard/src/components/ui/badge.tsx
Normal 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 };
|
||||
53
dashboard/src/components/ui/button.tsx
Normal file
53
dashboard/src/components/ui/button.tsx
Normal 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 };
|
||||
82
dashboard/src/components/ui/card.tsx
Normal file
82
dashboard/src/components/ui/card.tsx
Normal 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,
|
||||
};
|
||||
20
dashboard/src/components/ui/input.tsx
Normal file
20
dashboard/src/components/ui/input.tsx
Normal 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 };
|
||||
22
dashboard/src/components/ui/label.tsx
Normal file
22
dashboard/src/components/ui/label.tsx
Normal 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 };
|
||||
91
dashboard/src/components/ui/select.tsx
Normal file
91
dashboard/src/components/ui/select.tsx
Normal 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,
|
||||
};
|
||||
28
dashboard/src/components/ui/switch.tsx
Normal file
28
dashboard/src/components/ui/switch.tsx
Normal 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 };
|
||||
54
dashboard/src/components/ui/tabs.tsx
Normal file
54
dashboard/src/components/ui/tabs.tsx
Normal 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 };
|
||||
19
dashboard/src/components/ui/textarea.tsx
Normal file
19
dashboard/src/components/ui/textarea.tsx
Normal 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
620
dashboard/src/lib/docker.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
41
dashboard/src/lib/utils.ts
Normal file
41
dashboard/src/lib/utils.ts
Normal 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`;
|
||||
}
|
||||
Reference in New Issue
Block a user