Files
Homelab-manager/web/src/components/RunPlaybook.tsx
T
bobbanandClaude Sonnet 5.5 645816d5a8 Add a Swedish interface with a per-person language switch
A small translation system (the English text is its own key, so anything
without a Swedish entry stays English) and a Language switch in the user menu,
saved on the account (users.language) and following the browser when no choice
has been made. Swedish covers the menu, shared parts (search, tables, dialogs,
relative times), the sign-in page and the everyday pages: Dashboard, Alerts,
Servers, Updates, Maintenance, My work, Coming up, To do, Integrations and the
display settings. Server-written messages stay English for now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:49:49 +01:00

194 lines
8.6 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { api, type IntegrationSummary, type SemaphoreTask, type SemaphoreTemplate } from "../api/client";
import { confirmDialog } from "../utils/dialogs";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import TimeAgo from "./TimeAgo";
import { BlockSkeleton } from "./Skeleton";
import { t } from "../i18n";
interface Loaded {
integration: IntegrationSummary;
templates: SemaphoreTemplate[];
failed: boolean;
}
const STATUS_WORDS: Record<SemaphoreTask["status"], { label: string; badge: string }> = {
waiting: { label: "Waiting to start", badge: "bg-secondary-lt text-secondary" },
starting: { label: "Starting", badge: "bg-blue-lt text-blue" },
running: { label: "Running", badge: "bg-blue-lt text-blue" },
waiting_confirmation: { label: "Waiting for approval in Semaphore", badge: "bg-yellow-lt text-yellow" },
confirmed: { label: "Approved", badge: "bg-blue-lt text-blue" },
rejected: { label: "Rejected in Semaphore", badge: "bg-red-lt text-red" },
stopping: { label: "Stopping", badge: "bg-yellow-lt text-yellow" },
stopped: { label: "Stopped", badge: "bg-secondary-lt text-secondary" },
success: { label: "Finished — success", badge: "bg-green-lt text-green" },
error: { label: "Finished — failed", badge: "bg-red-lt text-red" },
};
const FINISHED = new Set<SemaphoreTask["status"]>(["success", "error", "stopped", "rejected"]);
/**
* Starts a Semaphore template — optionally on this server only — and shows how the run gets on. It is the same "run" the Semaphore page
* has, with the one addition that matters from a server or an alert: ansible's limit, so "apply updates" touches the one machine and
* not the whole inventory. Asks first, and says plainly when there is no limit.
*/
export default function RunPlaybook({ serverName, defaultLimit }: { serverName: string; defaultLimit: string }) {
const [loaded, setLoaded] = useState<Loaded[] | null>(null);
const [failed, setFailed] = useState(false);
const [choice, setChoice] = useState("");
const [limitOn, setLimitOn] = useState(true);
const [limit, setLimit] = useState(defaultLimit);
const [busy, setBusy] = useState(false);
const [run, setRun] = useState<{ integrationId: number; projectId: number; name: string; limit: string; task: SemaphoreTask } | null>(null);
const alive = useRef(true);
useEffect(() => {
alive.current = true;
api.integrations
.list()
.then(async (res) => {
const servers = res.integrations.filter((i) => i.type === "semaphore" && i.enabled);
const all = await Promise.all(
servers.map((integration) =>
api.integrations.semaphore
.templates(integration.id)
.then((r): Loaded => ({ integration, templates: r.templates, failed: false }))
.catch((): Loaded => ({ integration, templates: [], failed: true })),
),
);
if (alive.current) setLoaded(all);
})
.catch(() => alive.current && setFailed(true));
return () => {
alive.current = false;
};
}, []);
// Watch a run until it is over.
useEffect(() => {
if (!run || FINISHED.has(run.task.status)) return;
const timer = setInterval(() => {
api.integrations.semaphore
.task(run.integrationId, run.projectId, run.task.id)
.then((res) => alive.current && setRun((r) => (r && r.task.id === res.task.id ? { ...r, task: res.task } : r)))
.catch(() => {
// Keep asking: one missed answer isn't the end of the run.
});
}, 3000);
return () => clearInterval(timer);
}, [run?.task.id, run?.task.status, run?.integrationId, run?.projectId]);
const options = (loaded ?? []).flatMap((l) =>
l.templates.map((t) => ({
key: `${l.integration.id}:${t.projectId}:${t.id}`,
integration: l.integration,
template: t,
label: `${t.name} — ${t.projectName}${(loaded ?? []).length > 1 ? ` (${l.integration.name})` : ""}`,
})),
);
const picked = options.find((o) => o.key === choice);
const limitText = limitOn ? limit.trim() : "";
async function start() {
if (!picked) return;
const where = limitText ? `on ${limitText} only` : "on everything the playbook covers — it isn't limited to one server";
if (
!(await confirmDialog({
title: `Run ${picked.template.name}?`,
message: `This starts "${picked.template.name}" in ${picked.integration.name} ${where}.`,
confirmLabel: "Run it",
danger: !limitText,
}))
)
return;
setBusy(true);
try {
const res = await api.integrations.semaphore.run(picked.integration.id, picked.template.projectId, picked.template.id, limitText ? { limit: limitText } : undefined);
setRun({ integrationId: picked.integration.id, projectId: picked.template.projectId, name: picked.template.name, limit: limitText, task: res.task });
toast.success(`Started ${picked.template.name}${limitText ? ` on ${limitText}` : ""}.`);
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(false);
}
}
if (failed) return <div className="text-secondary">{t("Couldn't load the integrations.")}</div>;
if (loaded === null) return <BlockSkeleton lines={3} />;
if (loaded.length === 0) {
return (
<div className="text-secondary">
There is no Semaphore connected. Add one under <Link to="/integrations">{t("Integrations")}</Link> to run playbooks from here.
</div>
);
}
return (
<div>
{loaded.some((l) => l.failed) && <div className="text-secondary small mb-2">Couldn't read the templates of {loaded.filter((l) => l.failed).map((l) => l.integration.name).join(", ")}.</div>}
{options.length === 0 ? (
<div className="text-secondary">{t("No templates found in Semaphore.")}</div>
) : (
<>
<div className="mb-3">
<label className="form-label" htmlFor="run-template">
Template
</label>
<select id="run-template" className="form-select" value={choice} onChange={(e) => setChoice(e.target.value)}>
<option value="">{t("Choose a template…")}</option>
{options.map((o) => (
<option key={o.key} value={o.key}>
{o.label}
</option>
))}
</select>
{picked?.template.lastTask && (
<div className="form-hint text-secondary small mt-1">
Last run here: {picked.template.lastTask.status}
{picked.template.lastTask.end ? (
<>
, <TimeAgo value={picked.template.lastTask.end} />
</>
) : null}
</div>
)}
</div>
<div className="mb-3">
<label className="form-check">
<input type="checkbox" className="form-check-input" checked={limitOn} onChange={(e) => setLimitOn(e.target.checked)} />
<span className="form-check-label">Run on {serverName} only</span>
</label>
{limitOn ? (
<div className="mt-2">
<label className="form-label small" htmlFor="run-limit">
Limit — the host name or pattern as it is in the Semaphore inventory
</label>
<input id="run-limit" className="form-control" value={limit} maxLength={200} onChange={(e) => setLimit(e.target.value)} placeholder="e.g. web01" />
</div>
) : (
<div className="text-danger small mt-1">Not limited: it runs on every host the playbook is set up for.</div>
)}
</div>
<button type="button" className="btn btn-primary" disabled={!picked || busy || (limitOn && limit.trim() === "")} onClick={() => void start()}>
{busy ? "Starting…" : "Run"}
</button>
</>
)}
{run && (
<div className="mt-3 border-top pt-3" role="status" aria-live="polite">
<div className="d-flex flex-wrap align-items-center gap-2">
<strong>{run.name}</strong>
{run.limit && <span className="text-secondary">on {run.limit}</span>}
<span className={`badge ${STATUS_WORDS[run.task.status]?.badge ?? "bg-secondary-lt text-secondary"}`}>{STATUS_WORDS[run.task.status]?.label ?? run.task.status}</span>
</div>
<div className="text-secondary small mt-1">
Run #{run.task.id} in Semaphore{FINISHED.has(run.task.status) ? "" : " — checking every few seconds"}. The output is in Semaphore.
</div>
</div>
)}
</div>
);
}