From d7fe99edd7db9b4b9f495dc02534d6c78646b511 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Sat, 14 Nov 2026 19:03:47 +0700 Subject: [PATCH] feat: refresh console for QA and refresh-only access (auth M6d) - web: Refresh console (relation cards, overwrite confirmation, progress, cancel, distinct failure messages), rail item, and a single-screen view for people who may only refresh - hub: refresh-only users are authorized; /me exposes refresh_relations - docs and auth plan record the real rehearsal (Postgres, agent, Keycloak, browser) and what was not verified Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-hub/src/api/refresh_tests.rs | 19 ++ crates/tessera-hub/src/api/session.rs | 19 +- docs/DATABASE-CAPTURE.md | 5 + tasks/auth-plan.md | 8 + web/src/App.tsx | 48 ++++- web/src/api.ts | 23 +++ web/src/components/hud/HUDRail.tsx | 8 +- web/src/components/operator/OperatorGate.tsx | 7 + web/src/components/refresh/RefreshView.tsx | 183 +++++++++++++++++++ 9 files changed, 310 insertions(+), 10 deletions(-) create mode 100644 web/src/components/refresh/RefreshView.tsx diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 221f7f1..19b8056 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -673,3 +673,22 @@ async fn a_target_that_is_the_source_or_a_production_database_is_refused_when_th assert_eq!(lab.run(&run).blocked_reason.as_deref(), Some("target_matches_a_production_source")); assert_eq!(lab.restore_jobs(), 0); } + +#[tokio::test] +async fn someone_who_may_only_refresh_gets_into_the_app_but_sees_nothing_else() { + let lab = fresh().await; + let nobody = lab.person("nobody"); + let status = lab.send(&nobody, "GET", "/api/v1/operator/session", None).await.1; + assert_eq!((status["authorized"].clone(), status["admin"].clone()), (json!(false), json!(false)), "no grant at all: closed"); + let (qa, _) = lab.refresher("qa"); + let status = lab.send(&qa, "GET", "/api/v1/operator/session", None).await.1; + assert_eq!((status["authorized"].clone(), status["admin"].clone()), (json!(true), json!(false)), "a relation grant opens the app"); + let me = lab.send(&qa, "GET", "/api/v1/me", None).await.1; + assert_eq!(me["refresh_relations"], json!([lab.relation.clone()])); + assert_eq!(me["grants"].as_array().unwrap().len(), 0, "and carries no orbit permission"); + // nothing about orbits, snapshots or restores is visible to them + for path in ["/api/v1/orbits", "/api/v1/snapshots", "/api/v1/capture-jobs", "/api/v1/restore-jobs", "/api/v1/relations"] { + assert_eq!(lab.send(&qa, "GET", path, None).await.0, StatusCode::FORBIDDEN, "{path}"); + } + assert_eq!(lab.send(&qa, "GET", "/api/v1/refresh-relations", None).await.0, StatusCode::OK); +} diff --git a/crates/tessera-hub/src/api/session.rs b/crates/tessera-hub/src/api/session.rs index 6f8c306..1158adc 100644 --- a/crates/tessera-hub/src/api/session.rs +++ b/crates/tessera-hub/src/api/session.rs @@ -43,11 +43,14 @@ async fn status( let browser = state.sessions.active(&headers); // The app opens for an administrator or for anyone holding a live grant that lets them read an orbit. let reads_something = browser.as_ref().is_some_and(|session| { + let now = chrono::Utc::now().timestamp(); !session.admin - && state + && (state .db - .permitted_orbits(Some(&session.user_id), &session.groups, "orbit.read", chrono::Utc::now().timestamp()) + .permitted_orbits(Some(&session.user_id), &session.groups, "orbit.read", now) .is_ok_and(|p| p.everywhere || !p.orbits.is_empty()) + // someone who may only refresh a staging database still gets in, to that one screen + || state.db.granted_relations(Some(&session.user_id), &session.groups, now).is_ok_and(|r| !r.is_empty())) }); let authorized = browser.as_ref().is_some_and(|session| session.admin) || reads_something || (browser.is_none() && !state.sessions.enabled() && state.admin.token.is_none() @@ -82,6 +85,8 @@ struct Me { admin: bool, capabilities: Vec, grants: Vec, + /// Ids of the relations this person may refresh through (everything, for an administrator). + refresh_relations: Vec, } /// The caller's own identity. Every authenticated principal is an administrator @@ -113,9 +118,17 @@ async fn me( names }; capabilities.sort(); + let refresh_relations = if actor.subject.admin { + vec![] + } else { + state + .db + .granted_relations(actor.subject.user_id.as_deref(), &actor.subject.groups, chrono::Utc::now().timestamp()) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + }; Ok(( no_store(), - Json(Me { id, kind, auth_method, display_name: actor.name.clone(), admin: actor.subject.admin, capabilities, grants }), + Json(Me { id, kind, auth_method, display_name: actor.name.clone(), admin: actor.subject.admin, capabilities, grants, refresh_relations }), )) } diff --git a/docs/DATABASE-CAPTURE.md b/docs/DATABASE-CAPTURE.md index 20462fd..b1dae45 100644 --- a/docs/DATABASE-CAPTURE.md +++ b/docs/DATABASE-CAPTURE.md @@ -356,6 +356,11 @@ was shown: `REFRESH TO v`. The caller never picks the overwritten); 3. follows the restore job to its end. +In the web UI, people holding a relation grant use **Refresh** (administrators find it in the rail too). Someone whose +only permission is a relation grant gets that single screen: the vault screens are not loaded for them, since every +request would be refused. The screen shows what will be overwritten, requires an explicit confirmation, follows the +run, and lets the person cancel until the target starts being overwritten. + States: `capturing`, `restoring`, then `completed`, or `capture_failed`, `restore_failed`, `blocked` (with a reason), `expired`, `cancelled`, `recovery_required` (the restore was interrupted after it started overwriting: an administrator must reconcile it), `reconciled`. A target has at most one run in progress; a second request answers `409 run_active` diff --git a/tasks/auth-plan.md b/tasks/auth-plan.md index 1387363..2d3c223 100644 --- a/tasks/auth-plan.md +++ b/tasks/auth-plan.md @@ -117,6 +117,14 @@ Hasil: QA menekan "Refresh staging" dan melihat progres; developer mengunduh `.g - Rehearsal nyata: PostgreSQL production sintetis dan staging di Docker, agen nyata, capture → restore, bandingkan skema dan data, revoke di tengah run, retry, unduh `.gz` dan muat ulang. Selesai bila: e2e browser untuk QA dan developer dengan assertion API deny, dan hasilnya dicatat di sini. +Hasil (selesai, belum di-commit): +- Backend: orang yang hanya punya grant relasi (tanpa `orbit.read`) kini `authorized` (bisa masuk aplikasi) dan `/me.refresh_relations` memuat relasinya; semua endpoint vault tetap 403. Tes baru `someone_who_may_only_refresh_gets_into_the_app_but_sees_nothing_else`. Hub 120 tes hijau, web 75 tes, typecheck dan build bersih. +- UI: konsol "Refresh" (`components/refresh/RefreshView.tsx`): kartu per relasi, peringatan staging ditimpa + kotak centang sebelum tombol aktif, kunci idempotensi per percobaan, progres dari fase capture/restore, "data per" waktu snapshot, tombol batal (nonaktif saat menimpa), pesan terpisah untuk capture_failed / restore_failed / recovery_required / blocked (dengan alasan) / expired / cancelled. Item rail "Refresh" untuk admin dan pemegang grant; yang hanya boleh refresh mendapat layar tunggal tanpa memuat query vault. +- Rehearsal nyata (data sintetis; PostgreSQL 14.25 prod + staging di Docker, hub dan agen nyata, jalur payload langsung karena `rest-server` tidak ada): refresh admin selesai; skema dan data staging identik dengan prod (dump tanpa baris `\restrict` cocok); staging yang berisi tabel dan baris asing kembali persis seperti prod. Relasi dihapus di tengah run -> `blocked: relation_ended`, staging tidak berubah (baris sentinel tetap). Relasi baru + run ulang -> selesai, sentinel hilang, baris baru prod muncul. +- Browser nyata (Keycloak 26.1, Vite -> hub): `qa` "No access yet" -> admin memberi grant relasi -> layar Refresh saja; centang + Overwrite -> progres -> selesai, staging terisi data prod terbaru; request jaringan hanya `refresh-relations`/`refresh-runs`, tanpa 403. Dari sesi QA: orbits/snapshots/capture-jobs/restore-jobs/relations/access (users, grants)/capture-profiles 403; POST restore-jobs 403; POST relations (body valid) 403; refresh dengan konfirmasi salah 409, tanpa CSRF 403, relasi tak dikenal 404; respons relasi hanya id, versi, nama, environment, usable. Grant dicabut -> UI kembali ke "No access yet" pada poll berikutnya. `dev` (viewer 1 orbit): 1 orbit, 7 snapshot, hanya tab Vault dan Activity; refresh, relasi, restore-jobs, access semuanya 403. +- Unduhan: dump PostgreSQL custom diunduh sebagai `.dump` apa adanya (sudah terkompresi, `PGDMP`, `pg_restore --list` valid); bungkus gzip hanya untuk SQL polos, sesuai desain M6a. Jadi "unduh .gz" berlaku untuk SQL, bukan untuk format custom. +- Belum diverifikasi: tampilan admin (item rail Refresh) di browser nyata; Restic via `rest-server` TLS (agen wajib `rest:https://`, tidak ada di mesin ini); `cargo deny`/`cargo audit` tidak terpasang di shell ini (tidak ada perubahan dependensi di M6d, hasil M6c tetap berlaku). 422 untuk body kosong pada POST non-admin hanyalah urutan parse sebelum gate; dengan body valid 403. + Di luar M6: approval per refresh, masking data, restore lokal developer, multi-hub. Kebijakan data mentah: izin eksplisit adalah grant `snapshot.download` itu sendiri (UI memberi peringatan); tidak ada flag klasifikasi tambahan kecuali Sen meminta. ## M7 — Rilis diff --git a/web/src/App.tsx b/web/src/App.tsx index 9c0a847..ae155aa 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -7,9 +7,10 @@ import { } from "./api"; import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD"; import { HUDPanel } from "./components/hud/HUDPanel"; -import { accessItem, HUDRail, hudItems, relationsItem, type HUDMode } from "./components/hud/HUDRail"; +import { accessItem, HUDRail, hudItems, refreshItem, relationsItem, type HUDMode } from "./components/hud/HUDRail"; import { AccessView } from "./components/access/AccessView"; import { RelationsView } from "./components/relations/RelationsView"; +import { RefreshView } from "./components/refresh/RefreshView"; import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch"; import { OperatorGate, type Caps } from "./components/operator/OperatorGate"; import { OrbitsView } from "./components/orbits/OrbitsView"; @@ -37,6 +38,7 @@ const panelTitles: Record = { activity: "Activity", access: "Access", relations: "Refresh relations", + refresh: "Refresh staging", reconstitute: "Restore snapshot", snapshot: "Snapshot detail", }; @@ -47,10 +49,11 @@ const panelLabels: Record = { activity: "Console 04 · Activity", access: "Console 05 · Access", relations: "Console 06 · Relations", + refresh: "Console 07 · Refresh", reconstitute: "Restore from a snapshot", snapshot: "Recovery point", }; -const panelWidths: Record = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, reconstitute: 760, snapshot: 640 }; +const panelWidths: Record = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, refresh: 760, reconstitute: 760, snapshot: 640 }; const LOOK_KEY = "tessera.look"; @@ -69,7 +72,34 @@ function priority(orbit: Orbit) { } export default function App() { - return {(operator) => }; + return ( + + {(operator) => + // Someone who may only refresh a staging database has no orbits to show: give them that one screen, + // and do not load the vault screens at all (every request they make would be refused). + !operator.caps.admin && !operator.caps.orbits && operator.caps.refresh + ? + : } + + ); +} + +function RefreshOnly({ actor, onLogout }: { actor?: string; onLogout?: () => Promise }) { + return ( +
+
+
+

Tessera / Refresh

+

Refresh staging

+
+
+ {actor && {actor}} + {onLogout && } +
+
+ +
+ ); } function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise; caps: Caps }) { @@ -240,8 +270,11 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => const activity = useActivity(snaps.data, orbits.data, caps.admin); // Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access. const railItems = useMemo( - () => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")), - [caps.admin], + () => { + const base = caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity"); + return caps.refresh ? [...base.slice(0, 4), refreshItem, ...base.slice(4)] : base; + }, + [caps.admin, caps.refresh], ); const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length; @@ -281,7 +314,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => } function openConsole(next: HUDMode, target: string | null = null) { - if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot") return; + if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot" && !(next === "refresh" && caps.refresh)) return; if (next === "reconstitute" && !restoreBusy && (!restoreTarget || (target !== null && target !== restoreTarget.id))) { setRestoreTarget({ id: target }); @@ -432,6 +465,9 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => {mode === "wormhole" && caps.admin && ( )} + {mode === "refresh" && caps.refresh && ( + + )} {mode === "relations" && caps.admin && ( )} diff --git a/web/src/api.ts b/web/src/api.ts index a2bb1f4..6756886 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -69,6 +69,8 @@ export type Me = { admin: boolean; capabilities: string[]; grants: MyGrant[]; + /** Relations this person may refresh through (empty for an administrator, who may use all). */ + refresh_relations?: string[]; }; export async function fetchMe(signal?: AbortSignal): Promise { @@ -125,6 +127,27 @@ export const grantRelationAccess = (id: string, grant: { principal_type: "user" api(`/api/v1/relations/${id}/access`, json("POST", grant)); export const revokeRelationAccess = (id: string, grant: string) => api(`/api/v1/relations/${id}/access/${grant}`, { method: "DELETE" }); +export type RefreshRelation = { + id: string; version: number; source_name: string; source_environment: Environment | null; + target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null; +}; +export type RefreshRun = { + id: string; relation_id: string; source_name: string; target_name: string; status: string; blocked_reason: string | null; + capture_status: string | null; capture_phase: string | null; snapshot_taken_at: number | null; + restore_status: string | null; restore_phase: string | null; + created_at: number; updated_at: number; expires_at: number; requested_by?: string; +}; +export const fetchRefreshRelations = () => api("/api/v1/refresh-relations"); +export const fetchRefreshRuns = () => api("/api/v1/refresh-runs"); +export const startRefresh = (relation: RefreshRelation, idempotency_key: string) => + api("/api/v1/refresh-runs", json("POST", { + relation_id: relation.id, + // exactly what the person was shown, so a relation changed in the meantime is refused + confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`, + idempotency_key, + })); +export const cancelRefresh = (id: string) => api(`/api/v1/refresh-runs/${id}`, { method: "DELETE" }); + export type Look = "window" | "radar"; /** The account's saved display choices. A hub without this endpoint, or an account without one, yields `{}`. */ diff --git a/web/src/components/hud/HUDRail.tsx b/web/src/components/hud/HUDRail.tsx index 643cfb2..aa959b2 100644 --- a/web/src/components/hud/HUDRail.tsx +++ b/web/src/components/hud/HUDRail.tsx @@ -3,7 +3,7 @@ import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from " import { useScreenTransition } from "../../hooks/useScreenTransition"; import { uiSpring } from "../../lib/motion"; -export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "relations" | "reconstitute" | "snapshot"; +export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "relations" | "refresh" | "reconstitute" | "snapshot"; export const hudItems = [ { id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" }, @@ -20,6 +20,12 @@ export const accessItem: HUDItem = { icon: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z M9.5 12l2 2 3.5-4", }; +/** Start a refresh of a staging database from its production source. */ +export const refreshItem: HUDItem = { + id: "refresh", label: "Refresh", + icon: "M20 12a8 8 0 1 1-2.3-5.6 M20 4v4.5h-4.5", +}; + /** Only for administrators: which source may overwrite which target. */ export const relationsItem: HUDItem = { id: "relations", label: "Relations", diff --git a/web/src/components/operator/OperatorGate.tsx b/web/src/components/operator/OperatorGate.tsx index e0eea19..6d0dd87 100644 --- a/web/src/components/operator/OperatorGate.tsx +++ b/web/src/components/operator/OperatorGate.tsx @@ -23,12 +23,19 @@ function useSsoError() { /** What the signed-in user may do. The hub enforces it; this only decides what is worth showing. */ export type Caps = { admin: boolean; + /** Holds at least one orbit permission (so the vault screens have something to show). */ + orbits: boolean; + /** May start a refresh through at least one relation (administrators always may). */ + refresh: boolean; can: (permission: string, orbitId?: string) => boolean; }; export function capsFrom(me: Me | undefined, admin: boolean): Caps { return { admin, + orbits: admin || (Array.isArray(me?.grants) && me.grants.length > 0), + // An old hub that sends no relations leaves this to the administrator flag. + refresh: admin || (Array.isArray(me?.refresh_relations) && me.refresh_relations.length > 0), can: (permission, orbitId) => // A hub or mock that does not send grants simply grants nothing here; the server decides anyway. admin || (Array.isArray(me?.grants) && me.grants.some((g) => g.permission === permission && (g.orbit_id === null || g.orbit_id === orbitId))), diff --git a/web/src/components/refresh/RefreshView.tsx b/web/src/components/refresh/RefreshView.tsx new file mode 100644 index 0000000..420fb3f --- /dev/null +++ b/web/src/components/refresh/RefreshView.tsx @@ -0,0 +1,183 @@ +import { useRef, useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { + cancelRefresh, fetchRefreshRelations, fetchRefreshRuns, refusalReason, startRefresh, + type RefreshRelation, type RefreshRun, +} from "../../api"; +import { Button } from "../ui/Button"; + +const ACTIVE = new Set(["capturing", "restoring"]); + +const START_REFUSALS: Record = { + run_active: "A refresh of this database is already running.", + stale_confirmation: "This relation was changed while you were looking at it. Reload and check it again.", + source_unavailable: "The source cannot take a backup request right now (its Outpost is not available).", + relation_unusable: "This refresh cannot be used right now. Ask an administrator.", + too_many_runs: "Too many refreshes are running at once. Try again in a few minutes.", + key_reused: "That request was already used. Reload and try again.", +}; + +const BLOCKED: Record = { + access_revoked: "your access to this refresh was removed", + user_disabled: "your account was disabled", + relation_ended: "the relation was ended or replaced", + relation_unusable: "the relation can no longer be used", + target_matches_a_production_source: "the target looks like a production database", + target_rejected: "the target did not match the backup", + snapshot_not_restorable: "the backup could not be restored", +}; + +const CAPTURE_STEPS: Record = { + queued: "waiting for the Outpost", claimed: "the Outpost picked it up", dumping: "reading the database", + uploading: "sending the backup", completed: "done", +}; +const RESTORE_STEPS: Record = { + queued: "waiting for the Outpost", claimed: "the Outpost picked it up", checking: "checking the backup and the target", + safety: "saving a safety copy of the target", ready: "ready to overwrite", applying: "overwriting the target", + completed: "done", +}; + +function when(seconds: number | null) { + return seconds ? new Date(seconds * 1000).toLocaleString() : ""; +} + +/** What happened, in words, and what it means for the target database. */ +export function describe(run: RefreshRun): { tone: "busy" | "good" | "bad" | "plain"; title: string; detail: string } { + const target = run.target_name; + switch (run.status) { + case "capturing": + return { tone: "busy", title: "Taking a fresh backup", detail: `Reading ${run.source_name}: ${CAPTURE_STEPS[run.capture_phase ?? "queued"] ?? run.capture_phase}. ${target} is not touched yet.` }; + case "restoring": { + const phase = run.restore_phase ?? "queued"; + const overwriting = phase === "applying"; + return { tone: "busy", title: overwriting ? `Overwriting ${target}` : "Preparing the restore", + detail: `${RESTORE_STEPS[phase] ?? phase}.${overwriting ? " This can no longer be cancelled." : ` ${target} has not been changed yet.`}` }; + } + case "completed": + return { tone: "good", title: `${target} was refreshed`, detail: run.snapshot_taken_at ? `It now holds the data of ${run.source_name} as of ${when(run.snapshot_taken_at)}.` : "" }; + case "capture_failed": + return { tone: "bad", title: "The backup failed", detail: `${target} was not changed. Try again, or ask an administrator if it keeps failing.` }; + case "restore_failed": + return { tone: "bad", title: "The restore failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` }; + case "recovery_required": + return { tone: "bad", title: "The restore was interrupted", detail: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.` }; + case "blocked": + return { tone: "bad", title: "The refresh was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` }; + case "expired": + return { tone: "bad", title: "The refresh took too long to start", detail: `${target} was not changed. Start it again.` }; + case "cancelled": + return { tone: "plain", title: "The refresh was cancelled", detail: `${target} was not overwritten.` }; + case "reconciled": + return { tone: "plain", title: "An administrator recovered the target", detail: "" }; + default: + return { tone: "plain", title: run.status, detail: "" }; + } +} + +/** Start a refresh of a staging database and follow it. Everyone sees only what their grants allow. */ +export function RefreshView() { + const qc = useQueryClient(); + const relations = useQuery({ queryKey: ["refresh-relations"], queryFn: fetchRefreshRelations, refetchInterval: 15_000, retry: false }); + const runs = useQuery({ + queryKey: ["refresh-runs"], queryFn: fetchRefreshRuns, retry: false, + refetchInterval: (query) => (Array.isArray(query.state.data) && query.state.data.some((r) => ACTIVE.has(r.status)) ? 2_000 : 15_000), + }); + const list = Array.isArray(relations.data) ? relations.data : []; + const history = Array.isArray(runs.data) ? runs.data : []; + + if (relations.isPending) return

Loading…

; + if (relations.isError) { + return

You have not been given a database to refresh, or this hub does not support it.

; + } + return ( +
+

+ A refresh takes a new backup of the source and replaces the contents of its staging database with it. The source is only read. +

+ {list.length === 0 &&

Nothing to refresh yet.

} + {list.map((relation) => ( + r.relation_id === relation.id)} + onChanged={() => void qc.invalidateQueries({ queryKey: ["refresh-runs"] })} /> + ))} +
+ ); +} + +function RelationCard({ relation, runs, onChanged }: { relation: RefreshRelation; runs: RefreshRun[]; onChanged: () => void }) { + const latest = runs[0]; + const running = !!latest && ACTIVE.has(latest.status); + const [confirming, setConfirming] = useState(false); + const [understood, setUnderstood] = useState(false); + // One key per attempt: a double click or a retry after a network error starts a single run. + const key = useRef(crypto.randomUUID()); + const start = useMutation({ + mutationFn: () => startRefresh(relation, key.current), + onSuccess: () => { setConfirming(false); setUnderstood(false); key.current = crypto.randomUUID(); onChanged(); }, + }); + const cancel = useMutation({ mutationFn: (id: string) => cancelRefresh(id), onSuccess: onChanged }); + const seen = latest ? describe(latest) : undefined; + const overwriting = running && latest?.restore_phase === "applying"; + const refusal = start.isError ? START_REFUSALS[refusalReason(start.error) ?? ""] ?? "The refresh could not be started." : undefined; + + return ( +
+
+

+ {relation.target_name} + ({relation.target_environment ?? "?"}) is refreshed from {relation.source_name} ({relation.source_environment ?? "?"}) +

+ {!relation.usable &&

Not available right now. Ask an administrator.

} +
+ + {seen && ( +
+

{seen.title}

+ {seen.detail &&

{seen.detail}

} + {running && ( + + )} +
+ )} + +
+ {!confirming && !running && ( + + )} + {running && latest && ( + + )} +
+ + {confirming && !running && ( +
{ e.preventDefault(); if (understood) start.mutate(); }}> +

+ This replaces everything in {relation.target_name} with a fresh copy of {relation.source_name}. + Anything that exists only in {relation.target_name} is lost. {relation.source_name} is only read. +

+ +
+ + +
+
+ )} + {refusal &&

{refusal}

} + {cancel.isError &&

It could not be cancelled: it has already started overwriting.

} + + {runs.length > 1 && ( +
+ Earlier refreshes +
    + {runs.slice(1, 8).map((run) =>
  • {when(run.created_at)}: {describe(run).title}
  • )} +
+
+ )} +
+ ); +}