import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { AnimatePresence, useMotionValue } from "motion/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute, enqueueCapture, runOrbit, startReconstitute, type Orbit, } from "./api"; 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"; import { VaultScene } from "./components/scene/VaultScene"; import { EmptyState } from "./components/ui/EmptyState"; import { QueryGate } from "./components/ui/QueryGate"; import { SpringPane } from "./components/ui/SpringPane"; 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 = { scene: "Vault", orbits: "Orbit management", wormhole: "Wormhole uplink", reconstitute: "Restore snapshot", snapshot: "Snapshot detail", }; const LOOK_KEY = "tessera.look"; /** The look is a per-viewer preference. Storage can be blocked or empty, so every access is guarded. */ function readRadar() { try { return window.localStorage.getItem(LOOK_KEY) === "radar"; } catch { return false; } } function priority(orbit: Orbit) { if (orbit.last_status === "failed") return 0; return orbitStatus(orbit.last_status).busy ? 1 : 2; } export default function App() { return {(operator) => }; } function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promise }) { const [logoutError, setLogoutError] = useState(false); const workspaceScroll = useRef(undefined); const [bigScreen, setBigScreen] = useState(false); const [radar, setRadar] = useState(readRadar); const [mode, setMode] = useState("scene"); const [searchOpen, setSearchOpen] = useState(false); const searchTrigger = useRef(null); const searchDestination = useRef<() => HTMLElement | null>(undefined); const panelOpen = mode !== "scene"; const [orbitId, setOrbitId] = useState(); const [snapshotId, setSnapshotId] = useState(null); const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null); const [play, setPlay] = useState(true); const [restoreBusy, setRestoreBusy] = useState(false); const [restoreTarget, setRestoreTarget] = useState<{ id: string | null }>(); const reducedMotion = useReducedMotion(); const qc = useQueryClient(); 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 && !event.repeat) { setBigScreen(false); } }; window.addEventListener("keydown", exitOnEscape); return () => window.removeEventListener("keydown", exitOnEscape); }, [bigScreen, mode]); useLayoutEffect(() => { if (bigScreen || workspaceScroll.current === undefined) return; window.scrollTo(0, workspaceScroll.current); workspaceScroll.current = undefined; }, [bigScreen]); function toggleBigScreen() { if (!bigScreen) workspaceScroll.current = window.scrollY; setBigScreen(!bigScreen); } function toggleRadar() { const next = !radar; setRadar(next); try { window.localStorage.setItem(LOOK_KEY, next ? "radar" : "realistic"); } catch { // The look still changes for this visit; it just will not be remembered. } } 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: 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.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]); const totalBytes = useMemo(() => (snaps.data ?? []).reduce((sum, snap) => sum + snap.size_bytes, 0), [snaps.data]); const selected = sceneOrbits.find(({ id }) => id === orbitId); const history = (selected && grouped.get(selected.id)) ?? []; const snapshot = snaps.data?.find(({ id }) => id === snapshotId); 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 ? orbits.data ? "Live telemetry unavailable. Showing last known orbits." : "Orbit telemetry unavailable." : register.length ? undefined : "No backup jobs yet. Set up an orbit to begin."; 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.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 && (

{captureLabel} {capture.variables.name}{capture.isPending ? "…" : "."}

); const noticeInInspector = !!selected && selected.id === capture.variables?.id; function selectOrbit(id: string) { setOrbitId(id); setPlay(false); } function openSnapshot(id: string) { document.getElementById(`snapshot-${id}`)?.focus({ preventScroll: true }); setSnapshotId(id); setMode("snapshot"); } function runCapture(target: Orbit) { if (target.access === "outpost" && !target.application_id) return; selectOrbit(target.id); capture.mutate(target); } function openConsole(next: HUDMode, target: string | null = null) { if (next === "reconstitute" && !restoreBusy && (!restoreTarget || (target !== null && target !== restoreTarget.id))) { setRestoreTarget({ id: target }); } 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(".vault-dialog .dialog-heading h2"); } if (bigScreen) return document.querySelector(".scene-screen-control"); return result.kind === "orbit" ? document.getElementById(`register-${result.id}`) : document.querySelector(".vault-overview h1"); }; setSearchOpen(false); } return (
TesseraBackup control

{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}

{onLogout && } {logoutError &&

Could not sign out.

}

Vault / 01

Orbital vault

Backup jobs and recovery points

setPlay((value) => !value)} onSelectOrbit={(id) => { selectOrbit(id); document.getElementById(`register-${id}`)?.focus({ preventScroll: true }); }} onSelectSnapshot={openSnapshot} /> setMode("orbits")} /> {noticeInInspector && mode !== "orbits" && captureNotice} )} />
{(!noticeInInspector && mode !== "orbits" && captureNotice) ||

Vault telemetry

}

{restoreBusy ? "Restore active · open Restore to monitor" : "Local backup station"}

setMode("scene")} > {mode === "orbits" && ( {() => } )} {mode === "wormhole" && ( )} {mode === "snapshot" && ( {snapshot ? openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} /> : } )} {restoreTarget && (snaps.data?.length || restoreBusy ? ( ) : ( }> {() => null} ))} setSearchOpen(false)} onSelect={selectSearchResult} />
); }