feat: restore history, undo and redo in the Activity log for everyone who may refresh
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled

- Activity lists restores from refresh runs, so the Refresh permission is enough to see them; an administrator's
  restore jobs add the database, the person and the snapshot
- an undo is listed under the restore it reverses, and a redo under that undo; opening a restore or an undo opens
  its undo or redo dialog
- the dialog has an explicit undo mode: it describes what is put back instead of the snapshot that was open, and
  an interrupted restore offers Roll back
- a restore whose safety backup retention has forgotten shows "Safety backup expired" instead of a link, and the
  dialog says how long a safety copy is kept

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 20:37:21 +07:00
parent 62f0c68e89
commit d356c313ce
10 changed files with 418 additions and 79 deletions

View File

@@ -78,3 +78,112 @@ test("labels days relative to now", () => {
assert.equal(dayLabel(NOW - 86_400_000, NOW), "Yesterday");
assert.notEqual(dayLabel(NOW - 5 * 86_400_000, NOW), "Today");
});
test("lists an undo under the restore it reverses, and a redo under that undo", () => {
const snapshots = [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")];
const run = (id, job, extra = {}) => ({ id, restore_job_id: job, relation_id: "r", status: "completed", ...extra });
const refreshRuns = [
run("r1", "j1", { undo_available: false }),
run("r2", "j2", { undo: true, undo_of: "r1", undo_available: false }),
run("r3", "j3", { undo: true, undo_of: "r2", undo_available: true }),
];
const restoreJobs = [
restore("j1", "completed", "completed", "2026-11-14T03:00:00Z"),
restore("j2", "completed", "completed", "2026-11-14T04:00:00Z", { snapshot_id: "safety-1" }),
restore("j3", "completed", "completed", "2026-11-14T05:00:00Z", { snapshot_id: "safety-2" }),
];
const entries = build({ snapshots, restoreJobs, refreshRuns });
const roots = entries.filter(({ kind }) => kind === "restore");
assert.deepEqual(roots.map(({ id }) => id), ["restore-j1"], "only the restore is on its own");
const [undo] = roots[0].children;
assert.equal(undo.id, "restore-j2");
assert.equal(undo.variant, "undo");
assert.equal(undo.children[0].variant, "redo");
// the newest one can be put back, and what opening it offers is the opposite of what it did
assert.equal(undo.opens, null);
assert.equal(undo.children[0].opens.kind, "undo");
assert.equal(activityCounts(entries).running, 0);
});
test("a restore sits where its most urgent undo does, and an undo whose restore is missing stands alone", () => {
const refreshRuns = [
{ id: "r1", restore_job_id: "j1", relation_id: "r" },
{ id: "r2", restore_job_id: "j2", relation_id: "r", undo: true, undo_of: "r1" },
{ id: "r9", restore_job_id: "j9", relation_id: "r", undo: true, undo_of: "gone" },
];
const restoreJobs = [
restore("j1", "completed", "completed", "2026-11-10T03:00:00Z"),
restore("j2", "running", "safety", "2026-11-14T10:00:00Z"),
restore("j9", "completed", "completed", "2026-11-12T03:00:00Z"),
];
const entries = build({ restoreJobs, refreshRuns });
assert.deepEqual(entries.map(({ id, slotGroup }) => [id, slotGroup]), [["restore-j1", "running"], ["restore-j9", "history"]]);
assert.equal(activityCounts(entries).running, 1);
});
test("someone who may only read runs still gets the restore history, with undos under their restores", () => {
const run = (id, extra = {}) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", status: "completed", restore_phase: "completed", snapshot_taken_at: sec("2026-11-14T02:00:00Z"), created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const refreshRuns = [
run("r1"),
run("r2", { undo: true, undo_of: "r1", created_at: sec("2026-11-14T04:00:00Z"), undo_available: false }),
run("r3", { undo: true, undo_of: "r2", created_at: sec("2026-11-14T05:00:00Z"), undo_available: true }),
run("r4", { status: "restoring", restore_phase: "safety", created_at: sec("2026-11-14T11:00:00Z") }),
run("r5", { status: "recovery_required", restore_phase: "apply_failed", created_at: sec("2026-11-13T01:00:00Z") }),
run("r6", { status: "cancelled", restore_phase: null, created_at: sec("2026-11-12T01:00:00Z") }),
];
const entries = build({ refreshRuns });
assert.deepEqual(entries.map(({ id }) => id), ["restore-run-r5", "restore-run-r4", "restore-run-r1", "restore-run-r6"]);
const [locked, live, restored] = entries;
assert.equal(locked.group, "needs");
assert.equal(live.progress, 2);
assert.match(restored.title, /^ledger · .+ → staging$/);
assert.equal(restored.opens, null, "no snapshot id reaches them, and it cannot be undone any more");
const [undo] = restored.children;
assert.equal(undo.variant, "undo");
assert.equal(undo.children[0].variant, "redo");
assert.equal(undo.children[0].opens.kind, "undo");
assert.deepEqual(activityCounts(entries), { running: 1, needs: 1 });
});
test("a restore known by its run and its job is one entry, with the job's detail", () => {
const refreshRuns = [{ id: "r1", restore_job_id: "j1", relation_id: "r", source_name: "x", target_name: "y", status: "completed", created_at: sec("2026-11-14T03:00:00Z") }];
const entries = build({
snapshots: [snapshot("s1", "media-vault", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns,
}).filter(({ kind }) => kind === "restore");
assert.equal(entries.length, 1);
assert.match(entries[0].title, /pg-staging \/ orders$/);
});
test("a restore whose safety backup expired says so instead of leading anywhere", () => {
const run = (id, extra = {}) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", status: "completed", restore_phase: "completed", created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const gone = build({ refreshRuns: [run("r1", { undo_state: "expired", undo_available: false })] })[0];
assert.equal(gone.opens, null);
assert.equal(gone.note, "Safety backup expired");
// an administrator's restore job would normally open its snapshot; expired, it must not suggest the copy is there
const withJob = build({
snapshots: [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns: [run("r1", { restore_job_id: "j1", undo_state: "expired" })],
}).find(({ id }) => id === "restore-j1");
assert.equal(withJob.opens, null);
assert.equal(withJob.note, "Safety backup expired");
// superseded is not expired: its copy may still be there, and it keeps its normal link
const old = build({
snapshots: [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns: [run("r1", { restore_job_id: "j1", undo_state: "superseded" })],
}).find(({ id }) => id === "restore-j1");
assert.deepEqual(old.opens, { kind: "snapshot", id: "s1" });
});
test("an interrupted restore that can be rolled back says so, and a rolled back one is marked", () => {
const run = (id, extra) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const [locked] = build({ refreshRuns: [run("r1", { status: "recovery_required", restore_phase: "apply_failed", undo_available: true })] });
assert.equal(locked.group, "needs");
assert.match(locked.meta, /roll back available/);
assert.equal(locked.opens.kind, "undo");
const [done] = build({ refreshRuns: [run("r2", { status: "reconciled", restore_phase: "rolled_back" })] });
assert.equal(done.state, "Rolled back");
});

View File

@@ -59,3 +59,10 @@ test("restore points are named by environment, and by target only when two share
);
assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd");
});
test("an interrupted restore offers a rollback only when its safety copy can be used", () => {
const names = { target: "Staging" };
const stuck = { status: "recovery_required", restore_phase: "apply_failed" };
assert.match(outcomeOf({ ...stuck, undo_available: true }, names).detail, /roll it back/i);
assert.match(outcomeOf(stuck, names).detail, /administrator has to recover/i);
});

View File

@@ -3,7 +3,7 @@ import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences,
enqueueCapture, runOrbit, type Orbit,
enqueueCapture, runOrbit, type Orbit, type RefreshRun,
} from "./api";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel";
@@ -91,7 +91,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null);
const [play, setPlay] = useState(true);
const [restoreBusy, setRestoreBusy] = useState(false);
const [restoreTarget, setRestoreTarget] = useState<{ id: string | null }>();
const [restoreTarget, setRestoreTarget] = useState<{ id: string | null; undo?: RefreshRun }>();
const reducedMotion = useReducedMotion();
const tools = useRef<HTMLDivElement>(null);
useScreenTransition(tools, bigScreen, reducedMotion);
@@ -237,7 +237,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined }
: undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]);
const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId);
const activity = useActivity(snaps.data, orbits.data, caps.admin);
const activity = useActivity(snaps.data, orbits.data, { admin: caps.admin, refresh: caps.refresh });
// 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")),
@@ -293,6 +293,12 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
setMode(next);
}
/** Open the dialog that puts back a restore (or undo) shown in the Activity log. */
function openUndo(run: RefreshRun) {
if (!restoreBusy) setRestoreTarget({ id: null, undo: run });
setMode("reconstitute");
}
function selectSearchResult(result: SearchResult) {
if (result.kind === "navigation") openConsole(result.id);
else if (result.kind === "snapshot") openSnapshot(result.id);
@@ -424,7 +430,8 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
entries={activity.entries} counts={activity.counts} updatedAt={activity.updatedAt}
restoresUnavailable={activity.restoresUnavailable} capturesUnavailable={activity.capturesUnavailable}
onOpen={(target) => {
if (target.kind === "snapshot") openSnapshot(target.id);
if ("run" in target) openUndo(target.run);
else if (target.kind === "snapshot") openSnapshot(target.id);
else {
selectOrbit(target.id);
setMode("scene");
@@ -454,7 +461,18 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
)}
</AnimatePresence>
<SpringPane active={mode === "reconstitute"}>
{restoreSnapshot
{restoreTarget?.undo
? (
<RestoreWizard
key={restoreTarget.undo.id}
undo={restoreTarget.undo}
relations={restorePoints.filter((r) => r.id === restoreTarget.undo!.relation_id)}
admin={caps.admin}
onBusyChange={setRestoreBusy}
onDone={() => setMode("activity")}
/>
)
: restoreSnapshot
? (
<RestoreWizard
key={restoreSnapshot.id}

View File

@@ -139,6 +139,14 @@ export type RefreshRun = {
undo?: boolean;
/** A completed restore that can still be undone (the newest of its target, safety copy still there). */
undo_available?: boolean;
/** Why a restore with a safety copy can or cannot be put back: `expired` means retention has forgotten the copy. */
undo_state?: "available" | "superseded" | "expired";
/** While it can be undone: when its safety copy is first at risk of being forgotten (seconds since the epoch). */
undo_kept_until?: number;
/** For an undo: the run whose restore it puts back. */
undo_of?: string;
/** The restore job this run queued. */
restore_job_id?: string;
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;

View File

@@ -6,14 +6,14 @@ import { Segmented } from "../ui/Segmented";
type Kind = "all" | "backup" | "restore";
const PAGE = 80;
function Row({ entry, now, onOpen }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void }) {
function Row({ entry, now, onOpen, depth = 0 }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void; depth?: number }) {
const opens = entry.opens;
const content = (
<>
<span className="act-time">{entry.group === "running" && entry.id.startsWith("orbit-") ? "now" : entry.at === null ? "—" : clock(entry.at)}</span>
<span className="act-kind" data-kind={entry.kind}>
<i className="act-glyph" data-tone={entry.tone} aria-hidden="true" />
{entry.kind === "backup" ? "Backup" : "Restore"}
{entry.kind === "backup" ? "Backup" : entry.variant === "redo" ? "Redo" : entry.variant === "undo" ? "Undo" : "Restore"}
</span>
<span className="act-text">
<span className="act-title">{entry.title}</span>
@@ -29,14 +29,24 @@ function Row({ entry, now, onOpen }: { entry: ActivityEntry; now: number; onOpen
</span>
)}
</span>
<span className="act-open">{opens ? `${opens.kind} ›` : "removed"}</span>
<span className="act-open" data-note={!opens && entry.note ? "true" : undefined}>{opens ? `${opens.kind} ›` : entry.note ?? (depth ? "" : "removed")}</span>
</>
);
void now;
return opens ? (
<button type="button" className="act-row" data-group={entry.group} data-tone={entry.tone} onClick={() => onOpen(opens)}>{content}</button>
<button type="button" className="act-row" data-group={entry.group} data-tone={entry.tone} data-child={depth || undefined} style={depth ? { "--depth": depth } as React.CSSProperties : undefined} onClick={() => onOpen(opens)}>{content}</button>
) : (
<div className="act-row" data-group={entry.group} data-tone={entry.tone} data-static="true">{content}</div>
<div className="act-row" data-group={entry.group} data-tone={entry.tone} data-child={depth || undefined} style={depth ? { "--depth": depth } as React.CSSProperties : undefined} data-static="true">{content}</div>
);
}
/** A restore with its undos beneath it, each indented one step under what it reverses. */
function Tree({ entry, now, onOpen, depth = 0 }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void; depth?: number }) {
return (
<>
<Row entry={entry} now={now} onOpen={onOpen} depth={depth} />
{entry.children?.map((next) => <Tree key={next.id} entry={next} now={now} onOpen={onOpen} depth={depth + 1} />)}
</>
);
}
@@ -58,23 +68,26 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
}, []);
const term = query.trim().toLowerCase();
const matching = entries.filter((entry) =>
(kind === "all" || entry.kind === kind) && (!term || `${entry.title} ${entry.meta}`.toLowerCase().includes(term)));
const visible = matching.slice(0, Math.max(shown, matching.filter(({ group }) => group !== "history").length));
// A restore stays in the log when it or any undo under it matches, so an undo is never shown without its restore.
const matches = (entry: ActivityEntry): boolean =>
((kind === "all" || entry.kind === kind) && (!term || `${entry.title} ${entry.meta}`.toLowerCase().includes(term)))
|| (entry.children ?? []).some(matches);
const matching = entries.filter(matches);
const visible = matching.slice(0, Math.max(shown, matching.filter(({ slotGroup }) => slotGroup !== "history").length));
const sections: { label: string; tone?: string; items: ActivityEntry[] }[] = [];
for (const entry of visible) {
const label = entry.group === "needs" ? "Needs you" : entry.group === "running" ? "Running now"
: entry.at === null ? "Earlier" : dayLabel(entry.at, now);
const label = entry.slotGroup === "needs" ? "Needs you" : entry.slotGroup === "running" ? "Running now"
: entry.slotAt === null ? "Earlier" : dayLabel(entry.slotAt, now);
const last = sections.at(-1);
if (last?.label === label) last.items.push(entry);
else sections.push({ label, tone: entry.group === "history" ? undefined : entry.group, items: [entry] });
else sections.push({ label, tone: entry.slotGroup === "history" ? undefined : entry.slotGroup, items: [entry] });
}
const age = updatedAt ? Math.max(0, Math.round((now - updatedAt) / 1000)) : undefined;
return (
<div className="activity">
<div className="activity-bar">
<p className="activity-lead">One log of everything that has run or is running. Open an entry to see its snapshot; restores and exports start there.</p>
<p className="activity-lead">One log of everything that has run or is running. Open a backup to restore it; open a restore to undo it. Undos are listed under the restore they reverse.</p>
<dl className="activity-counts">
<div><dt><i className="act-glyph" data-tone="amber" aria-hidden="true" />Running</dt><dd>{counts.running}</dd></div>
<div data-alert={counts.needs > 0}><dt><i className="act-glyph" data-tone="red" aria-hidden="true" />Needs you</dt><dd>{counts.needs}</dd></div>
@@ -94,7 +107,7 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
</div>
{(restoresUnavailable || capturesUnavailable) && (
<p role="alert" className="activity-warning">
{restoresUnavailable ? "Restore history is unavailable. This hub may be too old to list restore jobs." : "Outpost backup jobs are unavailable."}
{restoresUnavailable ? "Restore history is unavailable. This hub may be too old to list restore runs." : "Outpost backup jobs are unavailable."}
{" "}The rest of the log is still shown.
</p>
)}
@@ -102,7 +115,7 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
{sections.map((section) => (
<section key={section.label} aria-label={section.label}>
<h3 data-tone={section.tone}>{section.label}</h3>
{section.items.map((entry) => <Row key={entry.id} entry={entry} now={now} onOpen={onOpen} />)}
{section.items.map((entry) => <Tree key={entry.id} entry={entry} now={now} onOpen={onOpen} />)}
</section>
))}
{!sections.length && (

View File

@@ -3,7 +3,7 @@ import { motion } from "motion/react";
import { useQuery } from "@tanstack/react-query";
import { cancelRefresh, fetchRefreshRun, fetchRefreshRuns, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format";
import { isFinal, outcomeOf, progressOf, relationLabels, STAGES } from "../../lib/restoreRun";
import { isFinal, outcomeOf, progressOf, relationLabels, STAGES, undoDepth, undoVerb } from "../../lib/restoreRun";
import { Button } from "../ui/Button";
import { Segmented } from "../ui/Segmented";
import { DatabaseRestore } from "../reconstitute/DatabaseRestore";
@@ -28,23 +28,30 @@ type Phase = "idle" | "countdown" | "running";
* when there are several), presses Begin restore, has ten seconds to abort, and then follows four steps until the
* target holds the backup. Administrators can still restore to any other registered target.
*/
export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
snapshot: Snapshot;
export function RestoreWizard({ snapshot, undo, relations, admin, onBusyChange, onDone }: {
/** The snapshot to restore. Absent when the dialog was opened from a restore in the Activity log, to undo it. */
snapshot?: Snapshot;
/** The restore (or undo) this dialog was opened to put back. */
undo?: RefreshRun;
/** The relations from this snapshot's orbit that the person may restore through. */
relations: RefreshRelation[];
admin: boolean;
onBusyChange: (busy: boolean) => void;
/** Leave the dialog once a run opened for an undo has finished. */
onDone?: () => void;
}) {
const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]);
const [pointId, setPointId] = useState(points[0]?.id ?? "");
const [pointId, setPointId] = useState(undo?.relation_id ?? points[0]?.id ?? "");
const point = points.find((p) => p.id === pointId) ?? points[0];
const [phase, setPhase] = useState<Phase>("idle");
const [left, setLeft] = useState(COUNTDOWN);
const [runId, setRunId] = useState<string>();
const [refusal, setRefusal] = useState<string>();
const [other, setOther] = useState(false);
// Set while an undo is being started or followed: the run whose restore is being put back.
const [undoOf, setUndoOf] = useState<string>();
// Set while an undo is being started or followed: the restore (or undo) being put back. Its presence is the
// wizard's undo mode, which shows what is being put back instead of the snapshot the person opened.
const [undoRun, setUndoRun] = useState<RefreshRun | undefined>(undo);
const undoOf = undoRun?.id;
// One key per attempt: the same press can never start two restores, even if the request is retried.
const attempt = useRef(globalThis.crypto?.randomUUID?.() ?? String(Math.random()));
@@ -69,7 +76,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
if (left <= 0) {
setPhase("running");
if (!point) return;
startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot.id })
startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot!.id })
.then((started) => setRunId(started.id))
.catch((error) => {
setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started.");
@@ -80,55 +87,80 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
}
const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000);
return () => clearTimeout(timer);
}, [phase, left, point, snapshot.id, undoOf]);
}, [phase, left, point, snapshot?.id, undoOf]);
const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2);
const abort = async () => {
if (phase === "countdown") {
setPhase("idle");
setUndoRun(undo);
setLeft(COUNTDOWN);
} else if (runId) {
try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ }
}
};
const again = () => {
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoOf(undefined);
// Opened to undo one restore: once it is done there is nothing left to do here.
if (!snapshot && onDone) { onDone(); return; }
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoRun(undefined);
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
};
// The newest restore on the chosen restore point, if it can still be undone.
const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, enabled: phase === "idle", retry: false, refetchInterval: 15_000 });
const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, retry: false, refetchInterval: 15_000 });
const runsById = new Map((Array.isArray(recent.data) ? recent.data : []).map((r) => [r.id, r]));
const undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined;
const beginUndo = (of: string) => {
setRefusal(undefined); setRunId(undefined); setUndoOf(of); setLeft(COUNTDOWN); setPhase("countdown");
const beginUndo = (of: RefreshRun) => {
setRefusal(undefined); setRunId(undefined); setUndoRun(of); setLeft(COUNTDOWN); setPhase("countdown");
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
};
const radius = 52;
const circumference = 2 * Math.PI * radius;
const target = point?.label ?? "the database";
const outcome = run.data && finished ? outcomeOf(run.data, { target, orbit: snapshot.orbit_name, when: formatWhen(snapshot.taken_at) }) : undefined;
const database = snapshot.capture;
const outcome = run.data && finished ? outcomeOf(run.data, { target, orbit: snapshot?.orbit_name, when: snapshot ? formatWhen(snapshot.taken_at) : undefined }) : undefined;
const database = snapshot?.capture;
const undoing = !!undoRun;
// An undo of an undo puts back what the first undo replaced, so it is a redo.
const verb = (r: RefreshRun) => undoVerb(undoDepth(r, runsById));
// What a run was: a restore, the undo of one, or the redo of that undo.
const what = (r: RefreshRun) => { const depth = undoDepth(r, runsById); return depth === 0 ? "restore" : depth % 2 === 1 ? "undo" : "redo"; };
const undoneAt = undoRun ? formatWhen(new Date(undoRun.updated_at * 1000).toISOString()) : "";
return (
<div className="restore-layout">
<div className="restore-top">
<p className="restore-lead">Review the restore point before starting.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span>
<div className="min-w-0">
<p className="restore-snap-name">{snapshot.orbit_name}</p>
<p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p>
</div>
</div>
{undoRun ? (
<>
<p className="restore-lead">{verb(undoRun)} the last {what(undoRun)} on {target}.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">↺</span>
<div className="min-w-0">
<p className="restore-snap-name">{target} as it was before {undoneAt}</p>
<p className="restore-snap-meta">From the safety copy taken just before that {what(undoRun)}</p>
</div>
</div>
</>
) : snapshot && (
<>
<p className="restore-lead">Review the restore point before starting.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span>
<div className="min-w-0">
<p className="restore-snap-name">{snapshot.orbit_name}</p>
<p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p>
</div>
</div>
</>
)}
</div>
{other && admin && database ? (
<DatabaseRestore snapshot={snapshot.id} application={database.application_id} applicationName={snapshot.orbit_name} engine={database.engine} />
{other && admin && database && snapshot ? (
<DatabaseRestore snapshot={snapshot!.id} application={database.application_id} applicationName={snapshot?.orbit_name ?? ""} engine={database.engine} />
) : (
<>
<div className="restore-fields">
<div>
<div hidden={undoing}>
<p className="field-label mb-1.5">Restore point</p>
{points.length > 1 ? (
<Segmented label="Restore point" value={point?.id ?? ""} disabled={phase !== "idle"} onChange={setPointId}
@@ -139,19 +171,27 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
</div>
<div className="restore-warning" role="note">
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 2 14.5 13.5h-13Z" /><path d="M8 6.5v3M8 11.5v.01" /></svg>
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot.orbit_name} itself is only read.</p>
{undoing ? (
<p>This replaces everything on {target} with its state from before {undoneAt}. Whatever changed on {target} since is lost, but its current state is kept as a new safety copy, so this can be reversed too.</p>
) : (
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot?.orbit_name} itself is only read. What {target} holds now is kept as a safety copy first, for at least a week, so the restore can be undone.</p>
)}
</div>
<div className="flex gap-2.5">
<Button variant="danger" className="flex-1" disabled={!abortable} onClick={() => void abort()}>Abort</Button>
<Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setUndoOf(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}>
Begin restore
<Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}>
{undoRun ? `Begin ${verb(undoRun).toLowerCase()}` : "Begin restore"}
</Button>
</div>
{refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>}
{undoable && phase === "idle" && !runId && (
{undoable && !undoRun && phase === "idle" && !runId && (
<div className="restore-undo">
<p>The last restore on {target} was {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}. Its safety copy can put {target} back as it was before.</p>
<Button onClick={() => beginUndo(undoable.id)}>Undo last restore</Button>
<p>
{undoable.undo ? `${target} was last put back (${what(undoable)}) on` : `${target} was last restored on`} {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}.
{" "}{`${verb(undoable)} returns it to what it held before.`}
{undoable.undo_kept_until ? ` Its safety copy is kept at least until ${formatWhen(new Date(undoable.undo_kept_until * 1000).toISOString())}.` : ""}
</p>
<Button onClick={() => beginUndo(undoable)}>{`${verb(undoable)} last ${what(undoable)}`}</Button>
</div>
)}
{admin && database && phase === "idle" && !runId && (
@@ -161,7 +201,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<aside className="restore-status">
<p className="restore-status-label">{phase === "running" ? "Progress" : "Countdown"}</p>
{phase === "idle" && <p className="restore-idle">No restore is running. Begin restore to start the countdown.</p>}
{phase === "idle" && <p className="restore-idle">Nothing is running. Begin to start the countdown.</p>}
{phase === "countdown" && (
<motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
<div className="restore-ring">
@@ -172,7 +212,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
</svg>
<span className="restore-ring-text"><b>{left}</b><i>seconds</i></span>
</div>
<p className="restore-count-note">{undoOf ? `Undoing the last restore on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}<br />Abort restores nothing.</p>
<p className="restore-count-note">{undoRun ? `${verb(undoRun)}ing on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}<br />Abort restores nothing.</p>
</motion.div>
)}
{phase === "running" && (
@@ -200,8 +240,8 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<p>{outcome.title}</p>
<p>{outcome.detail}</p>
<div className="flex flex-wrap gap-2">
{run.data?.undo_available && <Button onClick={() => beginUndo(run.data!.id)}>Undo this restore</Button>}
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button>
{run.data?.undo_available && <Button variant="primary" onClick={() => beginUndo(run.data!)}>{run.data.status === "recovery_required" ? "Roll back" : run.data.undo ? verb(run.data) : "Undo this restore"}</Button>}
<Button onClick={again}>{outcome.tone === "good" ? "Done" : "Try again"}</Button>
</div>
</div>
)}

View File

@@ -1,27 +1,32 @@
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { fetchCaptureJobs, fetchRecentRestoreJobs, type Orbit, type Snapshot } from "../api";
import { fetchCaptureJobs, fetchRecentRestoreJobs, fetchRefreshRuns, type Orbit, type Snapshot } from "../api";
import { activityCounts, buildActivity } from "../lib/activity";
/** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], canSeeRestores = true) {
// Restore history is administrator-only; asking would only produce a 403.
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: canSeeRestores });
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], { admin = true, refresh = true } = {}) {
// Restore jobs carry databases and people, so only administrators may read them; asking would only produce a 403.
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: admin });
// Which restore an undo reverses, and which of them can still be put back.
const runs = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, refetchInterval: 5_000, retry: false, enabled: refresh });
const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 });
const restoreData = restores.data;
const captureData = captures.data;
const runData = Array.isArray(runs.data) ? runs.data : undefined;
const entries = useMemo(() => buildActivity({
snapshots: snapshots ?? [],
orbits: orbits ?? [],
captureJobs: captureData ?? [],
restoreJobs: restoreData ?? [],
refreshRuns: runData ?? [],
now: Date.now(),
}), [snapshots, orbits, captureData, restoreData]);
}), [snapshots, orbits, captureData, restoreData, runData]);
return {
entries,
counts: activityCounts(entries),
restoresUnavailable: canSeeRestores && restores.isError,
// Runs are enough to list restores; jobs only add detail for an administrator.
restoresUnavailable: refresh ? runs.isError && (!admin || restores.isError) : admin && restores.isError,
capturesUnavailable: captures.isError,
updatedAt: Math.max(restores.dataUpdatedAt, captures.dataUpdatedAt),
updatedAt: Math.max(restores.dataUpdatedAt, runs.dataUpdatedAt, captures.dataUpdatedAt),
};
}

View File

@@ -979,11 +979,14 @@ button:disabled { cursor: default; }
.activity-list h3 { padding: 10px 16px 6px; background: #0b0d10; border-bottom: 1px solid #1f2327; font: 500 9.5px/1.4 var(--font-mono); letter-spacing: .14em; text-transform: uppercase; color: var(--quiet); }
.activity-list h3[data-tone="needs"] { color: var(--color-orbit-red); }
.activity-list h3[data-tone="running"] { color: var(--color-orbit-amber); }
.act-row { width: 100%; box-sizing: border-box; display: grid; grid-template-columns: 56px 82px minmax(0, 1fr) 188px 84px; gap: 14px; align-items: center; min-height: 52px; padding: 6px 16px; border-bottom: 1px solid #1a1d21; text-align: left; }
.act-row { width: 100%; box-sizing: border-box; display: grid; grid-template-columns: 56px 82px minmax(0, 1fr) 188px minmax(84px, max-content); gap: 14px; align-items: center; min-height: 52px; padding: 6px 16px; border-bottom: 1px solid #1a1d21; text-align: left; }
button.act-row:hover { background: #14171b; }
.act-row[data-group="needs"] { background: #1a1214; box-shadow: inset 2px 0 var(--color-orbit-red); }
button.act-row[data-group="needs"]:hover { background: #20161a; }
.act-row[data-static] { opacity: .65; }
.act-row[data-child] { position: relative; padding-left: calc(16px + 24px * var(--depth, 1)); background: #0c0e11; }
.act-row[data-child]::before { content: ""; position: absolute; left: calc(24px * var(--depth, 1)); top: 0; bottom: 50%; width: 10px; border-left: 1px solid #3a3f46; border-bottom: 1px solid #3a3f46; border-bottom-left-radius: 6px; }
.act-open[data-note] { color: var(--quiet); font-style: italic; text-align: right; }
.act-time { font: 11px var(--font-mono); color: var(--quiet); }
.act-kind { display: flex; align-items: center; gap: 7px; font: 500 9.5px/1 var(--font-mono); letter-spacing: .1em; text-transform: uppercase; }
.act-kind[data-kind="backup"] { color: #9db8e8; }

View File

@@ -1,8 +1,12 @@
import type { CaptureJob, Orbit, RestoreJob, Snapshot } from "../api";
import type { CaptureJob, Orbit, RefreshRun, RestoreJob, Snapshot } from "../api";
import { formatBytes, formatWhen } from "./format.ts";
import { undoDepth } from "./restoreRun.ts";
/** Where an entry leads. Restores and exports start from a snapshot, so that is where most entries go. */
export type ActivityTarget = { kind: "snapshot" | "orbit"; id: string };
export type ActivityTarget =
| { kind: "snapshot" | "orbit"; id: string }
/** A restore (or undo) that can still be put back: opens the undo (or redo) dialog for this run. */
| { kind: "undo" | "redo"; run: RefreshRun };
export type ActivityEntry = {
id: string;
@@ -17,8 +21,19 @@ export type ActivityEntry = {
opens: ActivityTarget | null;
/** Position along the five phases of a job in flight, 0 to 4. */
progress?: number;
/** Said in place of the link, when the entry leads nowhere on purpose (for instance, its safety backup expired). */
note?: string;
/** An undo (a restore put back) or a redo (an undo put back), shown under the restore it reverses. */
variant?: "undo" | "redo";
/** The undo or redo of this restore, oldest first. They are listed under it, not on their own. */
children?: ActivityEntry[];
/** Where the entry sits in the log: its own group and time, or the most urgent and newest of its subtree. */
slotGroup: "needs" | "running" | "history";
slotAt: number | null;
};
type Draft = Omit<ActivityEntry, "slotGroup" | "slotAt" | "children"> & { children?: Draft[] };
const captureLabels: Record<string, string> = {
queued: "Waiting for outpost",
claimed: "Assigned to agent",
@@ -41,6 +56,7 @@ const restoreLabels: Record<string, string> = {
wrong_target: "Target identity check failed",
invalid_payload: "Archive check failed",
safety_failed: "Safety copy could not be verified",
rolled_back: "Rolled back",
apply_failed: "Apply failed",
lease_lost: "Agent disconnected during apply",
reconciled: "Recovery verified",
@@ -48,23 +64,36 @@ const restoreLabels: Record<string, string> = {
};
const restoreOrder: string[][] = [["queued", "claimed"], ["checking"], ["safety"], ["ready", "applying"], ["completed", "reconciled"]];
const EXPIRED = "Safety backup expired";
const shortId = (id: string) => id.slice(0, 8);
const inFlight = (status: string) => status === "queued" || status === "running" || status === "applying";
function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>): ActivityEntry {
function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>, run: RefreshRun | undefined, runs: Map<string, RefreshRun>): Draft {
const source = snapshots.get(job.snapshot_id);
const from = source ? `${source.orbit_name} · ${formatWhen(source.taken_at)}` : `Snapshot ${shortId(job.snapshot_id)}`;
const phase = restoreLabels[job.phase] ?? job.status;
const depth = run ? undoDepth(run, runs) : 0;
// What this row did (an undo, then a redo of it, then an undo of that) and what opening it offers are opposites.
const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const;
const where = `${job.target.name} / ${job.target.identity.database}`;
// An undo restores the safety copy of an earlier restore, which has no snapshot to open: it opens its own dialog.
// A restore whose safety backup retention has forgotten says so, instead of leading anywhere that suggests it is there.
const expired = run?.undo_state === "expired";
const opens: ActivityTarget | null = expired ? null : run?.undo_available ? { kind: variant === "undo" ? "redo" : "undo", run }
: source ? { kind: "snapshot", id: source.id } : null;
const base = {
id: `restore-${job.id}`,
kind: "restore" as const,
variant,
at: job.created_at * 1000,
title: `${from} → ${job.target.name} / ${job.target.identity.database}`,
opens: source ? { kind: "snapshot" as const, id: source.id } : null,
title: variant ? `${variant === "redo" ? "Redo" : "Undo"} → ${where}` : `${from} → ${where}`,
opens,
note: expired ? EXPIRED : undefined,
};
if (job.status === "recovery_required") {
return { ...base, group: "needs", tone: "red", state: "Recovery required",
meta: `Restore · ${phase.toLowerCase()} · target locked until verified · open the snapshot` };
meta: `Restore · ${phase.toLowerCase()} · ${run?.undo_available ? "roll back available" : "target locked until verified · open the snapshot"}` };
}
if (inFlight(job.status)) {
const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(job.phase)));
@@ -78,11 +107,54 @@ function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>): Activi
return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: `Restore · by ${job.actor}` };
}
const recovered = job.status === "reconciled";
return { ...base, group: "history", tone: "green", state: recovered ? "Recovered" : "Complete",
meta: `Restore · ${job.safety_snapshot_id ? "safety copy kept · " : ""}by ${job.actor}` };
const rolledBack = job.phase === "rolled_back";
const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore";
const undoable = run?.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : "";
return { ...base, group: "history", tone: "green", state: rolledBack ? "Rolled back" : recovered ? "Recovered" : "Complete",
meta: `${noun} · ${job.safety_snapshot_id ? "safety copy kept · " : ""}by ${job.actor}${undoable}` };
}
function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): ActivityEntry | undefined {
/** The id a restore has in the log: its job's when it has one, so a run and its job are one entry. */
const restoreId = (run: RefreshRun) => (run.restore_job_id ? `restore-${run.restore_job_id}` : `restore-run-${run.id}`);
const runStopped: Record<string, string> = { restore_failed: "Failed", blocked: "Stopped", expired: "Expired", capture_failed: "Could not start" };
/**
* A restore as the run shows it, for people who may not read restore jobs (those are administrator-only): what was
* restored where, how far it got, and whether it can be put back. It carries no database names or who started it.
*/
function runEntry(run: RefreshRun, runs: Map<string, RefreshRun>): Draft {
const depth = undoDepth(run, runs);
const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const;
const taken = run.snapshot_taken_at ? formatWhen(new Date(run.snapshot_taken_at * 1000).toISOString()) : undefined;
const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore";
const base = {
id: restoreId(run),
kind: "restore" as const,
variant,
at: run.created_at * 1000,
title: variant ? `${noun} → ${run.target_name}` : `${run.source_name}${taken ? ` · ${taken}` : ""} → ${run.target_name}`,
opens: run.undo_available ? { kind: variant === "undo" ? "redo" as const : "undo" as const, run } : null,
// A restore known only by its run has nothing to open unless it can be put back; that is not "removed".
note: run.undo_state === "expired" ? EXPIRED : run.undo_available ? undefined : "",
};
const phase = (run.restore_phase && restoreLabels[run.restore_phase]) || undefined;
if (run.status === "recovery_required") {
return { ...base, group: "needs", tone: "red", state: "Recovery required",
meta: `${noun} · ${(phase ?? "interrupted").toLowerCase()} · ${run.undo_available ? "roll back available" : "target locked until an administrator verifies it"}` };
}
if (run.status === "capturing" || run.status === "restoring") {
const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(run.restore_phase ?? "queued")));
return { ...base, group: "running", tone: "amber", state: phase ?? "Running", progress, meta: `${noun} · step ${progress + 1} of 5` };
}
if (run.status === "cancelled") return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: noun };
const stopped = runStopped[run.status];
if (stopped) return { ...base, group: "history", tone: "red", state: stopped, meta: `${noun}${phase && run.status === "restore_failed" ? ` · ${phase.toLowerCase()}` : ""}` };
return { ...base, group: "history", tone: "green", state: run.restore_phase === "rolled_back" ? "Rolled back" : run.status === "reconciled" ? "Recovered" : "Complete",
meta: `${noun}${run.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : ""}` };
}
function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): Draft | undefined {
const orbit = orbits.get(job.profile.orbit_id);
const name = orbit?.name ?? job.profile.application_id;
const base = {
@@ -104,17 +176,35 @@ function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): ActivityEntr
return undefined;
}
export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, now }: {
const urgency = { needs: 0, running: 1, history: 2 } as const;
/** Entries sit in the log by their own group and time, except a restore, which sits by its most urgent and newest undo. */
function place(entry: Draft): ActivityEntry {
const children = entry.children?.map(place);
let slotGroup = entry.group;
let slotAt = entry.at;
for (const child of children ?? []) {
if (urgency[child.slotGroup] < urgency[slotGroup]) slotGroup = child.slotGroup;
if ((child.slotAt ?? -Infinity) > (slotAt ?? -Infinity)) slotAt = child.slotAt;
}
return { ...entry, children, slotGroup, slotAt };
}
export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, refreshRuns = [], now }: {
snapshots: readonly Snapshot[];
orbits: readonly Orbit[];
captureJobs: readonly CaptureJob[];
restoreJobs: readonly RestoreJob[];
/** The hub's restore runs: they say which restore an undo reverses. */
refreshRuns?: readonly RefreshRun[];
now: number;
}): ActivityEntry[] {
const snapshotById = new Map(snapshots.map((snapshot) => [snapshot.id, snapshot]));
const orbitById = new Map(orbits.map((orbit) => [orbit.id, orbit]));
const jobForSnapshot = new Map(captureJobs.filter((job) => job.snapshot_id).map((job) => [job.snapshot_id!, job]));
const entries: ActivityEntry[] = [];
const runByJob = new Map(refreshRuns.filter((run) => run.restore_job_id).map((run) => [run.restore_job_id!, run]));
const runById = new Map(refreshRuns.map((run) => [run.id, run]));
const entries: Draft[] = [];
for (const snapshot of snapshots) {
const job = jobForSnapshot.get(snapshot.id);
@@ -146,13 +236,40 @@ export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, now
opens: { kind: "orbit", id: orbit.id } });
}
}
for (const job of restoreJobs) entries.push(restoreEntry(job, snapshotById));
// Every restore comes from its run, which anyone with the refresh permission may read; an administrator's restore
// job adds the database, the person and the snapshot, and restores started without a run (another registered
// target) are only known by their job.
const jobById = new Map(restoreJobs.map((job) => [job.id, job]));
const parentOf = new Map<string, string>();
for (const run of refreshRuns) {
const job = run.restore_job_id ? jobById.get(run.restore_job_id) : undefined;
entries.push(job ? restoreEntry(job, snapshotById, run, runById) : runEntry(run, runById));
const parent = run.undo_of ? runById.get(run.undo_of) : undefined;
if (parent) parentOf.set(restoreId(run), restoreId(parent));
}
for (const job of restoreJobs) if (!runByJob.has(job.id)) entries.push(restoreEntry(job, snapshotById, undefined, runById));
const rank = { needs: 0, running: 1, history: 2 } as const;
return entries.sort((a, b) => rank[a.group] - rank[b.group] || (b.at ?? -Infinity) - (a.at ?? -Infinity) || a.id.localeCompare(b.id));
// An undo hangs under the restore it reverses, and a redo under that undo, when that restore is in the log.
const byId = new Map(entries.map((entry) => [entry.id, entry]));
const top: Draft[] = [];
for (const entry of entries) {
const parent = byId.get(parentOf.get(entry.id) ?? "");
if (parent && parent !== entry) (parent.children ??= []).push(entry);
else top.push(entry);
}
const oldestFirst = (entry: Draft) => { entry.children?.sort((x, y) => (x.at ?? 0) - (y.at ?? 0)); entry.children?.forEach(oldestFirst); };
top.forEach(oldestFirst);
return top.map(place)
.sort((a, b) => urgency[a.slotGroup] - urgency[b.slotGroup] || (b.slotAt ?? -Infinity) - (a.slotAt ?? -Infinity) || a.id.localeCompare(b.id));
}
export function activityCounts(entries: readonly ActivityEntry[]) {
/** Every entry in the log, undos included. */
export function flatten(entries: readonly ActivityEntry[]): ActivityEntry[] {
return entries.flatMap((entry) => [entry, ...flatten(entry.children ?? [])]);
}
export function activityCounts(all: readonly ActivityEntry[]) {
const entries = flatten(all);
return {
running: entries.filter(({ group }) => group === "running").length,
needs: entries.filter(({ group }) => group === "needs").length,

View File

@@ -2,10 +2,23 @@
export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const;
type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: boolean };
type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: boolean; undo_available?: boolean };
const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]);
/** How many undos deep a run is: a restore is 0, its undo 1, the undo of that undo 2. */
export function undoDepth(run: { undo_of?: string | null; undo?: boolean }, byId: ReadonlyMap<string, { undo_of?: string | null; undo?: boolean }>): number {
let depth = 0;
for (let at: typeof run | undefined = run, seen = 0; at?.undo && seen < 50; seen++) {
depth++;
at = at.undo_of ? byId.get(at.undo_of) : undefined;
}
return depth;
}
/** What opening a run offers: putting back a restore is an undo, putting back an undo is a redo, and so on. */
export const undoVerb = (depth: number) => (depth % 2 === 0 ? "Undo" : "Redo");
/** The step a restore job's phase belongs to. */
function stageOfPhase(phase: string | null): number {
switch (phase) {
@@ -76,7 +89,13 @@ export function outcomeOf(
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.` };
return {
tone: "bad",
title: "The restore was interrupted",
detail: run.undo_available
? `It stopped while overwriting ${target}, which may be half restored. Do not use that database: roll it back to what it held before, or ask an administrator to recover it.`
: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.`,
};
case "blocked":
return { tone: "bad", title: "The restore was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` };
case "expired":