Add controller node selector and accordion wizards
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { Client } from "ssh2"
|
||||
import { buildControllerNodePlan, type ControllerPlanRequest } from "@/app/lib/controllerNodePlan"
|
||||
import { upsertControllerNode } from "@/app/lib/controllerNodeRegistry"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
@@ -147,6 +148,13 @@ export async function POST(request: Request) {
|
||||
acceptUnknownHostKey,
|
||||
expectedHostKeySha256,
|
||||
})
|
||||
await upsertControllerNode({
|
||||
id: plan.controller.name,
|
||||
name: plan.controller.name,
|
||||
host: plan.controller.host,
|
||||
url: plan.controller.url,
|
||||
role: "controller-node",
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { buildControllerNodePlan, type ControllerPlanRequest } from "@/app/lib/controllerNodePlan"
|
||||
import { upsertControllerNode } from "@/app/lib/controllerNodeRegistry"
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = (await request.json().catch(() => ({}))) as ControllerPlanRequest
|
||||
return NextResponse.json({ ok: true, ...buildControllerNodePlan(body) })
|
||||
const plan = buildControllerNodePlan(body)
|
||||
await upsertControllerNode({
|
||||
id: plan.controller.name,
|
||||
name: plan.controller.name,
|
||||
host: plan.controller.host,
|
||||
url: plan.controller.url,
|
||||
role: "controller-node",
|
||||
})
|
||||
return NextResponse.json({ ok: true, ...plan })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to build controller node plan"
|
||||
return NextResponse.json({ ok: false, error: message }, { status: 400 })
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { listControllerNodes, renameControllerNode, upsertControllerNode } from "@/app/lib/controllerNodeRegistry"
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
return NextResponse.json({ nodes: await listControllerNodes() })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to load controller nodes"
|
||||
return NextResponse.json({ error: message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const action = typeof body?.action === "string" ? body.action : "upsert"
|
||||
|
||||
if (action === "rename") {
|
||||
const node = await renameControllerNode(String(body?.nodeId || ""), String(body?.name || ""))
|
||||
return NextResponse.json({ node, nodes: await listControllerNodes() })
|
||||
}
|
||||
|
||||
const node = await upsertControllerNode({
|
||||
id: body?.id,
|
||||
name: body?.name,
|
||||
host: body?.host,
|
||||
url: body?.url,
|
||||
role: body?.role,
|
||||
})
|
||||
|
||||
return NextResponse.json({ node, nodes: await listControllerNodes() })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to update controller nodes"
|
||||
return NextResponse.json({ error: message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
+156
-5
@@ -1,5 +1,16 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
|
||||
type ControllerNodeRecord = {
|
||||
id: string
|
||||
name: string
|
||||
host: string
|
||||
url: string
|
||||
role: "local" | "controller-node"
|
||||
status: "configured" | "local"
|
||||
}
|
||||
|
||||
interface SidebarProps {
|
||||
sandboxesRunning: number
|
||||
sandboxesTotal: number
|
||||
@@ -19,6 +30,8 @@ interface SidebarProps {
|
||||
terminalDisabled?: boolean
|
||||
}
|
||||
|
||||
const SELECTED_CONTROLLER_NODE_KEY = "openshell-control-selected-node"
|
||||
|
||||
export default function Sidebar({
|
||||
sandboxesRunning,
|
||||
sandboxesTotal,
|
||||
@@ -37,6 +50,80 @@ export default function Sidebar({
|
||||
onLogout,
|
||||
terminalDisabled = false,
|
||||
}: SidebarProps) {
|
||||
const [controllerNodes, setControllerNodes] = useState<ControllerNodeRecord[]>([])
|
||||
const [selectedNodeId, setSelectedNodeId] = useState("local")
|
||||
const [nodeMenuOpen, setNodeMenuOpen] = useState(false)
|
||||
const [friendlyNameDraft, setFriendlyNameDraft] = useState("")
|
||||
const [friendlyNameSaving, setFriendlyNameSaving] = useState(false)
|
||||
const [friendlyNameMessage, setFriendlyNameMessage] = useState("")
|
||||
|
||||
const selectedNode = useMemo(
|
||||
() => controllerNodes.find((node) => node.id === selectedNodeId) || controllerNodes[0] || null,
|
||||
[controllerNodes, selectedNodeId],
|
||||
)
|
||||
const hasRemoteNodes = controllerNodes.some((node) => node.role === "controller-node")
|
||||
|
||||
useEffect(() => {
|
||||
const stored = window.localStorage.getItem(SELECTED_CONTROLLER_NODE_KEY)
|
||||
if (stored) setSelectedNodeId(stored)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const loadControllerNodes = () => {
|
||||
fetch("/api/controller-node/registry", { cache: "no-store" })
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
if (cancelled) return
|
||||
const nodes = Array.isArray(data.nodes) ? data.nodes : []
|
||||
setControllerNodes(nodes)
|
||||
if (nodes.length > 1) setNodeMenuOpen(true)
|
||||
setSelectedNodeId((current) => nodes.some((node: ControllerNodeRecord) => node.id === current) ? current : nodes[0]?.id || "local")
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setControllerNodes([])
|
||||
})
|
||||
}
|
||||
|
||||
loadControllerNodes()
|
||||
window.addEventListener("controller-nodes-changed", loadControllerNodes)
|
||||
return () => {
|
||||
cancelled = true
|
||||
window.removeEventListener("controller-nodes-changed", loadControllerNodes)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedNode) return
|
||||
setFriendlyNameDraft(selectedNode.name)
|
||||
window.localStorage.setItem(SELECTED_CONTROLLER_NODE_KEY, selectedNode.id)
|
||||
}, [selectedNode])
|
||||
|
||||
async function saveFriendlyName() {
|
||||
if (!selectedNode || friendlyNameSaving) return
|
||||
try {
|
||||
setFriendlyNameSaving(true)
|
||||
setFriendlyNameMessage("")
|
||||
const response = await fetch("/api/controller-node/registry", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "rename",
|
||||
nodeId: selectedNode.id,
|
||||
name: friendlyNameDraft,
|
||||
}),
|
||||
})
|
||||
const data = await response.json()
|
||||
if (!response.ok) throw new Error(data.error || "Failed to save node name")
|
||||
setControllerNodes(Array.isArray(data.nodes) ? data.nodes : [])
|
||||
setFriendlyNameMessage("Saved")
|
||||
} catch (error) {
|
||||
setFriendlyNameMessage(error instanceof Error ? error.message : "Failed to save")
|
||||
} finally {
|
||||
setFriendlyNameSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const navItemClass = (active = false, danger = false) => `w-full flex items-center gap-3 rounded px-3 py-2.5 text-left transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)] max-lg:min-w-24 max-lg:flex-col max-lg:justify-center max-lg:gap-1 max-lg:px-2 max-lg:py-2 ${
|
||||
active
|
||||
? danger
|
||||
@@ -47,21 +134,85 @@ export default function Sidebar({
|
||||
|
||||
return (
|
||||
<aside className="fixed left-0 top-0 z-20 flex h-screen w-64 flex-col border-r border-[var(--border-subtle)] bg-[var(--background-secondary)]/95 shadow-[12px_0_40px_rgba(0,0,0,0.22)] backdrop-blur lg:w-64 max-lg:bottom-0 max-lg:top-auto max-lg:h-auto max-lg:w-full max-lg:border-r-0 max-lg:border-t max-lg:shadow-[0_-12px_40px_rgba(0,0,0,0.22)]">
|
||||
<div className="p-4 border-b border-[var(--border-subtle)] max-lg:hidden">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="border-b border-[var(--border-subtle)] p-4 max-lg:hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNodeMenuOpen((open) => !open)}
|
||||
aria-expanded={nodeMenuOpen}
|
||||
className="flex w-full items-center gap-3 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)]"
|
||||
>
|
||||
<div className="w-8 h-8 bg-[var(--nvidia-green)] rounded flex items-center justify-center shadow-[0_0_22px_rgba(118,185,0,0.28)]">
|
||||
<svg className="w-5 h-5 text-black" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M4 7l8-4 8 4v10l-8 4-8-4V7z" />
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M4 7l8 4 8-4M12 11v10" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-semibold text-[var(--foreground)] tracking-tight">OpenShell Control</p>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] font-mono mt-1">
|
||||
{sandboxesRunning} running / {sandboxesTotal} total
|
||||
{selectedNode ? `${selectedNode.name} / ${selectedNode.host}` : `${sandboxesRunning} running / ${sandboxesTotal} total`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<svg
|
||||
className={`h-4 w-4 shrink-0 text-[var(--foreground-dim)] transition-transform ${nodeMenuOpen ? "rotate-90" : ""}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
{nodeMenuOpen && (
|
||||
<div className="mt-4 space-y-3 border-t border-[var(--border-subtle)] pt-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className={`status-chip px-2 py-1 ${hasRemoteNodes ? "bg-[var(--status-running-bg)] text-[var(--status-running)]" : "bg-[var(--status-pending-bg)] text-[var(--status-pending)]"}`}>
|
||||
{hasRemoteNodes ? "multi-node" : "local"}
|
||||
</span>
|
||||
<span className="text-[10px] font-mono text-[var(--foreground-dim)]">
|
||||
{sandboxesRunning} running / {sandboxesTotal} total
|
||||
</span>
|
||||
</div>
|
||||
<label className="block space-y-2">
|
||||
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Managed Node</span>
|
||||
<select
|
||||
value={selectedNode?.id || ""}
|
||||
onChange={(event) => setSelectedNodeId(event.target.value)}
|
||||
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2 py-2 text-xs font-mono text-[var(--foreground)] focus:border-[var(--nvidia-green)] focus:outline-none"
|
||||
>
|
||||
{controllerNodes.map((node) => (
|
||||
<option key={node.id} value={node.id}>
|
||||
{node.name} - {node.host}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{selectedNode && (
|
||||
<div className="space-y-2 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3">
|
||||
<p className="truncate text-[11px] font-mono text-[var(--foreground)]">{selectedNode.url}</p>
|
||||
<label className="block space-y-2">
|
||||
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Friendly Name</span>
|
||||
<input
|
||||
value={friendlyNameDraft}
|
||||
onChange={(event) => setFriendlyNameDraft(event.target.value)}
|
||||
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono text-[var(--foreground)] focus:border-[var(--nvidia-green)] focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={saveFriendlyName}
|
||||
disabled={friendlyNameSaving || !friendlyNameDraft.trim()}
|
||||
className="action-button px-3 py-1.5 text-[10px] disabled:opacity-50"
|
||||
>
|
||||
{friendlyNameSaving ? "Saving" : "Save Name"}
|
||||
</button>
|
||||
{friendlyNameMessage && <span className="truncate text-[10px] text-[var(--foreground-dim)]">{friendlyNameMessage}</span>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-2 max-lg:flex max-lg:gap-1 max-lg:overflow-x-auto max-lg:[scrollbar-width:none]">
|
||||
|
||||
@@ -95,6 +95,8 @@ export default function WizardPanel({
|
||||
const [controllerPlanning, setControllerPlanning] = useState(false)
|
||||
const [controllerDeploying, setControllerDeploying] = useState(false)
|
||||
const [controllerDeployLog, setControllerDeployLog] = useState("")
|
||||
const [controllerWizardOpen, setControllerWizardOpen] = useState(true)
|
||||
const [cloneWizardOpen, setCloneWizardOpen] = useState(false)
|
||||
|
||||
const sourceSandbox = useMemo(
|
||||
() => sandboxes.find((sandbox) => sandbox.id === sourceSandboxId) || null,
|
||||
@@ -239,6 +241,7 @@ export default function WizardPanel({
|
||||
const data = await response.json()
|
||||
if (!response.ok) throw new Error(data.error || "Failed to generate controller node plan")
|
||||
setControllerPlan(data)
|
||||
window.dispatchEvent(new Event("controller-nodes-changed"))
|
||||
setControllerMessage(`Launch kit ready for ${data.controller.url}.`)
|
||||
} catch (error) {
|
||||
setControllerMessage(error instanceof Error ? error.message : "Failed to generate controller node plan")
|
||||
@@ -282,6 +285,7 @@ export default function WizardPanel({
|
||||
setControllerPlan((current) => current ?? data)
|
||||
setControllerDeployLog([data.note, data.hostKeySha256 ? `Host key SHA256: ${data.hostKeySha256}` : "", data.stdout, data.stderr].filter(Boolean).join("\n\n"))
|
||||
setRemotePassword("")
|
||||
window.dispatchEvent(new Event("controller-nodes-changed"))
|
||||
setControllerMessage(`Autodeploy complete for ${data.controller?.url || controllerHost}.`)
|
||||
} catch (error) {
|
||||
setControllerMessage(error instanceof Error ? error.message : "Autodeploy failed")
|
||||
@@ -310,19 +314,33 @@ export default function WizardPanel({
|
||||
</section>
|
||||
|
||||
<section className="panel overflow-hidden">
|
||||
<div className="border-b border-[var(--border-subtle)] p-5">
|
||||
<div className="flex items-center justify-between gap-4 max-md:flex-col max-md:items-start">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setControllerWizardOpen((open) => !open)}
|
||||
aria-expanded={controllerWizardOpen}
|
||||
className="flex w-full items-center justify-between gap-4 border-b border-[var(--border-subtle)] p-5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)] max-md:items-start"
|
||||
>
|
||||
<div className="flex min-w-0 items-start gap-4">
|
||||
<svg
|
||||
className={`mt-1 h-4 w-4 shrink-0 text-[var(--foreground-dim)] transition-transform ${controllerWizardOpen ? "rotate-90" : ""}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Spawn a Controller Node</h2>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Prepare a remote VPS to run OpenShell Control near another OpenShell gateway or sandbox host.</p>
|
||||
</div>
|
||||
<span className="status-chip border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2.5 py-1 text-[var(--foreground-dim)]">
|
||||
{controllerDeployMode === "auto" ? "autodeploy" : "manual deploy"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="status-chip shrink-0 border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2.5 py-1 text-[var(--foreground-dim)]">
|
||||
{controllerDeployMode === "auto" ? "autodeploy" : "manual deploy"}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="grid grid-cols-1 gap-5 p-5 xl:grid-cols-[minmax(0,1fr)_minmax(360px,0.8fr)]">
|
||||
{controllerWizardOpen && <div className="grid grid-cols-1 gap-5 p-5 xl:grid-cols-[minmax(0,1fr)_minmax(360px,0.8fr)]">
|
||||
<div className="space-y-5">
|
||||
<div className="grid grid-cols-2 gap-2 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-1">
|
||||
{(["manual", "auto"] as ControllerDeployMode[]).map((mode) => (
|
||||
@@ -493,23 +511,37 @@ export default function WizardPanel({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>}
|
||||
</section>
|
||||
|
||||
<section className="panel overflow-hidden">
|
||||
<div className="border-b border-[var(--border-subtle)] p-5">
|
||||
<div className="flex items-center justify-between gap-4 max-md:flex-col max-md:items-start">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCloneWizardOpen((open) => !open)}
|
||||
aria-expanded={cloneWizardOpen}
|
||||
className="flex w-full items-center justify-between gap-4 border-b border-[var(--border-subtle)] p-5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--nvidia-green)] max-md:items-start"
|
||||
>
|
||||
<div className="flex min-w-0 items-start gap-4">
|
||||
<svg
|
||||
className={`mt-1 h-4 w-4 shrink-0 text-[var(--foreground-dim)] transition-transform ${cloneWizardOpen ? "rotate-90" : ""}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Clone Sandbox</h2>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Create a fresh sandbox, back up the source, then restore into the target.</p>
|
||||
</div>
|
||||
<span className="status-chip border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2.5 py-1 text-[var(--foreground-dim)]">
|
||||
backup + restore
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="status-chip shrink-0 border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2.5 py-1 text-[var(--foreground-dim)]">
|
||||
backup + restore
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="border-b border-[var(--border-subtle)] p-4">
|
||||
{cloneWizardOpen && <><div className="border-b border-[var(--border-subtle)] p-4">
|
||||
<div className="grid grid-cols-5 gap-2 max-md:grid-cols-1">
|
||||
{steps.map((step, index) => (
|
||||
<button
|
||||
@@ -691,6 +723,7 @@ export default function WizardPanel({
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises"
|
||||
import { hostname } from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
export type ControllerNodeRecord = {
|
||||
id: string
|
||||
name: string
|
||||
host: string
|
||||
url: string
|
||||
role: "local" | "controller-node"
|
||||
status: "configured" | "local"
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
type StoreShape = {
|
||||
nodes: Record<string, ControllerNodeRecord>
|
||||
}
|
||||
|
||||
const STORE_DIR = process.env.OPENSHELL_CONTROL_STATE_DIR || path.join(process.cwd(), ".runtime")
|
||||
const STORE_PATH = path.join(STORE_DIR, "controller-nodes.json")
|
||||
const SAFE_ID = /^[a-z0-9][a-z0-9._:-]{0,127}$/i
|
||||
|
||||
function now() {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function text(value: unknown, fallback = "") {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : fallback
|
||||
}
|
||||
|
||||
function slugify(value: string) {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._:-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 128)
|
||||
}
|
||||
|
||||
function localControllerNode(): ControllerNodeRecord {
|
||||
const port = process.env.NEXT_PUBLIC_DASHBOARD_PORT || process.env.PORT || "3000"
|
||||
const url = process.env.OPENSHELL_CONTROL_PUBLIC_URL || `http://localhost:${port}`
|
||||
return {
|
||||
id: "local",
|
||||
name: process.env.OPENSHELL_CONTROL_FRIENDLY_NAME || "Local Controller",
|
||||
host: hostname(),
|
||||
url,
|
||||
role: "local",
|
||||
status: "local",
|
||||
updatedAt: now(),
|
||||
}
|
||||
}
|
||||
|
||||
function emptyStore(): StoreShape {
|
||||
return { nodes: {} }
|
||||
}
|
||||
|
||||
function normalizeNode(input: Partial<ControllerNodeRecord>, existing?: ControllerNodeRecord | null): ControllerNodeRecord {
|
||||
const host = text(input.host, existing?.host || "")
|
||||
const url = text(input.url, existing?.url || (host ? `http://${host}:3000` : ""))
|
||||
const id = slugify(text(input.id, existing?.id || host || url))
|
||||
if (!id || !SAFE_ID.test(id)) throw new Error("controller node id is invalid")
|
||||
if (!host) throw new Error("controller node host is required")
|
||||
if (!url) throw new Error("controller node url is required")
|
||||
|
||||
return {
|
||||
id,
|
||||
name: text(input.name, existing?.name || host),
|
||||
host,
|
||||
url,
|
||||
role: input.role === "local" ? "local" : "controller-node",
|
||||
status: input.status === "local" ? "local" : "configured",
|
||||
updatedAt: now(),
|
||||
}
|
||||
}
|
||||
|
||||
function parseEnvNodes() {
|
||||
const raw = process.env.OPENSHELL_CONTROLLER_NODES_JSON || process.env.OPENCLAW_INSTANCE_REGISTRY_JSON
|
||||
if (!raw?.trim()) return []
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
const entries = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.nodes) ? parsed.nodes : []
|
||||
return entries
|
||||
.map((entry: unknown) => {
|
||||
if (!entry || typeof entry !== "object") return null
|
||||
const record = entry as Record<string, unknown>
|
||||
const url = text(record.url, text(record.controlUiOrigin, text(record.dashboardUrl)))
|
||||
const host = text(record.host, url ? new URL(url).hostname : "")
|
||||
if (!host || !url) return null
|
||||
return normalizeNode({
|
||||
id: text(record.id, host),
|
||||
name: text(record.name, text(record.label, host)),
|
||||
host,
|
||||
url,
|
||||
role: record.role === "local" ? "local" : "controller-node",
|
||||
})
|
||||
})
|
||||
.filter((entry: ControllerNodeRecord | null): entry is ControllerNodeRecord => Boolean(entry))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async function readStore(): Promise<StoreShape> {
|
||||
try {
|
||||
const raw = await readFile(STORE_PATH, "utf8")
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!parsed || typeof parsed !== "object" || !parsed.nodes || typeof parsed.nodes !== "object") return emptyStore()
|
||||
return { nodes: parsed.nodes }
|
||||
} catch {
|
||||
return emptyStore()
|
||||
}
|
||||
}
|
||||
|
||||
async function writeStore(store: StoreShape) {
|
||||
await mkdir(STORE_DIR, { recursive: true, mode: 0o700 })
|
||||
await writeFile(STORE_PATH, JSON.stringify(store, null, 2), { mode: 0o600 })
|
||||
}
|
||||
|
||||
export async function listControllerNodes() {
|
||||
const store = await readStore()
|
||||
const merged = new Map<string, ControllerNodeRecord>()
|
||||
const local = localControllerNode()
|
||||
merged.set(local.id, { ...local, ...store.nodes[local.id], role: "local", status: "local" })
|
||||
|
||||
for (const node of parseEnvNodes()) {
|
||||
merged.set(node.id, { ...node, ...store.nodes[node.id] })
|
||||
}
|
||||
for (const node of Object.values(store.nodes)) {
|
||||
merged.set(node.id, node)
|
||||
}
|
||||
|
||||
return Array.from(merged.values()).sort((a, b) => {
|
||||
if (a.role === "local") return -1
|
||||
if (b.role === "local") return 1
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
}
|
||||
|
||||
export async function upsertControllerNode(input: Partial<ControllerNodeRecord>) {
|
||||
const store = await readStore()
|
||||
const id = slugify(text(input.id, input.host || input.url || ""))
|
||||
const existing = id ? store.nodes[id] : null
|
||||
const node = normalizeNode(input, existing)
|
||||
store.nodes[node.id] = node
|
||||
await writeStore(store)
|
||||
return node
|
||||
}
|
||||
|
||||
export async function renameControllerNode(nodeId: string, name: string) {
|
||||
const nodes = await listControllerNodes()
|
||||
const existing = nodes.find((node) => node.id === slugify(nodeId))
|
||||
if (!existing) throw new Error("controller node was not found")
|
||||
return upsertControllerNode({ ...existing, name })
|
||||
}
|
||||
Reference in New Issue
Block a user