runloopable / web /src /settings /AdminPane.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
103a492 verified
Raw History Blame Contribute Delete
49.8 kB
// --------------------------------------------------------------------------- // settings / AdminPane.tsx — THE LOOPABLE ADMIN PLANE (wave 19, owner item 13 / // R3+R4, contract C2). // // The one surface in this product that looks ACROSS tenants: who our customers // are, how many people use each workspace, what they have built in it, whether // their data sources are alive, and what the automation fleet costs. // // SELF-CONTAINED BY CONTRACT (C2). It fetches its own data via // `platformAdminApi` and takes ONE prop, so mounting it is a rail entry plus a // line in the pane switch — `SettingsModal.tsx` is another session's file this // wave and must not have to learn anything about this pane's data. // // ⚠ THE PROP IS TYPED STRUCTURALLY, not as `SessionUser` from `../shell/session`. // The mount site passes the shell's session user (a wider object), which // satisfies this shape by structural typing — and this pane therefore imports // nothing from the shell, which is what the wave's cross-fence rule asks for // while `session.ts` is open on another desk. // // ⛔ EVERY NUMBER HERE IS THE SERVER'S, AND EVERY NUMBER DRILLS. Clicking a count // opens the rows it was computed from — the same collector, projected twice // ([[no-unverifiable-aggregates]]). A count that could not be READ renders as an // its cause, never as a zero: "this customer has no databases" and // "we could not look" are different facts and the pane refuses to conflate them. // // DESIGN: sentence-case micro-labels (R6 — no caps in app chrome), short noun // headers, tabular figures right-aligned, hairlines not shadows, tokens only, // no emojis (DESIGN.md §2–§4). // --------------------------------------------------------------------------- import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT } from "../apiContract"; import { useEscapeClose } from "../ui/useEscapeClose"; import "../signup/signup.css"; import type { AutomationRow, ConnectorRow, DatabaseRow, FleetCost, Overview, PlatformUser, ReleasesPayload, SignupRequest, TenantRow, } from "./platformAdminApi"; import { getAutomations, getAws, getReleases, getConnectors, getDatabases, getOverview, getUsers, getSignupRequests, approveSignupRequest, declineSignupRequest, } from "./platformAdminApi"; // --- formatting ------------------------------------------------------------- const int = (n: number) => n.toLocaleString(); /** A count that may be unknown. `null` is NOT zero — see the api module's header. */ function Count({ n, why }: { n: number | null | undefined; why?: string }) { if (n === null || n === undefined) return ( <span className="padmin-unknown" title={why || "This could not be read just now"}> Unknown </span> ); return <>{int(n)}</>; } /** "3 days ago" for a stamp, "never" for an absent one. Never a fabricated date. * * ⛔ ONLY FOR OFFSET-BEARING STAMPS. `Date.parse` reads a stamp with no zone as * BROWSER-LOCAL, so running a container-local timestamp through this reports the * viewer's UTC offset as elapsed time — hours of error in a column people scan, * and a future-dated stamp that renders as "just now" indefinitely. Everything * this pane passes here (`last_login`, `last_active`, `generatedAt`) is written * with an explicit offset; the automation engine's `lastRunAt` is NOT, so it is * rendered verbatim instead. */ function ago(stamp: string): string { if (!stamp) return "never"; const t = Date.parse(stamp.includes("T") ? stamp : stamp.replace(" ", "T")); if (Number.isNaN(t)) return stamp; const mins = Math.floor((Date.now() - t) / 60000); if (mins < 2) return "just now"; if (mins < 60) return `${mins} minutes ago`; const hours = Math.floor(mins / 60); if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`; const days = Math.floor(hours / 24); if (days < 60) return `${days} day${days === 1 ? "" : "s"} ago`; return `${Math.floor(days / 30)} months ago`; } type DrillKind = "users" | "databases" | "connectors" | "automations"; const DRILL_NOUN: Record<DrillKind, string> = { users: "People", databases: "Databases", connectors: "Data sources", automations: "Automations", }; /** The loading shape — a skeleton, not a spinner (DESIGN.md §4). */ function Skeleton({ rows = 3 }: { rows?: number }) { return ( <div className="padmin-skel set-skeleton" role="status" aria-label="Loading admin data" aria-busy="true"> {Array.from({ length: rows }, (_, i) => ( <div key={i} className="padmin-skel-row set-skeleton-line" aria-hidden="true" /> ))} </div> ); } type NeonMetric = "transfer_gb" | "compute_hours" | "storage_gib"; type NeonNumbers = Record<NeonMetric, number | null>; interface NeonUsage { available: boolean; cause: string | null; read_at: string; period: { start: string; end: string }; usage: NeonNumbers; allowance: Record<NeonMetric, number>; share: NeonNumbers; rate: Record<NeonMetric, { per_day: number | null; cause: string | null }>; projection: { transfer: number | null; compute: number | null; storage: number | null; total: number | null; currency: string; cause: string | null; basis: Record<NeonMetric, string>; }; samples: { at: string; transfer_bytes: number; compute_seconds: number; storage_bytes: number; period_start: string }[]; sampler: { every_s: number; last_at: string | null; pending: number; persisted: string | null; cause: string | null }; alarm: { level: "red"; message: string; test: boolean } | null; guards: { ok: boolean; message: string } | null; } async function getNeon(): Promise<{ ok: true; data: NeonUsage } | { ok: false; message: string }> { try { const response = await fetch(`${API_V1}/platform-admin/neon`, { credentials: CREDENTIALS }); if (!response.ok) { return { ok: false, message: response.status === 403 ? "Neon usage is only available to platform operators." : response.status === 401 ? "Sign in to read Neon usage." : `Neon usage could not be loaded (HTTP ${response.status}).` }; } const data = await response.json() as NeonUsage; if (typeof data?.available !== "boolean") return { ok: false, message: "The Neon usage response could not be read." }; return { ok: true, data }; } catch { return { ok: false, message: "The Neon usage service could not be reached or its response could not be read." }; } } const neonNumber = (value: number) => value.toLocaleString(undefined, { maximumFractionDigits: 2 }); const neonDate = (value: string) => new Date(value).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric", timeZone: "UTC" }); const neonTime = (value: string) => new Date(value).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZone: "UTC" }); const neonMoney = (value: number) => value.toLocaleString(undefined, { style: "currency", currency: "USD" }); function NeonCard({ data, error, onRetry }: { data: NeonUsage | null; error: string; onRetry: () => void }) { const metrics: { key: NeonMetric; label: string; unit: string }[] = [ { key: "transfer_gb", label: "Transfer", unit: "GB" }, { key: "compute_hours", label: "Compute", unit: "CU-hours" }, { key: "storage_gib", label: "Storage", unit: "GiB" }, ]; const cause = error || (data && !data.available ? data.cause || "Neon usage could not be read." : ""); return ( <section className="padmin-block" aria-label="Neon usage" style={data?.alarm && !cause ? { border: "1px solid var(--lp-red-deep)", padding: 12 } : undefined}> <h4 className="padmin-h4">Neon</h4> {cause ? <div className="set-error" role="alert"><span title={cause}>Could not read Neon usage.</span> <button type="button" className="set-secondary" onClick={onRetry}>Retry</button></div> : !data ? <Skeleton rows={2} /> : ( <> {data.alarm ? ( <p className="set-help" role="status" style={{ color: "var(--lp-red-deep)", background: "var(--lp-red-tint)", padding: 8, fontVariantNumeric: "tabular-nums" }}> {data.alarm.test && !data.alarm.message.startsWith("TEST ") ? "TEST " : ""}{data.alarm.message} </p> ) : null} <p className="set-help"> {neonDate(data.period.start)} to {neonDate(data.period.end)} (UTC, end exclusive). {" "}Project totals include staging and production. Read {neonTime(data.read_at)} UTC. </p> <div className="padmin-totals"> {metrics.map(({ key, label, unit }) => ( <div className="padmin-total" key={key}> <span className="padmin-total-label">{label}</span> <span className="padmin-total-value" style={{ fontVariantNumeric: "tabular-nums" }}> {data.usage[key] === null ? "This total could not be read" : `${neonNumber(data.usage[key])} ${unit}`} </span> <span className="set-help"> of {neonNumber(data.allowance[key])} {unit} {data.share[key] === null ? "; usage share could not be read" : ` · ${neonNumber(data.share[key] * 100)}% used`} </span> </div> ))} </div> <p className="set-help" style={{ fontVariantNumeric: "tabular-nums" }}> GB per day: {data.rate.transfer_gb.per_day === null ? data.rate.transfer_gb.cause : neonNumber(data.rate.transfer_gb.per_day)} </p> <p className="set-help" style={{ fontVariantNumeric: "tabular-nums" }}> Projected bill: {data.projection.total === null ? data.projection.cause : `${neonMoney(data.projection.total)} at period end`} </p> {data.projection.total !== null ? ( <> <p className="set-help"> {metrics.map(({ key, label }) => `${label}: ${data.projection.basis[key]}`).join(". ")}. </p> <p className="set-help" style={{ fontVariantNumeric: "tabular-nums" }}> Transfer {neonMoney(data.projection.transfer!)} · Compute {neonMoney(data.projection.compute!)} {" "}· Storage {neonMoney(data.projection.storage!)}. Compute is billed from the first CU-hour. </p> </> ) : null} <h5 className="padmin-h4">Sample history</h5> {data.samples.length ? ( <div className="padmin-tablewrap" style={{ maxHeight: "18rem", overflow: "auto" }}> <table className="padmin-table" style={{ fontVariantNumeric: "tabular-nums" }}> <thead><tr> <th>Time (UTC)</th> <th className="padmin-num">Transfer (GB)</th> <th className="padmin-num">Compute (CU-hours)</th> <th className="padmin-num">Storage (GiB)</th> </tr></thead> <tbody>{[...data.samples].reverse().map((sample) => ( <tr key={`${sample.period_start}/${sample.at}`}> <td title={`Billing period starts ${neonDate(sample.period_start)}`}>{neonTime(sample.at)}</td> <td className="padmin-num">{neonNumber(sample.transfer_bytes / 1e9)}</td> <td className="padmin-num">{neonNumber(sample.compute_seconds / 3600)}</td> <td className="padmin-num">{neonNumber(sample.storage_bytes / 2 ** 30)}</td> </tr> ))}</tbody> </table> </div> ) : <p className="set-help">No sample history is available yet.</p>} <p className="set-help"> {data.sampler.every_s > 0 ? `Sampled every ${neonNumber(data.sampler.every_s / 3600)} hours. ` : ""} {data.sampler.persisted ? `History saved ${neonTime(data.sampler.persisted)} UTC. ` : ""} {data.sampler.pending > 0 ? `${data.sampler.pending} samples awaiting storage. ` : ""} {data.sampler.cause} </p> </> )} {data?.guards ? ( <p className="set-help" role="status" style={{ fontVariantNumeric: "tabular-nums", color: data.guards.ok ? undefined : "var(--lp-red-deep)" }}> {data.guards.message} </p> ) : null} </section> ); } interface DigitalOceanUsage { available: boolean; cause: string | null; read_at: string; cluster: { available: boolean; cause: string | null; source: string; read_at: string; name: string | null; size: string | null; num_nodes: number | null; region: string | null; status: string | null; }; fixed_price: { monthly_usd: number | null; source: string | null; read_at: string; cause: string | null }; balance: { available: boolean; cause: string | null; source: string; read_at: string; month_to_date_usage: number | null; account_balance: number | null; month_to_date_balance: number | null; generated_at: string | null; }; billing: { available: boolean; cause: string | null; source: string; read_at: string; has_more?: boolean }; billing_history: { date: string; description: string; amount: number; type: string }[]; sampler: { every_s: number; last_at: string | null; persisted: string | null; cause: string | null }; alarm: { level: "red"; message: string; test: boolean } | null; alarm_cause: string | null; } async function getDigitalOcean(): Promise<{ ok: true; data: DigitalOceanUsage } | { ok: false; message: string }> { try { const response = await fetch(`${API_V1}/platform-admin/do`, { credentials: CREDENTIALS }); if (!response.ok) { return { ok: false, message: response.status === 403 ? "DigitalOcean usage is only available to platform operators." : response.status === 401 ? "Sign in to read DigitalOcean usage." : `DigitalOcean usage could not be loaded (HTTP ${response.status}).` }; } const data = await response.json() as DigitalOceanUsage; if (typeof data?.available !== "boolean" || !data.cluster || !data.balance || !data.fixed_price || !data.billing || !Array.isArray(data.billing_history) || !data.sampler) return { ok: false, message: "The DigitalOcean usage response could not be read." }; return { ok: true, data }; } catch { return { ok: false, message: "The DigitalOcean usage service could not be reached or its response could not be read." }; } } // Provider labels are also screen copy. Preserve their meaning using words for ranges. const doText = (value: string) => value.replace(/\u2014/g, "; ").replace(/\u2013/g, " to "); const doTime = (value: string) => `${new Date(value).toLocaleString(undefined, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZone: "UTC" })} UTC`; function DigitalOceanCard({ data, error, onRetry }: { data: DigitalOceanUsage | null; error: string; onRetry: () => void }) { const cause = error || (data && !data.available ? data.cause || "DigitalOcean usage could not be read." : ""); return ( <section className="padmin-block" aria-label="DigitalOcean usage" style={data?.alarm && !cause ? { border: "1px solid var(--lp-red-deep)", padding: 12 } : undefined}> <h4 className="padmin-h4">DigitalOcean</h4> {cause ? <div className="set-error" role="alert"><span title={doText(cause)}>Could not read DigitalOcean usage.</span> <button type="button" className="set-secondary" onClick={onRetry}>Retry</button></div> : !data ? <Skeleton rows={2} /> : ( <> {data.alarm ? ( <p className="set-help" role="status" style={{ color: "var(--lp-red-deep)", background: "var(--lp-red-tint)", padding: 8, fontVariantNumeric: "tabular-nums" }}> {data.alarm.test && !data.alarm.message.startsWith("TEST ") ? "TEST " : ""}{doText(data.alarm.message)} </p> ) : null} {data.cluster.available ? ( <p className="set-help"> {doText(data.cluster.name!)} · {doText(data.cluster.size!)} · {data.cluster.num_nodes} {data.cluster.num_nodes === 1 ? " node" : " nodes"} · {doText(data.cluster.region!)} · {doText(data.cluster.status!)} </p> ) : <p className="set-help">Cluster: {doText(data.cluster.cause || "The cluster could not be read.")}</p>} <div className="padmin-totals"> <div className="padmin-total"> <span className="padmin-total-label">Fixed price</span> <span className="padmin-total-value" style={{ fontVariantNumeric: "tabular-nums" }}> {data.fixed_price.monthly_usd === null ? "Unknown" : `${neonMoney(data.fixed_price.monthly_usd)} a month`} </span> <span className="set-help"> {data.fixed_price.monthly_usd === null ? doText(data.fixed_price.cause || "The fixed price could not be read.") : `${doText(data.fixed_price.source!)}. Read ${doTime(data.fixed_price.read_at)}.`} </span> </div> <div className="padmin-total"> <span className="padmin-total-label">Month to date</span> <span className="padmin-total-value" style={{ fontVariantNumeric: "tabular-nums" }}> {!data.balance.available || data.balance.month_to_date_usage === null ? "This total could not be read" : neonMoney(data.balance.month_to_date_usage)} </span> <span className="set-help"> {data.balance.available && data.balance.generated_at ? `As of ${doTime(data.balance.generated_at)}.` : doText(data.balance.cause || "The balance snapshot could not be read.")} </span> </div> </div> {data.balance.available ? ( <p className="set-help">{doText(data.balance.source)}. Read {doTime(data.balance.read_at)}.</p> ) : null} <h5 className="padmin-h4">Billing history</h5> {!data.billing.available ? ( <p className="set-help">{doText(data.billing.cause || "Billing history could not be read.")}</p> ) : ( <> {data.billing_history.length ? ( <div className="padmin-tablewrap" style={{ maxHeight: "18rem", overflow: "auto" }}> <table className="padmin-table" style={{ fontVariantNumeric: "tabular-nums" }}> <thead><tr><th>Date (UTC)</th><th>Description</th><th className="padmin-num">Amount</th></tr></thead> <tbody>{data.billing_history.map((row, index) => ( <tr key={`${row.date}/${index}`}> <td>{neonDate(row.date)}</td><td>{doText(row.description)}</td> <td className="padmin-num">{neonMoney(row.amount)}</td> </tr> ))}</tbody> </table> </div> ) : <p className="set-help">No billing history yet</p>} <p className="set-help"> {doText(data.billing.source)}. Read {doTime(data.billing.read_at)}. {data.billing.has_more ? " Showing the latest page." : ""} </p> </> )} {data.alarm_cause ? <p className="set-help">{doText(data.alarm_cause)}</p> : null} <p className="set-help"> {data.sampler.every_s > 0 ? `Sampled every ${neonNumber(data.sampler.every_s / 3600)} hours. ` : ""} {data.sampler.persisted ? `History saved ${doTime(data.sampler.persisted)}. ` : ""} {doText(data.sampler.cause || "")} </p> </> )} </section> ); } // --- the pane --------------------------------------------------------------- function SignupRequests({ tenants, owner }: { tenants: TenantRow[]; owner: string }) { const [requests, setRequests] = useState<SignupRequest[] | null>(null); const [error, setError] = useState(""); const [notice, setNotice] = useState(""); const [approving, setApproving] = useState<string | null>(null); const [tenant, setTenant] = useState(""); const [busy, setBusy] = useState(false); const acting = useRef(false); const opener = useRef<HTMLButtonElement | null>(null); const picker = useRef<HTMLSelectElement | null>(null); const companies = tenants.filter((company) => company.status === "active"); const requestScope = useRef<AbortController | null>(null); const recordsGeneration = useRef(0); useLayoutEffect(() => { const scope = new AbortController(); requestScope.current = scope; acting.current = false; setBusy(false); const invalidate = () => scope.abort(); window.addEventListener(UNAUTHORIZED_EVENT, invalidate); window.addEventListener("aios:signed-out", invalidate); return () => { scope.abort(); window.removeEventListener(UNAUTHORIZED_EVENT, invalidate); window.removeEventListener("aios:signed-out", invalidate); }; }, [owner]); const load = useCallback(() => { const request = requestScope.current?.signal; if (!request || request.aborted) return; const generation = ++recordsGeneration.current; setRequests(null); setError(""); void getSignupRequests().then((result) => { if (request.aborted || generation !== recordsGeneration.current) return; if (result.ok) setRequests(result.data.requests); else setError(result.message); }); }, []); useEffect(load, [load, owner]); useEffect(() => { if (approving) picker.current?.focus(); }, [approving]); function closePicker() { setApproving(null); setTenant(""); opener.current?.focus(); } useEscapeClose(approving !== null && !busy, closePicker); async function act(id: string, action: "approve" | "decline") { const request = requestScope.current?.signal; if (!request || request.aborted) return; const generation = recordsGeneration.current; if (acting.current || (action === "approve" && !companies.some((company) => company.slug === tenant))) return; acting.current = true; setBusy(true); setError(""); setNotice(""); try { const result = action === "approve" ? await approveSignupRequest(id, tenant) : await declineSignupRequest(id); if (request.aborted || generation !== recordsGeneration.current) return; if (!result.ok) { window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: result.message, tone: "error" } })); return; } setRequests((rows) => rows?.filter((row) => row.id !== id) ?? null); setApproving(null); setTenant(""); if (action === "approve" && result.data.request.deliveryStatus === "failed") { window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: "Approved. The invitation could not be delivered.", tone: "error" }, })); } else setNotice(action === "decline" ? "Request declined." : "Request approved."); } finally { if (!request.aborted && generation === recordsGeneration.current) { acting.current = false; setBusy(false); } } } return ( <section className="signup-requests" aria-labelledby="signup-requests-title"> <div className="signup-requests-head"> <h4 id="signup-requests-title" className="padmin-h4">Sign-up requests</h4> <button className="signup-quiet set-secondary" type="button" onClick={load} disabled={busy || requests === null && !error}>Refresh</button> </div> {error ? <div className="set-error" role="alert"><span title={error}>Could not load sign-up requests.</span> <button type="button" className="set-secondary" disabled={busy} onClick={load}>Retry</button></div> : null} {notice ? <p className="set-help" role="status">{notice}</p> : null} {requests === null ? error ? null : <Skeleton rows={3} /> : requests.length === 0 ? ( <p className="set-help">No requests.</p> ) : ( <ul aria-label="Sign-up requests"> {requests.map((request) => { const stamp = new Date(request.at); const validTime = !Number.isNaN(stamp.getTime()); return ( <li className="signup-request" key={request.id}> <div className="signup-request-row"> <div> <span className="signup-request-phone">{request.phone}</span> <time dateTime={validTime ? request.at : undefined}> {validTime ? stamp.toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "Time unavailable"} </time> </div> <p className="signup-request-text">{request.text}</p> <div className="signup-request-actions"> <button className="signup-quiet set-secondary" type="button" disabled={busy} aria-label={`Approve request from ${request.phone}`} aria-expanded={approving === request.id} onClick={(event) => { opener.current = event.currentTarget; setApproving(request.id); setTenant(""); setError(""); }}>Approve</button> <button className="signup-quiet set-secondary" type="button" disabled={busy} aria-label={`Decline request from ${request.phone}`} onClick={() => void act(request.id, "decline")}>Decline</button> </div> </div> {approving === request.id ? ( <form className="signup-approval" aria-label="Choose company" onSubmit={(event) => { event.preventDefault(); void act(request.id, "approve"); }}> <label htmlFor="signup-company">Company</label> <select id="signup-company" ref={picker} value={tenant} required disabled={busy} onChange={(event) => setTenant(event.target.value)}> <option value="">Choose company</option> {companies.map((company) => <option key={company.slug} value={company.slug}>{company.name}</option>)} </select> <div className="signup-request-actions"> <button className="signup-primary set-secondary" type="submit" disabled={busy || !tenant} aria-busy={busy}>Approve</button> <button className="signup-quiet set-secondary" type="button" disabled={busy} onClick={closePicker}>Cancel</button> </div> {companies.length === 0 ? <p className="set-help">No companies available.</p> : null} </form> ) : null} </li> ); })} </ul> )} </section> ); } export function AdminPane({ user }: { user: { username: string; name: string; role: string } }) { const [ov, setOv] = useState<Overview | null>(null); const [err, setErr] = useState(""); const [loading, setLoading] = useState(true); const [fleet, setFleet] = useState<{ rows: AutomationRow[]; cost: FleetCost } | null>(null); const [fleetError, setFleetError] = useState(""); const [drill, setDrill] = useState<{ kind: DrillKind; tenant: string } | null>(null); const [drillRows, setDrillRows] = useState<unknown[] | null>(null); const [drillNote, setDrillNote] = useState(""); const [drillError, setDrillError] = useState(""); const [aws, setAws] = useState<{ text: string; note: string; available: boolean } | null>(null); // Wave 20 (R6): the releases panel. Loaded with the overview rather than on demand — it is // two small Hub reads and the first question an operator opens this pane to answer. const [rel, setRel] = useState<ReleasesPayload | null>(null); const [relError, setRelError] = useState(""); const [awsBusy, setAwsBusy] = useState(false); const [neon, setNeon] = useState<NeonUsage | null>(null); const [neonError, setNeonError] = useState(""); const [digitalOcean, setDigitalOcean] = useState<DigitalOceanUsage | null>(null); const [digitalOceanError, setDigitalOceanError] = useState(""); const load = useCallback(() => { setLoading(true); setErr(""); setOv(null); setFleet(null); setFleetError(""); setRel(null); setRelError(""); setNeon(null); setNeonError(""); setDigitalOcean(null); setDigitalOceanError(""); void getOverview().then((r) => { setLoading(false); if (r.ok) { setOv(r.data); setErr(""); } else setErr(r.message); }); void getAutomations().then((r) => { if (r.ok) setFleet({ rows: r.data.automations, cost: r.data.cost }); else setFleetError(r.message); }); void getReleases().then((r) => { if (r.ok) setRel(r.data); else setRelError(r.message); }); void getNeon().then((r) => { if (r.ok) { setNeon(r.data); setNeonError(""); } else setNeonError(r.message); }); void getDigitalOcean().then((r) => { if (r.ok) { setDigitalOcean(r.data); setDigitalOceanError(""); } else setDigitalOceanError(r.message); }); }, []); useEffect(load, [load]); const openDrill = useCallback((kind: DrillKind, tenant: string) => { setDrill({ kind, tenant }); setDrillRows(null); setDrillNote(""); setDrillError(""); const fetcher = kind === "users" ? getUsers : kind === "databases" ? getDatabases : kind === "connectors" ? getConnectors : getAutomations; void fetcher(tenant || undefined).then((r) => { if (!r.ok) { setDrillRows([]); setDrillError(r.message); return; } const d = r.data as Record<string, unknown>; setDrillRows((d[kind] as unknown[]) ?? []); // The server's own honest note travels with the rows rather than being // re-invented here: it is the one that knows WHY a tenant is missing. const errors = (d.errors as Record<string, string>) ?? {}; const words = Object.entries(errors).map(([t, e]) => `${t}: ${e}`); setDrillNote( [typeof d.stampsNote === "string" ? d.stampsNote : "", ...words] .filter(Boolean) .join(" · ") ); }); }, []); const loadAws = useCallback(() => { setAwsBusy(true); void getAws(7).then((r) => { setAwsBusy(false); if (r.ok) setAws(r.data.report); else setAws({ text: "", note: r.message, available: false }); }); }, []); return ( <div className="set-pane"> <h3 className="set-h">Loopable admin</h3> <p className="set-help set-pane-intro">Signed in as {user.name}.</p> <div className="set-actions"> <button type="button" className="set-primary" disabled={loading} onClick={load}>Refresh</button> </div> {err ? <div className="set-error" role="alert"><span title={err}>Could not read the platform overview.</span> <button type="button" className="set-secondary" onClick={load}>Retry</button></div> : null} {fleetError ? <div className="set-error" role="alert"><span title={fleetError}>Could not read automation costs.</span> <button type="button" className="set-secondary" onClick={load}>Retry</button></div> : null} {relError ? <div className="set-error" role="alert"><span title={relError}>Could not read releases.</span> <button type="button" className="set-secondary" onClick={load}>Retry</button></div> : null} <SignupRequests tenants={ov?.tenants ?? []} owner={user.username} /> {loading ? ( <Skeleton rows={4} /> ) : !ov ? null : ( <> <div className="padmin-totals"> <Total label="Workspaces" value={int(ov.totals.tenants)} /> <Total label="People" value={int(ov.totals.users)} /> <Total label="Databases" value={int(ov.totals.databases)} /> <Total label="Records" value={int(ov.totals.rows)} /> <Total label="Automation floor" value={fleet ? (fleet.cost.usd === 0 ? "$0.00 idle" : `~$${fleet.cost.usd.toFixed(2)}`) : "Cost has not loaded"} hint={fleet?.cost.basis} /> </div> {ov.totals.unknownTenants > 0 ? ( <p className="set-help padmin-caveat"> {ov.totals.unknownTenants} workspace {ov.totals.unknownTenants === 1 ? "" : "s"} could not be read, so the totals above exclude {ov.totals.unknownTenants === 1 ? "it" : "them"}. </p> ) : null} <div className="padmin-tablewrap"> <table className="padmin-table"> <thead> <tr> <th>Workspace</th> <th>Storage</th> <th className="padmin-num">People</th> <th className="padmin-num">Databases</th> <th className="padmin-num">Records</th> <th className="padmin-num">Sources</th> <th className="padmin-num">Automations</th> </tr> </thead> <tbody> {ov.tenants.map((t) => ( <tr key={t.slug}> <td> <span className="padmin-name">{t.name}</span> <span className="padmin-meta"> {t.slug} {t.status !== "active" ? ` · ${t.status}` : ""} {t.errors && t.errors.length ? ` · ${t.errors[0]}` : ""} </span> </td> <td> <span className="padmin-meta"> {t.storeRepo && t.storeRepo.includes("/") ? "own repository" : t.storePrefix ? "shared repository" : "tenant #0 repository"} {t.keychainLocked ? " · keychain locked" : ""} </span> </td> <DrillCell n={t.users} onOpen={() => openDrill("users", t.slug)} title={`${t.admins} administrator${t.admins === 1 ? "" : "s"}`} /> <DrillCell n={t.databases} onOpen={() => openDrill("databases", t.slug)} why={t.errors?.[0]} /> <DrillCell n={t.rows} onOpen={() => openDrill("databases", t.slug)} why={t.errors?.[0]} /> <DrillCell n={t.connectors} onOpen={() => openDrill("connectors", t.slug)} why={t.errors?.[0]} title={ t.connectorsPaused ? `${t.connectorsPaused} paused` : "none paused" } /> <DrillCell n={t.automations} onOpen={() => openDrill("automations", t.slug)} why={t.errors?.[0]} title={ t.automationsEnabled != null ? `${t.automationsEnabled} scheduled` : undefined } /> </tr> ))} </tbody> </table> </div> <p className="set-help padmin-caveat"> Read {ago(ov.generatedAt)} in {ov.tookMs} ms.{" "} {ov.totals.orphanUsers > 0 ? `${ov.totals.orphanUsers} account${ ov.totals.orphanUsers === 1 ? "" : "s" } belong to a workspace this deployment no longer knows. ` : ""} </p> {drill ? ( <section className="padmin-drill"> <div className="padmin-drill-head"> <h4 className="padmin-h4"> {DRILL_NOUN[drill.kind]} {drill.tenant ? `: ${drill.tenant}` : ""} </h4> <button type="button" className="padmin-link set-secondary" onClick={() => setDrill(null)}> Close </button> </div> {drillError ? <div className="set-error" role="alert"><span title={drillError}>Could not read these rows.</span> <button type="button" className="set-secondary" onClick={() => openDrill(drill.kind, drill.tenant)}>Retry</button></div> : drillRows === null ? ( <Skeleton rows={2} /> ) : drillRows.length === 0 ? ( <p className="set-help">Nothing here yet.</p> ) : ( <DrillTable kind={drill.kind} rows={drillRows} /> )} {drillNote ? <p className="set-help padmin-caveat">{drillNote}</p> : null} </section> ) : null} {!fleet && !fleetError ? <section className="padmin-block"> <h4 className="padmin-h4">Automation cost</h4> <Skeleton rows={2} /> </section> : fleet ? ( <section className="padmin-block"> {/* Named for what it SHOWS. The fleet's rows live one level down, behind the Automations count — this section is the cost and the reasoning behind it, so calling it "fleet" would promise a table that is deliberately not here. */} <h4 className="padmin-h4">Automation cost</h4> <p className="set-help"> {fleet.rows.filter((a) => a.enabled).length} automations of {fleet.rows.length} {`, ${fleet.cost.nativeSchedules} exact schedule${fleet.cost.nativeSchedules === 1 ? "" : "s"}`} {fleet.cost.fleetRunsPerDay ? `, about ${fleet.cost.fleetRunsPerDay} runs a day` : ""} {fleet.cost.unknownCadence ? ` (${fleet.cost.unknownCadence} on a custom cadence, not counted)` : ""} . {fleet.cost.basis} </p> </section> ) : null} {/* ── Wave 20 (owner item 12 / R6): what is running where ────────────────── READ-ONLY BY RULING. The operator sees both environments and every cut release; moving one is a CLI command, printed below rather than wired to a button, so no browser session can rewrite production. */} <section className="padmin-block"> <h4 className="padmin-h4">Releases</h4> {relError ? null : !rel ? ( <Skeleton rows={2} /> ) : ( <> <table className="padmin-table"> <thead> <tr> <th>Environment</th> <th>Version</th> <th>Stage</th> <th>Space</th> </tr> </thead> <tbody> {rel.environments.map((e) => ( <tr key={e.env}> <td>{e.env === "live" ? "Live (pinned)" : "Staging (follows the tree)"}</td> {/* ⚠ An unreadable version is a NOTE, never a blank. A blank cell in a column headed "Version" reads as "nothing is deployed", which about a production environment is the worst available way to be wrong. */} <td>{e.version || <span className="set-help">{e.note || "unknown"}</span>}</td> <td>{e.stage || "Stage could not be read"}</td> {/* The Space ID as TEXT, not a link: the server deliberately builds no URL (portability C1 — a host literal in runtime code hard-codes the current host into a process designed to move). */} <td>{e.space}</td> </tr> ))} </tbody> </table> {rel.releases.length ? ( <table className="padmin-table"> <thead> <tr> <th>Release</th> <th>Commit</th> <th>Cut</th> <th>What shipped</th> </tr> </thead> <tbody> {rel.releases.map((r) => ( <tr key={r.version}> <td>{r.version}</td> <td>{r.sha}</td> <td>{r.date}</td> <td>{r.subject}</td> </tr> ))} </tbody> </table> ) : ( <p className="set-help"> No tagged releases were readable from either Space. </p> )} <p className="set-help"> To move Live to another version, or roll it back, run:{" "} <code>{rel.promote}</code> </p> </> )} </section> <section className="padmin-block"> <h4 className="padmin-h4">AWS cron</h4> {awsBusy ? <Skeleton rows={2} /> : !aws ? ( <p className="set-help"> The external tick that wakes this app on schedule. Reading its usage runs a live CloudWatch query and takes a few seconds.{" "} <button type="button" className="padmin-link set-secondary" onClick={loadAws} disabled={awsBusy} > {awsBusy ? "Reading…" : "Check usage"} </button> </p> ) : aws.available ? ( <pre className="padmin-pre">{aws.text}</pre> ) : ( <div className="set-error" role="alert"><span title={aws.note}>Could not read AWS usage.</span> <button type="button" className="set-secondary" disabled={awsBusy} onClick={loadAws}>Retry</button></div> )} </section> </> )} <NeonCard data={neon} error={neonError} onRetry={load} /> <DigitalOceanCard data={digitalOcean} error={digitalOceanError} onRetry={load} /> </div> ); } function Total({ label, value, hint }: { label: string; value: string; hint?: string }) { // A tooltip nobody can see is a tooltip nobody reads: the label carries a // dotted underline exactly when there is something behind it. return ( <div className={"padmin-total" + (hint ? " has-hint" : "")} title={hint || undefined}> <span className="padmin-total-label">{label}</span> <span className="padmin-total-value">{value}</span> </div> ); } /** A numeric cell that opens its own rows. Unknown counts are not clickable — * there is nothing to drill INTO when the read failed, and a button that opens * an empty table would read as "none". */ function DrillCell({ n, onOpen, why, title, }: { n: number | null | undefined; onOpen: () => void; why?: string; title?: string; }) { if (n === null || n === undefined) return ( <td className="padmin-num"> <Count n={n} why={why} /> </td> ); return ( <td className="padmin-num"> <button type="button" className="padmin-drill-btn set-secondary" onClick={onOpen} title={title}> {int(n)} </button> </td> ); } function DrillTable({ kind, rows }: { kind: DrillKind; rows: unknown[] }) { if (kind === "users") { const rs = rows as PlatformUser[]; return ( <div className="padmin-tablewrap"> <table className="padmin-table"> <thead> <tr> <th>Person</th> <th>Workspace</th> <th>Role</th> <th>Last sign-in</th> <th>Last active</th> </tr> </thead> <tbody> {rs.map((u) => ( <tr key={`${u.tenant}/${u.username}`}> <td> <span className="padmin-name">{u.name}</span> <span className="padmin-meta"> {u.username} {u.email ? ` · ${u.email}` : ""} {u.active ? "" : " · deactivated"} </span> </td> <td>{u.tenant}</td> <td> {u.role} {u.platformAdmin ? " · platform" : ""} </td> <td>{ago(u.lastLogin)}</td> <td>{ago(u.lastActive)}</td> </tr> ))} </tbody> </table> </div> ); } if (kind === "databases") { const rs = rows as DatabaseRow[]; return ( <div className="padmin-tablewrap"> <table className="padmin-table"> <thead> <tr> <th>Database</th> <th>Workspace</th> <th>Built from</th> <th className="padmin-num">Fields</th> <th className="padmin-num">Records</th> </tr> </thead> <tbody> {rs.map((d) => ( <tr key={`${d.tenant}/${d.key}`}> <td> <span className="padmin-name">{d.label}</span> <span className="padmin-meta"> {d.key} {d.createdBy ? ` · ${d.createdBy}` : ""} </span> </td> <td>{d.tenant}</td> <td>{d.source}</td> <td className="padmin-num">{int(d.fields)}</td> <td className="padmin-num">{int(d.rowCount)}</td> </tr> ))} </tbody> </table> </div> ); } if (kind === "connectors") { const rs = rows as ConnectorRow[]; return ( <div className="padmin-tablewrap"> <table className="padmin-table"> <thead> <tr> <th>Source</th> <th>Workspace</th> <th>Kind</th> <th>Status</th> </tr> </thead> <tbody> {rs.map((c) => ( <tr key={`${c.tenant}/${c.key}`}> <td> <span className="padmin-name">{c.label}</span> <span className="padmin-meta"> {c.source === "env" ? "environment credentials" : "keychain"} </span> </td> <td>{c.tenant}</td> <td>{c.type}</td> <td> <span className={ "padmin-dot " + (c.paused ? "is-paused" : c.active ? "is-live" : "is-idle") } /> {c.paused ? "paused" : c.active ? "serving" : "stored"} </td> </tr> ))} </tbody> </table> </div> ); } const rs = rows as AutomationRow[]; return ( <div className="padmin-tablewrap"> <table className="padmin-table"> <thead> <tr> <th>Automation</th> <th>Workspace</th> <th>Schedule</th> <th className="padmin-num">Runs a day</th> <th>Last run</th> </tr> </thead> <tbody> {rs.map((a) => ( <tr key={`${a.tenant}/${a.id}`}> <td> <span className="padmin-name">{a.name}</span> <span className="padmin-meta"> {a.kind} {a.failedRetained ? ` · ${a.failedRetained} of the last ${a.runsRetained} runs failed` : ""} </span> </td> <td>{a.tenant}</td> <td>{a.enabled ? a.cron || "scheduled" : "paused"}</td> <td className="padmin-num"> {a.enabled ? (a.runsPerDay === null ? "custom" : a.runsPerDay) : "Disabled"} </td> <td> <span className={ "padmin-dot " + (a.state === "error" ? "is-error" : a.state === "ok" ? "is-live" : "is-idle") } /> {/* Verbatim, not relative: the engine writes this stamp with no zone (`automation_engine._iso()` is naive local-to-container), so "x hours ago" would be wrong by the viewer's offset. */} {a.lastRunAt ? a.lastRunAt.replace("T", " ") : "never"} </td> </tr> ))} </tbody> </table> </div> ); } export default AdminPane;
// ---------------------------------------------------------------------------
// settings / AdminPane.tsx — THE LOOPABLE ADMIN PLANE (wave 19, owner item 13 /
// R3+R4, contract C2).
//
// The one surface in this product that looks ACROSS tenants: who our customers
// are, how many people use each workspace, what they have built in it, whether
// their data sources are alive, and what the automation fleet costs.
//
// SELF-CONTAINED BY CONTRACT (C2). It fetches its own data via
// `platformAdminApi` and takes ONE prop, so mounting it is a rail entry plus a
// line in the pane switch — `SettingsModal.tsx` is another session's file this
// wave and must not have to learn anything about this pane's data.
//
// ⚠ THE PROP IS TYPED STRUCTURALLY, not as `SessionUser` from `../shell/session`.
// The mount site passes the shell's session user (a wider object), which
// satisfies this shape by structural typing — and this pane therefore imports
// nothing from the shell, which is what the wave's cross-fence rule asks for
// while `session.ts` is open on another desk.
//
// ⛔ EVERY NUMBER HERE IS THE SERVER'S, AND EVERY NUMBER DRILLS. Clicking a count
// opens the rows it was computed from — the same collector, projected twice
// ([[no-unverifiable-aggregates]]). A count that could not be READ renders as an
// its cause, never as a zero: "this customer has no databases" and
// "we could not look" are different facts and the pane refuses to conflate them.
//
// DESIGN: sentence-case micro-labels (R6 — no caps in app chrome), short noun
// headers, tabular figures right-aligned, hairlines not shadows, tokens only,
// no emojis (DESIGN.md §2–§4).
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT } from "../apiContract";
import { useEscapeClose } from "../ui/useEscapeClose";
import "../signup/signup.css";
import type {
AutomationRow,
ConnectorRow,
DatabaseRow,
FleetCost,
Overview,
PlatformUser,
ReleasesPayload,
SignupRequest,
TenantRow,
} from "./platformAdminApi";
import {
getAutomations,
getAws,
getReleases,
getConnectors,
getDatabases,
getOverview,
getUsers,
getSignupRequests,
approveSignupRequest,
declineSignupRequest,
} from "./platformAdminApi";
// --- formatting -------------------------------------------------------------
const int = (n: number) => n.toLocaleString();
/** A count that may be unknown. `null` is NOT zero — see the api module's header. */
function Count({ n, why }: { n: number | null | undefined; why?: string }) {
if (n === null || n === undefined)
return (
<span className="padmin-unknown" title={why || "This could not be read just now"}>
Unknown
</span>
);
return <>{int(n)}</>;
}
/** "3 days ago" for a stamp, "never" for an absent one. Never a fabricated date.
*
* ⛔ ONLY FOR OFFSET-BEARING STAMPS. `Date.parse` reads a stamp with no zone as
* BROWSER-LOCAL, so running a container-local timestamp through this reports the
* viewer's UTC offset as elapsed time — hours of error in a column people scan,
* and a future-dated stamp that renders as "just now" indefinitely. Everything
* this pane passes here (`last_login`, `last_active`, `generatedAt`) is written
* with an explicit offset; the automation engine's `lastRunAt` is NOT, so it is
* rendered verbatim instead. */
function ago(stamp: string): string {
if (!stamp) return "never";
const t = Date.parse(stamp.includes("T") ? stamp : stamp.replace(" ", "T"));
if (Number.isNaN(t)) return stamp;
const mins = Math.floor((Date.now() - t) / 60000);
if (mins < 2) return "just now";
if (mins < 60) return `${mins} minutes ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
const days = Math.floor(hours / 24);
if (days < 60) return `${days} day${days === 1 ? "" : "s"} ago`;
return `${Math.floor(days / 30)} months ago`;
}
type DrillKind = "users" | "databases" | "connectors" | "automations";
const DRILL_NOUN: Record<DrillKind, string> = {
users: "People",