Hub 2.15.0: install page as a header and tabs, popups for every action

- Install page (/servers/installs/[id]): header with status, Schedule update and a ⋯ menu
  (move onto the monorepo, demo site, uninstall, remove from the Hub, remove the record);
  tiles for site/registration, version, server, ports and last heartbeat.
- Tabs: Jobs, Settings (.env), Exports; the tab in the URL (?tab=settings).
- Every action is a popup (Update, Adopt, Demo, Uninstall, Remove) using the 2.14.0 Modal:
  asks before discarding, error by its button. Confirmations unchanged.
- EnvPanel: read view in the tab, each file edited in a popup.
- Banners for not registered, stale (no heartbeat for a day) and a planned uninstall.
- Shared PageMessage (also on the customer page); ModalButtons gets danger/disabled.
- Logic split into components/install/ (useSubmit, post with LIVE_EVENT re-confirm,
  uninstallPlan). Frontend only: no migration, no API changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 11:46:46 +02:00
co-authored by Claude Opus 5.5
parent 6080190452
commit bce6a7c019
18 changed files with 889 additions and 455 deletions
+21
View File
@@ -5,6 +5,27 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.15.0] - 2026-11-23
Frontend only: no migration, no API changes.
### Changed
- **An install's page is a header and tabs**, like the customer page. The header shows the church,
product and status, with tiles for the site (and whether it has registered), version, server,
ports and last heartbeat. Below are **Jobs**, **Settings (.env)** and **Exports** (when there are
any); the tab is in the address (`?tab=settings`).
- **Every action is a popup.** Schedule update (the header's button, or the Version tile), move
onto the monorepo, mark as a demo site / load demo data, uninstall, remove from the Hub and
remove the record open over the page, the rare and destructive ones from the ⋯ menu. Each asks
before discarding what you've typed, and shows its error by its button. The confirmations
(type the short name, two-factor code, the final "are you sure") are unchanged.
- **Settings (.env) shows the values; Edit opens one file in a popup** to change, remove or add
variables, then save and restart (or rebuild).
- **Banners for what needs attention**: not registered yet, no heartbeat for a day (with Remove
from the Hub), and an uninstall already planned for this install (with a link to its job).
- One message under the header for the whole page, shared with the customer page.
## [2.14.0] - 2026-11-23
Frontend only: no migration, no API changes.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.14.0",
"version": "2.15.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.14.0",
"version": "2.15.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.14.0",
"version": "2.15.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.14.0",
"version": "2.15.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.14.0",
"version": "2.15.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.14.0",
"version": "2.15.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+3 -15
View File
@@ -3,11 +3,11 @@
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { KeyRound, X } from "lucide-react";
import { KeyRound } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { PRODUCTS, byProduct } from "@/lib/products";
import type { Customer } from "@/lib/types";
import { Loading, Message, Tabs } from "@/components/ui";
import { Loading, Message, PageMessage, Tabs } from "@/components/ui";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { OneOffInvoice } from "@/components/billing/OneOffInvoice";
import { CustomerHeader, type HeaderAction } from "@/components/customer/CustomerHeader";
@@ -70,13 +70,6 @@ export default function CustomerPage() {
window.history.replaceState(null, "", t === "overview" ? window.location.pathname : `?tab=${t}`);
};
// An "ok" message fades after a while; an error stays until it's closed or replaced.
useEffect(() => {
if (msg?.type !== "ok") return;
const t = setTimeout(() => setMsg(m => (m === msg ? null : m)), 12000);
return () => clearTimeout(t);
}, [msg]);
/** Every card and popup reports here: close the popup, show the message, reload. */
const done: Done = m => { setPopup(null); setMsg(m); load(); };
const close = () => setPopup(null);
@@ -101,12 +94,7 @@ export default function CustomerPage() {
<>
<CustomerHeader c={c} b={b} preview={preview} canAdd={available.length > 0} onAction={onAction} onArchive={setArchivedState} />
{msg && (
<div className="sticky top-2 z-30 mb-4 flex items-start gap-2 [&>div]:flex-1 [&>div]:shadow-sm" role="status">
<Message msg={msg} />
<button type="button" aria-label="Dismiss" onClick={() => setMsg(null)} className="mt-2.5 rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"><X className="h-4 w-4" /></button>
</div>
)}
<PageMessage msg={msg} onClose={() => setMsg(null)} />
<Tabs tabs={TABS} active={tab} onChange={openTab} />
@@ -3,37 +3,29 @@
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { api, ApiError, errorText } from "@/lib/api";
import { ago, bytes, fmtDate } from "@/lib/format";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { useServerPaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import type { Release } from "@/lib/types";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job, type ServerSummary } from "@/components/servers";
import { Loading, Message, PageMessage, Tabs } from "@/components/ui";
import { ServersNav, type Job } from "@/components/servers";
import { EnvPanel } from "@/components/EnvPanel";
import { InstallHeader, type InstallAction } from "@/components/install/InstallHeader";
import { ExportsCard, JobsCard } from "@/components/install/JobsCard";
import { UpdateModal } from "@/components/install/UpdateModal";
import { AdoptModal } from "@/components/install/AdoptModal";
import { DemoModal } from "@/components/install/DemoModal";
import { UninstallModal } from "@/components/install/UninstallModal";
import { RemoveModal } from "@/components/install/RemoveModal";
import { post, productName, running, uninstallPlan, withWarnings, type Detail, type Done, type Msg } from "@/components/install/shared";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = {
deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null }[]; install: { version: string | null; url: string; lastHeartbeatAt: string | null } | null };
fastPanel: string;
canRemoveRecord: boolean;
/** 2.12.0: no heartbeat for 24 hours, so it can be removed from the Hub. */
stale: { since: string | null; stale: boolean };
/** 2.12.0: what an uninstall removes: this product only (agent 1.5.0+), or the whole church. */
uninstall: {
onlyThisProduct: boolean; minAgent: string; others: { id: string; product: string; domain: string; status: string }[];
/** The church's uninstalls not run yet; `products` null: the whole church. `joinable`: this one can still be added to it. */
pending: { jobId: string; notBefore: string; products: string[] | null; joinable: boolean }[];
/** Every other product is being uninstalled: this one takes the whole church with it. */
lastProduct: boolean;
};
};
type Tab = "jobs" | "settings" | "exports";
type Popup = Exclude<InstallAction, "undemo"> | null;
const productName = (p: string) => PRODUCT_NAMES[p as keyof typeof PRODUCT_NAMES] || p;
const H = 60 * 60 * 1000;
/** One install on a server: proxy, updates, adopt, uninstall (§7–9). */
/**
* One install on a server (§7–9). Hub 2.15.0: a header with the status and tiles, then Jobs,
* Settings (.env) and Exports as tabs; every update, move, demo, uninstall and removal is a popup.
*/
export default function DeploymentPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
@@ -41,16 +33,11 @@ export default function DeploymentPage() {
const [d, setD] = useState<Detail | null>(null);
const [msg, setMsg] = useState<Msg>(warn ? { type: "err", text: warn } : null);
const [problems, setProblems] = useState<string[]>([]);
const [upd, setUpd] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, asap: true, reason: "", totp: "" });
const [adopt, setAdopt] = useState({ eventsDir: "", version: "", address: "", at: toInput(new Date(Date.now() + 5 * H)) });
const [un, setUn] = useState({ at: toInput(new Date(Date.now() + 7 * 24 * H)), totp: "", confirm: "" });
const [demo, setDemo] = useState({ profile: "events", confirm: "", markConfirm: "" });
const [forget, setForget] = useState("");
// 2.12.0: with another product's uninstall pending, join it (the default) or a time of its own.
const [joining, setJoining] = useState(true);
const [releases, setReleases] = useState<Release[]>([]);
// Hub 2.6.0: every job of this install, a page at a time (it showed the last 50).
const [tab, setTab] = useState<Tab>("jobs");
const [popup, setPopup] = useState<Popup>(null);
// Hub 2.6.0: every job of this install, a page at a time.
const jobsPaged = useServerPaged<Job>("/api/admin/jobs", { deploymentId: String(id) }, r => r.jobs as Job[], 20);
const load = useCallback(() => {
jobsPaged.reload();
@@ -60,256 +47,108 @@ export default function DeploymentPage() {
useEffect(() => { load(); }, [load]);
useEffect(() => { api<Release[]>("/api/admin/releases").then(setReleases).catch(() => {}); }, []);
// 2.7.1: every button here is off from a click until the Hub answers, so one click is one job.
// The tab is in the address (?tab=settings), so a reload or a shared link opens it.
useEffect(() => {
const q = new URLSearchParams(window.location.search).get("tab");
if (q === "settings" || q === "exports") setTab(q);
}, []);
const openTab = (t: Tab) => {
setTab(t);
const q = new URLSearchParams(window.location.search);
if (t === "jobs") q.delete("tab"); else q.set("tab", t);
const s = q.toString();
window.history.replaceState(null, "", s ? `?${s}` : window.location.pathname);
};
/** Every popup and card reports here: close the popup, show the message, reload. */
const done: Done = m => { setPopup(null); setMsg(m); load(); };
const close = () => setPopup(null);
// 2.7.1: the page's own buttons (proxy done, cancel a job, not a demo) are off from a click until the Hub answers.
const [busy, setBusy] = useState(false);
const withBusy = async (fn: () => Promise<void>) => {
const act = async (fn: () => Promise<Msg>) => {
if (busy) return;
setBusy(true);
try {
await fn();
} finally {
setBusy(false);
}
};
const act = async (path: string, body: Record<string, unknown>, ok: string): Promise<void> => {
if (busy && !body.confirmLive) return;
setBusy(true);
try {
await doAct(path, body, ok);
} finally {
setBusy(false);
}
};
const doAct = async (path: string, body: Record<string, unknown>, ok: string): Promise<void> => {
setMsg(null);
try {
const r = await api<{ warnings?: string[] }>(path, { method: "POST", body });
setMsg({ type: "ok", text: `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
load();
} catch (e) {
// Hub 2.7.0: an event is on there now: ask once more, then go ahead.
if (e instanceof ApiError && e.code === "LIVE_EVENT" && !body.confirmLive && window.confirm(e.message)) return doAct(path, { ...body, confirmLive: true }, ok);
setMsg({ type: "err", text: errorText(e) });
}
};
const proxyDone = () => withBusy(proxyDoneNow);
const proxyDoneNow = async () => {
setMsg(null);
try {
const r = await api<{ live: boolean; problems: string[] }>(`/api/admin/deployments/${id}/proxy-done`, { method: "POST" });
setProblems(r.problems);
setMsg(r.live ? { type: "ok", text: "Live. The site admin got the welcome email." } : { type: "err", text: "The site isn't answering as expected yet:" });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const removeRecord = () => withBusy(removeRecordNow);
const removeRecordNow = async () => {
if (!d || !window.confirm(`Remove the record of ${d.deployment.shortName}? Its install failed, so nothing of it is on the server.`)) return;
setMsg(null);
try {
await api(`/api/admin/deployments/${id}`, { method: "DELETE" });
router.push("/servers/installs");
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const removeFromHub = () => withBusy(removeFromHubNow);
const removeFromHubNow = async () => {
if (!d || !window.confirm(`Remove ${d.deployment.domain} from the Hub? Nothing runs on the server: use this only when the site is already gone from it.`)) return;
setMsg(null);
try {
await api(`/api/admin/deployments/${id}/forget`, { method: "POST", body: { confirm: forget } });
router.push("/servers/installs");
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
try { done(await fn()); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
if (!d) return <div><ServersNav active="/servers/installs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const x = d.deployment;
const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H;
const plan = d.uninstall;
const othersStaying = plan.others.filter(o => o.status !== "uninstalling");
// Accounts goes last: the church's other products sign in through it.
const accountsInUse = x.product === "accounts" && othersStaying.length > 0;
const wholeChurch = !plan.onlyThisProduct && plan.others.length > 0;
// 2.12.0: the church's uninstalls not run yet (by product), and the one this could join.
const pendingRuns = plan.pending.filter(p => p.products);
const joinable = pendingRuns.find(p => p.joinable) || null;
const lastNow = plan.onlyThisProduct && plan.lastProduct;
const plan = uninstallPlan(d);
const hasEnv = ["events", "accounts"].includes(x.product) && running(x);
const tabs: { key: Tab; label: string }[] = [
{ key: "jobs", label: "Jobs" },
...(hasEnv ? [{ key: "settings" as const, label: "Settings (.env)" }] : []),
...(x.exports.length ? [{ key: "exports" as const, label: `Exports (${x.exports.length})` }] : []),
];
const shown = tabs.some(t => t.key === tab) ? tab : "jobs";
const proxyDone = () => act(async () => {
const r = await api<{ live: boolean; problems: string[] }>(`/api/admin/deployments/${id}/proxy-done`, { method: "POST" });
setProblems(r.problems);
return r.live ? { type: "ok", text: "Live. The site admin got the welcome email." } : { type: "err", text: "The site isn't answering as expected yet:" };
});
const cancelJob = (j: Job) => act(async () => {
const r = await post(`/api/admin/jobs/${j.id}/cancel`);
return { type: "ok", text: withWarnings("Cancelled; the church was told.", r) };
});
const onAction = (a: InstallAction) => {
if (a === "undemo") {
if (!window.confirm(`${x.shortName} won't be a demo site any more: its data can't be replaced from the Hub then.`)) return;
act(async () => { await post(`/api/admin/deployments/${x.id}/demo`, { isDemo: false }); return { type: "ok", text: "No longer a demo site." }; });
} else setPopup(a);
};
return (
<div className="space-y-6">
<div>
<PageTitle title={`${x.customer?.name} (${x.shortName})`} subtitle={<>{x.domain} · on <Link className="text-indigo-700 hover:underline" href={`/servers/${x.serverId}`}>{x.server.name}</Link> · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} <StatusPill status={d.stale.stale ? "stale" : x.status} /></>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
{/* Hub 2.6.0: whether the site has registered with the Hub (its banners, licence and heartbeats need it). */}
<p className="mt-2 text-sm text-slate-600">
{x.install
? <>Registered site: <a className="text-indigo-700 hover:underline" href={x.install.url} target="_blank" rel="noreferrer">{x.install.url}</a>, last heartbeat {x.install.lastHeartbeatAt ? ago(x.install.lastHeartbeatAt) : "never"}.</>
: <span className="text-amber-800">The site hasn&apos;t registered with the Hub yet. It registers by itself with its licence key when it starts, and is tied to this record at its first heartbeat; if that doesn&apos;t happen, check its HUB_URL and HUB_LICENCE_KEY.</span>}
</p>
{!!problems.length && <ul className="mt-2 list-disc pl-6 text-sm text-red-800">{problems.map(p => <li key={p}>{p}</li>)}</ul>}
<>
<InstallHeader d={d} onAction={onAction} />
<ServersNav active="/servers/installs" />
<PageMessage msg={msg} onClose={() => { setMsg(null); setProblems([]); }} />
{!!problems.length && <ul className="-mt-2 mb-4 list-disc pl-6 text-sm text-red-800">{problems.map(p => <li key={p}>{p}</li>)}</ul>}
<div className="mb-6 space-y-3 empty:hidden">
{/* Hub 2.6.0: the site registers with the Hub itself; its banners, licence and heartbeats need it. */}
{!x.install && running(x) && (
<p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">The site hasn&apos;t registered with the Hub yet. It registers by itself with its licence key when it starts, and is tied to this record at its first heartbeat; if that doesn&apos;t happen, check its HUB_URL and HUB_LICENCE_KEY.</p>
)}
{/* Hub 2.12.0: gone from its server without the Hub (uninstalled by hand, server rebuilt …)? */}
{d.stale.stale && (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-900">
<span>No heartbeat since {d.stale.since ? fmtDate(d.stale.since) : "it was made"}. If the site is gone from {x.server.name}, remove it from the Hub; if it&apos;s still there, uninstall it.</span>
<button type="button" className="btn-secondary px-2.5 py-1.5" onClick={() => setPopup("forget")}>Remove from the Hub…</button>
</div>
)}
{plan.planned && (
<p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
Uninstall planned for {fmtDate(plan.planned.notBefore)}{plan.planned.products ? (plan.planned.products.length > 1 ? `, with ${plan.planned.products.filter(p => p !== x.product).map(productName).join(" and ")}` : "") : ": the whole church"}.{" "}
<Link className="underline" href={`/jobs/${plan.planned.jobId}`}>See the job</Link> to cancel it.
</p>
)}
{(x.status === "waiting_for_proxy" || x.status === "installing") && (
<section className="card space-y-3">
<h2 className="font-semibold">Set up the site in FastPanel</h2>
<pre className="overflow-x-auto whitespace-pre-wrap rounded-lg bg-slate-50 p-3 text-xs">{d.fastPanel}</pre>
<div className="flex flex-wrap items-center gap-3">
<button type="button" className="btn-primary" disabled={x.status !== "waiting_for_proxy" || busy} aria-busy={busy} onClick={proxyDone}>{busy ? "Checking…" : "Proxy done"}</button>
{x.status === "installing" && <p className="text-xs text-slate-500">Waiting for the install to finish (see its job under Jobs).</p>}
</div>
</section>
)}
</div>
{(x.status === "waiting_for_proxy" || x.status === "installing") && (
<div className="card">
<h2 className="font-medium">Set up the site in FastPanel</h2>
<pre className="mt-3 overflow-x-auto whitespace-pre-wrap rounded-lg bg-slate-50 p-3 text-xs">{d.fastPanel}</pre>
<button className="btn-primary mt-3" disabled={x.status !== "waiting_for_proxy" || busy} onClick={proxyDone}>Proxy done</button>
{x.status === "installing" && <p className="mt-2 text-xs text-slate-500">Waiting for the install to finish (see its job below).</p>}
</div>
)}
{x.status === "live" && (
<form className="card grid gap-3 md:grid-cols-2" onSubmit={e => { e.preventDefault(); const asap = upd.emergency && upd.asap; act("/api/admin/updates", { deploymentIds: [x.id], product: x.product, version: upd.version || undefined, at: asap ? undefined : fromInput(upd.at), asap, emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, asap ? "Started: the agent picks it up within a minute. The site admin was emailed and sees a banner." : "Planned. The site admin was emailed and sees a banner."); }}>
<h2 className="font-medium md:col-span-2">Schedule an update</h2>
<div>
<label className="label" htmlFor="u-v">{PRODUCT_NAMES[x.product as keyof typeof PRODUCT_NAMES] || x.product} release</label>
<select id="u-v" className="input" value={upd.version} onChange={e => setUpd({ ...upd, version: e.target.value })}>
<option value="">Latest</option>
{releases.filter(r => r.product === x.product).map(r => <option key={r.id} value={r.version}>{r.version}{r.latest ? " (latest)" : ""}{r.requires?.length ? ` · needs ${r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(", ")}` : ""}</option>)}
</select>
</div>
{upd.emergency && upd.asap
? <div><span className="label">When</span><p className="mt-2 text-sm">As soon as possible: the agent starts within a minute.</p></div>
: <div><label className="label" htmlFor="u-at">When</label><input id="u-at" type="datetime-local" className="input" value={upd.at} min={toInput(new Date(Date.now() + minAt))} onChange={e => setUpd({ ...upd, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.</p></div>}
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={upd.emergency} onChange={e => setUpd({ ...upd, emergency: e.target.checked })} /> Emergency (security fix or broken release): a reason and your two-factor code</label>
{upd.emergency && <>
<fieldset className="md:col-span-2 flex flex-wrap gap-4 text-sm">
<legend className="sr-only">When the emergency update runs</legend>
<label className="flex items-center gap-2"><input type="radio" name="u-when" checked={upd.asap} onChange={() => setUpd({ ...upd, asap: true })} /> As soon as possible (within a minute)</label>
<label className="flex items-center gap-2"><input type="radio" name="u-when" checked={!upd.asap} onChange={() => setUpd({ ...upd, asap: false })} /> At a time, at least 15 minutes away</label>
</fieldset>
<div><label className="label" htmlFor="u-r">Reason (shown to the church)</label><input id="u-r" className="input" required value={upd.reason} onChange={e => setUpd({ ...upd, reason: e.target.value })} /></div>
<div><label className="label" htmlFor="u-t">Two-factor code</label><input id="u-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={upd.totp} onChange={e => setUpd({ ...upd, totp: e.target.value })} /></div>
</>}
<div className="md:col-span-2"><button className="btn-primary" disabled={busy} aria-busy={busy}>{busy ? "Working…" : upd.emergency && upd.asap ? "Update now" : "Schedule"}</button></div>
</form>
)}
{x.status === "live" && x.install?.version?.startsWith("2.1.") && (
<form className="card grid gap-3 md:grid-cols-3" onSubmit={e => { e.preventDefault(); act(`/api/admin/deployments/${x.id}/adopt`, { eventsDir: adopt.eventsDir, version: adopt.version || undefined, address: adopt.address || undefined, at: fromInput(adopt.at) }, "Adopt planned. The site admin was emailed."); }}>
<h2 className="font-medium md:col-span-3">Move onto the monorepo (crosscode adopt)</h2>
<p className="text-sm text-slate-500 md:col-span-3">Moves the site from its old folder to /var/www/sites/{x.shortName}/events. Same database, uploads, .env and ports; the old folder is kept 14 days for <code>crosscode adopt {x.shortName} --undo</code>.</p>
<div><label className="label" htmlFor="a-d">The old install&apos;s folder</label><input id="a-d" className="input font-mono" required placeholder="/var/www/hope-events" value={adopt.eventsDir} onChange={e => setAdopt({ ...adopt, eventsDir: e.target.value })} /></div>
<div><label className="label" htmlFor="a-a">The church&apos;s address</label><input id="a-a" className="input" required={!x.domain.startsWith("events.")} placeholder={x.domain.startsWith("events.") ? x.domain.slice("events.".length) : "hope.co.za"} value={adopt.address} onChange={e => setAdopt({ ...adopt, address: e.target.value })} /></div>
<div><label className="label" htmlFor="a-v">Release</label><input id="a-v" className="input" placeholder="latest" value={adopt.version} onChange={e => setAdopt({ ...adopt, version: e.target.value })} /></div>
<div><label className="label" htmlFor="a-at">When</label><input id="a-at" type="datetime-local" className="input" value={adopt.at} onChange={e => setAdopt({ ...adopt, at: e.target.value })} /></div>
<div className="md:col-span-3"><button className="btn-primary" disabled={busy}>Plan the move</button></div>
</form>
)}
{/* Hub 2.8.0: the install's .env, and changing it with a restart. */}
{["events", "accounts"].includes(x.product) && ["live", "waiting_for_proxy"].includes(x.status) && <EnvPanel deploymentId={x.id} product={x.product} />}
{x.product === "events" && ["live", "waiting_for_proxy"].includes(x.status) && (
<div className="card space-y-3">
<h2 className="font-medium">Demo site</h2>
{!x.isDemo ? (
<form className="grid gap-3 md:grid-cols-[1fr_auto] md:items-end" onSubmit={e => { e.preventDefault(); act(`/api/admin/deployments/${x.id}/demo`, { isDemo: true, confirm: demo.markConfirm }, "Marked as a demo site."); }}>
<p className="text-sm text-slate-500 md:col-span-2">A demo site&apos;s data can be replaced with demo data from here. Only mark sites used for showing Cross Events, never a church&apos;s real site.</p>
<div><label className="label" htmlFor="d-m">Type {x.shortName}</label><input id="d-m" className="input" value={demo.markConfirm} onChange={e => setDemo({ ...demo, markConfirm: e.target.value })} /></div>
<button className="btn-secondary" disabled={demo.markConfirm !== x.shortName || busy}>Mark as a demo site</button>
</form>
) : (
<>
<form className="grid gap-3 md:grid-cols-3 md:items-end" onSubmit={e => { e.preventDefault(); if (window.confirm(`Replace ALL of ${x.shortName}'s data with the "${demo.profile}" demo? A backup is taken first; one admin account is kept.`)) act(`/api/admin/deployments/${x.id}/seed-demo`, { profile: demo.profile, confirm: demo.confirm }, "Queued: the agent loads the demo data on its next poll (see Jobs below). You get an email when it's done."); }}>
<p className="text-sm text-slate-500 md:col-span-3">Replaces everything (events, people, payments) with a demo set, keeping the site settings and {x.adminEmail || "the site's first admin"}. Demo logins use the password Demo@1234.</p>
<div><label className="label" htmlFor="d-p">Demo</label>
<select id="d-p" className="input" value={demo.profile} onChange={e => setDemo({ ...demo, profile: e.target.value })}>
<option value="small">Small church: the essentials</option>
<option value="events">Events and conferences</option>
<option value="ministry">Weekly ministry: courses, kids, volunteers</option>
<option value="multicampus">Three campuses</option>
</select>
</div>
<div><label className="label" htmlFor="d-c">Type {x.shortName}</label><input id="d-c" className="input" value={demo.confirm} onChange={e => setDemo({ ...demo, confirm: e.target.value })} /></div>
<button className="btn-danger" disabled={demo.confirm !== x.shortName || busy}>Load demo data</button>
</form>
<button type="button" className="text-sm text-slate-500 underline" onClick={() => act(`/api/admin/deployments/${x.id}/demo`, { isDemo: false }, "No longer a demo site.")}>It isn&apos;t a demo site any more</button>
</>
)}
</div>
)}
<div className="card overflow-x-auto p-0">
<h2 className="px-5 pt-5 font-medium">Jobs</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="px-5 py-1">Job</th><th>When</th><th>Status</th><th>Result</th><th /></tr></thead>
<tbody>{(jobsPaged.rows ?? x.jobs).map(j => (
<tr key={j.id} className="border-t">
<td className="px-5 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td>
<td className="pr-5">{["queued", "scheduled"].includes(j.status) && <button className="btn-secondary px-2 py-1 text-xs" disabled={busy} onClick={() => act(`/api/admin/jobs/${j.id}/cancel`, {}, "Cancelled; the church was told.")}>Cancel</button>}</td>
</tr>
))}</tbody>
</table>
<Pager page={jobsPaged.page} pages={jobsPaged.pages} setPage={jobsPaged.setPage} total={jobsPaged.total} pageSize={jobsPaged.pageSize} />
<Tabs tabs={tabs} active={shown} onChange={openTab} />
<div role="tabpanel" id={`panel-${shown}`} aria-labelledby={`tab-${shown}`}>
{shown === "jobs" && <JobsCard paged={jobsPaged} fallback={x.jobs} busy={busy} onCancel={cancelJob} />}
{shown === "settings" && <EnvPanel deploymentId={x.id} product={x.product} onMessage={setMsg} />}
{shown === "exports" && <ExportsCard exports={x.exports} />}
</div>
{!!x.exports.length && (
<div className="card text-sm">
<h2 className="font-medium">Exports</h2>
{x.exports.map(e => <p key={e.id} className="mt-2">{e.id}: {bytes(e.bytes)}, {e.deletedAt ? `deleted ${fmtDate(e.deletedAt)}` : `until ${fmtDate(e.expiresAt)}`}{e.downloadedAt ? `, downloaded ${fmtDate(e.downloadedAt)}` : ", not downloaded yet"}</p>)}
</div>
)}
{d.canRemoveRecord && (
<div className="card border-red-200">
<h2 className="font-medium text-red-800">Remove the record</h2>
<p className="mt-1 text-sm text-slate-500">This install failed and the server already removed what it made, so there&apos;s nothing to export or uninstall. Removing the record frees the short name.</p>
<button className="btn-danger mt-3" disabled={busy} onClick={removeRecord}>Remove the record</button>
</div>
)}
{/* Hub 2.12.0: gone from its server without the Hub (uninstalled by hand, server rebuilt …). */}
{d.stale.stale && (
<form className="card grid gap-3 border-red-200 md:grid-cols-[1fr_auto] md:items-end" onSubmit={e => { e.preventDefault(); removeFromHub(); }}>
<div className="md:col-span-2">
<h2 className="font-medium text-red-800">Remove from the Hub</h2>
<p className="mt-1 text-sm text-slate-500">No heartbeat since {d.stale.since ? `${fmtDate(d.stale.since)} (${ago(d.stale.since)})` : "it was made"}. If the site is no longer on {x.server.name} (uninstalled by hand, or the server was rebuilt), remove it here: nothing runs on the server, what was planned for it is cancelled, its ports are freed after 30 days and its licence&apos;s heartbeats are refused. If it&apos;s still there, uninstall it instead.</p>
</div>
<div><label className="label" htmlFor="f-c">Type {x.shortName}</label><input id="f-c" className="input" value={forget} onChange={e => setForget(e.target.value)} /></div>
<button className="btn-danger" disabled={forget !== x.shortName || busy}>Remove from the Hub</button>
</form>
)}
{["live", "waiting_for_proxy"].includes(x.status) && (
<form className="card grid gap-3 border-red-200 md:grid-cols-3" onSubmit={e => {
e.preventDefault();
const together = joining && joinable;
const when = together ? fmtDate(together.notBefore) : un.at.replace("T", " ");
if (!window.confirm(`Uninstall ${productName(x.product)} of ${x.shortName} on ${when}${together ? `, together with ${together.products!.map(productName).join(" and ")}` : ""}?${lastNow ? ` It's the church's last product here, so the whole church goes.` : ""} The church gets its data first.`)) return;
act(`/api/admin/deployments/${x.id}/uninstall`, { at: together ? undefined : fromInput(un.at), totp: un.totp, confirm: un.confirm, ...(pendingRuns.length ? { join: !!together, joinJobId: together ? together.jobId : undefined } : {}) },
together ? "Added to that uninstall: one export and one uninstall for both. The site admin was emailed and sees a banner." : "Uninstall planned: the site admin was emailed and sees a banner. The export runs first.");
}}>
<h2 className="font-medium text-red-800 md:col-span-3">Uninstall {productName(x.product)}</h2>
<p className="text-sm text-slate-500 md:col-span-3">At the time: {productName(x.product)}&apos;s data is exported (encrypted; the link goes to the site admin), then {x.domain}, its tunnels and database are removed. The final backup stays on the server for 30 days.{plan.onlyThisProduct && plan.others.length > 0 && !plan.lastProduct && <> The church keeps {plan.others.map(o => `${productName(o.product)} (${o.domain})`).join(" and ")}.</>}</p>
{/* Hub 2.12.0: another product of the church is already planned for uninstall. */}
{plan.onlyThisProduct && pendingRuns.length > 0 && (
<fieldset className="space-y-2 rounded-lg border border-slate-200 p-3 text-sm md:col-span-3">
<legend className="px-1 font-medium">{pendingRuns.map(p => `${p.products!.map(productName).join(" and ")} on ${fmtDate(p.notBefore)}`).join("; ")}: already planned for uninstall</legend>
<label className={`flex items-start gap-2 ${joinable ? "" : "text-slate-400"}`}>
<input type="radio" name="x-join" className="mt-1" checked={joining && !!joinable} disabled={!joinable} onChange={() => setJoining(true)} />
<span>Add {productName(x.product)} to that uninstall{joinable ? ` on ${fmtDate(joinable.notBefore)}` : ""}: one export and one uninstall for both{plan.lastProduct ? ", which removes the whole church" : ""}.{!joinable && " (Not possible: it has already started.)"}{joinable && new Date(joinable.notBefore).getTime() - Date.now() < 4 * H && " (Under 4 hours away: the church wouldn't get notice in time, so the Hub will refuse.)"}</span>
</label>
<label className="flex items-start gap-2">
<input type="radio" name="x-join" className="mt-1" checked={!joining || !joinable} onChange={() => setJoining(false)} />
<span>At its own time (below).{plan.lastProduct && " It's then the church's last product here, so it removes the whole church (its folder and app user) when it runs."}</span>
</label>
</fieldset>
)}
{plan.onlyThisProduct && plan.lastProduct && !pendingRuns.length && <p className="text-sm text-slate-600 md:col-span-3">This is the church&apos;s last product here: the uninstall removes the whole church (its folder and app user).</p>}
{wholeChurch && <p className="text-sm font-medium text-red-800 md:col-span-3">The agent on {x.server.name} is {x.server.agentVersion || "an unknown version"}: it can only remove the whole church, with {plan.others.map(o => productName(o.product)).join(" and ")}. Update the agent to {plan.minAgent} or later first.</p>}
{accountsInUse && <p className="text-sm font-medium text-amber-800 md:col-span-3">{othersStaying.map(o => productName(o.product)).join(" and ")} signs in through Accounts: uninstall {othersStaying.length === 1 ? "it" : "them"} first, then Accounts (at the same time or later).</p>}
{joining && joinable
? <div><span className="label">When</span><p className="mt-2 text-sm">{fmtDate(joinable.notBefore)}, with {joinable.products!.map(productName).join(" and ")}</p></div>
: <div><label className="label" htmlFor="x-at">When</label><input id="x-at" type="datetime-local" className="input" value={un.at} onChange={e => setUn({ ...un, at: e.target.value })} /></div>}
<div><label className="label" htmlFor="x-c">Type {x.shortName}</label><input id="x-c" className="input" required value={un.confirm} onChange={e => setUn({ ...un, confirm: e.target.value })} /></div>
<div><label className="label" htmlFor="x-t">Two-factor code</label><input id="x-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={un.totp} onChange={e => setUn({ ...un, totp: e.target.value })} /></div>
<div className="md:col-span-3"><button className="btn-danger" disabled={un.confirm !== x.shortName || busy || wholeChurch || accountsInUse}>Plan the uninstall</button></div>
</form>
)}
</div>
{popup === "update" && <UpdateModal x={x} releases={releases} onClose={close} onDone={done} />}
{popup === "adopt" && <AdoptModal x={x} onClose={close} onDone={done} />}
{popup === "demo" && <DemoModal x={x} onClose={close} onDone={done} />}
{popup === "uninstall" && <UninstallModal x={x} plan={plan} onClose={close} onDone={done} />}
{(popup === "record" || popup === "forget") && <RemoveModal kind={popup} x={x} stale={d.stale} onClose={close} onRemoved={() => router.push("/servers/installs")} />}
</>
);
}
+192 -158
View File
@@ -2,14 +2,16 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Pencil } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { Message } from "@/components/ui";
import { FormError, Message, Modal } from "@/components/ui";
/**
* An install's .env (Hub 2.8.0, agent 1.3.0): what's in it (secrets only as set or not), changing
* plain values, then a restart (or a rebuild for the frontend's file). The server keeps a copy of
* the file and puts it back when the site doesn't start again with the new values.
* Hub 2.15.0: the page shows the values; each file's changes are made in a popup.
*/
type Variable = { name: string; value: string | null; secret: boolean; set: boolean; layer: string | null; description: string | null; editable: boolean };
@@ -37,18 +39,30 @@ const FILE_NOTE: Record<string, string> = {
"frontend/.env.production": "Next.js builds these values in: saving rebuilds the frontend (a few minutes), then restarts it.",
};
export function EnvPanel({ deploymentId, product }: { deploymentId: string; product: string }) {
const [state, setState] = useState<EnvState | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
// Edits per file: changed values, names to remove, and new variables.
const [edits, setEdits] = useState<Record<string, Record<string, string>>>({});
const [removed, setRemoved] = useState<Record<string, string[]>>({});
const [added, setAdded] = useState<Record<string, { name: string; value: string }>>({});
const [restart, setRestart] = useState(true);
const [showAll, setShowAll] = useState(false);
/** A variable's value as text: secrets only as set or not. */
function ValueText({ v }: { v: Variable }) {
if (v.secret) return <span className="text-xs text-slate-500">{v.set ? "•••••••• (secret, set)" : "secret, not set"}</span>;
if (!v.set) return <span className="text-xs text-amber-700">not set</span>;
return <span className="break-all font-mono text-xs">{v.value}{!v.editable && <span className="ml-2 font-sans text-[11px] text-slate-400">made by the server</span>}</span>;
}
const load = useCallback(() => api<EnvState>(`/api/admin/deployments/${deploymentId}/env`).then(setState).catch(e => setMsg({ type: "err", text: errorText(e) })), [deploymentId]);
function VarName({ v }: { v: Variable }) {
return (
<>
<div className="font-mono text-xs">{v.name}</div>
{(v.description || v.layer) && <div className="text-[11px] text-slate-400">{[v.layer, v.description].filter(Boolean).join(" · ")}</div>}
</>
);
}
export function EnvPanel({ deploymentId, product, onMessage }: { deploymentId: string; product: string; onMessage: (m: Msg) => void }) {
const [state, setState] = useState<EnvState | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [showAll, setShowAll] = useState(false);
const [editing, setEditing] = useState<string | null>(null);
const load = useCallback(() => api<EnvState>(`/api/admin/deployments/${deploymentId}/env`).then(s => { setState(s); setLoadError(null); }).catch(e => setLoadError(errorText(e))), [deploymentId]);
useEffect(() => { load(); }, [load]);
// While the agent has a job of ours, look again every few seconds.
const waiting = !!state?.pending.length;
@@ -58,46 +72,16 @@ export function EnvPanel({ deploymentId, product }: { deploymentId: string; prod
return () => clearInterval(t);
}, [waiting, load]);
const run = async (fn: () => Promise<void>) => {
const read = async () => {
if (busy) return;
setBusy(true);
setMsg(null);
try { await fn(); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
try {
await api(`/api/admin/deployments/${deploymentId}/env/read`, { method: "POST" });
onMessage({ type: "ok", text: "Asked the agent: the values show here within a minute." });
await load();
} catch (e) { onMessage({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const read = () => run(async () => {
await api(`/api/admin/deployments/${deploymentId}/env/read`, { method: "POST" });
setMsg({ type: "ok", text: "Asked the agent: the values show here within a minute." });
await load();
});
const changesFor = (file: string) => {
const set: Record<string, string> = { ...(edits[file] || {}) };
const a = added[file];
if (a?.name.trim()) set[a.name.trim()] = a.value;
return { set, unset: removed[file] || [] };
};
const save = (file: string) => run(async () => {
const { set, unset } = changesFor(file);
const names = [...Object.keys(set), ...unset];
if (!names.length) return;
const bad = names.find(n => !NAME.test(n));
if (bad) throw new Error(`${bad} isn't a variable name (A-Z, 0-9 and _, starting with a letter).`);
const secret = names.find(n => SECRET.test(n));
if (secret) throw new Error(`${secret} looks like a secret: change it on the server, not from the Hub.`);
const rebuild = file.startsWith("frontend/");
const lines = [...Object.entries(set).map(([k, v]) => ` ${k}=${v}`), ...unset.map(n => ` remove ${n}`)].join("\n");
const then = rebuild ? "The frontend is then rebuilt and restarted (the site is slow or unavailable for a few minutes)." : restart ? "The backend is then restarted (a few seconds)." : "Nothing is restarted: the new values apply at the next restart.";
if (!window.confirm(`Change ${file} on the server?\n\n${lines}\n\n${then} If it doesn't start again, the file is put back as it was.`)) return;
await api(`/api/admin/deployments/${deploymentId}/env`, { method: "POST", body: { file, set, unset, restart: rebuild || restart } });
setEdits(e => ({ ...e, [file]: {} }));
setRemoved(r => ({ ...r, [file]: [] }));
setAdded(a => ({ ...a, [file]: { name: "", value: "" } }));
setMsg({ type: "ok", text: "Queued: the agent changes the file at its next poll. This panel updates when it's done." });
await load();
});
const addresses = useMemo(() => {
const names = ADDRESSES[product] || [];
const out: { file: string; v: Variable }[] = [];
@@ -105,133 +89,183 @@ export function EnvPanel({ deploymentId, product }: { deploymentId: string; prod
return out;
}, [state, product]);
if (!state) return <div className="card"><h2 className="font-medium">Settings (.env)</h2>{msg ? <div className="mt-2"><Message msg={msg} /></div> : <p className="mt-2 text-sm text-slate-400">Loading…</p>}</div>;
if (!state.supported) return null;
if (!state) return <div className="card">{loadError ? <Message msg={{ type: "err", text: loadError }} /> : <p className="text-sm text-slate-400">Loading…</p>}</div>;
if (!state.supported) return <div className="card text-sm text-slate-500">The agent on this server can&apos;t read the .env files yet: it needs agent {state.minAgent} or later.</div>;
const pendingRead = state.pending.find(p => p.type === "env-read");
const pendingSet = state.pending.find(p => p.type === "env-set");
const editFile = state.env?.files.find(f => f.file === editing) || null;
return (
<div className="card space-y-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-medium">Settings (.env)</h2>
<p className="mt-1 text-sm text-slate-500">
The values in this install&apos;s .env files on the server. Secrets (passwords, keys, the database) are never sent to the Hub: only whether they&apos;re set.
Needs agent {state.minAgent} or later.
</p>
<div className="space-y-4">
<section className="card space-y-3">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-semibold">Settings (.env)</h2>
<p className="mt-1 text-sm text-slate-500">
The values in this install&apos;s .env files on the server. Secrets (passwords, keys, the database) are never sent to the Hub: only whether they&apos;re set.
</p>
</div>
<button type="button" className="btn-secondary" disabled={busy || !!pendingRead} onClick={read}>{pendingRead ? "Reading…" : state.env ? "Read again" : "Read from the server"}</button>
</div>
<button className="btn-secondary" disabled={busy || !!pendingRead} onClick={read}>{pendingRead ? "Reading…" : state.env ? "Read again" : "Read from the server"}</button>
</div>
<Message msg={msg} />
{pendingSet && <p className="rounded-lg border border-indigo-200 bg-indigo-50 p-3 text-sm text-indigo-900">A change is {pendingSet.status === "delivered" ? "being made on the server now" : "waiting for the agent"} (<Link className="underline" href={`/jobs/${pendingSet.id}`}>job</Link>).</p>}
{state.lastSet && !pendingSet && state.lastSet.status !== "succeeded" && (
<p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
The last change ({fmtDate(state.lastSet.finishedAt)}) {state.lastSet.status === "rolled_back" ? "was put back: the site didn't start with it" : `didn't go through (${state.lastSet.status.replace(/_/g, " ")})`}.
{state.lastSet.message ? ` ${state.lastSet.message}` : ""} <Link className="underline" href={`/jobs/${state.lastSet.id}`}>See the job</Link>.
</p>
)}
{loadError && <Message msg={{ type: "err", text: loadError }} />}
{pendingSet && <p className="rounded-lg border border-indigo-200 bg-indigo-50 p-3 text-sm text-indigo-900">A change is {pendingSet.status === "delivered" ? "being made on the server now" : "waiting for the agent"} (<Link className="underline" href={`/jobs/${pendingSet.id}`}>job</Link>).</p>}
{state.lastSet && !pendingSet && state.lastSet.status !== "succeeded" && (
<p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
The last change ({fmtDate(state.lastSet.finishedAt)}) {state.lastSet.status === "rolled_back" ? "was put back: the site didn't start with it" : `didn't go through (${state.lastSet.status.replace(/_/g, " ")})`}.
{state.lastSet.message ? ` ${state.lastSet.message}` : ""} <Link className="underline" href={`/jobs/${state.lastSet.id}`}>See the job</Link>.
</p>
)}
{!state.env && !pendingRead && <p className="text-sm text-slate-500">Not read yet. &ldquo;Read from the server&rdquo; asks the agent for them.</p>}
{state.env && <p className="text-xs text-slate-500">Read {ago(state.env.readAt)} ({fmtDate(state.env.readAt)}){state.readJobId && <> · <Link className="underline" href={`/jobs/${state.readJobId}`}>job</Link></>}.</p>}
{!state.env && !pendingRead && <p className="text-sm text-slate-500">Not read yet. &ldquo;Read from the server&rdquo; asks the agent for them.</p>}
{!!addresses.length && (
<div className="rounded-lg border border-slate-200 bg-slate-50 p-3">
<h3 className="text-sm font-medium">Addresses</h3>
<dl className="mt-2 grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[max-content_1fr]">
{addresses.map(({ file, v }) => (
<React.Fragment key={`${file}:${v.name}`}>
<dt className="font-mono text-xs text-slate-600">{v.name}<span className="ml-1 text-slate-400">({file.split("/")[0]})</span></dt>
<dd className="break-all font-mono text-xs">{v.set ? v.value : <span className="text-amber-700">not set</span>}</dd>
</React.Fragment>
))}
</dl>
<p className="mt-2 text-xs text-slate-500">Change them in the files below. The site&apos;s address on the Hub ({product}) and in FastPanel doesn&apos;t change with them.</p>
</div>
)}
{state.env && (
<>
<p className="text-xs text-slate-500">Read {ago(state.env.readAt)} ({fmtDate(state.env.readAt)}){state.readJobId && <> · <Link className="underline" href={`/jobs/${state.readJobId}`}>job</Link></>}.</p>
{state.env && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={showAll} onChange={e => setShowAll(e.target.checked)} /> Also show variables the file doesn&apos;t have yet (from the release&apos;s template)</label>}
</section>
{!!addresses.length && (
<div className="rounded-lg border border-slate-200 bg-slate-50 p-3">
<h3 className="text-sm font-medium">Addresses</h3>
<dl className="mt-2 grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[max-content_1fr]">
{addresses.map(({ file, v }) => (
<React.Fragment key={`${file}:${v.name}`}>
<dt className="font-mono text-xs text-slate-600">{v.name}<span className="ml-1 text-slate-400">({file.split("/")[0]})</span></dt>
<dd className="break-all font-mono text-xs">{v.set ? v.value : <span className="text-amber-700">not set</span>}</dd>
</React.Fragment>
))}
</dl>
<p className="mt-2 text-xs text-slate-500">Change them in the files below. The site&apos;s address on the Hub ({product}) and in FastPanel doesn&apos;t change with them.</p>
{state.env?.files.map(f => {
const rows = f.variables.filter(v => showAll || v.set);
return (
<section key={f.file} className="card space-y-3">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<h3 className="font-mono text-sm font-medium">{f.file}{!f.exists && <span className="ml-2 font-sans text-xs text-amber-700">missing on the server</span>}</h3>
<p className="mt-0.5 text-xs text-slate-500">{FILE_NOTE[f.file]}</p>
</div>
<button type="button" className="btn-secondary px-2.5 py-1.5" disabled={!!pendingSet} title={pendingSet ? "A change is already waiting for the agent" : undefined} onClick={() => setEditing(f.file)}><Pencil className="h-3.5 w-3.5" /> Edit</button>
</div>
)}
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={showAll} onChange={e => setShowAll(e.target.checked)} /> Also show variables the file doesn&apos;t have yet (from the release&apos;s template)</label>
{state.env.files.map(f => {
const fileEdits = edits[f.file] || {};
const fileRemoved = removed[f.file] || [];
const a = added[f.file] || { name: "", value: "" };
const { set, unset } = changesFor(f.file);
const count = Object.keys(set).length + unset.length;
const rebuild = f.file.startsWith("frontend/");
const rows = f.variables.filter(v => showAll || v.set || v.name in fileEdits);
return (
<form key={f.file} className="space-y-2" onSubmit={e => { e.preventDefault(); save(f.file); }}>
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h3 className="font-mono text-sm font-medium">{f.file}{!f.exists && <span className="ml-2 font-sans text-xs text-amber-700">missing on the server</span>}</h3>
<span className="text-xs text-slate-500">{FILE_NOTE[f.file]}</span>
</div>
{rows.length === 0
? <p className="text-sm text-slate-500">No variables set.</p>
: (
<div className="overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead><tr className="bg-slate-50 text-left text-xs text-slate-500"><th className="px-3 py-1.5">Name</th><th className="px-3 py-1.5">Value</th><th className="px-3 py-1.5"><span className="sr-only">Remove</span></th></tr></thead>
<tbody>
{rows.map(v => {
const isRemoved = fileRemoved.includes(v.name);
const value = v.name in fileEdits ? fileEdits[v.name] : (v.value ?? "");
const changed = v.name in fileEdits && fileEdits[v.name] !== (v.value ?? "");
return (
<tr key={v.name} className={`border-t align-top ${isRemoved ? "opacity-50" : ""}`}>
<td className="px-3 py-1.5">
<div className="font-mono text-xs">{v.name}</div>
{(v.description || v.layer) && <div className="text-[11px] text-slate-400">{[v.layer, v.description].filter(Boolean).join(" · ")}</div>}
</td>
<td className="w-full px-3 py-1.5">
{v.secret ? (
<span className="text-xs text-slate-500">{v.set ? "•••••••• (secret, set)" : "secret, not set"}</span>
) : v.editable ? (
<input className={`input py-1 font-mono text-xs ${changed ? "border-indigo-400 bg-indigo-50" : ""}`} aria-label={v.name} value={value} disabled={isRemoved || !!pendingSet}
placeholder={v.set ? "" : "not set"}
onChange={e => {
const next = e.target.value;
setEdits(x => {
const fe = { ...(x[f.file] || {}) };
if (next === (v.value ?? "")) delete fe[v.name]; else fe[v.name] = next;
return { ...x, [f.file]: fe };
});
}} />
) : (
<span className="font-mono text-xs text-slate-600">{v.value}<span className="ml-2 font-sans text-[11px] text-slate-400">made by the server</span></span>
)}
</td>
<td className="px-3 py-1.5 text-right">
{v.editable && v.set && (
<button type="button" className="text-xs text-slate-500 underline" disabled={!!pendingSet} onClick={() => setRemoved(r => {
const list = r[f.file] || [];
return { ...r, [f.file]: isRemoved ? list.filter(n => n !== v.name) : [...list, v.name] };
})}>{isRemoved ? "keep" : "remove"}</button>
)}
</td>
</tr>
);
})}
<tr className="border-t bg-slate-50/50">
<td className="px-3 py-1.5"><input className="input py-1 font-mono text-xs" aria-label={`New variable name in ${f.file}`} placeholder="NEW_NAME" value={a.name} disabled={!!pendingSet}
onChange={e => setAdded(x => ({ ...x, [f.file]: { ...a, name: e.target.value.toUpperCase() } }))} /></td>
<td className="px-3 py-1.5" colSpan={2}><input className="input py-1 font-mono text-xs" aria-label={`New variable value in ${f.file}`} placeholder="value" value={a.value} disabled={!!pendingSet}
onChange={e => setAdded(x => ({ ...x, [f.file]: { ...a, value: e.target.value } }))} /></td>
<thead><tr className="bg-slate-50 text-left text-xs text-slate-500"><th className="px-3 py-1.5">Name</th><th className="px-3 py-1.5">Value</th></tr></thead>
<tbody>{rows.map(v => (
<tr key={v.name} className="border-t align-top">
<td className="px-3 py-1.5"><VarName v={v} /></td>
<td className="w-full px-3 py-1.5"><ValueText v={v} /></td>
</tr>
</tbody>
))}</tbody>
</table>
</div>
<div className="flex flex-wrap items-center gap-3">
<button className="btn-primary" disabled={busy || !count || !!pendingSet}>{rebuild ? "Save, rebuild and restart" : restart ? "Save and restart" : "Save"}{count ? ` (${count})` : ""}</button>
{!rebuild && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={restart} onChange={e => setRestart(e.target.checked)} /> Restart the backend to apply it</label>}
{!!count && <button type="button" className="text-sm text-slate-500 underline" onClick={() => { setEdits(x => ({ ...x, [f.file]: {} })); setRemoved(x => ({ ...x, [f.file]: [] })); setAdded(x => ({ ...x, [f.file]: { name: "", value: "" } })); }}>Undo my changes</button>}
</div>
</form>
);
})}
</>
)}
</section>
);
})}
{editFile && (
<EnvFileModal deploymentId={deploymentId} f={editFile} onClose={() => setEditing(null)}
onSaved={() => { setEditing(null); onMessage({ type: "ok", text: "Queued: the agent changes the file at its next poll. The Settings tab updates when it's done." }); load(); }} />
)}
</div>
);
}
/** Change one .env file: edit values, remove some, add one; then restart (or rebuild) to apply it. */
function EnvFileModal({ deploymentId, f, onClose, onSaved }: { deploymentId: string; f: EnvFile; onClose: () => void; onSaved: () => void }) {
const [edits, setEdits] = useState<Record<string, string>>({});
const [removed, setRemoved] = useState<string[]>([]);
const [added, setAdded] = useState({ name: "", value: "" });
const [restart, setRestart] = useState(true);
const [showAll, setShowAll] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const set: Record<string, string> = { ...edits };
if (added.name.trim()) set[added.name.trim()] = added.value;
const unset = removed;
const count = Object.keys(set).length + unset.length;
const rebuild = f.file.startsWith("frontend/");
const rows = f.variables.filter(v => showAll || v.set || v.name in edits);
const save = async (e: React.FormEvent) => {
e.preventDefault();
if (busy || !count) return;
setError(null);
const names = [...Object.keys(set), ...unset];
const bad = names.find(n => !NAME.test(n));
if (bad) return setError(`${bad} isn't a variable name (A-Z, 0-9 and _, starting with a letter).`);
const secret = names.find(n => SECRET.test(n));
if (secret) return setError(`${secret} looks like a secret: change it on the server, not from the Hub.`);
const lines = [...Object.entries(set).map(([k, v]) => ` ${k}=${v}`), ...unset.map(n => ` remove ${n}`)].join("\n");
const then = rebuild ? "The frontend is then rebuilt and restarted (the site is slow or unavailable for a few minutes)." : restart ? "The backend is then restarted (a few seconds)." : "Nothing is restarted: the new values apply at the next restart.";
if (!window.confirm(`Change ${f.file} on the server?\n\n${lines}\n\n${then} If it doesn't start again, the file is put back as it was.`)) return;
setBusy(true);
try {
await api(`/api/admin/deployments/${deploymentId}/env`, { method: "POST", body: { file: f.file, set, unset, restart: rebuild || restart } });
onSaved();
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
};
return (
<Modal title={<span className="font-mono">{f.file}</span>} onClose={onClose} wide dirty={count > 0}>
<form onSubmit={save} className="space-y-3">
<p className="text-xs text-slate-500">{FILE_NOTE[f.file]}</p>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={showAll} onChange={e => setShowAll(e.target.checked)} /> Also show variables the file doesn&apos;t have yet</label>
<div className="overflow-x-auto rounded-lg border">
<table className="w-full text-sm">
<thead><tr className="bg-slate-50 text-left text-xs text-slate-500"><th className="px-3 py-1.5">Name</th><th className="px-3 py-1.5">Value</th><th className="px-3 py-1.5"><span className="sr-only">Remove</span></th></tr></thead>
<tbody>
{rows.map(v => {
const isRemoved = removed.includes(v.name);
const value = v.name in edits ? edits[v.name] : (v.value ?? "");
const isChanged = v.name in edits && edits[v.name] !== (v.value ?? "");
return (
<tr key={v.name} className={`border-t align-top ${isRemoved ? "opacity-50" : ""}`}>
<td className="px-3 py-1.5"><VarName v={v} /></td>
<td className="w-full px-3 py-1.5">
{v.editable && !v.secret ? (
<input className={`input py-1 font-mono text-xs ${isChanged ? "border-indigo-400 bg-indigo-50" : ""}`} aria-label={v.name} value={value} disabled={isRemoved}
placeholder={v.set ? "" : "not set"}
onChange={e => {
const next = e.target.value;
setEdits(x => {
const fe = { ...x };
if (next === (v.value ?? "")) delete fe[v.name]; else fe[v.name] = next;
return fe;
});
}} />
) : <ValueText v={v} />}
</td>
<td className="px-3 py-1.5 text-right">
{v.editable && v.set && (
<button type="button" className="text-xs text-slate-500 underline" onClick={() => setRemoved(r => (isRemoved ? r.filter(n => n !== v.name) : [...r, v.name]))}>{isRemoved ? "keep" : "remove"}</button>
)}
</td>
</tr>
);
})}
<tr className="border-t bg-slate-50/50">
<td className="px-3 py-1.5"><input className="input py-1 font-mono text-xs" aria-label={`New variable name in ${f.file}`} placeholder="NEW_NAME" value={added.name}
onChange={e => setAdded({ ...added, name: e.target.value.toUpperCase() })} /></td>
<td className="px-3 py-1.5" colSpan={2}><input className="input py-1 font-mono text-xs" aria-label={`New variable value in ${f.file}`} placeholder="value" value={added.value}
onChange={e => setAdded({ ...added, value: e.target.value })} /></td>
</tr>
</tbody>
</table>
</div>
{!rebuild && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={restart} onChange={e => setRestart(e.target.checked)} /> Restart the backend to apply it</label>}
<FormError error={error} />
<div className="flex flex-wrap gap-2 pt-1">
<button className="btn-primary" disabled={busy || !count} aria-busy={busy}>{busy ? "Saving…" : rebuild ? "Save, rebuild and restart" : restart ? "Save and restart" : "Save"}{count ? ` (${count})` : ""}</button>
<button type="button" className="btn-secondary" onClick={onClose}>Cancel</button>
</div>
</form>
</Modal>
);
}
@@ -34,11 +34,13 @@ export function Fields({ children }: { children: React.ReactNode }) {
return <dl className="grid gap-3 sm:grid-cols-2">{children}</dl>;
}
/** Save and Cancel at the foot of a popup form. */
export function ModalButtons({ busy, onCancel, label = "Save" }: { busy: boolean; onCancel: () => void; label?: string }) {
/** Save and Cancel at the foot of a popup form. `danger` for what can't be undone (Hub 2.15.0). */
export function ModalButtons({ busy, onCancel, label = "Save", busyLabel = "Saving…", danger, disabled }: {
busy: boolean; onCancel: () => void; label?: string; busyLabel?: string; danger?: boolean; disabled?: boolean;
}) {
return (
<div className="flex flex-wrap gap-2 pt-1">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : label}</button>
<button className={danger ? "btn-danger" : "btn-primary"} disabled={busy || disabled} aria-busy={busy}>{busy ? busyLabel : label}</button>
<button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>
</div>
);
@@ -0,0 +1,39 @@
"use client";
import React, { useState } from "react";
import { FormError, Modal } from "@/components/ui";
import { fromInput, toInput } from "@/components/servers";
import { ModalButtons } from "@/components/customer/ReadCard";
import { H, changed, post, useSubmit, withWarnings, type Done, type Install } from "./shared";
/** Move an old (2.1.x) Events install onto the monorepo: `crosscode adopt` at a planned time. */
export function AdoptModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) {
const [form0] = useState(() => ({ eventsDir: "", version: "", address: "", at: toInput(new Date(Date.now() + 5 * H)) }));
const [adopt, setAdopt] = useState(form0);
const { busy, error, run } = useSubmit();
const eventsSub = x.domain.startsWith("events.");
const save = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await post(`/api/admin/deployments/${x.id}/adopt`, { eventsDir: adopt.eventsDir, version: adopt.version || undefined, address: adopt.address || undefined, at: fromInput(adopt.at) });
onDone({ type: "ok", text: withWarnings("Adopt planned. The site admin was emailed.", r) });
});
};
return (
<Modal title="Move onto the monorepo" onClose={onClose} dirty={changed(adopt, form0)}>
<form onSubmit={save} className="space-y-4">
<p className="text-sm text-slate-500">Moves the site from its old folder to /var/www/sites/{x.shortName}/events. Same database, uploads, .env and ports; the old folder is kept 14 days for <code>crosscode adopt {x.shortName} --undo</code>.</p>
<div className="grid gap-3 sm:grid-cols-2">
<div className="sm:col-span-2"><label className="label" htmlFor="a-d">The old install&apos;s folder</label><input id="a-d" className="input font-mono" required placeholder="/var/www/hope-events" value={adopt.eventsDir} onChange={e => setAdopt({ ...adopt, eventsDir: e.target.value })} /></div>
<div><label className="label" htmlFor="a-a">The church&apos;s address</label><input id="a-a" className="input" required={!eventsSub} placeholder={eventsSub ? x.domain.slice("events.".length) : "hope.co.za"} value={adopt.address} onChange={e => setAdopt({ ...adopt, address: e.target.value })} /></div>
<div><label className="label" htmlFor="a-v">Release</label><input id="a-v" className="input" placeholder="latest" value={adopt.version} onChange={e => setAdopt({ ...adopt, version: e.target.value })} /></div>
<div><label className="label" htmlFor="a-at">When</label><input id="a-at" type="datetime-local" className="input" value={adopt.at} onChange={e => setAdopt({ ...adopt, at: e.target.value })} /></div>
</div>
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Plan the move" />
</form>
</Modal>
);
}
@@ -0,0 +1,74 @@
"use client";
import React, { useState } from "react";
import { FormError, Modal } from "@/components/ui";
import { ModalButtons } from "@/components/customer/ReadCard";
import { post, useSubmit, withWarnings, type Done, type Install } from "./shared";
const PROFILES = [
{ key: "small", label: "Small church: the essentials" },
{ key: "events", label: "Events and conferences" },
{ key: "ministry", label: "Weekly ministry: courses, kids, volunteers" },
{ key: "multicampus", label: "Three campuses" },
];
/**
* An Events site used for showing Cross Events: mark it as a demo site, or (once it is one) replace
* its data with a demo set. Unmarking is a menu item on the page.
*/
export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) {
const [profile, setProfile] = useState("events");
const [confirmName, setConfirmName] = useState("");
const { busy, error, run } = useSubmit();
const typed = confirmName === x.shortName;
const mark = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await post(`/api/admin/deployments/${x.id}/demo`, { isDemo: true, confirm: confirmName });
onDone({ type: "ok", text: withWarnings("Marked as a demo site.", r) });
});
};
const seed = (e: React.FormEvent) => {
e.preventDefault();
if (!window.confirm(`Replace ALL of ${x.shortName}'s data with the "${profile}" demo? A backup is taken first; one admin account is kept.`)) return;
run(async () => {
const r = await post(`/api/admin/deployments/${x.id}/seed-demo`, { profile, confirm: confirmName });
onDone({ type: "ok", text: withWarnings("Queued: the agent loads the demo data on its next poll (see Jobs). You get an email when it's done.", r) });
});
};
const confirmField = (
<div><label className="label" htmlFor="d-c">Type {x.shortName}</label><input id="d-c" className="input" autoComplete="off" value={confirmName} onChange={e => setConfirmName(e.target.value)} /></div>
);
if (!x.isDemo) return (
<Modal title="Mark as a demo site" onClose={onClose} dirty={!!confirmName}>
<form onSubmit={mark} className="space-y-4">
<p className="text-sm text-slate-500">A demo site&apos;s data can be replaced with demo data from the Hub. Only mark sites used for showing Cross Events, never a church&apos;s real site.</p>
{confirmField}
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Mark as a demo site" disabled={!typed} />
</form>
</Modal>
);
return (
<Modal title="Load demo data" onClose={onClose} dirty={!!confirmName || profile !== "events"}>
<form onSubmit={seed} className="space-y-4">
<p className="text-sm text-slate-500">Replaces everything (events, people, payments) with a demo set, keeping the site settings and {x.adminEmail || "the site's first admin"}. Demo logins use the password Demo@1234.</p>
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="d-p">Demo</label>
<select id="d-p" className="input" value={profile} onChange={e => setProfile(e.target.value)}>
{PROFILES.map(p => <option key={p.key} value={p.key}>{p.label}</option>)}
</select>
</div>
{confirmField}
</div>
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Load demo data" danger disabled={!typed} />
</form>
</Modal>
);
}
@@ -0,0 +1,70 @@
"use client";
import React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowLeft, RefreshCw } from "lucide-react";
import { ago } from "@/lib/format";
import { Menu, Stat } from "@/components/ui";
import { StatusPill } from "@/components/servers";
import { productName, running, type Detail } from "./shared";
/** What the header's buttons, menu and tiles open. */
export type InstallAction = "update" | "adopt" | "demo" | "undemo" | "uninstall" | "record" | "forget";
/**
* Hub 2.15.0: always at the top of an install's page: which church and product, its status, the
* everyday action (an update) and the rare ones in the ⋯ menu, and tiles for where it runs.
*/
export function InstallHeader({ d, onAction }: { d: Detail; onAction: (a: InstallAction) => void }) {
const router = useRouter();
const x = d.deployment;
const live = x.status === "live";
const version = x.install?.version || x.version;
const heard = x.install?.lastHeartbeatAt || null;
return (
<header className="mb-6 space-y-4">
<Link href="/servers/installs" className="inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Installs</Link>
<div className="flex flex-wrap items-end justify-between gap-3">
<div className="min-w-0">
<h1 className="flex flex-wrap items-center gap-2 text-2xl font-semibold">
<span className="break-words">{x.customer?.name} ({x.shortName})</span>
<StatusPill status={d.stale.stale ? "stale" : x.status} />
{x.isDemo && <span className="rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700 ring-1 ring-inset ring-indigo-200">Demo site</span>}
</h1>
<p className="mt-1 text-sm text-slate-500">
{productName(x.product)} · {x.customer ? <Link className="text-indigo-700 hover:underline" href={`/customers/${x.customerId}`}>customer</Link> : "customer"}
</p>
</div>
<div className="flex flex-wrap gap-2">
{live && <button type="button" className="btn-primary" onClick={() => onAction("update")}><RefreshCw className="h-4 w-4" /> Schedule update</button>}
<Menu label="More actions for this install" items={[
live && x.install?.version?.startsWith("2.1.") && { label: "Move onto the monorepo…", onClick: () => onAction("adopt") },
x.product === "events" && running(x) && (x.isDemo
? { label: "Load demo data…", onClick: () => onAction("demo") }
: { label: "Mark as a demo site…", onClick: () => onAction("demo") }),
x.product === "events" && running(x) && x.isDemo && { label: "It isn't a demo site any more", onClick: () => onAction("undemo") },
running(x) && { label: `Uninstall ${productName(x.product)}…`, onClick: () => onAction("uninstall"), danger: true },
d.stale.stale && { label: "Remove from the Hub…", onClick: () => onAction("forget"), danger: true },
d.canRemoveRecord && { label: "Remove the record…", onClick: () => onAction("record"), danger: true },
]} />
</div>
</div>
<div className="grid grid-cols-2 gap-3 lg:grid-cols-5">
<Stat label="Site" small value={<span className="break-all">{x.domain}</span>}
tone={x.install ? undefined : "amber"}
sub={x.install ? <a className="text-indigo-700 hover:underline" href={x.install.url} target="_blank" rel="noreferrer">{x.install.url}</a> : "Not registered with the Hub yet"} />
<Stat label="Version" small value={version || "–"} onClick={live ? () => onAction("update") : undefined}
sub={live ? "Schedule an update" : undefined} />
<Stat label="Server" small value={x.server.name} onClick={() => router.push(`/servers/${x.serverId}`)}
sub={`agent ${x.server.agentVersion || "unknown"}`} />
<Stat label="Ports" small value={`web ${x.webPort} · api ${x.apiPort}`} />
<Stat label="Last heartbeat" small value={heard ? ago(heard) : "Never"}
tone={d.stale.stale ? "red" : !heard && x.status === "live" ? "amber" : undefined}
sub={d.stale.stale ? "Over a day: check the site" : undefined} />
</div>
</header>
);
}
@@ -0,0 +1,56 @@
"use client";
import React from "react";
import Link from "next/link";
import { bytes, fmtDate } from "@/lib/format";
import { Pager } from "@/components/ui";
import { StatusPill, type Job } from "@/components/servers";
import type { useServerPaged } from "@/lib/paging";
import type { Export } from "./shared";
/** Hub 2.6.0: every job of this install, a page at a time; a job not run yet can be cancelled. */
export function JobsCard({ paged, fallback, busy, onCancel }: {
paged: ReturnType<typeof useServerPaged<Job>>; fallback: Job[]; busy: boolean; onCancel: (j: Job) => void;
}) {
const rows = paged.rows ?? fallback;
return (
<section className="card overflow-x-auto p-0">
{rows.length === 0
? <p className="p-5 text-sm text-slate-500">No jobs yet.</p>
: (
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="px-5 py-2">Job</th><th className="py-2">When</th><th className="py-2">Status</th><th className="py-2">Result</th><th className="py-2"><span className="sr-only">Actions</span></th></tr></thead>
<tbody>{rows.map(j => (
<tr key={j.id} className="border-t">
<td className="px-5 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td className="whitespace-nowrap">{fmtDate(j.notBefore)}</td>
<td><StatusPill status={j.status} /></td>
<td className="max-w-md truncate text-xs text-slate-500" title={j.message || undefined}>{j.message}</td>
<td className="pr-5 text-right">{["queued", "scheduled"].includes(j.status) && <button type="button" className="btn-secondary px-2 py-1 text-xs" disabled={busy} onClick={() => onCancel(j)}>Cancel</button>}</td>
</tr>
))}</tbody>
</table>
)}
<Pager page={paged.page} pages={paged.pages} setPage={paged.setPage} total={paged.total} pageSize={paged.pageSize} />
</section>
);
}
/** The church's data exports (made before an uninstall), and whether they've been downloaded. */
export function ExportsCard({ exports }: { exports: Export[] }) {
return (
<section className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="px-5 py-2">Export</th><th className="py-2">Size</th><th className="py-2">Kept until</th><th className="py-2 pr-5">Downloaded</th></tr></thead>
<tbody>{exports.map(e => (
<tr key={e.id} className="border-t">
<td className="px-5 py-1.5 font-mono text-xs">{e.id}</td>
<td className="tabular-nums">{bytes(e.bytes)}</td>
<td>{e.deletedAt ? <span className="text-slate-500">Deleted {fmtDate(e.deletedAt)}</span> : fmtDate(e.expiresAt)}</td>
<td className="pr-5">{e.downloadedAt ? fmtDate(e.downloadedAt) : <span className="text-amber-800">Not yet</span>}</td>
</tr>
))}</tbody>
</table>
</section>
);
}
@@ -0,0 +1,47 @@
"use client";
import React, { useState } from "react";
import { api } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { FormError, Modal } from "@/components/ui";
import { ModalButtons } from "@/components/customer/ReadCard";
import { useSubmit, type Detail, type Install } from "./shared";
export type RemoveKind = "record" | "forget";
/**
* Take an install off the Hub without running anything on its server:
* - "record": its install failed and the server already cleaned up (frees the short name);
* - "forget" (2.12.0): no heartbeat for a day, and the site is gone from the server by other means.
*/
export function RemoveModal({ kind, x, stale, onClose, onRemoved }: { kind: RemoveKind; x: Install; stale: Detail["stale"]; onClose: () => void; onRemoved: () => void }) {
const [typed, setTyped] = useState("");
const { busy, error, run } = useSubmit();
const record = kind === "record";
const save = (e: React.FormEvent) => {
e.preventDefault();
const sure = record
? `Remove the record of ${x.shortName}? Its install failed, so nothing of it is on the server.`
: `Remove ${x.domain} from the Hub? Nothing runs on the server: use this only when the site is already gone from it.`;
if (!window.confirm(sure)) return;
run(async () => {
if (record) await api(`/api/admin/deployments/${x.id}`, { method: "DELETE" });
else await api(`/api/admin/deployments/${x.id}/forget`, { method: "POST", body: { confirm: typed } });
onRemoved();
});
};
return (
<Modal title={record ? "Remove the record" : "Remove from the Hub"} onClose={onClose} dirty={!!typed}>
<form onSubmit={save} className="space-y-4">
{record
? <p className="text-sm text-slate-500">This install failed and the server already removed what it made, so there&apos;s nothing to export or uninstall. Removing the record frees the short name.</p>
: <p className="text-sm text-slate-500">No heartbeat since {stale.since ? `${fmtDate(stale.since)} (${ago(stale.since)})` : "it was made"}. If the site is no longer on {x.server.name} (uninstalled by hand, or the server was rebuilt), remove it here: nothing runs on the server, what was planned for it is cancelled, its ports are freed after 30 days and its licence&apos;s heartbeats are refused. If it&apos;s still there, uninstall it instead.</p>}
{!record && <div><label className="label" htmlFor="f-c">Type {x.shortName}</label><input id="f-c" className="input" autoComplete="off" value={typed} onChange={e => setTyped(e.target.value)} /></div>}
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label={record ? "Remove the record" : "Remove from the Hub"} danger disabled={!record && typed !== x.shortName} />
</form>
</Modal>
);
}
@@ -0,0 +1,75 @@
"use client";
import React, { useState } from "react";
import { fmtDate } from "@/lib/format";
import { FormError, Modal } from "@/components/ui";
import { fromInput, toInput } from "@/components/servers";
import { ModalButtons } from "@/components/customer/ReadCard";
import { H, post, productName, useSubmit, withWarnings, type Done, type Install, type UninstallPlan } from "./shared";
/**
* Plan an uninstall of one product (2.12.0): the church's data is exported first, then the site
* is removed. With another product of the church already planned, join that run (the default) or
* pick a time of its own.
*/
export function UninstallModal({ x, plan, onClose, onDone }: { x: Install; plan: UninstallPlan; onClose: () => void; onDone: Done }) {
const [at0] = useState(() => toInput(new Date(Date.now() + 7 * 24 * H)));
const [un, setUn] = useState({ at: at0, totp: "", confirm: "" });
const [joining, setJoining] = useState(true);
const { busy, error, run } = useSubmit();
const { joinable, pendingRuns, lastNow, wholeChurch, accountsInUse, othersStaying } = plan;
const together = joining && joinable ? joinable : null;
const save = (e: React.FormEvent) => {
e.preventDefault();
const when = together ? fmtDate(together.notBefore) : un.at.replace("T", " ");
if (!window.confirm(`Uninstall ${productName(x.product)} of ${x.shortName} on ${when}${together ? `, together with ${together.products!.map(productName).join(" and ")}` : ""}?${lastNow ? ` It's the church's last product here, so the whole church goes.` : ""} The church gets its data first.`)) return;
run(async () => {
const r = await post(`/api/admin/deployments/${x.id}/uninstall`, { at: together ? undefined : fromInput(un.at), totp: un.totp, confirm: un.confirm, ...(pendingRuns.length ? { join: !!together, joinJobId: together ? together.jobId : undefined } : {}) });
onDone({ type: "ok", text: withWarnings(together ? "Added to that uninstall: one export and one uninstall for both. The site admin was emailed and sees a banner." : "Uninstall planned: the site admin was emailed and sees a banner. The export runs first.", r) });
});
};
const blocked = wholeChurch || accountsInUse;
return (
<Modal title={`Uninstall ${productName(x.product)} of ${x.shortName}`} onClose={onClose} wide dirty={!!un.confirm || !!un.totp || un.at !== at0}>
<form onSubmit={save} className="space-y-4">
<p className="text-sm text-slate-500">
At the time: {productName(x.product)}&apos;s data is exported (encrypted; the link goes to the site admin), then {x.domain}, its tunnels and database are removed. The final backup stays on the server for 30 days.
{plan.onlyThisProduct && plan.others.length > 0 && !plan.lastProduct && <> The church keeps {plan.others.map(o => `${productName(o.product)} (${o.domain})`).join(" and ")}.</>}
</p>
{/* What stops it: say so first, before any fields. */}
{wholeChurch && <p className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">The agent on {x.server.name} is {x.server.agentVersion || "an unknown version"}: it can only remove the whole church, with {plan.others.map(o => productName(o.product)).join(" and ")}. Update the agent to {plan.minAgent} or later first.</p>}
{accountsInUse && <p className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">{othersStaying.map(o => productName(o.product)).join(" and ")} signs in through Accounts: uninstall {othersStaying.length === 1 ? "it" : "them"} first, then Accounts (at the same time or later).</p>}
{/* Another product of the church is already planned for uninstall. */}
{plan.onlyThisProduct && pendingRuns.length > 0 && (
<fieldset className="space-y-2 rounded-lg border border-slate-200 p-3 text-sm">
<legend className="px-1 font-medium">{pendingRuns.map(p => `${p.products!.map(productName).join(" and ")} on ${fmtDate(p.notBefore)}`).join("; ")}: already planned for uninstall</legend>
<label className={`flex items-start gap-2 ${joinable ? "" : "text-slate-400"}`}>
<input type="radio" name="x-join" className="mt-1" checked={!!together} disabled={!joinable} onChange={() => setJoining(true)} />
<span>Add {productName(x.product)} to that uninstall{joinable ? ` on ${fmtDate(joinable.notBefore)}` : ""}: one export and one uninstall for both{plan.lastProduct ? ", which removes the whole church" : ""}.{!joinable && " (Not possible: it has already started.)"}{joinable && new Date(joinable.notBefore).getTime() - Date.now() < 4 * H && " (Under 4 hours away: the church wouldn't get notice in time, so the Hub will refuse.)"}</span>
</label>
<label className="flex items-start gap-2">
<input type="radio" name="x-join" className="mt-1" checked={!together} onChange={() => setJoining(false)} />
<span>At its own time (below).{plan.lastProduct && " It's then the church's last product here, so it removes the whole church (its folder and app user) when it runs."}</span>
</label>
</fieldset>
)}
{lastNow && !pendingRuns.length && <p className="text-sm text-slate-600">This is the church&apos;s last product here: the uninstall removes the whole church (its folder and app user).</p>}
<div className="grid gap-3 sm:grid-cols-3">
{together
? <div><span className="label">When</span><p className="mt-2 text-sm">{fmtDate(together.notBefore)}, with {together.products!.map(productName).join(" and ")}</p></div>
: <div><label className="label" htmlFor="x-at">When</label><input id="x-at" type="datetime-local" className="input" value={un.at} onChange={e => setUn({ ...un, at: e.target.value })} /></div>}
<div><label className="label" htmlFor="x-c">Type {x.shortName}</label><input id="x-c" className="input" autoComplete="off" required value={un.confirm} onChange={e => setUn({ ...un, confirm: e.target.value })} /></div>
<div><label className="label" htmlFor="x-t">Two-factor code</label><input id="x-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={un.totp} onChange={e => setUn({ ...un, totp: e.target.value })} /></div>
</div>
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Plan the uninstall" danger disabled={un.confirm !== x.shortName || blocked} />
</form>
</Modal>
);
}
@@ -0,0 +1,73 @@
"use client";
import React, { useState } from "react";
import type { Release } from "@/lib/types";
import { PRODUCT_NAMES } from "@/lib/products";
import { FormError, Modal } from "@/components/ui";
import { fromInput, toInput } from "@/components/servers";
import { ModalButtons } from "@/components/customer/ReadCard";
import { H, changed, post, productName, useSubmit, withWarnings, type Done, type Install } from "./shared";
/**
* Schedule an update of one install: at a time at least 4 hours away (the church gets notice), or
* an emergency with a reason and a two-factor code, at least 15 minutes away or as soon as possible.
*/
export function UpdateModal({ x, releases, onClose, onDone }: { x: Install; releases: Release[]; onClose: () => void; onDone: Done }) {
const [form0] = useState(() => ({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, asap: true, reason: "", totp: "" }));
const [upd, setUpd] = useState(form0);
const { busy, error, run } = useSubmit();
const asap = upd.emergency && upd.asap;
const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H;
const mine = releases.filter(r => r.product === x.product);
const save = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await post("/api/admin/updates", { deploymentIds: [x.id], product: x.product, version: upd.version || undefined, at: asap ? undefined : fromInput(upd.at), asap, emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null });
onDone({ type: "ok", text: withWarnings(asap ? "Started: the agent picks it up within a minute. The site admin was emailed and sees a banner." : "Planned. The site admin was emailed and sees a banner.", r) });
});
};
return (
<Modal title={`Update ${productName(x.product)} of ${x.shortName}`} onClose={onClose} dirty={changed(upd, form0)}>
<form onSubmit={save} className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="u-v">Release</label>
<select id="u-v" className="input" value={upd.version} onChange={e => setUpd({ ...upd, version: e.target.value })}>
<option value="">Latest</option>
{mine.map(r => <option key={r.id} value={r.version}>{r.version}{r.latest ? " (latest)" : ""}{r.requires?.length ? ` · needs ${r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(", ")}` : ""}</option>)}
</select>
<p className="mt-1 text-xs text-slate-500">Now on {x.install?.version || x.version || "an unknown version"}.</p>
</div>
{asap
? <div><span className="label">When</span><p className="mt-2 text-sm">As soon as possible: the agent starts within a minute.</p></div>
: <div>
<label className="label" htmlFor="u-at">When</label>
<input id="u-at" type="datetime-local" className="input" value={upd.at} min={toInput(new Date(Date.now() + minAt))} onChange={e => setUpd({ ...upd, at: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.</p>
</div>}
</div>
<label className="flex items-start gap-2 text-sm"><input type="checkbox" className="mt-1" checked={upd.emergency} onChange={e => setUpd({ ...upd, emergency: e.target.checked })} /> <span>Emergency (security fix or broken release): a reason and your two-factor code</span></label>
{upd.emergency && (
<div className="space-y-3 rounded-lg border border-red-200 bg-red-50/40 p-3">
<fieldset className="flex flex-wrap gap-4 text-sm">
<legend className="sr-only">When the emergency update runs</legend>
<label className="flex items-center gap-2"><input type="radio" name="u-when" checked={upd.asap} onChange={() => setUpd({ ...upd, asap: true })} /> As soon as possible (within a minute)</label>
<label className="flex items-center gap-2"><input type="radio" name="u-when" checked={!upd.asap} onChange={() => setUpd({ ...upd, asap: false })} /> At a time, at least 15 minutes away</label>
</fieldset>
<div className="grid gap-3 sm:grid-cols-2">
<div><label className="label" htmlFor="u-r">Reason (shown to the church)</label><input id="u-r" className="input" required value={upd.reason} onChange={e => setUpd({ ...upd, reason: e.target.value })} /></div>
<div><label className="label" htmlFor="u-t">Two-factor code</label><input id="u-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={upd.totp} onChange={e => setUpd({ ...upd, totp: e.target.value })} /></div>
</div>
</div>
)}
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} danger={upd.emergency} label={asap ? "Update now" : "Schedule"} />
</form>
</Modal>
);
}
+95
View File
@@ -0,0 +1,95 @@
"use client";
import { useRef, useState } from "react";
import { api, ApiError, errorText } from "@/lib/api";
import { PRODUCT_NAMES } from "@/lib/products";
import type { Deployment, Job, ServerSummary } from "@/components/servers";
// Hub 2.15.0: what the install page loads once and passes to its cards and popups.
export type { Msg, Done } from "@/components/customer/shared";
export { changed } from "@/components/customer/shared";
export type Export = { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null };
export type Detail = {
deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: Export[]; install: { version: string | null; url: string; lastHeartbeatAt: string | null } | null };
fastPanel: string;
canRemoveRecord: boolean;
/** 2.12.0: no heartbeat for 24 hours, so it can be removed from the Hub. */
stale: { since: string | null; stale: boolean };
/** 2.12.0: what an uninstall removes: this product only (agent 1.5.0+), or the whole church. */
uninstall: {
onlyThisProduct: boolean; minAgent: string; others: { id: string; product: string; domain: string; status: string }[];
/** The church's uninstalls not run yet; `products` null: the whole church. `joinable`: this one can still be added to it. */
pending: { jobId: string; notBefore: string; products: string[] | null; joinable: boolean }[];
/** Every other product is being uninstalled: this one takes the whole church with it. */
lastProduct: boolean;
};
};
export type Install = Detail["deployment"];
export const productName = (p: string) => PRODUCT_NAMES[p as keyof typeof PRODUCT_NAMES] || p;
export const H = 60 * 60 * 1000;
/** The statuses an install can be changed in (its .env, demo data, an uninstall). */
export const running = (x: Install) => ["live", "waiting_for_proxy"].includes(x.status);
/**
* A POST to the Hub. Hub 2.7.0: when an event is on the site now, the Hub refuses with LIVE_EVENT:
* ask once more and send it again with confirmLive.
*/
export async function post<T = { warnings?: string[] }>(path: string, body: Record<string, unknown> = {}): Promise<T> {
try {
return await api<T>(path, { method: "POST", body });
} catch (e) {
if (e instanceof ApiError && e.code === "LIVE_EVENT" && !body.confirmLive && window.confirm(e.message)) return post<T>(path, { ...body, confirmLive: true });
throw e;
}
}
/** A success message with the Hub's warnings after it. */
export const withWarnings = (ok: string, r?: { warnings?: string[] } | null) => `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}`;
/**
* 2.7.1: one click is one job: `run` does nothing while the last one hasn't answered. A thrown
* error lands in `error`, for the popup to show by its button.
*/
export function useSubmit() {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const inFlight = useRef(false);
const run = async (fn: () => Promise<void>) => {
if (inFlight.current) return;
inFlight.current = true;
setBusy(true);
setError(null);
try { await fn(); } catch (e) { setError(errorText(e)); } finally { inFlight.current = false; setBusy(false); }
};
return { busy, error, run };
}
/** 2.12.0: what an uninstall of this install takes with it, and what stops it. */
export function uninstallPlan(d: Detail) {
const x = d.deployment;
const plan = d.uninstall;
const othersStaying = plan.others.filter(o => o.status !== "uninstalling");
// The church's uninstalls not run yet (by product), and the one this could join.
const pendingRuns = plan.pending.filter(p => p.products);
const joinable = pendingRuns.find(p => p.joinable) || null;
return {
...plan,
othersStaying,
pendingRuns,
joinable,
// Accounts goes last: the church's other products sign in through it.
accountsInUse: x.product === "accounts" && othersStaying.length > 0,
// An agent before minAgent can only remove the whole church, with its other products.
wholeChurch: !plan.onlyThisProduct && plan.others.length > 0,
lastNow: plan.onlyThisProduct && plan.lastProduct,
/** An uninstall already planned that takes this install: its own, or the whole church's. */
planned: plan.pending.find(p => !p.products || p.products.includes(x.product)) || null,
};
}
export type UninstallPlan = ReturnType<typeof uninstallPlan>;
+21
View File
@@ -143,6 +143,27 @@ export function Modal({ title, onClose, dirty = false, wide = false, children }:
);
}
/**
* The one message under a page's header (Hub 2.14.0, shared in 2.15.0): it stays in view while you
* scroll, an "ok" fades after a while, an error stays until it's closed or replaced.
*/
export function PageMessage({ msg, onClose }: { msg: { type: "ok" | "err"; text: string } | null; onClose: () => void }) {
const close = React.useRef(onClose);
close.current = onClose;
React.useEffect(() => {
if (msg?.type !== "ok") return;
const t = setTimeout(() => close.current(), 12000);
return () => clearTimeout(t);
}, [msg]);
if (!msg) return null;
return (
<div className="sticky top-2 z-30 mb-4 flex items-start gap-2 [&>div]:flex-1 [&>div]:shadow-sm" role="status">
<Message msg={msg} />
<button type="button" aria-label="Dismiss" onClick={onClose} className="mt-2.5 rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700"><X className="h-4 w-4" /></button>
</div>
);
}
/** The error of a form in a popup, next to its Save button. */
export function FormError({ error }: { error: string | null }) {
return error ? <p role="alert" className="text-sm text-red-700">{error}</p> : null;