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 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 19:03:47 +07:00
parent da46453c13
commit d7fe99edd7
9 changed files with 310 additions and 10 deletions

View File

@@ -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);
}

View File

@@ -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<String>,
grants: Vec<MyGrant>,
/// Ids of the relations this person may refresh through (everything, for an administrator).
refresh_relations: Vec<String>,
}
/// 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 }),
))
}

View File

@@ -356,6 +356,11 @@ was shown: `REFRESH <source> TO <target> v<version>`. 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`

View File

@@ -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

View File

@@ -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<HUDMode, string> = {
activity: "Activity",
access: "Access",
relations: "Refresh relations",
refresh: "Refresh staging",
reconstitute: "Restore snapshot",
snapshot: "Snapshot detail",
};
@@ -47,10 +49,11 @@ const panelLabels: Record<HUDMode, string> = {
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<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, reconstitute: 760, snapshot: 640 };
const panelWidths: Record<HUDMode, number> = { 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 <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
return (
<OperatorGate>
{(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
? <RefreshOnly actor={operator.actor} onLogout={operator.onLogout} />
: <VaultApp {...operator} />}
</OperatorGate>
);
}
function RefreshOnly({ actor, onLogout }: { actor?: string; onLogout?: () => Promise<void> }) {
return (
<main className="vault-app mx-auto min-h-screen max-w-3xl p-5">
<header className="flex items-center justify-between py-4">
<div>
<p className="instrument-label">Tessera / Refresh</p>
<h1 className="text-2xl font-semibold text-star-100">Refresh staging</h1>
</div>
<div className="flex items-center gap-3 text-sm text-star-300">
{actor && <span>{actor}</span>}
{onLogout && <button type="button" className="console-control" onClick={() => void onLogout()}>Sign out</button>}
</div>
</header>
<RefreshView />
</main>
);
}
function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise<void>; 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 && (
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
{mode === "refresh" && caps.refresh && (
<SpringPane key="refresh"><RefreshView /></SpringPane>
)}
{mode === "relations" && caps.admin && (
<SpringPane key="relations"><RelationsView /></SpringPane>
)}

View File

@@ -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<Me> {
@@ -125,6 +127,27 @@ export const grantRelationAccess = (id: string, grant: { principal_type: "user"
api<RelationGrant>(`/api/v1/relations/${id}/access`, json("POST", grant));
export const revokeRelationAccess = (id: string, grant: string) => api<void>(`/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<RefreshRelation[]>("/api/v1/refresh-relations");
export const fetchRefreshRuns = () => api<RefreshRun[]>("/api/v1/refresh-runs");
export const startRefresh = (relation: RefreshRelation, idempotency_key: string) =>
api<RefreshRun>("/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<RefreshRun>(`/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 `{}`. */

View File

@@ -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",

View File

@@ -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))),

View File

@@ -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<string, string> = {
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<string, string> = {
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<string, string> = {
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<string, string> = {
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 <p role="status" className="p-6 text-star-300">Loading…</p>;
if (relations.isError) {
return <p role="alert" className="p-6 text-star-300">You have not been given a database to refresh, or this hub does not support it.</p>;
}
return (
<div className="space-y-8 p-6">
<p className="text-sm text-star-300">
A refresh takes a new backup of the source and replaces the contents of its staging database with it. The source is only read.
</p>
{list.length === 0 && <p className="text-star-300">Nothing to refresh yet.</p>}
{list.map((relation) => (
<RelationCard key={relation.id} relation={relation} runs={history.filter((r) => r.relation_id === relation.id)}
onChanged={() => void qc.invalidateQueries({ queryKey: ["refresh-runs"] })} />
))}
</div>
);
}
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<string>(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 (
<section className="rounded-xl border border-space-700 p-5" aria-label={`${relation.source_name} to ${relation.target_name}`}>
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-lg font-semibold text-star-100">
{relation.target_name}
<span className="ml-2 text-sm font-normal text-star-300">({relation.target_environment ?? "?"}) is refreshed from {relation.source_name} ({relation.source_environment ?? "?"})</span>
</h3>
{!relation.usable && <p className="text-sm text-orbit-red">Not available right now. Ask an administrator.</p>}
</div>
{seen && (
<div className="mt-4" role="status" aria-live="polite">
<p className={seen.tone === "bad" ? "font-medium text-orbit-red" : "font-medium text-star-100"}>{seen.title}</p>
{seen.detail && <p className="mt-1 text-sm text-star-300">{seen.detail}</p>}
{running && (
<progress className="mt-3 block h-1 w-full" aria-label="Refresh progress"
value={latest.status === "capturing" ? 1 : latest.restore_phase === "applying" ? 3 : 2} max={4} />
)}
</div>
)}
<div className="mt-4 flex flex-wrap items-center gap-3">
{!confirming && !running && (
<Button variant="primary" disabled={!relation.usable} onClick={() => setConfirming(true)}>Refresh {relation.target_name}</Button>
)}
{running && latest && (
<Button disabled={cancel.isPending || overwriting} onClick={() => cancel.mutate(latest.id)}>
{overwriting ? "Overwriting: cannot cancel" : "Cancel"}
</Button>
)}
</div>
{confirming && !running && (
<form className="mt-4 space-y-3 rounded-lg border border-space-700 p-4" onSubmit={(e) => { e.preventDefault(); if (understood) start.mutate(); }}>
<p className="text-sm text-star-100">
This replaces <strong>everything</strong> in <strong>{relation.target_name}</strong> with a fresh copy of <strong>{relation.source_name}</strong>.
Anything that exists only in {relation.target_name} is lost. {relation.source_name} is only read.
</p>
<label className="flex items-start gap-2 text-sm text-star-300">
<input type="checkbox" checked={understood} onChange={(e) => setUnderstood(e.target.checked)} className="mt-1" />
<span>I understand that {relation.target_name} will be overwritten.</span>
</label>
<div className="flex gap-2">
<Button type="button" onClick={() => { setConfirming(false); setUnderstood(false); }}>Not now</Button>
<Button type="submit" variant="danger" disabled={!understood || start.isPending}>{start.isPending ? "Starting…" : `Overwrite ${relation.target_name}`}</Button>
</div>
</form>
)}
{refusal && <p role="alert" className="mt-3 text-sm text-orbit-red">{refusal}</p>}
{cancel.isError && <p role="alert" className="mt-3 text-sm text-orbit-red">It could not be cancelled: it has already started overwriting.</p>}
{runs.length > 1 && (
<details className="mt-4 text-sm text-star-300">
<summary className="cursor-pointer">Earlier refreshes</summary>
<ul className="mt-2 space-y-1">
{runs.slice(1, 8).map((run) => <li key={run.id}>{when(run.created_at)}: {describe(run).title}</li>)}
</ul>
</details>
)}
</section>
);
}