From f7587b7b835aa36b69e620844a7a406677af0864 Mon Sep 17 00:00:00 2001 From: TheRealToxicDev Date: Mon, 18 May 2026 23:46:11 -0600 Subject: [PATCH] sync agent module --- .env.example | 2 +- agent | 2 +- app/admin/actions/create-server.ts | 16 +- .../components/admin-sidebar-enhanced.tsx | 2 +- app/admin/components/admin-sidebar.tsx | 2 +- app/admin/servers/actions/delete.ts | 10 +- app/api/agent/heartbeat/route.ts | 11 + app/api/servers/[id]/members/route.ts | 23 +- app/api/servers/[id]/metrics/live/route.ts | 87 ++++--- .../[id]/actions/approve-provision.ts | 91 +++++++ app/dashboard/[id]/approve-provision/page.tsx | 244 ++++++++++++++++++ .../[id]/components/backups-panel.tsx | 2 +- .../[id]/components/live-metrics-panel.tsx | 24 +- app/dashboard/[id]/components/logs-stream.tsx | 6 +- .../[id]/components/provisioning-status.tsx | 238 +++++++++++++---- app/dashboard/[id]/components/shell.tsx | 83 ++++-- .../[id]/components/use-live-metrics.ts | 2 + app/dashboard/[id]/console/page.tsx | 194 ++++++++------ app/dashboard/[id]/layout.tsx | 11 +- app/dashboard/account/backend/page.tsx | 2 - app/dashboard/components/app-sidebar.tsx | 2 +- app/dashboard/components/server-card.tsx | 94 +++---- app/dashboard/new/components/form.tsx | 2 +- components/panel.tsx | 2 +- lib/mail.ts | 116 +++++++++ lib/rbac.ts | 12 +- .../migration.sql | 12 + prisma/schema.prisma | 12 + protocol/schemas.ts | 5 + 29 files changed, 1048 insertions(+), 261 deletions(-) create mode 100644 app/dashboard/[id]/actions/approve-provision.ts create mode 100644 app/dashboard/[id]/approve-provision/page.tsx create mode 100644 prisma/migrations/20260519050228_add_agent_metrics/migration.sql diff --git a/.env.example b/.env.example index 97094f3..8396519 100644 --- a/.env.example +++ b/.env.example @@ -13,7 +13,7 @@ HETZNER_API_TOKEN= HETZNER_SNAPSHOT_IMAGE_ID= # Optional builder defaults used by provider profile. -HETZNER_BUILDER_BASE_IMAGE=ubuntu-24.04 +HETZNER_BUILDER_BASE_IMAGE=docker-ce HETZNER_BUILDER_SERVER_TYPE=cx23 HETZNER_BUILDER_LOCATION=nbg1 diff --git a/agent b/agent index 1a1a3eb..f19ef9c 160000 --- a/agent +++ b/agent @@ -1 +1 @@ -Subproject commit 1a1a3ebb5790ef5939cdcb973443a9806924ccd5 +Subproject commit f19ef9cd6935c98f70e72e20cb56e8de9b82d583 diff --git a/app/admin/actions/create-server.ts b/app/admin/actions/create-server.ts index 1af1748..76d4a3d 100644 --- a/app/admin/actions/create-server.ts +++ b/app/admin/actions/create-server.ts @@ -6,17 +6,16 @@ import type { Prisma } from "@prisma/client"; import { humanId } from "human-id"; import { revalidatePath } from "next/cache"; import { ulid } from "ulid"; -import { start } from "workflow/api"; import { z } from "zod"; import { games, validateSettings } from "@/games"; import { logEvent } from "@/lib/audit"; import { prisma } from "@/lib/db"; import { SNAPSHOT_ENVIRONMENT } from "@/lib/env"; +import { sendServerProvisionInitiatedEmail } from "@/lib/mail"; import { getProviderForUserWithImage } from "@/lib/providers"; import type { Catalog } from "@/lib/providers/types"; import { requireSuperAdmin } from "@/lib/session"; -import { provisionServer } from "@/lib/workflows/provision-server"; const adminCreateServerSchema = z.object({ game: z.enum(games.map((g) => g.id) as [string, ...string[]]), @@ -112,7 +111,7 @@ export const adminCreateServer = async ( location: parsed.data.location, name: parsed.data.name, observedState: "pending", - phase: "queued", + phase: "pending", rconPassword, serverType: parsed.data.serverType, settings: settings as Prisma.InputJsonValue, @@ -197,7 +196,16 @@ export const adminCreateServer = async ( } } - await start(provisionServer, [{ serverId: server.id }]); + // Email user to approve and trigger provisioning + void sendServerProvisionInitiatedEmail({ + approveUrl: `${process.env.BETTER_AUTH_URL}/dashboard/${server.id}/approve-provision`, + game: game.name, + location: parsed.data.location, + serverName: parsed.data.name, + serverType: parsed.data.serverType, + toEmail: targetUser.email, + userName: targetUser.name ?? targetUser.email, + }); await logEvent({ action: "admin.server.create", diff --git a/app/admin/components/admin-sidebar-enhanced.tsx b/app/admin/components/admin-sidebar-enhanced.tsx index 83de6fb..9c34092 100644 --- a/app/admin/components/admin-sidebar-enhanced.tsx +++ b/app/admin/components/admin-sidebar-enhanced.tsx @@ -71,7 +71,7 @@ export const AdminSidebarEnhanced = ({ user={user} headerTitle="NodeByte" headerSubtitle="Admin Panel" - headerHref="/admin" + headerHref="/" showAdminLink={false} onSignOut={handleSignOut} > diff --git a/app/admin/components/admin-sidebar.tsx b/app/admin/components/admin-sidebar.tsx index 4fc2d3c..095503d 100644 --- a/app/admin/components/admin-sidebar.tsx +++ b/app/admin/components/admin-sidebar.tsx @@ -109,7 +109,7 @@ export const AdminSidebar = ({ user }: { user: AdminSidebarUser }) => { diff --git a/app/admin/servers/actions/delete.ts b/app/admin/servers/actions/delete.ts index 3cfc6d4..0dc8d8e 100644 --- a/app/admin/servers/actions/delete.ts +++ b/app/admin/servers/actions/delete.ts @@ -4,6 +4,7 @@ import { revalidatePath } from "next/cache"; import { z } from "zod"; import { prisma } from "@/lib/db"; +import { sendServerDeletedEmail } from "@/lib/mail"; import { getProviderForUser } from "@/lib/providers"; import { requireAdmin } from "@/lib/session"; @@ -31,7 +32,7 @@ export const adminDeleteServer = async ( } const server = await prisma.server.findFirst({ - include: { user: { select: { id: true } } }, + include: { user: { select: { email: true, id: true, name: true } } }, where: { id: parsed.data.serverId }, }); @@ -68,6 +69,13 @@ export const adminDeleteServer = async ( where: { serverId: parsed.data.serverId }, }); + // Notify the server owner (fire-and-forget) + void sendServerDeletedEmail({ + serverName: server.name, + toEmail: server.user.email, + userName: server.user.name, + }); + revalidatePath("/admin/servers"); return { ok: true }; } catch (error) { diff --git a/app/api/agent/heartbeat/route.ts b/app/api/agent/heartbeat/route.ts index 23e29be..8de04a4 100644 --- a/app/api/agent/heartbeat/route.ts +++ b/app/api/agent/heartbeat/route.ts @@ -28,8 +28,19 @@ export const POST = async (request: Request) => { await prisma.agent.update({ data: { + cpuPercent: parsed.data.cpuPercent ?? undefined, + diskTotalBytes: parsed.data.diskTotalBytes ?? undefined, + diskUsedBytes: parsed.data.diskUsedBytes ?? undefined, lastCommandId: parsed.data.lastCommandId ?? undefined, lastHeartbeatAt: new Date(), + maxPlayers: parsed.data.maxPlayers ?? undefined, + memTotalBytes: parsed.data.memTotalBytes ?? undefined, + memUsedBytes: parsed.data.memUsedBytes ?? undefined, + networkInBps: parsed.data.networkInBps ?? undefined, + networkOutBps: parsed.data.networkOutBps ?? undefined, + playerCount: parsed.data.playerCount ?? undefined, + tps: parsed.data.tps ?? undefined, + uptimeSeconds: parsed.data.uptimeSeconds, }, where: { id: verified.agentId }, }); diff --git a/app/api/servers/[id]/members/route.ts b/app/api/servers/[id]/members/route.ts index 505e5e0..f212835 100644 --- a/app/api/servers/[id]/members/route.ts +++ b/app/api/servers/[id]/members/route.ts @@ -4,7 +4,7 @@ import { z } from "zod"; import { prisma } from "@/lib/db"; import { env } from "@/lib/env"; -import { sendServerInviteEmail } from "@/lib/mail"; +import { sendServerInviteEmail, sendServerMemberAddedEmail } from "@/lib/mail"; import { requireServerRole } from "@/lib/rbac"; import { requireUser } from "@/lib/session"; @@ -123,6 +123,27 @@ export const POST = async ( user: { select: { email: true, id: true, image: true, name: true } }, }, }); + + // Notify the added user by email (fire-and-forget) + const [serverInfo, inviter] = await Promise.all([ + prisma.server.findUnique({ + select: { name: true }, + where: { id: serverId }, + }), + prisma.user.findUnique({ + select: { email: true, name: true }, + where: { id: user.id }, + }), + ]); + const baseUrl = env.BETTER_AUTH_URL.replace(/\/$/u, ""); + void sendServerMemberAddedEmail({ + addedByName: inviter?.name ?? inviter?.email ?? "A NodeByte user", + role, + serverName: serverInfo?.name ?? "a server", + serverUrl: `${baseUrl}/dashboard/${serverId}`, + toEmail: member.user.email, + }); + return NextResponse.json({ member, type: "added" }, { status: 201 }); } diff --git a/app/api/servers/[id]/metrics/live/route.ts b/app/api/servers/[id]/metrics/live/route.ts index 0c66e89..fa44c37 100644 --- a/app/api/servers/[id]/metrics/live/route.ts +++ b/app/api/servers/[id]/metrics/live/route.ts @@ -5,19 +5,6 @@ import { requireUser } from "@/lib/session"; export const runtime = "nodejs"; -/** - * GET /api/servers/[id]/metrics/live - * - * Returns current live server metrics (CPU, Memory, Network, etc.) - * This endpoint would typically pull from an agent monitoring system - * or container monitoring service. - * - * In a production system, this would: - * - Query Prometheus/Grafana - * - Call the server agent API - * - Poll container stats (docker stats) - * - Get game-specific metrics from the server - */ export const GET = async ( _request: Request, context: { params: Promise<{ id: string }> } @@ -26,12 +13,29 @@ export const GET = async ( const { id } = await context.params; const server = await prisma.server.findFirst({ - select: { - id: true, - lastHeartbeatAt: true, - observedState: true, + include: { + agent: { + select: { + cpuPercent: true, + diskTotalBytes: true, + diskUsedBytes: true, + lastHeartbeatAt: true, + maxPlayers: true, + memTotalBytes: true, + memUsedBytes: true, + networkInBps: true, + networkOutBps: true, + playerCount: true, + tps: true, + uptimeSeconds: true, + }, + }, + }, + where: { + OR: [{ userId: user.id }, { members: { some: { userId: user.id } } }], + deletedAt: null, + id, }, - where: { deletedAt: null, id, userId: user.id }, }); if (!server) { @@ -45,32 +49,35 @@ export const GET = async ( ); } - // Integrate with monitoring system (Prometheus, agent API, container stats, etc.) - // For now, return mock data to demonstrate the API structure + const { agent } = server; + if (!agent || !agent.lastHeartbeatAt) { + return NextResponse.json({ metrics: null }); + } - const uptime = (server.lastHeartbeatAt as Date | null) - ? Math.floor( - (Date.now() - (server.lastHeartbeatAt as Date).getTime()) / 1000 - ) - : 0; + // Consider metrics stale if no heartbeat in the last 60 seconds + const staleSec = (Date.now() - agent.lastHeartbeatAt.getTime()) / 1000; + if (staleSec > 60) { + return NextResponse.json({ metrics: null }); + } + + const memTotal = agent.memTotalBytes ?? 0; + const memUsed = agent.memUsedBytes ?? 0; + const memPercent = memTotal > 0 ? (memUsed / memTotal) * 100 : 0; return NextResponse.json({ metrics: { - // System metrics (typically from container/host monitoring) - // cpu: value from container/host monitoring - // memory: value from container/host monitoring - // networkIn: bytes per second - // networkOut: bytes per second - cpu: Math.random() * 50 + 10, - memory: Math.random() * 40 + 20, - networkIn: Math.random() * 1_000_000, - networkOut: Math.random() * 500_000, - uptime: Math.max(uptime, 0), - - // Game-specific metrics (if available) - // playerCount: 0, - // maxPlayers: 32, - // tps: 20, + cpu: agent.cpuPercent ?? 0, + diskPercent: + agent.diskTotalBytes && agent.diskTotalBytes > 0 + ? ((agent.diskUsedBytes ?? 0) / agent.diskTotalBytes) * 100 + : undefined, + maxPlayers: agent.maxPlayers ?? undefined, + memory: memPercent, + networkIn: agent.networkInBps ?? 0, + networkOut: agent.networkOutBps ?? 0, + playerCount: agent.playerCount ?? undefined, + tps: agent.tps ?? undefined, + uptime: agent.uptimeSeconds ?? 0, }, }); }; diff --git a/app/dashboard/[id]/actions/approve-provision.ts b/app/dashboard/[id]/actions/approve-provision.ts new file mode 100644 index 0000000..0d399a9 --- /dev/null +++ b/app/dashboard/[id]/actions/approve-provision.ts @@ -0,0 +1,91 @@ +"use server"; + +import type { Prisma } from "@prisma/client"; +import { revalidatePath } from "next/cache"; +import { start } from "workflow/api"; +import { z } from "zod"; + +import { getGame, validateSettings } from "@/games"; +import { prisma } from "@/lib/db"; +import { env } from "@/lib/env"; +import { sendServerCreatedEmail } from "@/lib/mail"; +import { requireUser } from "@/lib/session"; +import { provisionServer } from "@/lib/workflows/provision-server"; + +const inputSchema = z.object({ + serverId: z.string().min(1), + settings: z.record(z.string(), z.unknown()).optional(), +}); + +export type ApproveProvisionInput = z.infer; + +export type ApproveProvisionResult = + | { ok: true } + | { error: string; ok: false }; + +export const approveProvision = async ( + input: ApproveProvisionInput +): Promise => { + const user = await requireUser(); + + const parsed = inputSchema.safeParse(input); + if (!parsed.success) { + return { error: "Invalid input", ok: false }; + } + + const server = await prisma.server.findFirst({ + include: { user: { select: { email: true, name: true } } }, + where: { deletedAt: null, id: parsed.data.serverId, userId: user.id }, + }); + if (!server) { + return { error: "Not found", ok: false }; + } + + if (server.phase !== "pending") { + return { error: "Server is not awaiting approval", ok: false }; + } + + // Save game-config settings the user reviewed on this page before launching + if (parsed.data.settings && Object.keys(parsed.data.settings).length > 0) { + const game = getGame(server.game); + if (game) { + const validation = validateSettings(game.settings, parsed.data.settings); + if (!validation.ok) { + return { error: validation.error, ok: false }; + } + await prisma.server.update({ + data: { + settings: { + ...(server.settings as Record | null), + ...validation.data, + } as Prisma.InputJsonValue, + }, + where: { id: parsed.data.serverId }, + }); + } + } + + // Transition to queued and kick off the provisioning workflow + await prisma.server.update({ + data: { phase: "queued" }, + where: { id: parsed.data.serverId }, + }); + + await start(provisionServer, [{ serverId: parsed.data.serverId }]); + + // Notify the user that provisioning has started (fire-and-forget) + if (server.user) { + void sendServerCreatedEmail({ + game: server.game, + region: server.location, + serverName: server.name, + serverUrl: `${env.BETTER_AUTH_URL}/dashboard/${parsed.data.serverId}`, + toEmail: server.user.email, + userName: server.user.name, + }); + } + + revalidatePath("/dashboard", "layout"); + + return { ok: true }; +}; diff --git a/app/dashboard/[id]/approve-provision/page.tsx b/app/dashboard/[id]/approve-provision/page.tsx new file mode 100644 index 0000000..6ad70ff --- /dev/null +++ b/app/dashboard/[id]/approve-provision/page.tsx @@ -0,0 +1,244 @@ +"use client"; +import { + AlertCircleIcon, + CheckCircleIcon, + CheckIcon, + CpuIcon, + Loader2Icon, + MapPinIcon, + RocketIcon, + ServerIcon, +} from "lucide-react"; +import Image from "next/image"; +import { useState } from "react"; +import { toast } from "sonner"; + +import { Panel, PanelCard } from "@/components/panel"; +import { Button } from "@/components/ui/button"; +import { getGame, missingRequiredFields, resolveSettings } from "@/games"; + +import { approveProvision } from "../actions/approve-provision"; +import type { + FieldValue, + SettingsValuesRecord, +} from "../components/game-settings-form"; +import { SettingsFields } from "../components/game-settings-form"; +import { useServer } from "../components/server-context"; + +const formatSpecs = ( + specs: { cores: number; disk: number; memory: number } | null | undefined, + serverType: string +): string => + specs + ? `${specs.cores} vCPU · ${specs.memory} GB RAM · ${specs.disk} GB disk` + : serverType; + +const InfoRow = ({ + icon: Icon, + label, + value, +}: { + icon: React.ElementType; + label: string; + value: React.ReactNode; +}) => ( +
+
+ +
+
+

{label}

+

{value}

+
+
+); + +export default function ApprovePage() { + const { server } = useServer(); + const game = getGame(server.game); + const hasSettings = Boolean(game && Object.keys(game.settings).length > 0); + + const initial = game + ? (resolveSettings(game.settings, server.settings) as SettingsValuesRecord) + : ({} as SettingsValuesRecord); + + const [values, setValues] = useState(initial); + const [isApproving, setIsApproving] = useState(false); + + const setField = (key: string, value: FieldValue) => + setValues((prev) => ({ ...prev, [key]: value })); + + const missingRequired = game + ? missingRequiredFields(game.settings, values) + : []; + const canApprove = missingRequired.length === 0; + + if (server.phase !== "pending") { + return ( +
+
+ +
+

Already in progress

+

+ This server has already been approved and is{" "} + {server.phase === "healthy" || server.observedState === "running" + ? "running" + : "provisioning"} + . +

+
+
+
+ ); + } + + const handleApprove = async () => { + setIsApproving(true); + try { + const result = await approveProvision({ + serverId: server.id, + settings: hasSettings ? values : undefined, + }); + if (result.ok) { + toast.success( + "Provisioning started — you'll get an email when it's ready." + ); + } else { + toast.error(result.error); + } + } catch { + toast.error("Failed to start provisioning"); + } finally { + setIsApproving(false); + } + }; + + const locationLabel = server.location + ? [server.location.city, server.location.country] + .filter(Boolean) + .join(", ") || server.location.name + : "—"; + + const specsLabel = formatSpecs(server.specs, server.serverType); + + return ( +
+ {/* Page header */} +
+
+ +

Review & provision

+
+

+ An admin has created this server for you. Review the configuration + below and launch it when you're ready. +

+
+ + {/* Server summary */} + + +
+ {/* Game + name identity row */} +
+ {game && ( + {game.name} + )} +
+

{server.name}

+

+ {game?.name ?? server.game} +

+
+
+ +
+ + {/* Info grid */} +
+ + + +
+
+ + + + {/* Game configuration */} + {hasSettings && game && ( + + + + + {missingRequired.length > 0 && ( +

+ Fill in required fields before launching:{" "} + {missingRequired + .map( + (k) => + (game.settings as Record)[k] + ?.label ?? k + ) + .join(", ")} +

+ )} +
+ )} + + {/* What happens next */} + + +
    + {[ + "A VM will be booted in your chosen region", + "The NodeByte agent connects and installs the game", + "Your server starts up and health checks run (~60 seconds total)", + "You'll receive an email and can connect immediately", + ].map((step) => ( +
  • + + {step} +
  • + ))} +
+
+
+ + {/* CTA */} +
+ + {!canApprove && !isApproving && ( +

+ Fill in all required fields above +

+ )} +
+
+ ); +} diff --git a/app/dashboard/[id]/components/backups-panel.tsx b/app/dashboard/[id]/components/backups-panel.tsx index 7c34166..8ad8da9 100644 --- a/app/dashboard/[id]/components/backups-panel.tsx +++ b/app/dashboard/[id]/components/backups-panel.tsx @@ -331,7 +331,7 @@ export const BackupsPanel = ({ } > - Daily snapshots taken by Hetzner, retained for 7 days. + Daily snapshots, retained for 7 days.
diff --git a/app/dashboard/[id]/components/live-metrics-panel.tsx b/app/dashboard/[id]/components/live-metrics-panel.tsx index 0f06ce9..ae48354 100644 --- a/app/dashboard/[id]/components/live-metrics-panel.tsx +++ b/app/dashboard/[id]/components/live-metrics-panel.tsx @@ -7,6 +7,7 @@ import { ArrowUpIcon, ClockIcon, CpuIcon, + HardDriveIcon, MemoryStickIcon, UsersIcon, } from "lucide-react"; @@ -67,13 +68,13 @@ const MetricItem = ({ pct?: number; mono?: boolean; }) => ( -
-
+
+
{icon} - {label} + {label}
{value} @@ -121,7 +122,7 @@ export const LiveMetricsPanel = ({ } return ( -
+
} label="CPU" @@ -151,8 +152,8 @@ export const LiveMetricsPanel = ({ icon={} label="Players" value={ - maxPlayers - ? `${metrics.playerCount}/${maxPlayers}` + (metrics.maxPlayers ?? maxPlayers) + ? `${metrics.playerCount}/${metrics.maxPlayers ?? maxPlayers}` : String(metrics.playerCount) } /> @@ -161,9 +162,18 @@ export const LiveMetricsPanel = ({ } label="TPS" + pct={(metrics.tps / 20) * 100} value={metrics.tps.toFixed(1)} /> )} + {metrics.diskPercent !== undefined && ( + } + label="Disk" + pct={metrics.diskPercent} + value={`${metrics.diskPercent.toFixed(1)}%`} + /> + )} } label="Uptime" diff --git a/app/dashboard/[id]/components/logs-stream.tsx b/app/dashboard/[id]/components/logs-stream.tsx index 0f1588f..401479f 100644 --- a/app/dashboard/[id]/components/logs-stream.tsx +++ b/app/dashboard/[id]/components/logs-stream.tsx @@ -49,7 +49,7 @@ const AnsiLine = ({ text }: { text: string }) => { [text] ); return ( - + {parts.map((part, i) => ( ))} @@ -98,11 +98,11 @@ export const LogsStream = ({ serverId }: { serverId: string }) => { return ( - + {lines.length === 0 && ( Waiting for logs… diff --git a/app/dashboard/[id]/components/provisioning-status.tsx b/app/dashboard/[id]/components/provisioning-status.tsx index 6aa3d02..a42beba 100644 --- a/app/dashboard/[id]/components/provisioning-status.tsx +++ b/app/dashboard/[id]/components/provisioning-status.tsx @@ -1,23 +1,58 @@ "use client"; -import { CheckIcon, CircleXIcon } from "lucide-react"; +import { + AlertTriangleIcon, + CheckIcon, + CircleXIcon, + Loader2Icon, + RocketIcon, +} from "lucide-react"; -import { Spinner } from "@/components/ui/spinner"; import { cn } from "@/lib/utils"; const STEPS = [ - { key: "create", label: "Create server", phases: ["queued", "provisioning"] }, - { key: "boot", label: "Boot VM", phases: ["booting"] }, - { key: "agent", label: "Connect agent", phases: ["agent_connected"] }, - { key: "install", label: "Install game", phases: ["installing"] }, - { key: "start", label: "Start server", phases: ["starting"] }, - { key: "health", label: "Run health checks", phases: ["healthy"] }, + { + description: "Reserving a virtual machine in your chosen region", + key: "create", + label: "Create server", + phases: ["queued", "provisioning"], + }, + { + description: "Operating system booting and network interfaces coming up", + key: "boot", + label: "Boot VM", + phases: ["booting"], + }, + { + description: "NodeByte agent connecting and enrolling with the panel", + key: "agent", + label: "Connect agent", + phases: ["agent_connected"], + }, + { + description: "Downloading and configuring game server files", + key: "install", + label: "Install game", + phases: ["installing"], + }, + { + description: "Game server process initialising", + key: "start", + label: "Start server", + phases: ["starting"], + }, + { + description: "Verifying server health and network connectivity", + key: "health", + label: "Run health checks", + phases: ["healthy"], + }, ] as const; const PHASE_ORDER: string[] = STEPS.flatMap((s) => [...s.phases]); type StepStatus = "done" | "active" | "pending" | "error"; -const stepStatus = ( +const resolveStepStatus = ( currentIndex: number, stepStart: number, stepEnd: number, @@ -35,17 +70,57 @@ const stepStatus = ( return "pending"; }; -const StepIcon = ({ status }: { status: StepStatus }) => { +const StepCircle = ({ status }: { status: StepStatus }) => { if (status === "done") { - return ; + return ( +
+ +
+ ); } if (status === "active") { - return ; + return ( +
+ + {/* Outer pulse ring */} + +
+ ); } if (status === "error") { - return ; + return ( +
+ +
+ ); } - return
; + return ( +
+
+
+ ); +}; + +const ConnectorLine = ({ status }: { status: StepStatus }) => ( +
+); + +const PHASE_LABEL: Record = { + agent_connected: "Connecting agent", + booting: "Booting VM", + errored: "Provisioning failed", + healthy: "Checking health", + installing: "Installing game", + provisioning: "Creating VM", + queued: "Queued", + starting: "Starting server", }; export const ProvisioningStatus = ({ @@ -58,44 +133,115 @@ export const ProvisioningStatus = ({ errorReason: string | null; }) => { const currentIndex = PHASE_ORDER.indexOf(phase); - // Legacy fallback: older records stored phase='errored' (now we preserve - // the in-flight phase), which returns -1 — pin the error to the first step. const errorIndex = errored && currentIndex === -1 ? 0 : currentIndex; + const phaseLabel = PHASE_LABEL[phase] ?? "In progress"; + return ( -
- {STEPS.map((step) => { - const stepStart = PHASE_ORDER.indexOf(step.phases[0]); - const stepEnd = stepStart + step.phases.length - 1; - const isErrorStep = - errored && errorIndex >= stepStart && errorIndex <= stepEnd; - const status = stepStatus( - currentIndex, - stepStart, - stepEnd, - isErrorStep - ); +
+ {/* Status banner */} + {errored ? ( +
+ +
+

+ Provisioning failed +

+

+ {errorReason ?? + "An error occurred during provisioning. Our team has been notified."} +

+
+
+ ) : ( +
+ +
+

{phaseLabel}…

+

+ Your server will be ready in approximately 60 seconds. +

+
+
+ )} + + {/* Step timeline */} +
+ {STEPS.map((step, i) => { + const stepStart = PHASE_ORDER.indexOf(step.phases[0]); + const stepEnd = stepStart + step.phases.length - 1; + const isErrorStep = + errored && errorIndex >= stepStart && errorIndex <= stepEnd; + const status = resolveStepStatus( + currentIndex, + stepStart, + stepEnd, + isErrorStep + ); + const isLast = i === STEPS.length - 1; + + return ( +
+ {/* Left: circle + connector */} +
+ + {!isLast && } +
+ + {/* Right: content */} +
+

+ {step.label} +

+

+ {step.description} +

+ {isErrorStep && errorReason && ( +

+ {errorReason} +

+ )} +
- return ( -
-
- - + {status === "done" && ( + + Done + + )} + {status === "active" && ( + + In progress + )} - > - {step.label} - + {status === "error" && ( + + Failed + + )} +
- {isErrorStep && errorReason && ( -

{errorReason}

- )} -
- ); - })} + ); + })} +
); }; diff --git a/app/dashboard/[id]/components/shell.tsx b/app/dashboard/[id]/components/shell.tsx index 8674fc5..b1d155c 100644 --- a/app/dashboard/[id]/components/shell.tsx +++ b/app/dashboard/[id]/components/shell.tsx @@ -1,9 +1,17 @@ "use client"; import { + ActivityIcon, + ArchiveIcon, + BarChart2Icon, + FolderIcon, + InfoIcon, + LayoutDashboardIcon, MoreHorizontalIcon, PlayIcon, RotateCcwIcon, + Settings2Icon, SquareIcon, + TerminalIcon, Trash2Icon, Users2Icon, } from "lucide-react"; @@ -72,15 +80,60 @@ const STATE_BADGE: Record = { }; const ALL_TABS = [ - { label: "Overview", minRole: "viewer" as ServerRole, value: "connect" }, - { label: "Activity", minRole: "viewer" as ServerRole, value: "activity" }, - { label: "Console", minRole: "viewer" as ServerRole, value: "console" }, - { label: "Graphs", minRole: "viewer" as ServerRole, value: "graphs" }, - { label: "Backups", minRole: "admin" as ServerRole, value: "backups" }, - { label: "Files", minRole: "admin" as ServerRole, value: "files" }, - { label: "Details", minRole: "member" as ServerRole, value: "details" }, - { label: "Settings", minRole: "admin" as ServerRole, value: "settings" }, - { label: "Team", minRole: "owner" as ServerRole, value: "team" }, + { + icon: LayoutDashboardIcon, + label: "Overview", + minRole: "viewer" as ServerRole, + value: "connect", + }, + { + icon: ActivityIcon, + label: "Activity", + minRole: "viewer" as ServerRole, + value: "activity", + }, + { + icon: TerminalIcon, + label: "Console", + minRole: "viewer" as ServerRole, + value: "console", + }, + { + icon: BarChart2Icon, + label: "Graphs", + minRole: "viewer" as ServerRole, + value: "graphs", + }, + { + icon: ArchiveIcon, + label: "Backups", + minRole: "admin" as ServerRole, + value: "backups", + }, + { + icon: FolderIcon, + label: "Files", + minRole: "admin" as ServerRole, + value: "files", + }, + { + icon: InfoIcon, + label: "Details", + minRole: "member" as ServerRole, + value: "details", + }, + { + icon: Settings2Icon, + label: "Settings", + minRole: "admin" as ServerRole, + value: "settings", + }, + { + icon: Users2Icon, + label: "Team", + minRole: "owner" as ServerRole, + value: "team", + }, ] as const; const ROLE_ORDER: Record = { @@ -389,14 +442,10 @@ export const ServerShell = ({ : `/dashboard/${server.id}/${tab.value}` } > - {tab.value === "team" ? ( - - - Team - - ) : ( - tab.label - )} + + + {tab.label} + ))} diff --git a/app/dashboard/[id]/components/use-live-metrics.ts b/app/dashboard/[id]/components/use-live-metrics.ts index 33f72b8..d60c931 100644 --- a/app/dashboard/[id]/components/use-live-metrics.ts +++ b/app/dashboard/[id]/components/use-live-metrics.ts @@ -16,6 +16,8 @@ export interface LiveMetrics { networkOut: number; // Seconds uptime: number; + // Disk usage percentage (if available) + diskPercent?: number; // Current players playerCount?: number; // Max players diff --git a/app/dashboard/[id]/console/page.tsx b/app/dashboard/[id]/console/page.tsx index bc31426..6a67429 100644 --- a/app/dashboard/[id]/console/page.tsx +++ b/app/dashboard/[id]/console/page.tsx @@ -1,8 +1,9 @@ "use client"; -import { HistoryIcon, SendIcon, TerminalIcon } from "lucide-react"; +import { CopyIcon, HistoryIcon, SendIcon, TerminalIcon } from "lucide-react"; import { useState } from "react"; import { toast } from "sonner"; +import { Panel, PanelCard } from "@/components/panel"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; @@ -16,8 +17,9 @@ const ConsoleTab = () => { const { server } = useServer(); const [commandInput, setCommandInput] = useState(""); const [commandHistory, setCommandHistory] = useState([]); - const [, setHistoryIndex] = useState(-1); + const [_historyIndex, setHistoryIndex] = useState(-1); const [isSending, setIsSending] = useState(false); + const [showHistory, setShowHistory] = useState(false); const handleSendCommand = async () => { if (!commandInput.trim() || server.observedState !== "running") { @@ -52,6 +54,7 @@ const ConsoleTab = () => { void handleSendCommand(); } else if (e.key === "ArrowUp") { e.preventDefault(); + setShowHistory(true); setHistoryIndex((prev) => { const next = prev + 1; if (next < commandHistory.length) { @@ -69,6 +72,7 @@ const ConsoleTab = () => { return next; } else if (prev === 0) { setCommandInput(""); + setShowHistory(false); return -1; } return prev; @@ -79,84 +83,128 @@ const ConsoleTab = () => { const isRunning = server.observedState === "running"; return ( -
- {/* Live metrics — compact bar when running */} +
+ {/* Live metrics */} {isRunning && ( -
- -
+ + + + + )} - {/* Terminal window */} -
- {/* Terminal title bar */} -
- - {server.name} -
-
- - {isRunning ? "live" : server.observedState} - - {commandHistory.length > 0 && ( - - - {commandHistory.length} + {/* Terminal */} + + + {/* Title bar */} +
+
+ + + {server.name} - )} +
+
+
+ + {isRunning ? "live" : server.observedState} + +
-
- - {/* Log output — fills remaining space */} -
- -
- {/* Command input */} - {isRunning ? ( -
- - $ - - { - setCommandInput(e.target.value); - setHistoryIndex(-1); - }} - onKeyDown={handleKeyDown} - /> - + {/* Log output — fills remaining height */} +
+
- ) : ( -
-

- Server is {server.observedState}. Start the server to send - commands. -

-
- )} -
+ + {/* History dropdown */} + {showHistory && commandHistory.length > 0 && ( +
+
+ + Recent Commands +
+
    + {commandHistory.slice(0, 10).map((cmd, idx) => ( +
  • + +
  • + ))} +
+
+ )} + + {/* Command input */} + {isRunning ? ( +
+ + $ + + { + setCommandInput(e.target.value); + setHistoryIndex(-1); + }} + onKeyDown={handleKeyDown} + /> +
+ {commandInput && ( + + )} + +
+
+ ) : ( +
+

+ Server is {server.observedState}. Start the server to send + commands. +

+
+ )} +
+
); }; diff --git a/app/dashboard/[id]/layout.tsx b/app/dashboard/[id]/layout.tsx index 61a394b..35b5238 100644 --- a/app/dashboard/[id]/layout.tsx +++ b/app/dashboard/[id]/layout.tsx @@ -59,7 +59,16 @@ const ServerLayout = async ({ user.id, SNAPSHOT_ENVIRONMENT ); - const catalog = await provider.getCatalog(imageId); + + // Fetch catalog with fallback for missing images + let catalog; + try { + catalog = await provider.getCatalog(imageId); + } catch { + // Image not found or catalog unavailable — use empty fallback + catalog = { currency: "gbp", serverTypes: [] }; + } + const serverType = catalog.serverTypes.find( (t) => t.name === server.serverType ); diff --git a/app/dashboard/account/backend/page.tsx b/app/dashboard/account/backend/page.tsx index 991afde..9fb4c26 100644 --- a/app/dashboard/account/backend/page.tsx +++ b/app/dashboard/account/backend/page.tsx @@ -1,7 +1,5 @@ import { redirect } from "next/navigation"; -// The "Backend" page (user Hetzner token management) has been removed now that -// NodeByte manages infrastructure centrally. Redirect users to the new billing page. const BackendPage = () => { redirect("/dashboard/account/billing"); }; diff --git a/app/dashboard/components/app-sidebar.tsx b/app/dashboard/components/app-sidebar.tsx index 3c10f4f..d0cd7f8 100644 --- a/app/dashboard/components/app-sidebar.tsx +++ b/app/dashboard/components/app-sidebar.tsx @@ -123,7 +123,7 @@ export const AppSidebar = ({ {/* Header */} diff --git a/app/dashboard/components/server-card.tsx b/app/dashboard/components/server-card.tsx index ef190db..0699aef 100644 --- a/app/dashboard/components/server-card.tsx +++ b/app/dashboard/components/server-card.tsx @@ -94,53 +94,23 @@ const statusConfig = { }, }; -const metricsCache = new Map(); - -const fetchMetrics = async (serverId: string): Promise => { - const cached = metricsCache.get(serverId); - if (cached && Date.now() - cached.timestamp < 5000) { - return cached.data; - } - +const fetchLiveMetrics = async (serverId: string): Promise => { try { - const now = new Date(); - const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000); - - const response = await fetch( - `/api/servers/${serverId}/metrics?type=cpu&start=${fiveMinutesAgo.toISOString()}&end=${now.toISOString()}` - ); - + const response = await fetch(`/api/servers/${serverId}/metrics/live`, { + cache: "no-store", + }); if (!response.ok) { return {}; } - const data = await response.json(); - const timeSeries = data.metrics?.time_series || {}; - const cpuValues = timeSeries["node_cpu_seconds_total"]?.values || []; - const memoryValues = - timeSeries["node_memory_MemAvailable_bytes"]?.values || []; - - let cpu = 0; - if (cpuValues.length > 0) { - cpu = Math.min( - Math.round(Number.parseFloat(cpuValues.at(-1)[1]) * 100) / 100, - 100 - ); - } - - let memory = 0; - if (memoryValues.length > 0) { - memory = Math.min( - Math.round( - Number.parseFloat(memoryValues.at(-1)[1]) / 1024 / 1024 / 10 - ), - 100 - ); + const m = data.metrics; + if (!m) { + return {}; } - - const metrics = { cpu: cpu || undefined, memory: memory || undefined }; - metricsCache.set(serverId, { data: metrics, timestamp: Date.now() }); - return metrics; + return { + cpu: typeof m.cpu === "number" ? m.cpu : undefined, + memory: typeof m.memory === "number" ? m.memory : undefined, + }; } catch { return {}; } @@ -192,20 +162,38 @@ export const ServerCard = ({ server, game }: Props) => { statusConfig.stopped; useEffect(() => { - if (server.observedState === "running") { - setMetricsLoading(true); - const load = async () => { - try { - const m = await fetchMetrics(server.id); - setMetrics(m); - } finally { - setMetricsLoading(false); - } - }; - void load(); - } else { + if (server.observedState !== "running") { setMetrics({}); + setMetricsLoading(false); + return; } + + setMetricsLoading(true); + let cancelled = false; + + const load = async () => { + const m = await fetchLiveMetrics(server.id); + if (!cancelled) { + setMetrics(m); + setMetricsLoading(false); + } + }; + void load(); + + // Poll every 10s while running + const interval = setInterval(() => { + void (async () => { + const m = await fetchLiveMetrics(server.id); + if (!cancelled) { + setMetrics(m); + } + })(); + }, 10_000); + + return () => { + cancelled = true; + clearInterval(interval); + }; }, [server.id, server.observedState]); const handleCommand = useCallback( diff --git a/app/dashboard/new/components/form.tsx b/app/dashboard/new/components/form.tsx index f117701..7290abe 100644 --- a/app/dashboard/new/components/form.tsx +++ b/app/dashboard/new/components/form.tsx @@ -380,7 +380,7 @@ const GameStep = ({ games, gameId, setGameId }: GameStepProps) => ( Select the game you want to run on your server.

-
+
{games.map((game) => (