diff --git a/app/src/components/ConvergePanel.tsx b/app/src/components/ConvergePanel.tsx new file mode 100644 index 0000000..639df38 --- /dev/null +++ b/app/src/components/ConvergePanel.tsx @@ -0,0 +1,104 @@ +import { useState } from "react" +import { useQueryClient } from "@tanstack/react-query" +import { Check, GitCompare, Loader2, Play } from "lucide-react" +import { apiClient } from "@/services/api/client" +import type { ApplyResult } from "@/services/api/hooks" + +// A terraform-style "plan then apply" for the whole node: preview the diff the +// converge would enact (activate/restart/deactivate), then apply it. +export function ConvergePanel() { + const qc = useQueryClient() + const [plan, setPlan] = useState(null) + const [busy, setBusy] = useState<"plan" | "apply" | null>(null) + const [msg, setMsg] = useState(null) + + const preview = async () => { + setBusy("plan") + setMsg(null) + try { + setPlan(await apiClient.post("/apply", { plan: true })) + } finally { + setBusy(null) + } + } + + const apply = async () => { + setBusy("apply") + setMsg(null) + try { + await apiClient.post("/apply", {}) + setPlan(null) + setMsg("Applied — the node is converged.") + qc.invalidateQueries() + } catch (e) { + // A self-apply restarts castle-api, dropping the connection — expected. + if (e instanceof TypeError) { + setPlan(null) + setMsg("Applied — services are restarting.") + } else { + setMsg(`Apply failed: ${e instanceof Error ? e.message : String(e)}`) + } + } finally { + setBusy(null) + } + } + + const row = (label: string, names: string[], color: string) => + names.length > 0 && ( +
+ {label} + {names.join(", ")} +
+ ) + + return ( +
+
+
+ + Convergence +
+
+ + {plan?.changed && ( + + )} +
+
+ + {msg && ( +
+ {msg} +
+ )} + + {plan && ( +
+ {plan.changed ? ( + <> + {row("activate", plan.activated, "text-green-400")} + {row("restart", plan.restarted, "text-blue-400")} + {row("deactivate", plan.deactivated, "text-red-400")} + + ) : ( +
In sync — nothing to converge.
+ )} +
+ )} +
+ ) +} diff --git a/app/src/components/JobCard.tsx b/app/src/components/JobCard.tsx index b0f23e5..2110444 100644 --- a/app/src/components/JobCard.tsx +++ b/app/src/components/JobCard.tsx @@ -1,7 +1,7 @@ -import { Clock, Play, RefreshCw, Square, Terminal } from "lucide-react" +import { Clock, Power, RefreshCw, Terminal } from "lucide-react" import { Link } from "react-router-dom" import type { JobSummary, HealthStatus } from "@/types" -import { useServiceAction } from "@/services/api/hooks" +import { useServiceAction, useSetEnabled } from "@/services/api/hooks" import { launcherLabel } from "@/lib/labels" import { StackBadge } from "./StackBadge" @@ -11,12 +11,9 @@ interface JobCardProps { } export function JobCard({ job, health }: JobCardProps) { - const { mutate, isPending } = useServiceAction() - const isDown = health?.status === "down" - - const doAction = (action: string) => { - mutate({ name: job.id, action }) - } + const restart = useServiceAction() + const setEnabled = useSetEnabled() + const busy = restart.isPending || setEnabled.isPending return (
@@ -60,32 +57,26 @@ export function JobCard({ job, health }: JobCardProps) { {job.managed && (
- {isDown && ( - - )} - {!isDown && ( + {job.enabled && ( )}
diff --git a/app/src/components/ServiceCard.tsx b/app/src/components/ServiceCard.tsx index d81605b..f1c1a9b 100644 --- a/app/src/components/ServiceCard.tsx +++ b/app/src/components/ServiceCard.tsx @@ -1,7 +1,7 @@ -import { ExternalLink, Play, RefreshCw, Server, Square, Terminal } from "lucide-react" +import { ExternalLink, Power, RefreshCw, Server, Terminal } from "lucide-react" import { Link } from "react-router-dom" import type { ServiceSummary, HealthStatus } from "@/types" -import { useServiceAction } from "@/services/api/hooks" +import { useServiceAction, useSetEnabled } from "@/services/api/hooks" import { launcherLabel, subdomainUrl } from "@/lib/labels" import { HealthBadge } from "./HealthBadge" import { StackBadge } from "./StackBadge" @@ -14,13 +14,9 @@ interface ServiceCardProps { export function ServiceCard({ service, health }: ServiceCardProps) { const hasHttp = service.port != null - const { mutate, isPending } = useServiceAction() - - const doAction = (action: string) => { - mutate({ name: service.id, action }) - } - - const isDown = health?.status === "down" + const restart = useServiceAction() + const setEnabled = useSetEnabled() + const busy = restart.isPending || setEnabled.isPending return (
@@ -82,32 +78,26 @@ export function ServiceCard({ service, health }: ServiceCardProps) { {service.managed && (
- {isDown && ( - - )} - {!isDown && ( + {service.enabled && ( )}
diff --git a/app/src/components/detail/ConfigPanel.tsx b/app/src/components/detail/ConfigPanel.tsx index 26ea2a2..e455899 100644 --- a/app/src/components/detail/ConfigPanel.tsx +++ b/app/src/components/detail/ConfigPanel.tsx @@ -42,7 +42,7 @@ export function ConfigPanel({ deployment, configSection, onRefetch }: ConfigPane setMessage({ type: "ok", text: isDeployment - ? "Saved to castle.yaml — not live yet; apply to deploy & restart." + ? "Saved to castle.yaml — not live yet; apply to converge." : "Saved to castle.yaml", }) if (isDeployment) setPendingApply(true) @@ -58,16 +58,21 @@ export function ConfigPanel({ deployment, configSection, onRefetch }: ConfigPane setApplying(true) setMessage(null) try { - await apiClient.post(`/deploy`, { name: deployment.id }) - if (configSection === "services") { - await apiClient.post(`/services/${deployment.id}/restart`, {}) - } + // One converge: renders units/routes and reconciles the runtime (restarts + // only what changed). No separate restart call needed. + await apiClient.post(`/apply`, { name: deployment.id }) setPendingApply(false) setMessage({ type: "ok", text: "Applied — the change is now live." }) - qc.invalidateQueries({ queryKey: ["status"] }) - qc.invalidateQueries({ queryKey: [configSection] }) + qc.invalidateQueries() onRefetch() } catch (e: unknown) { + // A self-apply of castle-api restarts it, killing the connection — expected. + if (e instanceof TypeError) { + setPendingApply(false) + setMessage({ type: "ok", text: "Applied — the service is restarting." }) + setApplying(false) + return + } let msg = e instanceof Error ? e.message : String(e) try { msg = JSON.parse((e as Error).message).detail ?? msg @@ -122,11 +127,7 @@ export function ConfigPanel({ deployment, configSection, onRefetch }: ConfigPane className="shrink-0 flex items-center gap-1.5 px-3 py-1 text-xs rounded bg-amber-700 hover:bg-amber-600 text-white transition-colors disabled:opacity-50" > - {applying - ? "Applying…" - : configSection === "services" - ? "Apply (deploy & restart)" - : "Apply (deploy)"} + {applying ? "Applying…" : "Apply"} )}
diff --git a/app/src/components/detail/CreateDeploymentForm.tsx b/app/src/components/detail/CreateDeploymentForm.tsx index 48e98f9..5b38ed3 100644 --- a/app/src/components/detail/CreateDeploymentForm.tsx +++ b/app/src/components/detail/CreateDeploymentForm.tsx @@ -108,12 +108,9 @@ export function CreateDeploymentForm({ try { setBusy("Saving…") await apiClient.put(`/config/deployments/${name}`, { config: buildConfig() }) - setBusy("Deploying…") - await apiClient.post(`/deploy`, { name }) - if (kind === "service") { - setBusy("Starting…") - await apiClient.post(`/services/${name}/start`, {}) - } + // Converge: render + activate the new deployment in one step. + setBusy("Applying…") + await apiClient.post(`/apply`, { name }) qc.invalidateQueries({ queryKey: ["services"] }) qc.invalidateQueries({ queryKey: ["jobs"] }) qc.invalidateQueries({ queryKey: ["programs"] }) diff --git a/app/src/components/detail/ServiceControls.tsx b/app/src/components/detail/ServiceControls.tsx index 5ff3a33..8cfaaa6 100644 --- a/app/src/components/detail/ServiceControls.tsx +++ b/app/src/components/detail/ServiceControls.tsx @@ -1,44 +1,40 @@ -import { Play, RefreshCw, Square } from "lucide-react" -import { useServiceAction } from "@/services/api/hooks" -import type { HealthStatus } from "@/types" +import { Power, RefreshCw } from "lucide-react" +import { useServiceAction, useSetEnabled } from "@/services/api/hooks" interface ServiceControlsProps { name: string - health?: HealthStatus + enabled: boolean } -export function ServiceControls({ name, health }: ServiceControlsProps) { - const { mutate, isPending } = useServiceAction() - const isDown = health?.status === "down" +// Lifecycle is convergence: the Power toggle sets desired on/off state and applies +// (activate/deactivate); Restart is the one imperative bounce. No raw start/stop. +export function ServiceControls({ name, enabled }: ServiceControlsProps) { + const restart = useServiceAction() + const setEnabled = useSetEnabled() + const busy = restart.isPending || setEnabled.isPending return (
- {isDown && ( - - )} - {!isDown && ( + {enabled && ( )}
diff --git a/app/src/pages/Overview.tsx b/app/src/pages/Overview.tsx index a06bdd8..30d2d9b 100644 --- a/app/src/pages/Overview.tsx +++ b/app/src/pages/Overview.tsx @@ -11,6 +11,7 @@ import { } from "@/services/api/hooks" import { NodeBar } from "@/components/NodeBar" import { PageHeader } from "@/components/PageHeader" +import { ConvergePanel } from "@/components/ConvergePanel" export function Overview() { const { data: services } = useServices() @@ -96,6 +97,8 @@ export function Overview() { ))}
+ + ) } diff --git a/app/src/pages/ScheduledDetail.tsx b/app/src/pages/ScheduledDetail.tsx index edccbb9..c38a007 100644 --- a/app/src/pages/ScheduledDetail.tsx +++ b/app/src/pages/ScheduledDetail.tsx @@ -1,6 +1,6 @@ import { useParams } from "react-router-dom" import { Clock } from "lucide-react" -import { useJob, useStatus } from "@/services/api/hooks" +import { useJob } from "@/services/api/hooks" import { LogViewer } from "@/components/LogViewer" import { DetailHeader } from "@/components/detail/DetailHeader" import { ServiceControls } from "@/components/detail/ServiceControls" @@ -10,8 +10,6 @@ import { ConfigPanel } from "@/components/detail/ConfigPanel" export function ScheduledDetailPage() { const { name } = useParams<{ name: string }>() const { data: deployment, isLoading, error, refetch } = useJob(name ?? "") - const { data: statusResp } = useStatus() - const health = statusResp?.statuses.find((s) => s.id === name) if (isLoading) { return ( @@ -38,7 +36,7 @@ export function ScheduledDetailPage() { stack={deployment.stack} source={deployment.source} > - + {deployment.schedule && ( diff --git a/app/src/pages/ServiceDetail.tsx b/app/src/pages/ServiceDetail.tsx index f1a78e6..74882ce 100644 --- a/app/src/pages/ServiceDetail.tsx +++ b/app/src/pages/ServiceDetail.tsx @@ -51,7 +51,7 @@ export function ServiceDetailPage() { {!isStatic && (
{health && } - +
)} diff --git a/app/src/pages/ToolDetail.tsx b/app/src/pages/ToolDetail.tsx index b747dfa..80a0161 100644 --- a/app/src/pages/ToolDetail.tsx +++ b/app/src/pages/ToolDetail.tsx @@ -1,6 +1,6 @@ import { useParams, Link } from "react-router-dom" import { Loader2, Package } from "lucide-react" -import { useDeployment, useProgramAction } from "@/services/api/hooks" +import { useDeployment, useSetEnabled } from "@/services/api/hooks" import { DetailHeader } from "@/components/detail/DetailHeader" import { ConfigPanel } from "@/components/detail/ConfigPanel" @@ -38,9 +38,14 @@ export function ToolDetailPage() {

{deployment.description}

)} - {/* A tool's PATH deployment: install/uninstall is its start/stop. Its - live state is `installed` (on PATH), which the endpoint sets directly. */} - + {/* A tool's PATH deployment: enabling converges it onto PATH, disabling + removes it. `installed` is the live state; `enabled` the desired one. */} +

@@ -63,17 +68,19 @@ export function ToolDetailPage() { ) } -/** Install/uninstall a tool on PATH — the path deployment's lifecycle. */ +/** Enable/disable a tool — convergence installs it onto PATH or removes it. */ function PathLifecycle({ name, + enabled, installed: installedState, onDone, }: { name: string + enabled: boolean installed: boolean | null onDone: () => void }) { - const { mutate, isPending } = useProgramAction() + const { mutate, isPending } = useSetEnabled() const installed = installedState === true const dot = installedState === true @@ -86,21 +93,20 @@ function PathLifecycle({
{installed ? "Installed on PATH" : "Not installed"} + {!enabled && disabled} manager: path

) diff --git a/app/src/services/api/hooks.ts b/app/src/services/api/hooks.ts index 3f282c6..a68e3fa 100644 --- a/app/src/services/api/hooks.ts +++ b/app/src/services/api/hooks.ts @@ -154,6 +154,65 @@ export function useServiceAction() { }) } +export interface ApplyResult { + status: string + planned: boolean + changed: boolean + activated: string[] + restarted: string[] + deactivated: string[] + unchanged: string[] + messages: string[] +} + +// Converge the running system to config. Pass a name to converge one deployment, +// or plan:true for a dry-run diff. Handles the API restarting itself mid-apply. +export function useApply() { + const qc = useQueryClient() + return useMutation({ + mutationFn: async ({ name, plan }: { name?: string; plan?: boolean } = {}) => { + try { + return await apiClient.post("/apply", { name, plan }) + } catch (err) { + if (err instanceof TypeError) { + // Self-restart killed the connection — treat as accepted, wait + refresh. + await waitForApi() + return { + status: "ok", planned: false, changed: true, + activated: [], restarted: name ? [name] : [], deactivated: [], + unchanged: [], messages: [], + } as ApplyResult + } + throw err + } + }, + onSuccess: (data) => { + if (!data.planned) qc.invalidateQueries() + }, + }) +} + +// Set a deployment's desired on/off state, then converge it. One click = "make it +// so": edit config (declarative), then apply that single deployment. +export function useSetEnabled() { + const qc = useQueryClient() + return useMutation({ + mutationFn: async ({ name, enabled }: { name: string; enabled: boolean }) => { + await apiClient.put(`/config/deployments/${name}/enabled`, { enabled }) + try { + return await apiClient.post("/apply", { name }) + } catch (err) { + if (err instanceof TypeError) { + await waitForApi() + return null + } + throw err + } + }, + onSuccess: () => qc.invalidateQueries(), + }) +} + export function useProgramAction() { const qc = useQueryClient() return useMutation({ diff --git a/app/src/types/index.ts b/app/src/types/index.ts index 3740b91..c6de932 100644 --- a/app/src/types/index.ts +++ b/app/src/types/index.ts @@ -19,6 +19,7 @@ export interface ServiceSummary { systemd: SystemdInfo | null program: string | null source: string | null + enabled: boolean // declared desired state; `apply` converges to it node: string | null } @@ -37,6 +38,7 @@ export interface JobSummary { systemd: SystemdInfo | null program: string | null source: string | null + enabled: boolean // declared desired state; `apply` converges to it node: string | null } @@ -98,6 +100,7 @@ export interface DeploymentSummary { schedule: string | null installed: boolean | null active: boolean | null + enabled: boolean // declared desired state; `apply` converges to it node: string | null } diff --git a/castle-api/src/castle_api/config_editor.py b/castle-api/src/castle_api/config_editor.py index e672ba1..33295b8 100644 --- a/castle-api/src/castle_api/config_editor.py +++ b/castle-api/src/castle_api/config_editor.py @@ -323,6 +323,29 @@ def delete_deployment(name: str) -> dict: return _delete_deployment(name) +class EnabledRequest(BaseModel): + enabled: bool + + +@router.put("/deployments/{name}/enabled") +def set_deployment_enabled(name: str, request: EnabledRequest) -> dict: + """Set a deployment's declared `enabled` state (desired on/off). + + Edits config only — the caller runs `POST /apply` to converge. Keeps the + declarative flow: change what you want, then apply. + """ + config = get_config() + dep = config.deployments.get(name) + if dep is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Deployment '{name}' not found", + ) + dep.enabled = request.enabled + save_config(config) + return {"ok": True, "deployment": name, "enabled": request.enabled} + + @router.put("/services/{name}") def save_service(name: str, request: ServiceConfigRequest) -> dict: """Alias of PUT /deployments/{name} (kept for the existing dashboard)."""