feat: add managed database capture and operator restore

PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-10 23:26:49 +07:00
parent 30a1a9b8f0
commit 6320b6f244
96 changed files with 11061 additions and 725 deletions

View File

@@ -1,14 +1,15 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence } from "motion/react";
import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute,
runOrbit, startReconstitute, type Orbit,
enqueueCapture, runOrbit, startReconstitute, type Orbit,
} from "./api";
import { DecayView } from "./components/decay/DecayView";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel";
import { HUDRail, type HUDMode } from "./components/hud/HUDRail";
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
import { OperatorGate } from "./components/operator/OperatorGate";
import { OrbitsView } from "./components/orbits/OrbitsView";
import { WormholeView } from "./components/outposts/WormholeView";
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
@@ -20,12 +21,12 @@ import { SnapshotSheet } from "./components/vault/SnapshotSheet";
import { useReducedMotion } from "./hooks/useReducedMotion";
import { orbitStatus } from "./lib/format";
import { groupSnapshots } from "./lib/galaxyLayout";
import type { SearchResult } from "./lib/vaultSearch";
const panelTitles: Record<HUDMode, string> = {
scene: "Vault",
orbits: "Orbit management",
wormhole: "Wormhole uplink",
decay: "Snapshot retention",
reconstitute: "Restore snapshot",
snapshot: "Snapshot detail",
};
@@ -36,10 +37,17 @@ function priority(orbit: Orbit) {
}
export default function App() {
const app = useRef<HTMLDivElement>(null);
return <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
}
function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promise<void> }) {
const [logoutError, setLogoutError] = useState(false);
const workspaceScroll = useRef<number>(undefined);
const [bigScreen, setBigScreen] = useState(false);
const [mode, setMode] = useState<HUDMode>("scene");
const [searchOpen, setSearchOpen] = useState(false);
const searchTrigger = useRef<HTMLButtonElement>(null);
const searchDestination = useRef<() => HTMLElement | null>(undefined);
const panelOpen = mode !== "scene";
const [orbitId, setOrbitId] = useState<string>();
const [snapshotId, setSnapshotId] = useState<string | null>(null);
@@ -50,18 +58,40 @@ export default function App() {
const reducedMotion = useReducedMotion();
const qc = useQueryClient();
useEffect(() => {
const root = app.current;
if (!root) return;
const syncFullscreen = () => setBigScreen(document.fullscreenElement === root);
root.addEventListener("fullscreenchange", syncFullscreen);
return () => root.removeEventListener("fullscreenchange", syncFullscreen);
}, []);
useLayoutEffect(() => {
function searchKeys(event: KeyboardEvent) {
const composing = event.isComposing || event.keyCode === 229;
if (event.key === "Escape" && searchOpen) {
event.stopPropagation();
if (!composing) {
event.preventDefault();
if (!event.repeat) setSearchOpen(false);
}
} else if (!composing && (event.metaKey || event.ctrlKey) && !event.altKey &&
!event.shiftKey && event.key.toLowerCase() === "k") {
event.preventDefault();
if (!event.repeat) setSearchOpen(true);
}
}
window.addEventListener("keydown", searchKeys, true);
return () => window.removeEventListener("keydown", searchKeys, true);
}, [searchOpen]);
useLayoutEffect(() => {
if (searchOpen) {
searchDestination.current = () => searchTrigger.current;
return;
}
if (!searchDestination.current) return;
const target = searchDestination.current() ?? searchTrigger.current;
searchDestination.current = undefined;
target?.focus();
}, [searchOpen]);
useEffect(() => {
if (!bigScreen || mode !== "scene") return;
const exitOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape" && !event.defaultPrevented && !document.fullscreenElement) {
if (event.key === "Escape" && !event.defaultPrevented && !event.repeat) {
setBigScreen(false);
}
};
@@ -76,37 +106,32 @@ export default function App() {
}, [bigScreen]);
function toggleBigScreen() {
const root = app.current;
if (bigScreen) {
if (document.fullscreenElement === root) {
void document.exitFullscreen().catch(() => {});
} else {
setBigScreen(false);
}
return;
}
workspaceScroll.current = window.scrollY;
setBigScreen(true);
// The viewport layout also works when the browser declines native fullscreen.
if (document.fullscreenEnabled) void root?.requestFullscreen?.().catch(() => {});
if (!bigScreen) workspaceScroll.current = window.scrollY;
setBigScreen(!bigScreen);
}
const health = useQuery({ queryKey: ["health"], queryFn: fetchHealth, refetchInterval: 15_000, retry: 1 });
const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8_000, retry: 1 });
const orbits = useQuery({ queryKey: ["orbits"], queryFn: fetchOrbits, refetchInterval: 8_000, retry: 1 });
const capture = useMutation({
mutationFn: (target: Orbit) => runOrbit(target.id),
mutationFn: async (target: Orbit) => {
if (target.application_id) {
await enqueueCapture(target.application_id);
return null;
}
return runOrbit(target.id);
},
onSettled: () => {
void qc.invalidateQueries({ queryKey: ["orbits"] });
void qc.invalidateQueries({ queryKey: ["snapshots"] });
void qc.invalidateQueries({ queryKey: ["capture-jobs"] });
},
});
const online = health.isSuccess;
const activeId = capture.isPending ? capture.variables.id : undefined;
const sceneOrbits = useMemo(() => (orbits.data ?? []).map((orbit) =>
orbit.id === activeId ? { ...orbit, last_status: orbit.dry_run ? "rehearsing" : "running" } : orbit,
orbit.id === activeId ? { ...orbit, last_status: orbit.application_id ? "queued" : orbit.dry_run ? "rehearsing" : "running" } : orbit,
), [orbits.data, activeId]);
const register = useMemo(() => [...sceneOrbits].sort((a, b) => priority(a) - priority(b)), [sceneOrbits]);
const grouped = useMemo(() => groupSnapshots(orbits.data ?? [], snaps.data ?? []), [orbits.data, snaps.data]);
@@ -114,10 +139,12 @@ export default function App() {
const selected = sceneOrbits.find(({ id }) => id === orbitId);
const history = (selected && grouped.get(selected.id)) ?? [];
const snapshot = snaps.data?.find(({ id }) => id === snapshotId);
const completedOrbitId = capture.isSuccess ? capture.variables.id : undefined;
const arrival = useMemo(() => !reducedMotion && completedOrbitId && capture.data
? { orbitId: completedOrbitId, snapshotId: capture.data }
: undefined, [reducedMotion, completedOrbitId, capture.data]);
const captureGlow = useMotionValue(0);
const captureOrbitId = capture.variables?.id;
const captureEffect = useMemo(() => captureOrbitId && (capture.isError || capture.data)
? { 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 failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
@@ -126,8 +153,9 @@ export default function App() {
const snapshotMessage = snaps.isPending ? "Loading snapshot history…" : snaps.isError
? snaps.data ? "Showing last known snapshots." : "Snapshot history unavailable."
: history.length ? undefined : "This orbit has no snapshots yet.";
const captureLabel = capture.isPending ? capture.variables.dry_run ? "Rehearsing" : "Capturing"
const captureLabel = capture.isPending ? capture.variables.application_id ? "Queueing backup for" : capture.variables.dry_run ? "Rehearsing" : "Capturing"
: capture.isError ? "Capture failed for"
: capture.variables?.application_id ? "Backup queued for"
: capture.variables?.dry_run ? "Rehearsal complete for"
: capture.data ? "Snapshot secured from" : "Capture finished for";
const captureNotice = capture.variables && (
@@ -149,6 +177,7 @@ export default function App() {
}
function runCapture(target: Orbit) {
if (target.access === "outpost" && !target.application_id) return;
selectOrbit(target.id);
capture.mutate(target);
}
@@ -161,9 +190,28 @@ export default function App() {
setMode(next);
}
function selectSearchResult(result: SearchResult) {
if (result.kind === "navigation") openConsole(result.id);
else if (result.kind === "snapshot") openSnapshot(result.id);
else if (result.kind === "orbit") {
selectOrbit(result.id);
openConsole("scene");
}
searchDestination.current = () => {
if (result.kind === "snapshot" || (result.kind === "navigation" && result.id !== "scene")) {
return document.querySelector<HTMLElement>(".vault-dialog .dialog-heading h2");
}
if (bigScreen) return document.querySelector<HTMLElement>(".scene-screen-control");
return result.kind === "orbit" ? document.getElementById(`register-${result.id}`)
: document.querySelector<HTMLElement>(".vault-overview h1");
};
setSearchOpen(false);
}
return (
<div ref={app} className={`vault-app${bigScreen ? " big-screen" : ""}`}>
<header className="vault-topbar">
<div className={`vault-app${bigScreen ? " big-screen" : ""}`}>
<header className="vault-topbar" inert={searchOpen}>
<div className="vault-brand">
<svg viewBox="0 0 38 38" width="34" height="34" aria-hidden="true">
<circle cx="19" cy="19" r="10.5" fill="none" stroke="currentColor" opacity=".5" />
@@ -173,26 +221,40 @@ export default function App() {
<div><strong>Tessera</strong><span>Backup control</span></div>
</div>
<HUDRail active={mode === "snapshot" ? "scene" : mode} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
<p className="hub-link" role="status">
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}
</p>
<div className="vault-topbar-tools">
<p className="hub-link" role="status">
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}
</p>
{onLogout && <button type="button" className="console-control" aria-label="Sign out"
onClick={() => void onLogout().catch(() => setLogoutError(true))}>
Sign out <span className="sr-only">{actor}</span>
</button>}
{logoutError && <p role="alert" className="text-sm text-orbit-red">Could not sign out.</p>}
<button type="button" ref={searchTrigger} className="console-control search-trigger"
aria-label="Search" aria-haspopup="dialog" aria-expanded={searchOpen} aria-keyshortcuts="Meta+K Control+K"
onClick={() => setSearchOpen(true)}>
<SearchIcon />
<span>Search</span>
<kbd aria-hidden="true">⌘K / Ctrl+K</kbd>
</button>
</div>
</header>
<main className="vault-main" inert={panelOpen}>
<main className="vault-main" inert={panelOpen || searchOpen}>
<div className="vault-overview">
<div>
<p className="instrument-label overview-label"><span aria-hidden="true">◈</span> Vault / 01</p>
<h1>Orbital vault</h1>
<h1 tabIndex={-1}>Orbital vault</h1>
<p className="overview-copy">Backup jobs and recovery points</p>
</div>
<TelemetryStrip orbitCount={orbits.data?.length} failedCount={failedCount} snapCount={snaps.data?.length} totalBytes={totalBytes} />
<TelemetryStrip orbitCount={orbits.data?.length} failedCount={failedCount} snapCount={snaps.data?.length} totalBytes={totalBytes} bigScreen={bigScreen} reducedMotion={reducedMotion} />
</div>
<div className="vault-workspace">
<VaultScene
orbits={sceneOrbits} selectedOrbitId={selected?.id} recentSnapshots={history.slice(0, 3)}
flowing={play && !reducedMotion} reducedMotion={reducedMotion} arrival={arrival}
flowing={play && !reducedMotion} reducedMotion={reducedMotion} captureEffect={captureEffect} captureGlow={captureGlow} captureReady={captureReady}
bigScreen={bigScreen} onToggleBigScreen={toggleBigScreen}
onToggleFlow={() => setPlay((value) => !value)}
onSelectOrbit={(id) => {
@@ -202,21 +264,23 @@ export default function App() {
onSelectSnapshot={openSnapshot}
/>
<OrbitRegister
orbits={register} selected={selected?.id} message={orbitMessage}
orbits={register} selected={selected?.id} message={orbitMessage} bigScreen={bigScreen}
onSelect={selectOrbit} onManage={() => setMode("orbits")}
/>
<OrbitInspector
orbit={selected} snapshots={history} snapshotMessage={snapshotMessage}
highlightedId={captureEffect?.snapshotId} captureGlow={captureGlow} bigScreen={bigScreen}
onSelectSnapshot={openSnapshot}
capture={selected && (
<>
<button
type="button" className="console-control capture-button"
onClick={() => runCapture(selected)}
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy}
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy ||
(selected.access === "outpost" && !selected.application_id)}
>
<span aria-hidden="true">↘</span>
<span>{selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
<span>{selected.application_id ? "Queue backup for" : selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
</button>
{noticeInInspector && mode !== "orbits" && captureNotice}
</>
@@ -231,6 +295,7 @@ export default function App() {
<HUDPanel
open={panelOpen}
inert={searchOpen}
title={panelTitles[mode]}
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
onClose={() => setMode("scene")}
@@ -239,20 +304,17 @@ export default function App() {
{mode === "orbits" && (
<SpringPane key="orbits">
<QueryGate query={orbits}>
{() => <OrbitsView orbits={sceneOrbits} onRun={runCapture} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
{() => <OrbitsView snapshots={snaps.isSuccess ? snaps.data : undefined} orbits={sceneOrbits} onRun={runCapture} onOpenSnapshot={openSnapshot} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
</QueryGate>
</SpringPane>
)}
{mode === "wormhole" && (
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
{mode === "decay" && (
<SpringPane key="decay"><DecayView orbits={sceneOrbits} /></SpringPane>
)}
{mode === "snapshot" && (
<SpringPane key="snapshot">
{snapshot
? <SnapshotSheet snap={snapshot} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
? <SnapshotSheet snap={snapshot} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
</SpringPane>
)}
@@ -261,7 +323,7 @@ export default function App() {
{restoreTarget && (snaps.data?.length || restoreBusy ? (
<ReconstituteWizard
key={restoreTarget.id ?? "manual"}
snapshots={snaps.data ?? []} selected={restoreTarget.id}
snapshots={snaps.data ?? []} selected={restoreTarget.id} scopedExport={!!actor}
onStart={startReconstitute} onPoll={pollReconstitute} onAbort={abortReconstitute} onBusyChange={setRestoreBusy}
/>
) : (
@@ -271,6 +333,14 @@ export default function App() {
))}
</SpringPane>
</HUDPanel>
<VaultSearch
open={searchOpen} reducedMotion={reducedMotion}
orbits={orbits.data} snapshots={snaps.data}
orbitStatus={orbits.isPending ? "Loading orbits…" : orbits.isError
? orbits.data ? "Showing last known orbits." : "Orbits unavailable." : undefined}
snapshotStatus={snaps.isPending || snaps.isError ? snapshotMessage : undefined}
onClose={() => setSearchOpen(false)} onSelect={selectSearchResult}
/>
</div>
);
}

View File

@@ -4,18 +4,27 @@ export type Snapshot = {
taken_at: string;
orbit_name: string;
size_bytes: number;
capture?: { job_id: string; application_id: string; engine: "postgres" | "mysql"; format: string; restore_ready: boolean } | null;
};
export type BackupSource = "filesystem" | "database";
export type BackupAccess = "hub" | "outpost";
export type Orbit = {
id: string;
name: string;
provider: string;
provider_config?: string;
source: BackupSource | null;
access: BackupAccess;
last_status: string;
dry_run: boolean;
schedule?: string | null;
decay_preset?: string;
retention?: RetentionPolicy | null;
application_id?: string | null;
capture_schedule?: { hour: number; minute: number; timezone: string } | null;
capture_retention?: { mode: "age"; days: number } | { mode: "count"; keep: number } | null;
retention_source?: "orbit" | "profile" | "default";
};
export type RetentionPolicy = {
@@ -29,14 +38,52 @@ export type RetentionSettings = { decay_preset: string } | { retention: Retentio
export type CreateOrbitInput = {
name: string;
provider: "filesystem" | "postgres";
paths: string[];
schedule?: string;
dry_run: boolean;
} & RetentionSettings;
} & RetentionSettings & (
| { source: "filesystem"; access: "hub"; provider_config: { paths: string[] } }
| { source: "database"; access: "hub"; provider_config: {
engine: "postgres" | "mysql"; transport?: "direct"; host: string; port?: number;
database: string; user: string; password_file: string;
tls?: { mode: "verify_full_with_ca" | "verify_identity_with_ca"; ca_file: string };
} }
| { source: BackupSource; access: "outpost"; provider_config: Record<string, never> }
);
export type OperatorSession = {
login_enabled: boolean;
authorized: boolean;
actor: string | null;
csrf: string | null;
};
let csrf: string | null = null;
export async function fetchOperatorSession(signal?: AbortSignal): Promise<OperatorSession> {
const session = await api<OperatorSession>("/api/v1/operator/session", { signal });
csrf = session.csrf;
return session;
}
export async function loginOperator(password: string): Promise<OperatorSession> {
const session = await api<OperatorSession>("/api/v1/operator/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
});
csrf = session.csrf;
return session;
}
export async function logoutOperator(): Promise<void> {
await request("/api/v1/operator/session", { method: "DELETE" });
csrf = null;
}
async function request(path: string, init?: RequestInit): Promise<Response> {
const r = await fetch(path, init);
const headers = new Headers(init?.headers);
if (csrf && init?.method && init.method !== "GET") headers.set("X-Tessera-CSRF", csrf);
const r = await fetch(path, { ...init, headers });
if (!r.ok) {
const text = await r.text().catch(() => "");
throw new Error(text || `${path} failed`);
@@ -68,14 +115,7 @@ export async function createOrbit(input: CreateOrbitInput): Promise<Orbit> {
return api("/api/v1/orbits", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: input.name,
provider: input.provider,
provider_config: { paths: input.paths },
schedule: input.schedule || null,
...("retention" in input ? { retention: input.retention } : { decay_preset: input.decay_preset }),
dry_run: input.dry_run,
}),
body: JSON.stringify(input),
});
}
@@ -120,3 +160,120 @@ export async function pollReconstitute(sessionId: string) {
if (!response.ok) throw new Error("Could not read restore status");
return response.json() as Promise<{ state: string; seconds_remaining: number }>;
}
export type CaptureProfile = {
application_id: string;
orbit_id: string;
outpost_id: string;
format: "postgres_custom" | "postgres_sql" | "mysql_sql" | "filesystem";
schedule?: Orbit["capture_schedule"];
};
export function registerCaptureProfile(profile: CaptureProfile): Promise<CaptureProfile> {
return api("/api/v1/capture-profiles", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(profile),
});
}
export type CaptureJob = {
id: string;
profile: CaptureProfile;
actor: string;
status: "queued" | "running" | "completed" | "failed";
phase: string;
created_at: number;
snapshot_id: string | null;
offsite_status: "pending" | "failed" | "copied" | null;
};
export type CaptureEvent = { at: number; phase: string };
export function fetchCaptureProfiles(): Promise<CaptureProfile[]> {
return api("/api/v1/capture-profiles");
}
export function enqueueCapture(application: string): Promise<CaptureJob> {
return api(`/api/v1/capture-profiles/${application}/jobs`, { method: "POST" });
}
export function fetchCaptureJobs(application: string, status: string): Promise<CaptureJob[]> {
const filter = new URLSearchParams();
if (application) filter.set("application_id", application);
if (status) filter.set("status", status);
return api(`/api/v1/capture-jobs?${filter}`);
}
export function fetchCaptureEvents(job: string): Promise<CaptureEvent[]> {
return api(`/api/v1/capture-jobs/${job}/events`);
}
export function deleteSnapshot(snapshot: string): Promise<void> {
return api(`/api/v1/snapshots/${snapshot}`, { method: "DELETE" });
}
export type Outpost = { id: string; name: string | null; last_seen: string | null; pairing_state: string };
export function fetchOutposts(): Promise<Outpost[]> {
return api("/api/v1/wormhole/outposts");
}
export type RestoreTarget = {
id: string;
name: string;
outpost_id: string;
engine: "postgres" | "mysql";
application_id: string;
identity: { instance: string; database: string };
};
export type SnapshotRestoreTarget = RestoreTarget & { ineligible_reason: string | null };
export function registerRestoreTarget(target: RestoreTarget): Promise<RestoreTarget> {
return api("/api/v1/restore-targets", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(target),
});
}
export type RestoreJob = {
id: string;
snapshot_id: string;
target: RestoreTarget;
status: "queued" | "running" | "applying" | "failed" | "completed" | "recovery_required" | "reconciled" | "cancelled";
phase: string;
safety_snapshot_id: string | null;
};
export function fetchRestoreTargets(snapshot: string): Promise<SnapshotRestoreTarget[]> {
return api(`/api/v1/snapshots/${snapshot}/restore-targets`);
}
export function fetchRestoreJobs(snapshot: string): Promise<RestoreJob[]> {
return api(`/api/v1/snapshots/${snapshot}/restore-jobs`);
}
export function enqueueRestore(snapshot: string, target: string, confirmation: string): Promise<RestoreJob> {
return api("/api/v1/restore-jobs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ snapshot_id: snapshot, target_id: target, confirmation }),
});
}
export function cancelRestore(job: string): Promise<void> {
return api(`/api/v1/restore-jobs/${job}`, { method: "DELETE" });
}
export function reconcileRestore(job: string, confirmation: string): Promise<void> {
return api(`/api/v1/restore-jobs/${job}/reconcile`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ confirmation }),
});
}

View File

@@ -1,68 +0,0 @@
import type { Orbit } from "../../api";
import { DECAY_PRESETS } from "../../lib/format";
import { describeRetention } from "../orbits/RetentionFields";
import { Hint } from "../ui/EmptyState";
import { TelemetryPanel } from "../ui/Telemetry";
export function DecayView({ orbits }: { orbits: Orbit[] }) {
const appliedPresets = new Set(orbits.filter((orbit) => !orbit.retention).map((orbit) => orbit.decay_preset ?? DECAY_PRESETS[0].id));
const custom = orbits.filter((orbit) => orbit.retention);
return (
<div className="h-full overflow-y-auto px-4 py-4 pb-28">
<h2 className="text-2xl font-semibold text-star-100">Decay</h2>
<p className="text-sm text-star-300 mt-1 mb-6">
Choose a preset or set daily, weekly, monthly and yearly counts for each orbit.
</p>
<span className="text-xs text-star-400">Retention presets</span>
<ul className="space-y-3 mt-3">
{DECAY_PRESETS.map((p) => {
const active = appliedPresets.has(p.id);
return (
<li
key={p.id}
className={`rounded-2xl border p-4 ${
active
? "border-orbit-green/35 bg-orbit-green/5"
: "border-space-700 bg-space-800/40"
}`}
>
<div className="flex items-start gap-2 flex-wrap">
<h3 className="font-medium text-star-100">{p.title}</h3>
{active && (
<span className="text-[10px] text-orbit-green border border-orbit-green/30 rounded px-1.5">
In use
</span>
)}
</div>
<p className="text-sm text-star-400 mt-1">{p.blurb}</p>
</li>
);
})}
</ul>
{custom.length > 0 && (
<div className="mt-4 space-y-2">
<h3 className="text-sm font-medium text-star-100">Custom policies</h3>
<ul className="space-y-2">
{custom.map((orbit) => (
<li key={orbit.id} className="rounded-2xl border border-space-700 bg-space-800/40 p-4">
<p className="text-sm font-medium text-star-100">{orbit.name}</p>
<p className="text-sm text-star-400">{describeRetention(orbit)}</p>
</li>
))}
</ul>
</div>
)}
<Hint>
Decay runs after a successful capture — rehearsed orbits never prune the vault.
</Hint>
<TelemetryPanel label="Decay policy IDs">
{JSON.stringify(DECAY_PRESETS.map((p) => p.id), null, 2)}
</TelemetryPanel>
</div>
);
}

View File

@@ -1,34 +1,62 @@
import { AnimatePresence, motion } from "motion/react";
import type { KeyboardEvent, ReactNode } from "react";
import { AnimatePresence, motion, useMotionValue, useSpring, useTransform, type MotionValue } from "motion/react";
import { useLayoutEffect, useRef, type KeyboardEvent, type ReactNode } from "react";
import type { Orbit, Snapshot } from "../../api";
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { gentleSpring } from "../../lib/motion";
import { useReducedMotion } from "../../hooks/useReducedMotion";
import { formatBytes, formatWhen, orbitStatus, schedulePhrase } from "../../lib/format";
import { SpringPane } from "../ui/SpringPane";
function TelemetryValue({ value, bytes = false }: { value?: number; bytes?: boolean }) {
const reducedMotion = useReducedMotion();
const target = useMotionValue(value ?? 0);
const count = useSpring(target, gentleSpring);
const text = useTransform(count, number => bytes ? formatBytes(Math.max(0, number)) : String(Math.round(number)));
useLayoutEffect(() => {
if (reducedMotion || value === undefined) count.jump(value ?? 0);
target.set(value ?? 0);
}, [value, reducedMotion, target, count]);
if (value === undefined) return "—";
return (
<>
<span className="sr-only">{bytes ? formatBytes(value) : value}</span>
<motion.span aria-hidden="true">{text}</motion.span>
</>
);
}
export function TelemetryStrip({
orbitCount, failedCount, snapCount, totalBytes,
orbitCount, failedCount, snapCount, totalBytes, bigScreen, reducedMotion,
}: {
orbitCount?: number;
failedCount: number;
snapCount?: number;
totalBytes: number;
bigScreen: boolean;
reducedMotion: boolean;
}) {
const strip = useRef<HTMLDListElement>(null);
useScreenTransition(strip, bigScreen, reducedMotion, undefined, true);
return (
<dl className="vault-telemetry">
<div><dt>Orbits</dt><dd>{orbitCount ?? "—"}</dd></div>
<div><dt>Failed</dt><dd className={failedCount ? "telemetry-alert" : ""}>{orbitCount === undefined ? "—" : failedCount}</dd></div>
<div><dt>Snapshots</dt><dd>{snapCount ?? "—"}</dd></div>
<div><dt>Payload</dt><dd>{snapCount === undefined ? "—" : formatBytes(totalBytes)}</dd></div>
<dl ref={strip} className="vault-telemetry">
<div><dt>Orbits</dt><dd><TelemetryValue value={orbitCount} /></dd></div>
<div><dt>Failed</dt><dd className={failedCount ? "telemetry-alert" : ""}>
<TelemetryValue value={orbitCount === undefined ? undefined : failedCount} />
</dd></div>
<div><dt>Snapshots</dt><dd><TelemetryValue value={snapCount} /></dd></div>
<div><dt>Payload</dt><dd><TelemetryValue value={snapCount === undefined ? undefined : totalBytes} bytes /></dd></div>
</dl>
);
}
export function OrbitRegister({
orbits, selected, message, onSelect, onManage,
orbits, selected, message, bigScreen, onSelect, onManage,
}: {
orbits: Orbit[];
selected?: string;
message?: string;
bigScreen: boolean;
onSelect: (id: string) => void;
onManage: () => void;
}) {
@@ -45,7 +73,8 @@ export function OrbitRegister({
}
return (
<section className="vault-console orbit-register" aria-labelledby="register-title">
<motion.section className="vault-console orbit-register" aria-labelledby="register-title" inert={bigScreen}
initial={false} animate={{ opacity: bigScreen ? 0 : 1 }}>
<header className="console-heading">
<p className="instrument-label">Flight register</p>
<h2 id="register-title">Orbits</h2>
@@ -56,13 +85,14 @@ export function OrbitRegister({
const status = orbitStatus(orbit.last_status);
return (
<motion.li key={orbit.id} layout={reducedMotion ? false : "position"}>
<button
<motion.button
type="button"
id={`register-${orbit.id}`}
className="register-row"
aria-pressed={selected === orbit.id}
tabIndex={active === orbit.id ? 0 : -1}
onClick={() => onSelect(orbit.id)}
whileHover={{ backgroundColor: selected === orbit.id ? "#28252b" : "#1b1e23" }}
onKeyDown={(event) => moveFocus(event, index)}
>
<span className={`register-signal signal-${status.tone}`} aria-hidden="true" />
@@ -71,7 +101,7 @@ export function OrbitRegister({
<small>{orbit.provider}</small>
</span>
<span className={`register-state tone-${status.tone}`}>{status.label}</span>
</button>
</motion.button>
</motion.li>
);
})}
@@ -81,22 +111,26 @@ export function OrbitRegister({
{orbits.length ? "Manage orbits" : "Set up an orbit"} <span aria-hidden="true">↗</span>
</button>
</div>
</section>
</motion.section>
);
}
export function OrbitInspector({
orbit, snapshots, snapshotMessage, capture, onSelectSnapshot,
orbit, snapshots, snapshotMessage, capture, highlightedId, captureGlow, bigScreen, onSelectSnapshot,
}: {
orbit?: Orbit;
snapshots: Snapshot[];
snapshotMessage?: string;
capture?: ReactNode;
highlightedId?: string;
captureGlow: MotionValue<number>;
bigScreen: boolean;
onSelectSnapshot: (id: string) => void;
}) {
const status = orbitStatus(orbit?.last_status ?? "idle");
return (
<section className="vault-console orbit-inspector" aria-labelledby="inspector-title">
<motion.section className="vault-console orbit-inspector" aria-labelledby="inspector-title" inert={bigScreen}
initial={false} animate={{ opacity: bigScreen ? 0 : 1 }}>
<header className="console-heading">
<p className="instrument-label">Orbit detail</p>
<h2 id="inspector-title">{orbit?.name ?? "Select an orbit"}</h2>
@@ -106,7 +140,7 @@ export function OrbitInspector({
<AnimatePresence initial={false}>
{orbit ? (
<SpringPane key={orbit.id}>
<p className="inspector-schedule">{schedulePhrase(orbit.schedule, orbit.dry_run)}</p>
<p className="inspector-schedule">{schedulePhrase(orbit)}</p>
<div className="inspector-capture">{capture}</div>
<section className="inspector-history" aria-label="Snapshot history">
<header>
@@ -118,6 +152,9 @@ export function OrbitInspector({
{snapshots.map((snapshot, index) => (
<li key={snapshot.id}>
<button id={`snapshot-${snapshot.id}`} type="button" className="snapshot-row" onClick={() => onSelectSnapshot(snapshot.id)}>
{snapshot.id === highlightedId && (
<motion.span className="snapshot-row-flash" aria-hidden="true" style={{ opacity: captureGlow }} />
)}
<span className="snapshot-glyph" aria-hidden="true">◇</span>
<span>
<strong>{formatWhen(snapshot.taken_at)}</strong>
@@ -137,6 +174,6 @@ export function OrbitInspector({
)}
</AnimatePresence>
</div>
</section>
</motion.section>
);
}

View File

@@ -2,13 +2,14 @@ import { motion } from "motion/react";
import { useEffect, useId, useLayoutEffect, useRef, type ReactNode } from "react";
export function HUDPanel({
open, title, subtitle, onClose, children,
open, title, subtitle, onClose, children, inert,
}: {
open: boolean;
title: string;
subtitle?: string;
onClose: () => void;
children: ReactNode;
inert?: boolean;
}) {
const panel = useRef<HTMLElement>(null);
const heading = useRef<HTMLHeadingElement>(null);
@@ -61,7 +62,7 @@ export function HUDPanel({
aria-labelledby={labelId}
aria-describedby={display.subtitle ? descriptionId : undefined}
aria-hidden={!open}
inert={!open}
inert={!open || inert}
initial={false}
animate={{ x: open ? "0%" : "100%" }}
>

View File

@@ -1,14 +1,14 @@
import { animate, motion, useMotionValue, useTransform, useVelocity } from "motion/react";
import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "react";
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { uiSpring } from "../../lib/motion";
export type HUDMode = "scene" | "orbits" | "wormhole" | "decay" | "reconstitute" | "snapshot";
export type HUDMode = "scene" | "orbits" | "wormhole" | "reconstitute" | "snapshot";
const items = [
export const hudItems = [
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
{ id: "orbits", label: "Orbits", icon: "M21 12a9 5 0 1 1-18 0 9 5 0 1 1 18 0z M12 10.5a1.5 1.5 0 1 1 0 3 1.5 1.5 0 1 1 0-3z M18 5h.01" },
{ id: "wormhole", label: "Outposts", icon: "M12 3v3 M4.2 7.5l2.6 1.5 M4.2 16.5 6.8 15 M12 18v3 M17.2 15l2.6 1.5 M17.2 9l2.6-1.5 M15.5 12a3.5 3.5 0 1 1-7 0 3.5 3.5 0 1 1 7 0z" },
{ id: "decay", label: "Retention", icon: "M6 4h12 M6 20h12 M8 4v3l4 5-4 5v3 M16 4v3l-4 5 4 5v3" },
{ id: "reconstitute", label: "Restore", icon: "M4 12a8 8 0 1 1 2.3 5.7 M4 6v6h6 M12 8v4l3 2" },
] as const;
@@ -25,6 +25,7 @@ export function HUDRail({
onSelect: (mode: HUDMode) => void;
}) {
const nav = useRef<HTMLElement>(null);
useScreenTransition(nav, floating, reducedMotion);
const slots = useRef<Slot[]>([]);
const gesture = useRef<Gesture>(undefined);
const suppressClick = useRef(false);
@@ -33,7 +34,7 @@ export function HUDRail({
const velocity = useVelocity(center);
const tail = useTransform(() => center.get() - Math.max(-22, Math.min(22, velocity.get() * 0.032)));
const id = useId();
const activeIndex = Math.max(0, items.findIndex(item => item.id === active));
const activeIndex = Math.max(0, hudItems.findIndex(item => item.id === active));
const snap = useCallback((index: number, immediate = false) => {
const slot = slots.current[index];
@@ -56,11 +57,10 @@ export function HUDRail({
const element = nav.current!;
const buttons = Array.from(element.querySelectorAll("button"));
const measure = () => {
const left = element.getBoundingClientRect().left + element.clientLeft;
const next = buttons.map(button => {
const rect = button.getBoundingClientRect();
return { center: rect.left + rect.width / 2 - left, width: rect.width - 10 };
});
const next = buttons.map(button => ({
center: button.offsetLeft + button.offsetWidth / 2,
width: button.offsetWidth - 10,
}));
const changed = next.some((slot, index) =>
slot.center !== slots.current[index]?.center || slot.width !== slots.current[index]?.width,
);
@@ -115,7 +115,7 @@ export function HUDRail({
Math.abs(slot.center - projected) < Math.abs(slots.current[nearest].center - projected) ? index : nearest,
0);
if (next === activeIndex) snap(activeIndex);
else onSelect(items[next].id);
else onSelect(hudItems[next].id);
}
return (
@@ -144,44 +144,43 @@ export function HUDRail({
}
}}
>
{floating ? (
<svg className="nav-liquid" aria-hidden="true">
<defs>
<filter id={`${id}-goo`} x="-25%" y="-50%" width="150%" height="200%">
<feGaussianBlur in="SourceGraphic" stdDeviation="3.5" result="blur" />
<feColorMatrix in="blur" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -8" result="goo" />
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
<linearGradient id={`${id}-fill`} x2="0%" y2="100%">
<stop stopColor="#724a34" />
<stop offset="100%" stopColor="#38251e" />
</linearGradient>
</defs>
<g filter={`url(#${id}-goo)`} fill={`url(#${id}-fill)`}>
<motion.ellipse cx={reducedMotion ? center : tail} cy="50%" rx="17" ry="13" />
<motion.ellipse cx={center} cy="50%" rx="21" ry="17" />
</g>
</svg>
) : (
<>
<span aria-hidden="true" className="nav-text-dock" />
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }} />
</>
)}
{items.map(({ id, label, icon }) => (
<motion.svg className="nav-liquid" aria-hidden="true" initial={false} animate={{ opacity: floating ? 1 : 0 }}>
<defs>
<filter id={`${id}-goo`} x="-25%" y="-50%" width="150%" height="200%">
<feGaussianBlur in="SourceGraphic" stdDeviation="3.5" result="blur" />
<feColorMatrix in="blur" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -8" result="goo" />
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
<linearGradient id={`${id}-fill`} x2="0%" y2="100%">
<stop stopColor="#724a34" />
<stop offset="100%" stopColor="#38251e" />
</linearGradient>
</defs>
<g filter={`url(#${id}-goo)`} fill={`url(#${id}-fill)`}>
<motion.ellipse cx={reducedMotion ? center : tail} cy="50%" rx="17" ry="13" />
<motion.ellipse cx={center} cy="50%" rx="21" ry="17" />
</g>
</motion.svg>
<span aria-hidden="true" className="nav-text-dock" />
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }}
initial={false} animate={{ opacity: floating ? 0 : 1 }} />
{hudItems.map(({ id, label, icon }) => (
<button
key={id}
type="button"
aria-label={floating ? label : undefined}
aria-label={label}
title={floating ? label : undefined}
onClick={() => onSelect(id)}
aria-current={active === id ? "page" : undefined}
>
{floating ? (
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d={icon} />
</svg>
) : label}
<motion.svg className="nav-icon" viewBox="0 0 24 24" width="22" height="22" fill="none"
stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"
initial={false} animate={{ opacity: floating ? 1 : 0 }}>
<path d={icon} />
</motion.svg>
<motion.span className="nav-label" aria-hidden="true" initial={false} animate={{ opacity: floating ? 0 : 1 }}>
{label}
</motion.span>
</button>
))}
</motion.nav>

View File

@@ -0,0 +1,171 @@
import { useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { animate, motion, useMotionValue, useTransform } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
import { gentleSpring, uiSpring } from "../../lib/motion";
import { createVaultSearch, type SearchResult } from "../../lib/vaultSearch";
import { hudItems } from "./HUDRail";
const resultKey = ({ kind, id }: SearchResult) => `${kind}-${id}`;
export function SearchIcon() {
return (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor"
strokeWidth="1.5" strokeLinecap="round" aria-hidden="true">
<circle cx="10.5" cy="10.5" r="5.5" /><path d="m15 15 4 4" />
</svg>
);
}
export function VaultSearch({ open, reducedMotion, orbits, snapshots, orbitStatus, snapshotStatus, onClose, onSelect }: {
open: boolean;
reducedMotion: boolean;
orbits?: Orbit[];
snapshots?: Snapshot[];
orbitStatus?: string;
snapshotStatus?: string;
onClose: () => void;
onSelect: (result: SearchResult) => void;
}) {
const id = useId();
const input = useRef<HTMLInputElement>(null);
const close = useRef<HTMLButtonElement>(null);
const overlay = useRef<HTMLDivElement>(null);
const body = useRef<HTMLDivElement>(null);
const progress = useMotionValue(0);
const y = useTransform(progress, [0, 1], [-12, 0]);
const height = useMotionValue(0);
const [query, setQuery] = useState("");
const [activeId, setActiveId] = useState<string>();
const search = useMemo(() => createVaultSearch(hudItems, orbits, snapshots), [orbits, snapshots]);
const groups = useMemo(() => search(query), [query, search]);
const results = useMemo(() => groups.flatMap(group => group.results), [groups]);
const active = results.find(result => resultKey(result) === activeId) ?? results[0];
const activeKey = active && resultKey(active);
const activeOption = activeKey && `${id}-${encodeURIComponent(activeKey)}`;
useLayoutEffect(() => {
if (!open) return;
setQuery("");
setActiveId(undefined);
input.current?.focus({ preventScroll: true });
const viewport = window.visualViewport;
if (!viewport) return;
const style = overlay.current!.style;
const updateViewport = () => {
style.setProperty("--search-viewport", `${viewport.height}px`);
style.setProperty("--search-viewport-top", `${viewport.offsetTop}px`);
};
updateViewport();
viewport.addEventListener("resize", updateViewport);
viewport.addEventListener("scroll", updateViewport);
return () => {
viewport.removeEventListener("resize", updateViewport);
viewport.removeEventListener("scroll", updateViewport);
};
}, [open]);
useLayoutEffect(() => {
if (reducedMotion) progress.jump(Number(open));
else animate(progress, Number(open), uiSpring);
}, [open, reducedMotion, progress]);
useLayoutEffect(() => {
const element = body.current!;
let target = element.offsetHeight;
height.jump(target);
const observer = new ResizeObserver(() => {
const next = element.offsetHeight;
if (next === target) return;
target = next;
if (reducedMotion) height.jump(next);
else animate(height, next, gentleSpring);
});
observer.observe(element);
return () => observer.disconnect();
}, [height, reducedMotion]);
useLayoutEffect(() => () => {
progress.stop();
height.stop();
}, [progress, height]);
useLayoutEffect(() => {
if (!open) return;
if (activeKey !== activeId) setActiveId(activeKey);
if (activeOption) document.getElementById(activeOption)?.scrollIntoView({ block: "nearest" });
}, [open, activeId, activeKey, activeOption, results]);
function handleKeys(event: KeyboardEvent) {
if (event.key === "Tab") {
event.preventDefault();
(event.target === input.current ? close.current : input.current)?.focus();
return;
}
if (event.target !== input.current || event.nativeEvent.isComposing || event.keyCode === 229) return;
if (event.key === "Enter" && active && !event.repeat) {
event.preventDefault();
onSelect(active);
} else if ((event.key === "ArrowDown" || event.key === "ArrowUp") && results.length) {
event.preventDefault();
const offset = event.key === "ArrowDown" ? 1 : -1;
const next = results[(results.indexOf(active) + offset + results.length) % results.length];
setActiveId(resultKey(next));
}
}
return (
<motion.div ref={overlay} className="search-overlay" inert={!open} style={{ opacity: progress }} onClick={event => {
if (event.target === event.currentTarget) onClose();
}}>
<motion.section className="search-panel" style={{ y }} role="dialog" aria-modal="true" aria-label="Vault search" onKeyDown={handleKeys}>
<div className="search-field">
<SearchIcon />
<input ref={input} type="text" role="combobox" aria-label="Search vault"
aria-autocomplete="list" aria-expanded={!!results.length} aria-controls={`${id}-results`}
aria-activedescendant={activeOption}
autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="Search the vault…"
value={query} onChange={event => {
setQuery(event.currentTarget.value);
setActiveId(undefined);
}} />
<button ref={close} className="console-control search-close" type="button" aria-label="Close search" onClick={onClose}>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor"
strokeWidth="1.5" strokeLinecap="round" aria-hidden="true"><path d="m7 7 10 10M17 7 7 17" /></svg>
</button>
</div>
<motion.div className="search-list-frame" style={{ height }}>
<div ref={body} className="search-body">
<div role="listbox" id={`${id}-results`} aria-label="Search results" hidden={!results.length}>
{groups.map(group => (
<div key={group.label} role="group" aria-label={group.label}>
<p className="instrument-label search-group" aria-hidden="true">{group.label}</p>
{group.results.map(result => {
const key = resultKey(result);
const icon = result.kind === "navigation" ? result.icon
: result.kind === "orbit" ? hudItems[1].icon : "M12 3l8 9-8 9-8-9z M12 9v6";
return (
<div key={key} id={`${id}-${encodeURIComponent(key)}`} role="option" className="search-result"
aria-selected={activeKey === key} onMouseDown={event => event.preventDefault()} onClick={() => onSelect(result)}>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor"
strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={icon} /></svg>
<span className="search-result-text">
<span>{result.label}</span>
{result.detail && <small>{result.detail}</small>}
</span>
</div>
);
})}
</div>
))}
</div>
<p className="search-status" role="status">
<span>{results.length ? `${results.length} ${query.trim() ? "results shown" : "destinations"}` : "No matching results."}</span>
{orbitStatus && <span>{orbitStatus}</span>}
{snapshotStatus && <span>{snapshotStatus}</span>}
</p>
</div>
</motion.div>
</motion.section>
</motion.div>
);
}

View File

@@ -0,0 +1,82 @@
import { useState, type FormEvent, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { fetchOperatorSession, loginOperator, logoutOperator } from "../../api";
import { Button } from "../ui/Button";
export function OperatorGate({
children,
}: {
children: (operator: { actor?: string; onLogout?: () => Promise<void> }) => ReactNode;
}) {
const queryClient = useQueryClient();
const session = useQuery({
queryKey: ["operator-session"],
queryFn: ({ signal }) => fetchOperatorSession(signal),
refetchInterval: 15_000,
retry: false,
});
const [pending, setPending] = useState(false);
const [error, setError] = useState<string>();
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = event.currentTarget;
const password = new FormData(form).get("password");
if (pending || typeof password !== "string" || !password) return;
setPending(true);
setError(undefined);
form.reset();
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
try {
const signedIn = await loginOperator(password);
queryClient.setQueryData(["operator-session"], signedIn);
} catch {
setError("Could not sign in. Check the password or try again shortly.");
} finally {
setPending(false);
}
}
if (session.isSuccess && session.data.authorized) {
const actor = session.data.actor ?? undefined;
return children({
actor,
onLogout: actor ? async () => {
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
await logoutOperator();
queryClient.setQueryData(["operator-session"], {
login_enabled: true, authorized: false, actor: null, csrf: null,
});
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" });
} : undefined,
});
}
return (
<main className="vault-app flex min-h-screen items-center justify-center p-5">
<section className="w-full max-w-sm rounded-2xl border border-space-700 bg-space-900 p-6 sm:p-8">
<p className="instrument-label mb-3">Tessera / Backup control</p>
<h1 className="text-2xl font-semibold text-star-100">Operator sign-in</h1>
{session.isPending ? <p role="status" className="mt-4 text-star-300">Connecting to the hub…</p>
: session.isError ? (
<div className="mt-4 space-y-3">
<p role="alert" className="text-star-300">Could not reach the hub.</p>
<Button onClick={() => void session.refetch()}>Try again</Button>
</div>
) : session.data.login_enabled ? (
<form onSubmit={submit} className="mt-5 space-y-4">
<label className="block text-sm text-star-300">
Operator password
<input type="password" name="password" autoComplete="current-password" required
maxLength={1024} className="mt-1 block w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100" />
</label>
{error && <p role="alert" className="text-sm text-orbit-red">{error}</p>}
<Button type="submit" variant="primary" className="w-full" disabled={pending}>
{pending ? "Signing in…" : "Sign in"}
</Button>
</form>
) : <p className="mt-4 text-star-300">Browser sign-in is disabled on this hub.</p>}
</section>
</main>
);
}

View File

@@ -0,0 +1,65 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { registerCaptureProfile, type BackupSource, type CaptureProfile } from "../../api";
import { OutpostField } from "../outposts/OutpostField";
import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState";
const field = "mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2";
const uuidPattern = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
export function CaptureProfileForm({ orbitId, source, onClose }: { orbitId: string; source: BackupSource | null; onClose: () => void }) {
const [initialId] = useState(() => globalThis.crypto?.randomUUID?.() ?? "");
const qc = useQueryClient();
const register = useMutation({
mutationFn: registerCaptureProfile,
onSuccess: async () => {
await Promise.all([
qc.invalidateQueries({ queryKey: ["capture-profiles"] }),
qc.invalidateQueries({ queryKey: ["orbits"] }),
]);
onClose();
},
});
return (
<form className="mt-4 space-y-3 border-t border-space-700 pt-3" onSubmit={(event) => {
event.preventDefault();
if (register.isPending) return;
const data = new FormData(event.currentTarget);
const time = String(data.get("time"));
const [hour, minute] = time.split(":").map(Number);
register.mutate({
application_id: String(data.get("application")),
orbit_id: orbitId,
outpost_id: String(data.get("outpost")),
format: source === "filesystem" ? "filesystem" : data.get("format") as CaptureProfile["format"],
schedule: time ? { hour, minute, timezone: "UTC" } : undefined,
});
}}>
<h4 className="font-medium text-star-100">Register Outpost backup profile</h4>
<label className="block text-sm text-star-300">
Application UUID
<input name="application" defaultValue={initialId} required pattern={uuidPattern} className={field} />
</label>
<OutpostField className={field} />
{source !== "filesystem" && <label className="block text-sm text-star-300">
Database engine
<select name="format" className={field}>
<option value="postgres_sql">PostgreSQL</option>
<option value="mysql_sql">MySQL</option>
</select>
</label>}
<label className="block text-sm text-star-300">
Daily backup time (UTC, optional)
<input name="time" type="time" className={field} />
</label>
<Hint>Use the same application UUID in the agent’s local capture configuration. Set the source and Restic repository there before queueing a backup.</Hint>
{register.isError && <p role="alert" className="text-sm text-orbit-red">Could not register the profile. Check that the UUID is unused and the Outpost is paired.</p>}
<div className="flex gap-2">
<Button type="button" disabled={register.isPending} onClick={onClose}>Cancel</Button>
<Button type="submit" variant="primary" disabled={register.isPending}>Register profile</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,120 @@
import { useId, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { enqueueCapture, fetchCaptureEvents, fetchCaptureJobs, fetchSnapshots, type CaptureProfile, type Orbit } from "../../api";
import { formatWhen } from "../../lib/format";
import { Button } from "../ui/Button";
const labels: Record<string, string> = {
queued: "Waiting for outpost",
claimed: "Assigned to agent",
dumping: "Preparing source",
uploading: "Saving backup",
dump_failed: "Source preparation failed or timed out",
upload_failed: "Backup transfer failed",
completed: "Backup completed",
};
const input = "mt-1 block w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100";
export function JobHistory({
profiles, orbits, snapshots, onOpenSnapshot,
}: {
profiles: CaptureProfile[];
orbits: Orbit[];
snapshots?: ReadonlySet<string>;
onOpenSnapshot: (id: string) => void;
}) {
const filters = useId();
const [application, setApplication] = useState("");
const [status, setStatus] = useState("");
const [selected, setSelected] = useState<string>();
const qc = useQueryClient();
const name = (profile: CaptureProfile) =>
orbits.find((orbit) => orbit.id === profile.orbit_id)?.name ?? profile.application_id;
const jobs = useQuery({
queryKey: ["capture-jobs", application, status],
queryFn: () => fetchCaptureJobs(application, status),
refetchInterval: 3_000,
});
const events = useQuery({
queryKey: ["capture-events", selected],
queryFn: () => fetchCaptureEvents(selected!),
enabled: !!selected,
refetchInterval: 3_000,
});
const enqueue = useMutation({
mutationFn: enqueueCapture,
onSuccess: (job) => {
setStatus("");
setSelected(job.id);
void qc.invalidateQueries({ queryKey: ["capture-jobs"] });
},
});
return (
<section className="mb-6 space-y-4 rounded-2xl border border-space-700 bg-space-800/50 p-4">
<div>
<h3 className="font-semibold text-star-100">Outpost backup jobs</h3>
<p className="mt-1 text-sm text-star-300">Jobs wait for the assigned outpost when it is offline.</p>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div>
<label className="text-sm text-star-300" htmlFor={`${filters}-application`}>Application</label>
<select id={`${filters}-application`} className={input} value={application} onChange={(event) => setApplication(event.target.value)}>
<option value="">All applications</option>
{profiles.map((profile) => <option key={profile.application_id} value={profile.application_id}>{name(profile)}</option>)}
</select>
</div>
<div>
<label className="text-sm text-star-300" htmlFor={`${filters}-status`}>Job status</label>
<select id={`${filters}-status`} className={input} value={status} onChange={(event) => setStatus(event.target.value)}>
<option value="">Any status</option>
<option value="queued">Queued</option>
<option value="running">Running</option>
<option value="completed">Completed</option>
<option value="failed">Failed</option>
</select>
</div>
</div>
<Button variant="success" disabled={!application || enqueue.isPending}
onClick={() => enqueue.mutate(application)}>
{enqueue.isPending ? "Queueing…" : "Back up selected application"}
</Button>
{enqueue.isError && <p role="alert" className="text-sm text-orbit-red">Could not queue the backup.</p>}
{enqueue.isSuccess && <p role="status" className="text-sm text-star-300">Backup queued.</p>}
{jobs.isPending && <p role="status" className="text-sm text-star-300">Loading jobs…</p>}
{jobs.isError && <p role="alert" className="text-sm text-orbit-red">Job history is unavailable.</p>}
{jobs.data?.length === 0 && <p className="text-sm text-star-300">No jobs match these filters.</p>}
<ul className="space-y-2">
{jobs.data?.map((job) => (
<li key={job.id} className="rounded-xl border border-space-700 px-3 py-2">
<button type="button" aria-expanded={selected === job.id}
className="flex w-full flex-wrap items-center justify-between gap-2 py-1 text-left text-sm text-star-100"
onClick={() => setSelected(selected === job.id ? undefined : job.id)}>
<strong>{name(job.profile)}</strong>
<span className={job.status === "failed" ? "text-orbit-red" : "text-star-300"}>{labels[job.phase] ?? job.status}</span>
</button>
{selected === job.id && (
<div className="mt-2 space-y-2 border-t border-space-700 pt-2 text-xs text-star-300">
<p>Queued by {job.actor} · {formatWhen(new Date(job.created_at * 1000).toISOString())}</p>
{job.offsite_status && <p>Off-site copy {job.offsite_status}</p>}
{events.isError && <p role="alert">Could not load job events.</p>}
<ol className="space-y-1">
{events.data?.map((event, i) => <li key={i}>{labels[event.phase] ?? event.phase}</li>)}
</ol>
{job.snapshot_id && (snapshots?.has(job.snapshot_id) ? (
<Button onClick={async () => {
const catalog = await qc.fetchQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots })
.catch(() => undefined);
const available = catalog?.find(({ id }) => id === job.snapshot_id);
if (available) onOpenSnapshot(available.id);
}}>Open snapshot</Button>
) : <p>{snapshots ? "Snapshot is no longer in the catalog." : "Snapshot availability unknown."}</p>)}
</div>
)}
</li>
))}
</ul>
</section>
);
}

View File

@@ -1,9 +1,11 @@
import { useState, type ReactNode } from "react";
import { AnimatePresence } from "motion/react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Orbit } from "../../api";
import { createOrbit, updateOrbitRetention } from "../../api";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { BackupAccess, BackupSource, Orbit, Snapshot } from "../../api";
import { createOrbit, fetchCaptureProfiles, updateOrbitRetention } from "../../api";
import { orbitStatus, schedulePhrase } from "../../lib/format";
import { CaptureProfileForm } from "./CaptureProfileForm";
import { JobHistory } from "./JobHistory";
import { describeRetention, retentionDraft, RetentionFields, retentionSettings } from "./RetentionFields";
import { Button } from "../ui/Button";
import { OrbitStatusDot } from "../ui/StatusDot";
@@ -12,16 +14,24 @@ import { Hint } from "../ui/EmptyState";
import { SpringPane } from "../ui/SpringPane";
export function OrbitsView({
orbits, onRun, captureDisabled, notice,
orbits, snapshots, onRun, onOpenSnapshot, captureDisabled, notice,
}: {
orbits: Orbit[];
snapshots?: Snapshot[];
onRun: (orbit: Orbit) => void;
onOpenSnapshot: (id: string) => void;
captureDisabled: boolean;
notice?: ReactNode;
}) {
const [editing, setEditing] = useState(false);
const qc = useQueryClient();
const profiles = useQuery({ queryKey: ["capture-profiles"], queryFn: fetchCaptureProfiles });
const [name, setName] = useState("nightly-docs");
const [source, setSource] = useState<BackupSource>("filesystem");
const [access, setAccess] = useState<BackupAccess>("hub");
const [engine, setEngine] = useState<"postgres" | "mysql">("postgres");
const viaOutpost = access === "outpost";
const [profileOrbit, setProfileOrbit] = useState<string>();
const [path, setPath] = useState("./docs");
const [retention, setRetention] = useState(() => retentionDraft());
const [editingRetention, setEditingRetention] = useState<string | null>(null);
@@ -29,20 +39,31 @@ export function OrbitsView({
const [schedule, setSchedule] = useState("0 2 * * *");
const create = useMutation({
mutationFn: () => {
mutationFn: (data: FormData) => {
const settings = retentionSettings(retention);
if (!settings) throw new Error("Invalid retention policy");
return createOrbit({
name,
provider: "filesystem",
paths: [path],
schedule: schedule || undefined,
const orbit = {
name: name.trim(),
schedule: viaOutpost ? undefined : schedule.trim() || undefined,
...settings,
dry_run: rehearse,
});
dry_run: !viaOutpost && rehearse,
};
if (access === "outpost") return createOrbit({ ...orbit, source, access, provider_config: {} });
if (source === "filesystem") {
return createOrbit({ ...orbit, source, access, provider_config: { paths: [path.trim()] } });
}
const field = (key: string) => String(data.get(key) ?? "").trim();
const caFile = field("ca_file");
return createOrbit({ ...orbit, source, access, provider_config: {
engine, ...(engine === "mysql" ? { transport: "direct" } : {}),
host: field("host"), ...(field("port") ? { port: Number(field("port")) } : {}),
database: field("database"), user: field("user"), password_file: field("password_file"),
...(caFile ? { tls: { mode: engine === "postgres" ? "verify_full_with_ca" : "verify_identity_with_ca", ca_file: caFile } } : {}),
} });
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["orbits"] });
onSuccess: (orbit) => {
void qc.invalidateQueries({ queryKey: ["orbits"] });
if (orbit.access === "outpost") setProfileOrbit(orbit.id);
setEditing(false);
},
});
@@ -50,6 +71,12 @@ export function OrbitsView({
return (
<div>
{notice}
{profiles.isError && <p role="alert" className="mb-4 text-sm text-orbit-red">Outpost backup profiles are unavailable.</p>}
<JobHistory profiles={profiles.data ?? []} orbits={orbits}
snapshots={snapshots && new Set(snapshots.map(({ id }) => id))} onOpenSnapshot={onOpenSnapshot} />
{profiles.data?.length === 0 && <p className="mb-4 text-sm text-star-300">
Register an Outpost capture profile to start queueing jobs.
</p>}
<div className="space-y-3 mb-6">
{orbits.map((o) => (
@@ -62,7 +89,10 @@ export function OrbitsView({
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-star-100 truncate">{o.name}</h3>
<p className="text-sm text-star-300">{orbitStatus(o.last_status).label}</p>
<p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o.schedule, o.dry_run)}</p>
<p className="text-xs text-star-400">
{o.source === "filesystem" ? "Filesystem / Folder" : o.source === "database" ? "Database" : "Backup"} · {o.access === "outpost" ? "Via Outpost" : "Via Hub"}
</p>
<p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o)}</p>
<p className="text-xs text-star-400 mt-0.5">{describeRetention(o)}</p>
{o.dry_run && (
<span className="inline-block mt-2 text-[10px] uppercase tracking-wider text-orbit-amber border border-orbit-amber/30 rounded px-2 py-0.5">
@@ -75,17 +105,22 @@ export function OrbitsView({
<Button
variant="success"
className="flex-1 text-xs py-2"
disabled={captureDisabled || orbitStatus(o.last_status).busy}
disabled={(o.access === "outpost" && !o.application_id) || captureDisabled || orbitStatus(o.last_status).busy}
onClick={() => onRun(o)}
>
{o.dry_run ? "Rehearse" : "Capture now"}
{o.application_id ? "Queue backup" : o.access === "outpost" ? "Outpost capture" : o.dry_run ? "Rehearse" : "Capture now"}
</Button>
<Button className="flex-1 text-xs py-2" onClick={() => setEditingRetention(o.id)}
disabled={editingRetention === o.id}>
disabled={editingRetention === o.id || o.retention_source === "profile"}>
Edit retention
</Button>
</div>
{editingRetention === o.id && <OrbitRetentionEditor orbit={o} onClose={() => setEditingRetention(null)} />}
{o.access === "outpost" && !o.dry_run && !o.application_id && (
profileOrbit === o.id
? <CaptureProfileForm key={o.id} orbitId={o.id} source={o.source} onClose={() => setProfileOrbit(undefined)} />
: <Button className="mt-3" onClick={() => setProfileOrbit(o.id)}>Register Outpost backup profile</Button>
)}
<TelemetryPanel>
{JSON.stringify(o, null, 2)}
</TelemetryPanel>
@@ -97,55 +132,94 @@ export function OrbitsView({
<AnimatePresence initial={false}>
{editing ? (
<SpringPane key="form">
<div className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3">
<form className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3"
onSubmit={(event) => { event.preventDefault(); if (!create.isPending) create.mutate(new FormData(event.currentTarget)); }}>
<h3 className="font-medium text-star-100">New orbit</h3>
<label className="block text-sm">
<span className="text-star-400">Name</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={name}
required value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<label className="block text-sm">
<span className="text-star-400">Folder path</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
value={path}
onChange={(e) => setPath(e.target.value)}
/>
<span className="text-star-400">Backup source</span>
<select className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={source} onChange={(event) => setSource(event.target.value as BackupSource)}>
<option value="filesystem">Filesystem / Folder</option>
<option value="database">Database</option>
</select>
</label>
<label className="block text-sm">
<span className="text-star-400">Schedule (cron)</span>
<span className="text-star-400">Access</span>
<select className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={access} onChange={(event) => setAccess(event.target.value as BackupAccess)}>
<option value="hub">Via Hub</option>
<option value="outpost">Via Outpost</option>
</select>
</label>
{!viaOutpost && source === "filesystem" && <label className="block text-sm">
<span className="text-star-400">Folder path visible to the hub</span>
<input className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
required value={path} onChange={(e) => setPath(e.target.value)} />
</label>}
{!viaOutpost && source === "database" && <>
<label className="block text-sm text-star-400">
Database engine
<select className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={engine} onChange={(event) => setEngine(event.target.value as typeof engine)}>
<option value="postgres">PostgreSQL</option>
<option value="mysql">MySQL</option>
</select>
</label>
{[
["host", "Database host"], ["port", "Port (optional)"], ["database", "Database name"],
["user", "Database user"], ["password_file", "Absolute password file path on hub"],
["ca_file", "CA certificate path on hub (optional)"],
].map(([key, label]) => <label key={key} className="block text-sm text-star-400">
{label}
<input name={key} required={key !== "port" && key !== "ca_file"} type={key === "port" ? "number" : "text"}
min={key === "port" ? 1 : undefined} max={key === "port" ? 65535 : undefined}
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2" />
</label>)}
</>}
{!viaOutpost && <label className="block text-sm">
<span className="text-star-400">Schedule (cron, UTC)</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
value={schedule}
onChange={(e) => setSchedule(e.target.value)}
/>
</label>
<RetentionFields draft={retention} onChange={setRetention} />
<label className="flex items-center gap-2 text-sm text-star-300">
<input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} />
Rehearse only (dry run)
</label>
<Hint>
Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”.
</Hint>
{create.isError && <p role="alert" className="text-sm text-orbit-red">The orbit could not be saved.</p>}
<span className="text-xs text-star-400">Leave blank for manual capture. Use weekday names such as MON to avoid ambiguity.</span>
</label>}
{viaOutpost && <Hint>After saving, assign a paired Outpost and schedule. Configure the source and Restic repository on the agent.</Hint>}
<RetentionFields draft={retention} onChange={setRetention} managed={viaOutpost} />
{!viaOutpost && <div className="space-y-1">
<label className="flex items-center gap-2 text-sm text-star-300">
<input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} />
Rehearse only (dry run)
</label>
<p className="text-xs text-star-400">A rehearsal never prunes snapshots.</p>
</div>}
{create.isError && <p role="alert" className="text-sm text-orbit-red">{create.error.message}</p>}
<div className="flex gap-2">
<Button className="flex-1" onClick={() => setEditing(false)}>
<Button type="button" className="flex-1" disabled={create.isPending} onClick={() => {
setEditing(false);
create.reset();
}}>
Cancel
</Button>
<Button
variant="primary"
className="flex-1"
disabled={create.isPending || !retentionSettings(retention)}
onClick={() => create.mutate()}
type="submit"
disabled={create.isPending || !name.trim() || !retentionSettings(retention)}
>
Save orbit
</Button>
</div>
</div>
</form>
</SpringPane>
) : (
<SpringPane key="add">
@@ -176,8 +250,10 @@ function OrbitRetentionEditor({ orbit, onClose }: { orbit: Orbit; onClose: () =>
e.preventDefault();
if (settings && !save.isPending) save.mutate(settings);
}}>
<RetentionFields draft={draft} onChange={setDraft} />
<Hint>Changes apply after the next successful capture.</Hint>
<RetentionFields draft={draft} onChange={setDraft} managed={!!orbit.application_id} />
<Hint>{orbit.application_id
? "Managed backups use custom GFS counts or the managed default. Changes apply after the next successful capture."
: "Changes apply after the next successful capture. A rehearsal never prunes snapshots."}</Hint>
{save.isError && <p role="alert" className="text-sm text-orbit-red">Retention could not be saved.</p>}
<div className="flex gap-2">
<Button type="button" className="flex-1" disabled={save.isPending} onClick={onClose}>Cancel</Button>

View File

@@ -36,25 +36,38 @@ export function retentionSettings({ preset, counts }: Draft): RetentionSettings
}
export function describeRetention(orbit: Orbit): string {
if (orbit.capture_retention) {
const policy = orbit.capture_retention;
const source = orbit.retention_source === "profile" ? "Capture profile" : "Managed default";
const description = policy.mode === "age"
? `Keep ${policy.days} days and always keep the newest`
: `Keep ${policy.keep} most recent`;
return `${description} · ${source}`;
}
if (orbit.retention) {
const policy = orbit.retention;
return tiers.map(([key, label]) => `${policy[key]} ${label.toLowerCase()}`).join(" · ");
return tiers.map(([key, label]) => `${policy[key]} ${label.toLowerCase()}`).join(" · ") + " · Orbit policy";
}
const preset = orbit.decay_preset ?? DECAY_PRESETS[0].id;
return DECAY_PRESETS.find((item) => item.id === preset)?.title ?? preset;
}
export function RetentionFields({ draft, onChange }: { draft: Draft; onChange: (draft: Draft) => void }) {
export function RetentionFields({ draft, onChange, managed = false }: {
draft: Draft; onChange: (draft: Draft) => void; managed?: boolean;
}) {
const invalid = !retentionSettings(draft);
return (
<div className="space-y-3">
<label className="block text-sm">
<span className="text-star-400">Retention</span>
<select className={inputClass} value={draft.preset} onChange={(e) => onChange({ ...draft, preset: e.target.value })}>
{!DECAY_PRESETS.some((item) => item.id === draft.preset) && draft.preset !== "custom" && (
<option value={draft.preset}>{draft.preset}</option>
)}
{DECAY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.title}</option>)}
<select className={inputClass} value={managed && draft.preset !== "custom" ? DECAY_PRESETS[0].id : draft.preset}
onChange={(e) => onChange({ ...draft, preset: e.target.value })}>
{managed ? <option value={DECAY_PRESETS[0].id}>Managed default</option> : <>
{!DECAY_PRESETS.some((item) => item.id === draft.preset) && draft.preset !== "custom" && (
<option value={draft.preset}>{draft.preset}</option>
)}
{DECAY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.title}</option>)}
</>}
<option value="custom">Custom (GFS)</option>
</select>
</label>

View File

@@ -0,0 +1,18 @@
import { useQuery } from "@tanstack/react-query";
import { fetchOutposts } from "../../api";
export function OutpostField({ className }: { className: string }) {
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
const paired = outposts.data?.filter((outpost) => outpost.pairing_state === "active");
return (
<label className="block text-sm text-star-300">
Assigned Outpost
<select name="outpost" required className={className} defaultValue="">
<option value="">Choose a paired Outpost</option>
{paired?.map(({ id, name }) => <option key={id} value={id}>{name || "Outpost"} · {id}</option>)}
</select>
{outposts.isError && <span role="alert">Could not load paired Outposts.</span>}
{paired?.length === 0 && <span>Pair an agent in Outposts first.</span>}
</label>
);
}

View File

@@ -1,6 +1,7 @@
import { useMutation } from "@tanstack/react-query";
import { useMutation, useQuery } from "@tanstack/react-query";
import { motion } from "motion/react";
import { startPairing } from "../../api";
import { fetchOutposts, startPairing } from "../../api";
import { formatWhen } from "../../lib/format";
import { useReducedMotion } from "../../hooks/useReducedMotion";
import { ambientPulse } from "../../lib/motion";
import { Button } from "../ui/Button";
@@ -19,6 +20,7 @@ export function WormholeView({
onSuccess: onPaired,
});
const reducedMotion = useReducedMotion();
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
const expires = pairing ? new Date(pairing.expires_at).toLocaleTimeString() : "";
@@ -44,7 +46,7 @@ export function WormholeView({
<p className="text-sm text-star-400 mt-4">Burns at {expires}</p>
<Hint>
On the outpost:{" "}
<code className="font-mono text-orbit-amber">tessera-agent pair {pairing.code}</code>
<code className="font-mono text-orbit-amber">tessera-agent --hub-url {window.location.origin} --credentials wormhole.json pair {pairing.code}</code>
</Hint>
<Button variant="ghost" className="mt-4 w-full" onClick={() => gen.mutate()}>
Generate fresh code
@@ -57,13 +59,21 @@ export function WormholeView({
<section className="mt-8 space-y-3">
<h3 className="text-sm font-medium text-star-200">Outpost health</h3>
<div className="rounded-xl border border-space-700 bg-space-800/40 p-4 flex items-center gap-3">
<span className="w-2 h-2 rounded-full bg-star-400/50" />
<div>
<p className="text-sm text-star-300">No outposts paired yet</p>
<p className="text-xs text-star-400">Grey dot means offline or waiting.</p>
</div>
</div>
{outposts.isPending && <p role="status" className="text-sm text-star-300">Loading paired outposts…</p>}
{outposts.isError && <p role="alert" className="text-sm text-orbit-red">Could not read outpost health.</p>}
{outposts.data?.length === 0 && <p className="text-sm text-star-300">No outposts paired yet.</p>}
{outposts.data?.map((outpost) => {
const online = outpost.last_seen && Date.now() - Date.parse(outpost.last_seen) < 120_000;
return (
<div key={outpost.id} className="flex items-center gap-3 rounded-xl border border-space-700 bg-space-800/40 p-4">
<span aria-hidden="true" className={`register-signal signal-${online ? "green" : "grey"}`} />
<div className="min-w-0">
<p className="break-words text-sm text-star-100">{outpost.name || "Outpost"}</p>
<p className="text-xs text-star-400">{outpost.last_seen ? `Last activity ${formatWhen(outpost.last_seen)}` : "No agent activity recorded"} · {outpost.id}</p>
</div>
</div>
);
})}
</section>
</div>
);
@@ -77,6 +87,7 @@ function EmptyWormhole({
loading: boolean;
}) {
const reducedMotion = useReducedMotion();
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
return (
<div className="text-center py-8">
<div className="relative mx-auto w-24 h-24 rounded-full border border-wormhole-violet/30 flex items-center justify-center text-3xl">

View File

@@ -0,0 +1,154 @@
import { useId, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { cancelRestore, enqueueRestore, fetchOutposts, fetchRestoreJobs, fetchRestoreTargets, reconcileRestore, type RestoreJob, type RestoreTarget } from "../../api";
import { RestoreTargetForm } from "./RestoreTargetForm";
import { Button } from "../ui/Button";
const field = "mt-1 w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100";
const phases: Record<string, string> = {
queued: "Waiting for outpost",
claimed: "Assigned to agent",
checking: "Verifying archive and target",
safety: "Creating safety backup",
ready: "Safety backup verified",
applying: "Applying restore",
completed: "Restore complete",
wrong_target: "Target identity verification failed",
invalid_payload: "Archive verification failed",
safety_failed: "Safety backup could not be verified",
apply_failed: "Apply failed. Recovery required.",
lease_lost: "Agent disconnected during apply. Recovery required.",
reconciled: "Recovery verified by operator",
cancelled: "Cancelled",
};
export function DatabaseRestore({ snapshot, application, engine }: {
snapshot: string; application: string; engine: RestoreTarget["engine"];
}) {
const fieldId = useId();
const query = useQueryClient();
const [target, setTarget] = useState("");
const [confirmation, setConfirmation] = useState("");
const [registering, setRegistering] = useState(false);
const targets = useQuery({
queryKey: ["restore-targets", snapshot],
queryFn: () => fetchRestoreTargets(snapshot),
refetchInterval: 5_000,
});
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
const targetLabel = (entry: RestoreTarget) => {
const name = outposts.data?.find(({ id }) => id === entry.outpost_id)?.name;
return `${entry.name} · ${entry.identity.database} · ${name || entry.outpost_id}`;
};
const selected = targets.isSuccess
? targets.data.find((entry) => entry.id === target && !entry.ineligible_reason)
: undefined;
const jobs = useQuery({
queryKey: ["restore-jobs", snapshot],
queryFn: () => fetchRestoreJobs(snapshot),
refetchInterval: 2_000,
});
const refresh = () => void query.invalidateQueries({ queryKey: ["restore-jobs", snapshot] });
const submit = useMutation({
mutationFn: () => enqueueRestore(snapshot, target, confirmation),
onSuccess: (job) => {
query.setQueryData<RestoreJob[]>(["restore-jobs", snapshot],
(previous) => [job, ...(previous ?? []).filter(({ id }) => id !== job.id)]);
setConfirmation("");
refresh();
},
});
const required = `RESTORE ${snapshot} TO ${target}`;
return (
<section className="space-y-4 rounded-xl border border-space-700 bg-space-800/50 p-4">
<h3 className="font-semibold text-star-100">Database restore</h3>
{targets.isPending && <p role="status" className="text-sm text-star-300">Loading registered targets…</p>}
{targets.isError && <p role="alert" className="text-sm text-orbit-red">Could not read restore targets.</p>}
{targets.data?.length === 0 && <p className="text-sm text-star-300">This application has no registered restore targets.</p>}
{registering
? <RestoreTargetForm application={application} engine={engine} onClose={() => setRegistering(false)} />
: <Button type="button" onClick={() => setRegistering(true)}>Register restore target</Button>}
{targets.data?.length && !targets.data.some((entry) => !entry.ineligible_reason)
? <p className="text-sm text-star-300">No registered targets are eligible for this snapshot.</p>
: null}
{!!targets.data?.length && (
<form className="space-y-3" onSubmit={(event) => {
event.preventDefault();
if (selected && confirmation === required && !submit.isPending) submit.mutate();
}}>
<label htmlFor={fieldId} className="block text-sm text-star-300">Registered target</label>
<select id={fieldId} className={field} value={target}
onChange={(event) => { setTarget(event.target.value); setConfirmation(""); }}>
<option value="">Choose a target</option>
{targets.data.map((entry) => (
<option key={entry.id} value={entry.id} disabled={!!entry.ineligible_reason}>
{targetLabel(entry)}{entry.ineligible_reason ? ` · ${entry.ineligible_reason}` : ""}
</option>
))}
</select>
{selected && <>
<p className="break-words text-sm text-star-100">
Restore to {selected.identity.database} on {outposts.data?.find(({ id }) => id === selected.outpost_id)?.name || "Outpost"} ({selected.outpost_id})
· {selected.engine} instance {selected.identity.instance}
</p>
<p className="text-sm text-star-300">The agent will verify the target and save a safety backup before applying this snapshot.</p>
<label className="block text-sm text-star-300">
Confirmation
<code className="my-1 block break-all text-xs text-star-100">{required}</code>
<input aria-label="Restore confirmation" className={field} value={confirmation} autoComplete="off"
onChange={(event) => setConfirmation(event.target.value)} />
</label>
</>}
<Button type="submit" variant="warn" disabled={!selected || confirmation !== required || submit.isPending}>
{submit.isPending ? "Queueing…" : "Queue database restore"}
</Button>
{submit.isError && <p role="alert" className="text-sm text-orbit-red">Restore could not be queued. Verify the selected target and confirmation.</p>}
</form>
)}
{jobs.isError && <p role="alert" className="text-sm text-orbit-red">Restore history is unavailable.</p>}
{!!jobs.data?.length && (
<ul className="space-y-2">
{jobs.data.map((job) => <RestoreStatus key={job.id} job={job} destination={targetLabel(job.target)} refresh={refresh} />)}
</ul>
)}
</section>
);
}
function RestoreStatus({ job, destination, refresh }: { job: RestoreJob; destination: string; refresh: () => void }) {
const [acknowledgement, setAcknowledgement] = useState("");
const required = `RECONCILE ${job.id}`;
const cancel = useMutation({ mutationFn: () => cancelRestore(job.id), onSuccess: refresh });
const reconcile = useMutation({
mutationFn: () => reconcileRestore(job.id, acknowledgement), onSuccess: refresh,
});
return (
<li className="space-y-2 rounded-xl border border-space-700 p-3 text-sm">
<strong className="text-star-100">{destination}</strong>
<p role="status" className={job.status === "recovery_required" || job.status === "failed" ? "text-orbit-red" : "text-star-300"}>
{phases[job.phase] ?? job.status}
</p>
{job.safety_snapshot_id && (
<a className="break-all text-orbit-amber underline" href={`/api/v1/snapshots/${job.safety_snapshot_id}/download`} download>
Safety backup {job.safety_snapshot_id}
</a>
)}
{(job.status === "queued" || job.status === "running") && (
<div><Button disabled={cancel.isPending} onClick={() => cancel.mutate()}>Cancel queued restore</Button></div>
)}
{job.status === "recovery_required" && (
<div className="space-y-2">
<label className="block text-star-300">
Verify the target data before releasing its lock.
<code className="my-1 block break-all text-xs text-star-100">{required}</code>
<input aria-label="Reconciliation confirmation" className={field} value={acknowledgement}
onChange={(event) => setAcknowledgement(event.target.value)} />
</label>
<Button variant="warn" disabled={acknowledgement !== required || reconcile.isPending}
onClick={() => reconcile.mutate()}>Mark target recovered</Button>
</div>
)}
{(cancel.isError || reconcile.isError) && <p role="alert" className="text-orbit-red">Action failed. Check the current job state.</p>}
</li>
);
}

View File

@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { motion } from "motion/react";
import type { Snapshot } from "../../api";
import { DatabaseRestore } from "./DatabaseRestore";
import { formatBytes, formatWhen } from "../../lib/format";
import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState";
@@ -11,6 +12,7 @@ const GRACE = 12;
export function ReconstituteWizard({
snapshots,
selected,
scopedExport,
onStart,
onPoll,
onAbort,
@@ -18,6 +20,7 @@ export function ReconstituteWizard({
}: {
snapshots: Snapshot[];
selected: string | null;
scopedExport?: boolean;
onStart: (snapId: string, target: string) => Promise<{
session_id: string;
session: { seconds_remaining: number; state: string };
@@ -27,7 +30,8 @@ export function ReconstituteWizard({
onBusyChange: (busy: boolean) => void;
}) {
const [snapId, setSnapId] = useState(selected ?? snapshots[0]?.id ?? "");
const [target, setTarget] = useState("./restore/out");
const [databaseMode, setDatabaseMode] = useState(true);
const [target, setTarget] = useState(scopedExport ? "restored.dump" : "./restore/out");
const [sessionId, setSessionId] = useState<string | null>(null);
const [remaining, setRemaining] = useState(GRACE);
const [state, setState] = useState("idle");
@@ -36,6 +40,7 @@ export function ReconstituteWizard({
const [reconnecting, setReconnecting] = useState(false);
const snap = snapshots.find((s) => s.id === snapId);
const managed = snap?.capture?.restore_ready ? snap.capture : undefined;
const inCountdown = state === "countdown" || state === "confirming";
const busy = !!action || inCountdown || state === "restoring";
@@ -72,7 +77,7 @@ export function ReconstituteWizard({
return (
<div className="space-y-4">
<p className="text-sm text-star-300">
Choose a snapshot and a destination on the hub.
Choose a recovery point and a destination.
</p>
{snap && (
@@ -87,7 +92,7 @@ export function ReconstituteWizard({
<select
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5"
value={snapId}
onChange={(e) => setSnapId(e.target.value)}
onChange={(e) => { setSnapId(e.target.value); setDatabaseMode(true); }}
disabled={busy}
>
{snapshots.map((s) => (
@@ -98,8 +103,25 @@ export function ReconstituteWizard({
</select>
</label>
{managed && (
<div className="flex flex-wrap gap-2" aria-label="Recovery destination" role="group">
<Button type="button" aria-pressed={databaseMode} disabled={busy}
variant={databaseMode ? "primary" : "ghost"} onClick={() => setDatabaseMode(true)}>
Restore to database
</Button>
<Button type="button" aria-pressed={!databaseMode} disabled={busy}
variant={databaseMode ? "ghost" : "primary"} onClick={() => setDatabaseMode(false)}>
Export file on hub
</Button>
</div>
)}
{managed && databaseMode ? (
<DatabaseRestore key={snapId} snapshot={snapId} application={managed.application_id}
engine={managed.engine} />
) : <>
<label className="block text-sm">
<span className="text-star-400">Target path</span>
<span className="text-star-400">{scopedExport ? "Export filename on hub" : "Export file path on hub"}</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5 font-mono text-xs"
value={target}
@@ -151,7 +173,7 @@ export function ReconstituteWizard({
await onAbort(sessionId);
} catch {
setAction(undefined);
setError("Could not cancel the restore. Check the current session status.");
setError("Could not cancel the file export. Check the current session status.");
}
}}
>
@@ -170,39 +192,40 @@ export function ReconstituteWizard({
setState(res.session.state);
setRemaining(res.session.seconds_remaining);
} catch {
setError("Could not confirm that the hub started the restore.");
setError("Could not confirm that the hub started writing to the destination.");
} finally {
setAction(undefined);
}
}}
>
Begin restore
Begin file export
</Button>
</div>
{error && <p role="alert" className="text-orbit-red text-sm">{error}</p>}
{reconnecting && <p role="status" className="text-orbit-amber text-sm">Reconnecting to the restore session…</p>}
{state === "restoring" && <p role="status" className="text-orbit-amber text-sm">Restoring snapshot…</p>}
{reconnecting && <p role="status" className="text-orbit-amber text-sm">Reconnecting to the export session…</p>}
{state === "restoring" && <p role="status" className="text-orbit-amber text-sm">Exporting snapshot…</p>}
{state === "unavailable" && (
<p role="alert" className="text-orbit-red text-sm">The hub no longer has this restore session. Check the destination before retrying.</p>
<p role="alert" className="text-orbit-red text-sm">The hub no longer has this export session. Check the destination before retrying.</p>
)}
{state === "completed" && (
<p className="text-orbit-green text-sm text-center">Reconstitute complete.</p>
<p className="text-orbit-green text-sm text-center">File export complete.</p>
)}
{state === "aborted" && (
<p className="text-star-300 text-sm text-center">Reconstitute cancelled. Nothing was changed.</p>
<p className="text-star-300 text-sm text-center">File export cancelled.</p>
)}
{state === "failed" && (
<p className="text-orbit-red text-sm text-center">Reconstitute failed — check telemetry.</p>
<p className="text-orbit-red text-sm text-center">File export failed. Check telemetry.</p>
)}
<Hint>The hub writes after the countdown. An existing file at the destination may be overwritten.</Hint>
<Hint>{scopedExport ? "The hub writes to its exports directory after the countdown." : "The hub writes after the countdown. An existing file at the destination may be overwritten."}</Hint>
{sessionId && (
<TelemetryPanel label="Session">
{JSON.stringify({ sessionId, state, remaining }, null, 2)}
</TelemetryPanel>
)}
</>}
</div>
);
}

View File

@@ -0,0 +1,68 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { registerRestoreTarget, type RestoreTarget } from "../../api";
import { OutpostField } from "../outposts/OutpostField";
import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState";
const field = "mt-1 w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100";
const uuidPattern = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
export function RestoreTargetForm({ application, engine, onClose }: {
application: string;
engine: RestoreTarget["engine"];
onClose: () => void;
}) {
const [initialId] = useState(() => globalThis.crypto?.randomUUID?.() ?? "");
const qc = useQueryClient();
const register = useMutation({
mutationFn: registerRestoreTarget,
onSuccess: async () => {
await qc.invalidateQueries({ queryKey: ["restore-targets"] });
onClose();
},
});
return (
<form className="space-y-3 rounded-xl border border-space-700 p-3" onSubmit={(event) => {
event.preventDefault();
if (register.isPending) return;
const data = new FormData(event.currentTarget);
register.mutate({
id: String(data.get("id")).toLowerCase(),
application_id: application,
outpost_id: String(data.get("outpost")),
name: String(data.get("name")).trim(),
engine,
identity: {
instance: String(data.get("instance")).trim().toLowerCase(),
database: String(data.get("database")),
},
});
}}>
<h4 className="font-medium text-star-100">Register a {engine === "postgres" ? "PostgreSQL" : "MySQL"} restore target</h4>
<label className="block text-sm text-star-300">
Target name
<input name="name" required maxLength={128} className={field} />
</label>
<label className="block text-sm text-star-300">
Target UUID
<input name="id" defaultValue={initialId} required pattern={uuidPattern} className={field} />
</label>
<OutpostField className={field} />
<label className="block text-sm text-star-300">
{engine === "postgres" ? "Cluster system identifier" : "Server UUID"}
<input name="instance" required pattern={engine === "postgres" ? "[0-9]+" : uuidPattern} className={field} />
</label>
<label className="block text-sm text-star-300">
Database name
<input name="database" required maxLength={255} className={field} />
</label>
<Hint>Configure this target UUID under the application’s targets on the assigned agent. Keep the connection settings and credentials on that agent.</Hint>
{register.isError && <p role="alert" className="text-sm text-orbit-red">Could not register the target. Verify its identity, UUID, and Outpost.</p>}
<div className="flex gap-2">
<Button type="button" disabled={register.isPending} onClick={onClose}>Cancel</Button>
<Button type="submit" variant="primary" disabled={register.isPending}>Register target</Button>
</div>
</form>
);
}

View File

@@ -1,17 +1,18 @@
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import { animate, spring, useMotionValue } from "motion/react";
import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { animate, motion, spring, useMotionValue, useTransform, type MotionStyle, type MotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
import { orbitStatus } from "../../lib/format";
import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout";
import {
assignOrbitSlots, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
assignOrbitSlots, CAPTURE_HIGHLIGHT_START, capturePhases, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, type Vec2,
} from "../../lib/galaxyLayout";
import { useGalaxyMotion } from "../../hooks/useGalaxyMotion";
import { uiSpring } from "../../lib/motion";
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { ambientSpring, gentleSpring, uiSpring } from "../../lib/motion";
import { VaultCore } from "./VaultCore";
export type CaptureArrival = { orbitId: string; snapshotId: string };
export type CaptureEffect = { orbitId: string; key: number; snapshotId?: string };
type Props = {
orbits: Orbit[];
@@ -19,7 +20,10 @@ type Props = {
recentSnapshots: Snapshot[];
flowing: boolean;
reducedMotion: boolean;
arrival?: CaptureArrival;
bigScreen: boolean;
captureEffect?: CaptureEffect;
captureGlow: MotionValue<number>;
captureReady: boolean;
onSelectOrbit: (id: string) => void;
onSelectSnapshot: (id: string) => void;
};
@@ -28,107 +32,198 @@ const HALF_WIDTH = SCENE_WIDTH / 2;
const HALF_HEIGHT = SCENE_HEIGHT / 2;
const labelFont = "500 11px ui-monospace, monospace";
const MAX_LABELS = 12;
const clamp = (value: number) => Math.max(0, Math.min(1, value));
const ACCRETION_SECONDS = 6.4;
const TRAIL_WIDTHS = [0.8, 1.4, 2.3];
export function BlackholeGalaxy({
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival, onSelectOrbit, onSelectSnapshot,
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, captureReady, onSelectOrbit, onSelectSnapshot,
}: Props) {
const frame = useRef<HTMLDivElement>(null);
const bodyNodes = useRef(new Map<SVGGElement, { id: string; far: boolean }>());
const bodyNodes = useRef(new Map<SVGGElement, { id: string; index: number }>());
const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined);
const elapsed = useRef(0);
const entrance = useRef(0);
const core = useRef<SVGGElement>(null);
const meteor = useRef<{ id: string; time: number; source: Vec2; progress: ReturnType<typeof spring> }>(undefined);
const capture = useRef<{ event: CaptureEffect; time: number; source: Vec2; progress: ReturnType<typeof spring>; done: boolean; waiting: boolean }>(undefined);
const skippedCapture = useRef<CaptureEffect>(undefined);
const sourceFlare = useRef<SVGCircleElement>(null);
const busyAngle = useRef(0);
const diskTime = useRef(0);
const hasRunning = orbits.some(orbit => orbitStatus(orbit.last_status).busy);
const trailId = useId();
const trail = useRef<SVGPathElement>(null);
const trailSegments = useRef<(SVGUseElement | null)[]>([]);
const head = useRef<SVGCircleElement>(null);
const effect = useRef<SVGGElement>(null);
const [width, setWidth] = useState(0);
const [coasting, setCoasting] = useState(false);
const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0);
const moving = !reducedMotion && (flowing || coasting);
const [lockedPhase, setLockedPhase] = useState(0);
const reveal = useMotionValue(flowing ? 0 : 1);
const revealStyle = useTransform(reveal, clamp);
const revealVariables: MotionStyle & { "--lock-reveal": MotionValue<number> } = { "--lock-reveal": revealStyle };
const selectionX = useMotionValue(0);
const selectionY = useMotionValue(0);
const selectionPlaced = useRef(false);
useLayoutEffect(() => () => rate.stop(), [rate]);
useLayoutEffect(() => () => {
rate.stop();
reveal.stop();
selectionX.stop();
selectionY.stop();
}, [rate, reveal, selectionX, selectionY]);
useLayoutEffect(() => {
if (reducedMotion) {
rate.jump(0);
reveal.jump(1);
setLockedPhase(elapsed.current);
setCoasting(false);
return;
}
if (flowing) animate(reveal, 0, gentleSpring);
const target = flowing ? 1 : 0;
if (rate.get() === target && !rate.isAnimating()) return;
setCoasting(!flowing);
animate(rate, target, { ...uiSpring, onComplete: () => setCoasting(false) });
}, [flowing, rate, reducedMotion]);
animate(rate, target, {
...uiSpring,
restDelta: 0.025,
restSpeed: 0.25,
onComplete: () => {
if (!flowing) {
setLockedPhase(elapsed.current);
animate(reveal, 1, gentleSpring);
}
setCoasting(false);
},
});
}, [flowing, rate, reducedMotion, reveal]);
const slots = useMemo(
() => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId),
[orbits, selectedOrbitId],
);
useLayoutEffect(() => { slotsBefore.current = slots; }, [slots]);
useLayoutEffect(() => {
const element = frame.current;
if (!element) return;
const measure = () => setWidth(element.clientWidth);
const observer = new ResizeObserver(measure);
observer.observe(element);
measure();
return () => observer.disconnect();
}, []);
useScreenTransition(frame, bigScreen, reducedMotion, setWidth);
const draw = useCallback((delta: number) => {
if (moving && delta > 0) {
elapsed.current += delta * Math.max(0, rate.get());
const phase = (elapsed.current % ACCRETION_SECONDS) / ACCRETION_SECONDS;
const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined;
const selectedPosition = selectedSlot && orbitPose(selectedSlot, lockedPhase);
const selectedX = selectedPosition?.x;
const selectedY = selectedPosition?.y;
useLayoutEffect(() => {
if (selectedX === undefined || selectedY === undefined) {
selectionPlaced.current = false;
} else if (!selectionPlaced.current || reducedMotion) {
selectionX.jump(selectedX);
selectionY.jump(selectedY);
selectionPlaced.current = true;
} else if (!moving) {
animate(selectionX, selectedX, uiSpring);
animate(selectionY, selectedY, uiSpring);
}
}, [moving, reducedMotion, selectedX, selectedY, selectionX, selectionY]);
useGalaxyMotion((delta) => {
const speed = moving ? Math.max(0, rate.get()) : 0;
elapsed.current += delta * speed;
if (hasRunning && !reducedMotion && delta > 0) {
busyAngle.current = (busyAngle.current + 105 * delta) % 360;
frame.current?.style.setProperty("--busy-angle", `${busyAngle.current}deg`);
}
const wasEntering = entrance.current < 0.6;
if (slots.size) entrance.current = reducedMotion ? 0.6 : Math.min(0.6, entrance.current + delta);
const entering = !reducedMotion && slots.size > 0 && entrance.current < 0.6;
if (!delta || moving || (!reducedMotion && wasEntering)) {
for (const [node, { id, index }] of bodyNodes.current) {
const slot = slots.get(id)!;
const { x, y } = orbitPose(slot, elapsed.current);
const depth = y / (slot.radius * ORBIT_TILT);
const appear = entering ? clamp((entrance.current - Math.min(index * 0.013, 0.33)) / 0.23) : 1;
node.setAttribute("transform", `translate(${x} ${y}) scale(${0.95 + depth * 0.08})`);
node.setAttribute("opacity", String(appear * (0.88 + depth * 0.12)));
}
}
if (moving && selectedSlot) {
const point = orbitPose(selectedSlot, elapsed.current);
selectionX.jump(point.x);
selectionY.jump(point.y);
}
if (reducedMotion) skippedCapture.current = captureEffect;
const event = captureEffect === skippedCapture.current ? undefined : captureEffect;
const slot = event && slots.get(event.orbitId);
if (event && slot && capture.current?.event !== event) {
captureGlow.set(0);
effect.current?.setAttribute("opacity", "0");
const source = orbitPose(slot, elapsed.current);
capture.current = {
event, source, time: 0, done: false, waiting: false,
progress: spring({ ...ambientSpring, keyframes: [0, 1], restDelta: 0.002 }),
};
if (event.snapshotId) {
const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35));
trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" "));
}
}
const current = capture.current;
let absorption = 0;
let capturing = false;
if (event && current?.event === event && !current.done) {
// The impact can finish while the snapshot list is still refreshing.
if (!current.waiting || captureReady) current.time += delta * 1000;
const { value, done } = current.progress.next(current.time);
const success = !!event.snapshotId;
current.waiting = success && !captureReady && value >= CAPTURE_HIGHLIGHT_START;
const progress = current.waiting ? CAPTURE_HIGHLIGHT_START : done ? 1 : value;
const phases = capturePhases(progress);
current.done = done && !current.waiting;
const source = slot ? orbitPose(slot, elapsed.current) : current.source;
const pulse = success ? phases.flare : phases.failure;
sourceFlare.current?.setAttribute("cx", String(source.x));
sourceFlare.current?.setAttribute("cy", String(source.y));
sourceFlare.current?.setAttribute("r", String(7 + 13 * clamp(value)));
sourceFlare.current?.setAttribute("stroke", success ? "#ffd3a5" : "#f59183");
sourceFlare.current?.setAttribute("opacity", String(0.75 * pulse));
if (success) {
const { x, y } = spiralPoint(current.source, phases.flight);
head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y));
head.current?.setAttribute("r", String(3.5 * (1 - phases.flight ** 4)));
const segmentLength = Math.min(phases.flight, 0.19) * (1 - phases.flight ** 6) / TRAIL_WIDTHS.length;
trailSegments.current.forEach((segment, index) => {
segment?.setAttribute("stroke-dasharray", `${segmentLength} 1`);
segment?.setAttribute("stroke-dashoffset", String((TRAIL_WIDTHS.length - index) * segmentLength - phases.flight));
});
effect.current?.setAttribute("opacity", String(clamp(phases.flight * 14) * (1 - phases.flight ** 8)));
absorption = phases.absorption;
captureGlow.set(phases.highlight);
}
capturing = !current.done && !current.waiting;
} else {
sourceFlare.current?.setAttribute("opacity", "0");
effect.current?.setAttribute("opacity", "0");
captureGlow.set(0);
}
if (delta > 0 && (speed || absorption)) {
diskTime.current += delta * (speed + 3.2 * absorption);
const phase = (diskTime.current % ACCRETION_SECONDS) / ACCRETION_SECONDS;
core.current?.style.setProperty("--accretion-offset", String(-100 * phase));
}
for (const [node, { id, far }] of bodyNodes.current) {
const slot = slots.get(id);
if (!slot) continue;
const { x, y } = orbitPose(slot, elapsed.current);
const visible = far === (y < 0);
const display = visible ? "" : "none";
if (node.style.display !== display) node.style.display = display;
if (!visible) continue;
node.setAttribute("transform", `translate(${x} ${y})`);
const coreStyle = core.current?.style;
if (coreStyle && (absorption || coreStyle.getPropertyValue("--capture-absorption") !== "0")) {
coreStyle.setProperty("--capture-absorption", String(absorption));
}
if (!arrival || reducedMotion) {
effect.current?.setAttribute("opacity", "0");
return moving;
}
const slot = slots.get(arrival.orbitId);
if (meteor.current?.id !== arrival.snapshotId && slot) {
const source = orbitPose(slot, elapsed.current);
meteor.current = {
id: arrival.snapshotId,
time: 0,
source,
progress: spring({ ...uiSpring, stiffness: 36, damping: 12, keyframes: [0, 1], restDelta: 0.002 }),
};
const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35));
trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" "));
}
const current = meteor.current;
if (!current || current.id !== arrival.snapshotId) return moving;
current.time += delta * 1000;
const { value: progress, done } = current.progress.next(current.time);
const { x, y } = spiralPoint(current.source, progress);
head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y));
trail.current?.setAttribute("stroke-dashoffset", String(0.2 - progress));
effect.current?.setAttribute("opacity", String(progress >= 1 ? 0 : Math.min(1, (1 - progress) * 6)));
return moving || !done;
}, [arrival, moving, rate, reducedMotion, slots]);
useGalaxyMotion(moving || (!reducedMotion && !!arrival), draw);
return moving || entering || capturing || (hasRunning && !reducedMotion);
});
const scale = width / SCENE_WIDTH;
const height = SCENE_HEIGHT * scale;
const hitRadius = Math.max(12, scale ? 12 / scale : 12);
const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined;
const selectedPosition = !moving && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined;
const positions = !moving ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : [];
const positions = [...slots.values()].map((slot) => orbitPose(slot, lockedPhase));
const moons = selectedPosition
? moonPoses(selectedPosition, recentSnapshots.length, 2 * hitRadius + 3, positions)
: [];
@@ -146,87 +241,100 @@ export function BlackholeGalaxy({
};
let labels: ReturnType<typeof placeLabels> = [];
if (!moving && width && labelCandidates.length) {
if (width && labelCandidates.length) {
const measure = document.createElement("canvas").getContext("2d");
if (measure) measure.font = labelFont;
const markers = positions.map((point) => box(point, 7));
const core = box({ x: 0, y: 0 }, 65 * scale);
labels = placeLabels(labelCandidates.map(({ id, name }) => {
const point = screen(orbitPose(slots.get(id)!, elapsed.current));
const point = screen(orbitPose(slots.get(id)!, lockedPhase));
return { id, ...point, width: Math.min(146, Math.ceil(measure?.measureText(name).width ?? name.length * 7) + 16) };
}), width, height, [core, ...markers, ...moons.map((moon) => box(moon, 12))]);
}), width, height, [core, ...markers, ...moons.map((moon) => box(moon, 12))], selectedOrbitId);
}
const focusLabel = labels.find(({ id }) => id === selectedOrbitId);
const renderOrbits = (far: boolean) => visible.map((orbit) => {
const point = orbitPose(slots.get(orbit.id)!, elapsed.current);
// Each marker switches layers when it crosses the orbital plane.
const renderOrbits = visible.map((orbit, index) => {
const selected = orbit.id === selectedOrbitId;
const status = orbitStatus(orbit.last_status);
return (
<g
<motion.g
key={orbit.id}
ref={(node) => {
if (!node) return;
bodyNodes.current.set(node, { id: orbit.id, far });
bodyNodes.current.set(node, { id: orbit.id, index });
return () => { bodyNodes.current.delete(node); };
}}
transform={`translate(${point.x} ${point.y})`}
style={{ display: far === (point.y < 0) ? "" : "none" }}
initial={false}
animate="idle"
whileHover="hover"
data-orbit-marker={orbit.id}
className={`orbit-marker orbit-marker--${status.tone}${selected ? " orbit-marker--selected" : ""}`}
>
<circle className="orbit-halo" r={selected ? 16 : 10} />
<motion.circle className="orbit-halo" r={selected ? 16 : 10}
variants={{ idle: { opacity: 0.08 }, hover: { opacity: 0.3 } }} />
{status.tone === "red" && <path className="orbit-alert" d="M0 -8 8 0 0 8 -8 0Z" />}
{status.busy && <circle className="orbit-busy" r="8.5" />}
{selected && <circle className="orbit-selection" r="13" />}
<circle className="orbit-light" r="4.6" />
<circle className="orbit-hit" r={hitRadius} onClick={() => onSelectOrbit(orbit.id)} />
</g>
</motion.g>
);
});
return (
<div ref={frame} className="galaxy-frame" data-flowing={flowing}>
<motion.div ref={frame} className="galaxy-frame" data-flowing={flowing} style={revealVariables}>
<svg viewBox={`${-HALF_WIDTH} ${-HALF_HEIGHT} ${SCENE_WIDTH} ${SCENE_HEIGHT}`} aria-hidden="true">
<g className="orbit-tracks" pointerEvents="none">
{orbitRadii.map((radius) => (
<ellipse key={radius} rx={radius} ry={radius * ORBIT_TILT} className={selectedSlot?.radius === radius ? "is-selected" : ""} />
))}
</g>
<g className="orbit-layer orbit-layer--far">{renderOrbits(true)}</g>
<VaultCore ref={core} />
<g className="orbit-layer orbit-layer--near">{renderOrbits(false)}</g>
{selectedPosition && moons.map(({ x, y }, index) => {
const snapshot = recentSnapshots[index];
return (
<g key={snapshot.id} data-snapshot-marker={snapshot.id} className="snapshot-marker">
<line x1={selectedPosition.x} y1={selectedPosition.y} x2={x} y2={y} />
<rect className="snapshot-light" x={x - 4} y={y - 4} width="8" height="8" rx="1" transform={`rotate(45 ${x} ${y})`} />
<circle className="orbit-hit" cx={x} cy={y} r={hitRadius} onClick={() => onSelectSnapshot(snapshot.id)} />
</g>
);
})}
{selectedPosition && focusLabel && (
<line className="focus-leader"
x1={selectedPosition.x} y1={selectedPosition.y}
x2={(focusLabel.x + focusLabel.width / 2) / scale - HALF_WIDTH}
y2={(focusLabel.y + LABEL_HEIGHT / 2) / scale - HALF_HEIGHT}
/>
)}
<g className="orbit-layer">{renderOrbits}</g>
{selectedPosition && <motion.circle className="orbit-selection" cx={selectionX} cy={selectionY} r="13" />}
<g className="lock-details" pointerEvents={moving ? "none" : undefined}>
{selectedPosition && moons.map(({ x, y }, index) => {
const snapshot = recentSnapshots[index];
return (
<g key={index} data-snapshot-marker={snapshot.id} className="snapshot-marker">
<motion.line x1={selectionX} y1={selectionY} initial={false} animate={{ x2: x, y2: y }} />
<motion.g initial={false} animate={{ x, y }}>
<rect className="snapshot-light" x="-4" y="-4" width="8" height="8" rx="1" transform="rotate(45)" />
{snapshot.id === captureEffect?.snapshotId && (
<motion.circle className="snapshot-flash" r="9" style={{ opacity: captureGlow }} />
)}
<circle className="orbit-hit" r={hitRadius} onClick={() => onSelectSnapshot(snapshot.id)} />
</motion.g>
</g>
);
})}
{selectedPosition && focusLabel && (
<motion.line className="focus-leader"
x1={selectionX} y1={selectionY} initial={false}
animate={{
x2: (focusLabel.x + focusLabel.width / 2) / scale - HALF_WIDTH,
y2: (focusLabel.y + LABEL_HEIGHT / 2) / scale - HALF_HEIGHT,
}}
/>
)}
</g>
<circle ref={sourceFlare} className="capture-flare" opacity="0" pointerEvents="none" fill="none" />
<g ref={effect} className="capture-arrival" opacity="0" pointerEvents="none">
<path ref={trail} pathLength="1" strokeDasharray=".2 1" fill="none" />
<defs><path id={trailId} ref={trail} pathLength="1" /></defs>
{TRAIL_WIDTHS.map((strokeWidth, index) => (
<use key={strokeWidth} ref={node => { trailSegments.current[index] = node; }}
href={`#${trailId}`} fill="none" strokeWidth={strokeWidth} opacity={0.35 + index * 0.3} />
))}
<circle ref={head} r="3.5" />
</g>
</svg>
<div aria-hidden="true" className="scene-labels" style={{ font: labelFont }}>
{labels.map(({ id, x, y, width: labelWidth }) => (
<span key={id} style={{ left: x, top: y, width: labelWidth }} className={id === selectedOrbitId ? "is-selected" : ""}>
{labels.map(({ id, x, y, width: labelWidth }, index) => (
<span key={id} style={{ left: `${100 * x / width}%`, top: `${100 * y / height}%`, width: labelWidth, opacity: reducedMotion ? 1 : `clamp(0, (var(--lock-reveal) - ${index * 0.035}) * 1.8, 1)` }} className={id === selectedOrbitId ? "is-selected" : ""}>
{labelCandidates.find((orbit) => orbit.id === id)?.name}
</span>
))}
</div>
{orbits.length >= orbitCapacity && <p className="scene-density">Select an orbit in the list to inspect it</p>}
</div>
</motion.div>
);
}

View File

@@ -44,6 +44,7 @@ export const VaultCore = memo(function VaultCore({ ref }: { ref: Ref<SVGGElement
</filter>
</defs>
<ellipse rx="162" ry="81" cy="6" fill={paint("halo")} />
<ellipse className="core-absorption" rx="178" ry="89" cy="6" fill={paint("halo")} />
<g transform="rotate(-11)">
<path
d={`${LENS_ARC} M-114 13 C-62 38 -28 53 13 51 C54 48 89 27 111 6`}

View File

@@ -1,9 +1,10 @@
import { BlackholeGalaxy, type CaptureArrival } from "./BlackholeGalaxy";
import { BlackholeGalaxy, type CaptureEffect } from "./BlackholeGalaxy";
import { SpaceBackdrop } from "./SpaceBackdrop";
import { motion, type MotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
export function VaultScene({
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival,
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, captureEffect, captureGlow, captureReady,
bigScreen, onToggleBigScreen, onToggleFlow, onSelectOrbit, onSelectSnapshot,
}: {
orbits: Orbit[];
@@ -11,7 +12,9 @@ export function VaultScene({
recentSnapshots: Snapshot[];
flowing: boolean;
reducedMotion: boolean;
arrival?: CaptureArrival;
captureEffect?: CaptureEffect;
captureGlow: MotionValue<number>;
captureReady: boolean;
bigScreen: boolean;
onToggleBigScreen: () => void;
onToggleFlow: () => void;
@@ -27,7 +30,11 @@ export function VaultScene({
<div>
<p className="instrument-label">Vault map</p>
<p className="scene-mode">
<span className={`mode-signal${flowing ? " is-live" : ""}`} />
<motion.span className="mode-signal" initial={false} animate={{
rotate: flowing ? 0 : 45,
borderRadius: flowing ? 3 : 1,
backgroundColor: flowing ? "var(--color-orbit-green)" : "var(--accent)",
}} />
{flowing ? "Flowing" : "Locked"}
{!flowing && selected && <span className="scene-focus" title={selected.name}>· {selected.name}</span>}
</p>
@@ -64,7 +71,10 @@ export function VaultScene({
recentSnapshots={recentSnapshots}
flowing={flowing}
reducedMotion={reducedMotion}
arrival={arrival}
bigScreen={bigScreen}
captureEffect={captureEffect}
captureGlow={captureGlow}
captureReady={captureReady}
onSelectOrbit={onSelectOrbit}
onSelectSnapshot={onSelectSnapshot}
/>

View File

@@ -1,4 +1,6 @@
import type { Snapshot } from "../../api";
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { deleteSnapshot, type Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format";
import { Button } from "../ui/Button";
import { TelemetryPanel } from "../ui/Telemetry";
@@ -6,10 +8,21 @@ import { TelemetryPanel } from "../ui/Telemetry";
export function SnapshotSheet({
snap,
onReconstitute,
onDeleted,
}: {
snap: Snapshot;
onReconstitute: () => void;
onDeleted: () => void;
}) {
const [confirmDelete, setConfirmDelete] = useState(false);
const qc = useQueryClient();
const deletion = useMutation({
mutationFn: () => deleteSnapshot(snap.id),
onSuccess: () => {
void qc.invalidateQueries({ queryKey: ["snapshots"] });
onDeleted();
},
});
return (
<div className="space-y-4">
<p className="text-sm text-star-300">
@@ -22,8 +35,20 @@ export function SnapshotSheet({
<p className="text-star-100">{formatBytes(snap.size_bytes)}</p>
</div>
<Button variant="warn" className="w-full" onClick={onReconstitute}>
Restore this snapshot
{snap.capture?.restore_ready ? "Database recovery options" : "Export file on hub"}
</Button>
<a href={`/api/v1/snapshots/${snap.id}/download`} download
className="console-control block w-full text-center">Download snapshot</a>
{confirmDelete ? (
<div className="space-y-2 rounded-xl border border-orbit-red/40 p-3">
<p className="text-sm text-star-300">Remove this recovery point from the hub catalogue?</p>
{deletion.isError && <p role="alert" className="text-sm text-orbit-red">Snapshot could not be removed. It may be in use.</p>}
<div className="flex gap-2">
<Button disabled={deletion.isPending} onClick={() => setConfirmDelete(false)}>Cancel</Button>
<Button variant="warn" disabled={deletion.isPending} onClick={() => deletion.mutate()}>Confirm deletion</Button>
</div>
</div>
) : <Button className="w-full" onClick={() => setConfirmDelete(true)}>Delete snapshot</Button>}
<TelemetryPanel label="Snapshot ID">{snap.id}</TelemetryPanel>
</div>
);

View File

@@ -1,25 +1,40 @@
import { useLayoutEffect } from "react";
import { useLayoutEffect, useRef } from "react";
export function useGalaxyMotion(draw: (elapsed: number) => boolean) {
const latest = useRef(draw);
const wake = useRef<() => void>(undefined);
export function useGalaxyMotion(active: boolean, draw: (elapsed: number) => boolean) {
useLayoutEffect(() => {
let frame = 0;
let previous: number | undefined;
const tick = (now: number) => {
const keepDrawing = draw(previous === undefined ? 0 : (now - previous) / 1000);
previous = now;
if (keepDrawing) frame = requestAnimationFrame(tick);
frame = 0;
const keepDrawing = latest.current(previous === undefined ? 0 : (now - previous) / 1000);
previous = keepDrawing ? now : undefined;
if (keepDrawing) schedule();
};
const sync = () => {
const schedule = () => {
if (!frame && !document.hidden) frame = requestAnimationFrame(tick);
};
const visibilityChanged = () => {
cancelAnimationFrame(frame);
frame = 0;
previous = undefined;
if (!document.hidden && active) frame = requestAnimationFrame(tick);
if (!document.hidden && latest.current(0)) schedule();
};
draw(0);
sync();
document.addEventListener("visibilitychange", sync);
wake.current = schedule;
document.addEventListener("visibilitychange", visibilityChanged);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener("visibilitychange", sync);
wake.current = undefined;
document.removeEventListener("visibilitychange", visibilityChanged);
};
}, [active, draw]);
}, []);
useLayoutEffect(() => {
latest.current = draw;
if (draw(0)) wake.current?.();
});
}

View File

@@ -0,0 +1,97 @@
import { animate, useMotionValue } from "motion/react";
import { useLayoutEffect, useRef, type RefObject } from "react";
import { gentleSpring } from "../lib/motion";
export function useScreenTransition(
ref: RefObject<HTMLElement | null>,
bigScreen: boolean,
reducedMotion: boolean,
onSettled?: (width: number) => void,
fade = false,
) {
const centerX = useMotionValue(0);
const centerY = useMotionValue(0);
const width = useMotionValue(0);
const height = useMotionValue(0);
const target = useRef<DOMRect>(undefined);
const lastMode = useRef(bigScreen);
useLayoutEffect(() => {
if (!ref.current) return;
const element = ref.current;
const values = [centerX, centerY, width, height];
const changedMode = lastMode.current !== bigScreen;
lastMode.current = bigScreen;
let revision = 0;
function paint() {
const rect = target.current;
if (!rect?.width || !rect.height) return;
const x = centerX.get() - rect.left - rect.width / 2;
const y = centerY.get() - rect.top - rect.height / 2;
const sx = width.get() / rect.width;
const sy = height.get() / rect.height;
element.style.transform = `translate(${x}px, ${y}px) scale(${sx}, ${sy})`;
if (fade) element.style.opacity = String(1 - Math.min(0.35, Math.hypot(x, y) / 300));
}
function measure(transition = false) {
const previous = target.current;
element.style.transform = "";
const next = element.getBoundingClientRect();
target.current = next;
const destination = [next.left + next.width / 2, next.top + next.height / 2, next.width, next.height];
const animating = values.some(value => value.isAnimating());
if (previous && next.x === previous.x && next.y === previous.y &&
next.width === previous.width && next.height === previous.height && !reducedMotion && !transition) {
if (animating) paint();
return;
}
const version = ++revision;
const finish = () => {
element.style.transform = "";
if (fade) element.style.opacity = "";
onSettled?.(element.clientWidth);
};
if (reducedMotion || !previous?.width || !previous.height || (!transition && !animating)) {
values.forEach((value, index) => value.jump(destination[index]));
finish();
return;
}
let remaining = values.length;
paint();
values.forEach((value, index) => animate(value, destination[index], {
...gentleSpring,
restDelta: 0.25,
restSpeed: 2,
onComplete: () => {
if (version === revision && --remaining === 0) finish();
},
}));
}
const unsubscribes = values.map(value => value.on("change", paint));
const resize = () => measure();
const observer = new ResizeObserver(resize);
observer.observe(element);
window.addEventListener("resize", resize);
window.addEventListener("scroll", resize, { passive: true });
measure(changedMode);
return () => {
revision++;
unsubscribes.forEach(unsubscribe => unsubscribe());
observer.disconnect();
window.removeEventListener("resize", resize);
window.removeEventListener("scroll", resize);
};
}, [ref, bigScreen, reducedMotion, onSettled, fade, centerX, centerY, width, height]);
useLayoutEffect(() => () => {
centerX.stop();
centerY.stop();
width.stop();
height.stop();
}, [centerX, centerY, width, height]);
}

View File

@@ -83,6 +83,7 @@ button:disabled { cursor: default; }
touch-action: pan-y;
user-select: none;
}
.nav-icon { position: absolute; inset: 0; margin: auto; }
.vault-nav button:hover, .vault-nav button[aria-current] { color: var(--color-star-100); }
.vault-nav button[aria-current] { cursor: grab; }
.vault-nav:active button[aria-current] { cursor: grabbing; }
@@ -125,6 +126,87 @@ button:disabled { cursor: default; }
}
.hub-link { justify-self: end; display: flex; align-items: center; gap: 8px; color: var(--color-star-300); font: 500 11px var(--font-mono); white-space: nowrap; }
.vault-topbar-tools { justify-self: end; display: flex; align-items: center; gap: clamp(8px, 1.5vw, 20px); }
.search-trigger kbd { color: var(--quiet); font: 10px var(--font-mono); }
.big-screen .vault-topbar-tools {
position: absolute;
z-index: 30;
bottom: var(--screen-bottom);
right: max(var(--screen-gutter), env(safe-area-inset-right));
}
.search-overlay {
--search-viewport: 100dvh;
--search-top: clamp(12px, calc(var(--search-viewport) * .09), 84px);
--search-body-limit: max(0px, calc(var(--search-viewport) - var(--search-top) - 74px));
position: fixed;
inset: var(--search-viewport-top, 0px) 0 auto;
height: var(--search-viewport);
z-index: 50;
display: grid;
justify-items: center;
align-items: start;
padding: var(--search-top) 12px 12px;
background: #030508a6;
}
.search-overlay[inert] { pointer-events: none; }
.search-panel {
width: min(100%, 560px);
min-width: 0;
overflow: clip;
border: 1px solid #44434a;
border-radius: 12px;
background: #15181cf5;
backdrop-filter: blur(16px);
box-shadow: 0 18px 64px #0009;
}
.search-field {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 10px 8px 16px;
height: 60px;
border-bottom: 1px solid var(--line);
color: var(--accent);
}
.search-field > svg { flex: none; }
.search-field input { flex: 1; min-width: 0; padding: 6px; font-size: 16px; color: var(--color-star-100); }
.search-field input::placeholder { color: var(--quiet); }
.search-field .search-close { justify-content: center; width: 44px; height: 44px; padding: 0; }
.search-list-frame, .search-body { max-height: var(--search-body-limit); }
.search-list-frame { overflow: clip; }
.search-body { overflow: auto; overscroll-behavior: contain; }
.search-group { padding: 10px 14px 4px; }
.search-result {
display: flex;
align-items: center;
gap: 10px;
margin-inline: 6px;
min-height: 44px;
padding: 6px 8px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
}
.search-result > svg { flex: none; color: var(--accent); }
.search-result[aria-selected="true"] { background: #493329; box-shadow: inset 2px 0 var(--accent); }
.search-result:hover { background: #352c29; }
.search-result-text { min-width: 0; }
.search-result-text > * { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.search-result-text small, .search-status { font: 11px/1.5 var(--font-mono); color: var(--quiet); }
.search-status { display: flex; flex-wrap: wrap; gap: 4px 12px; padding: 10px 14px; }
@media (max-width: 840px) {
.vault-topbar-tools .search-trigger { justify-content: center; width: 44px; min-height: 44px; padding: 0; }
.search-trigger span { display: none; }
}
@media (max-width: 1120px) {
.search-trigger kbd { display: none; }
}
@media (max-width: 420px) {
.big-screen .vault-topbar-tools { bottom: auto; top: var(--screen-top); }
.big-screen .vault-overlay .vault-dialog { top: calc(var(--screen-top) + 52px); }
}
.vault-main { max-width: 1720px; padding: 30px clamp(16px, 3vw, 44px) 10px; margin-inline: auto; }
.vault-overview { display: flex; align-items: end; justify-content: space-between; gap: 18px; margin-bottom: 25px; }
.overview-label span { color: var(--accent); margin-right: 5px; }
@@ -168,7 +250,7 @@ button:disabled { cursor: default; }
padding: 7px 10px;
text-align: left;
}
.register-row:hover, .snapshot-row:hover { background: #1b1e23; }
.snapshot-row:hover { background: #1b1e23; }
.register-row[aria-pressed="true"] { background: #222025; box-shadow: inset 2px 0 var(--accent); }
.register-content { min-width: 0; }
.register-content span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
@@ -214,10 +296,11 @@ button:disabled { cursor: default; }
.inspector-history h3 { font-size: 12px; font-weight: 550; }
.inspector-history header span { color: var(--quiet); font: 11px var(--font-mono); }
.inspector-history .console-empty { padding-top: 10px; }
.snapshot-row { width: 100%; min-height: 52px; display: grid; grid-template-columns: 17px minmax(0, 1fr) 12px; align-items: center; gap: 8px; padding: 7px 13px; text-align: left; }
.snapshot-row { position: relative; width: 100%; min-height: 52px; display: grid; grid-template-columns: 17px minmax(0, 1fr) 12px; align-items: center; gap: 8px; padding: 7px 13px; text-align: left; }
.snapshot-row strong { display: block; font-size: 12px; font-weight: 550; }
.snapshot-row small { display: block; margin-top: 3px; font: 10px/1.3 var(--font-mono); color: var(--quiet); }
.snapshot-glyph { color: #c6d2e6; font-size: 18px; }
.snapshot-row-flash { position: absolute; inset: 0; background: #ffb9752b; box-shadow: inset 2px 0 var(--accent); pointer-events: none; }
.snapshot-arrow { color: var(--quiet); }
.vault-scene {
@@ -242,8 +325,7 @@ button:disabled { cursor: default; }
.scene-controls { display: flex; align-items: center; gap: 6px; }
.scene-toolbar button { flex: none; }
.scene-mode { display: flex; align-items: center; gap: 7px; margin-top: 3px; font-size: 13px; }
.mode-signal { flex: none; width: 6px; height: 6px; background: var(--accent); transform: rotate(45deg); border-radius: 1px; }
.mode-signal.is-live { background: var(--color-orbit-green); border-radius: 50%; transform: none; }
.mode-signal { flex: none; width: 6px; height: 6px; background: var(--accent); border-radius: 1px; }
.scene-focus { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: var(--quiet); }
.scene-footer { border-top: 1px solid #24282c; background: #0a0c10bb; }
.scene-footer > p span { color: var(--accent); }
@@ -265,17 +347,19 @@ button:disabled { cursor: default; }
.orbit-halo { opacity: .08; }
.orbit-alert, .orbit-selection, .orbit-busy { fill: none; stroke: currentColor; stroke-width: 1.15; pointer-events: none; }
.orbit-selection { stroke: #f8eadc; stroke-width: 1; }
.orbit-busy { stroke-dasharray: 3 3; }
.orbit-layer--far .orbit-marker:not(.orbit-marker--red, .orbit-marker--selected) { opacity: .76; }
.orbit-busy { stroke-dasharray: 3 3; transform: rotate(var(--busy-angle, 0deg)); }
.orbit-hit { fill: transparent; cursor: pointer; }
.orbit-marker:hover .orbit-halo { opacity: .3; }
.lock-details { opacity: var(--lock-reveal, 0); }
.snapshot-marker line { stroke: #bdc4ce; opacity: .58; stroke-dasharray: 2 3; pointer-events: none; }
.snapshot-light { fill: #dce5f7; stroke: #272c35; stroke-width: 1.1; pointer-events: none; }
.snapshot-marker:hover .snapshot-light { fill: #fff; }
.focus-leader { stroke: var(--accent); opacity: .65; pointer-events: none; }
.accretion-flow { stroke-dashoffset: var(--accretion-offset, 0); }
.accretion-flow--inner { stroke-dashoffset: calc(32 + 2 * var(--accretion-offset, 0)); }
.capture-arrival path { stroke: #ffce9b; stroke-width: 2.3; stroke-linecap: round; }
.core-absorption { opacity: var(--capture-absorption, 0); }
.capture-flare, .snapshot-flash { stroke-width: 1.5; }
.snapshot-flash { fill: none; stroke: #ffce9b; pointer-events: none; }
.capture-arrival use { stroke: #ffce9b; stroke-linecap: round; }
.capture-arrival circle { fill: #fff0d9; }
.scene-labels { position: absolute; inset: 0; pointer-events: none; }
.scene-labels span { display: block; position: absolute; height: 24px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; line-height: 22px; color: #dde0e6; background: #111519ed; border: 1px solid #353c46; border-radius: 4px; padding-inline: 7px; }
@@ -327,8 +411,18 @@ button:disabled { cursor: default; }
.big-screen .vault-topbar { display: contents; }
.big-screen .vault-dialog { top: var(--screen-top); bottom: calc(var(--screen-bottom) + 64px); }
.big-screen :is(.vault-brand, .hub-link, .vault-console, .vault-footer, .scene-footer) { display: none; }
.big-screen :is(.vault-brand, .hub-link, .vault-footer, .scene-footer) { display: none; }
.big-screen .vault-main { padding: 0; }
.big-screen .vault-console {
position: absolute;
z-index: 1;
top: 185px;
bottom: 70px;
width: clamp(190px, 16%, 260px);
pointer-events: none;
}
.big-screen .orbit-register { left: clamp(16px, 3vw, 44px); }
.big-screen .orbit-inspector { right: clamp(16px, 3vw, 44px); }
.big-screen .vault-workspace,
.big-screen .vault-scene { position: absolute; inset: 0; display: grid; }
.big-screen .vault-workspace { grid-template: 1fr / 1fr; height: auto; }
@@ -371,11 +465,11 @@ button:disabled { cursor: default; }
position: absolute;
z-index: 30;
bottom: var(--screen-bottom);
left: 50%;
transform: translateX(-50%);
inset-inline: 0;
width: max-content;
gap: 4px;
max-width: calc(100% - 2 * var(--screen-gutter));
margin: 0;
margin: 0 auto;
padding: 5px 7px;
border-radius: 999px;
box-shadow: inset 0 1px #ffffff12, 0 8px 30px #0008;
@@ -387,6 +481,7 @@ button:disabled { cursor: default; }
border-radius: 999px;
padding: 0;
}
.big-screen .nav-label { position: absolute; }
.big-screen .vault-nav button[aria-current] { color: #ffe2c9; }
@media (max-width: 1060px) {

View File

@@ -12,12 +12,18 @@ export function formatWhen(iso: string): string {
});
}
export function schedulePhrase(cron?: string | null, dryRun?: boolean): string {
if (dryRun) return "Rehearse — no vault write";
if (!cron) return "On your command";
if (cron.includes("0 2")) return "Every night at 2am";
if (cron.includes("0 */6")) return "Every six hours";
return cron;
export function schedulePhrase(orbit: import("../api").Orbit): string {
if (orbit.access === "outpost") {
const schedule = orbit.capture_schedule;
if (!schedule) return orbit.application_id ? "On your command" : "Started by the Outpost";
const time = [schedule.hour, schedule.minute].map((part) => String(part).padStart(2, "0")).join(":");
return `Daily at ${time} ${schedule.timezone}`;
}
const cron = orbit.schedule?.trim().replace(/\s+/g, " ");
if (!cron) return orbit.dry_run ? "Rehearse on command" : "On your command";
if (cron === "0 2 * * *" || cron === "0 0 2 * * *") return "Daily at 02:00 UTC";
if (cron === "0 */6 * * *" || cron === "0 0 */6 * * *") return "Every six hours (UTC)";
return `${cron} (UTC)`;
}
export type VaultStatus = "green" | "amber" | "grey" | "red";
@@ -25,6 +31,7 @@ export type VaultStatus = "green" | "amber" | "grey" | "red";
export function orbitStatus(status: string): { label: string; tone: VaultStatus; busy?: boolean } {
switch (status) {
case "failed": return { label: "Failed", tone: "red" };
case "queued": return { label: "Queued", tone: "amber", busy: true };
case "running": return { label: "Running", tone: "amber", busy: true };
case "rehearsing": return { label: "Rehearsing", tone: "amber", busy: true };
case "rehearsed": return { label: "Rehearsed", tone: "amber" };

View File

@@ -13,12 +13,14 @@ export function placeLabels(
width: number,
height: number,
obstacles: Rect[],
selectedId?: string,
): Label[] {
const occupied = [...obstacles];
const placed: Label[] = [];
for (const label of candidates) {
const { x, y, width: w } = label;
const offsets = [12, 28, 44].flatMap((gap) => [
const gaps = label.id === selectedId ? [12, 28, 44, 64, 88, 112, 144, 180] : [12, 28, 44];
const offsets = gaps.flatMap((gap) => [
[gap, -LABEL_HEIGHT / 2], [-w - gap, -LABEL_HEIGHT / 2],
[-w / 2, -LABEL_HEIGHT - gap], [-w / 2, gap],
[gap, -LABEL_HEIGHT - gap / 2], [-w - gap, gap / 2],

View File

@@ -103,3 +103,16 @@ export function spiralPoint(source: Vec2, progress: number): Vec2 {
const radius = Math.hypot(source.x, source.y) * (1 - u ** 1.4);
return { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };
}
export const CAPTURE_HIGHLIGHT_START = 0.94;
export function capturePhases(progress: number) {
const stage = (start: number, end: number) => Math.min(1, Math.max(0, (progress - start) / (end - start)));
return {
flare: stage(0, 0.06) * (1 - stage(0.08, 0.24)),
flight: stage(0.09, 0.79),
absorption: stage(0.76, 0.84) * (1 - stage(0.85, CAPTURE_HIGHLIGHT_START)),
highlight: stage(CAPTURE_HIGHLIGHT_START, 0.97) * (1 - stage(0.97, 0.998)),
failure: stage(0, 0.15) * (1 - stage(0.17, 0.9)),
};
}

View File

@@ -5,12 +5,24 @@ export const uiSpring = {
stiffness: 320,
damping: 36,
mass: 1,
restDelta: 0.01,
restSpeed: 0.05,
} as const satisfies Transition;
export const ambientPulse = {
export const gentleSpring = {
...uiSpring,
stiffness: 180,
damping: 28,
} as const satisfies Transition;
export const ambientSpring = {
...uiSpring,
stiffness: 40,
damping: 13,
} as const satisfies Transition;
export const ambientPulse = {
...ambientSpring,
repeat: Infinity,
repeatType: "mirror",
} as const satisfies Transition;

View File

@@ -0,0 +1,65 @@
import type { Orbit, Snapshot } from "../api";
import type { HUDMode } from "../components/hud/HUDRail";
import { formatWhen } from "./format.ts";
type Navigation = { id: Exclude<HUDMode, "snapshot">; label: string; icon: string };
export type SearchResult =
| (Navigation & { kind: "navigation"; detail?: undefined })
| { kind: "orbit" | "snapshot"; id: string; label: string; detail: string };
type Candidate = { result: SearchResult; fields: string[]; timestamp?: number };
function matchRank(fields: string[], term: string) {
return Math.min(...fields.map(value => {
const field = value.toLowerCase();
if (field === term) return 0;
if (field.startsWith(term)) return 1;
if (field.includes(term)) return 2;
return Infinity;
}));
}
export function createVaultSearch(
navigation: readonly Navigation[],
orbits: readonly Pick<Orbit, "id" | "name" | "provider">[] = [],
snapshots: readonly Snapshot[] = [],
) {
const destinations = navigation.map(item => ({ ...item, kind: "navigation" as const }));
const categories: [string, Candidate[]][] = [
["Navigation", destinations.map(result => ({ result, fields: [result.label] }))],
["Orbits", orbits.map(({ id, name, provider }) => ({
result: { kind: "orbit", id, label: name, detail: `${provider} · ${id}` },
fields: [name, id, provider],
}))],
["Snapshots", snapshots.map(({ id, orbit_id, orbit_name, taken_at }) => {
const date = formatWhen(taken_at);
return {
result: { kind: "snapshot", id, label: orbit_name, detail: `${date} · ${id}` },
fields: [orbit_name, id, orbit_id ?? "", date],
timestamp: Date.parse(taken_at) || 0,
};
})],
];
return (query: string): { label: string; results: SearchResult[] }[] => {
const term = query.trim().toLowerCase();
if (!term) return [{ label: "Navigation", results: destinations.slice(0, 8) }];
const groups = categories.map(([label, candidates]) => ({
label,
results: candidates
.map(candidate => ({ ...candidate, rank: matchRank(candidate.fields, term) }))
.filter(({ rank }) => Number.isFinite(rank))
.sort((a, b) => a.rank - b.rank || (b.timestamp ?? 0) - (a.timestamp ?? 0) ||
a.result.id.localeCompare(b.result.id))
.map(({ result }) => result),
})).filter(({ results }) => results.length);
let remaining = 8;
return groups.map(({ label, results }, index) => {
// Leave at least one slot for each later category with matches.
const visible = results.slice(0, remaining - (groups.length - index - 1));
remaining -= visible.length;
return { label, results: visible };
});
};
}