Files
tessera/web/src/App.tsx
Adnan Zahir 34e9afc8a4 feat: render the black hole and sky with a WebGL2 ray tracer
Replace the SVG core and backdrop with one shader that traces each pixel
through Schwarzschild spacetime. The shadow, the arch of the far side of the
disk, the second image and the Einstein ring come from the physics rather than
artwork. The disk is a thin disk seen from a low angle, about five times the
shadow's radius, with Doppler beaming and a filtered, cloud-like texture.

- Sky: a procedural galaxy baked once into a cubemap. Point sources are small,
  few and brightness-capped so they never rival the orbit markers, which now
  carry a dark backing disc and outline.
- Quality: tiers from high to still, a startup calibration cached per canvas
  size, an fps cap, and an idle sleep. A locked realistic map draws nothing.
- Integration: the canvas follows the galaxy frame through Big Screen, draws in
  Motion's post-render step, takes the disk clock and capture absorption from
  the galaxy loop, and falls back to the SVG core without WebGL2.
- Radar view: a toolbar toggle switches to a radar look that spreads outward
  from the hole as a wave, with a sweep on its own clock. The choice is
  remembered per browser; reduced motion switches at once and holds the sweep.
- Tests for the geodesics, quality governor, look spring and layout, plus a
  standalone preview page (web/blackhole-proto.html) for tuning the look.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 21:51:35 +07:00

369 lines
17 KiB
TypeScript

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<HUDMode, string> = {
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 <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 [radar, setRadar] = useState(readRadar);
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);
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 && (
<p className={`capture-notice${capture.isError ? " tone-red" : ""}`} role="status">
{captureLabel} {capture.variables.name}{capture.isPending ? "…" : "."}
</p>
);
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<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 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" />
<ellipse cx="19" cy="19" rx="17" ry="5.8" transform="rotate(-32 19 19)" fill="none" stroke="currentColor" />
<circle cx="19" cy="19" r="3" fill="currentColor" />
</svg>
<div><strong>Tessera</strong><span>Backup control</span></div>
</div>
<HUDRail active={mode === "snapshot" ? "scene" : mode} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
<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 || searchOpen}>
<div className="vault-overview">
<div>
<p className="instrument-label overview-label"><span aria-hidden="true">◈</span> Vault / 01</p>
<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} 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} captureEffect={captureEffect} captureGlow={captureGlow} captureReady={captureReady}
bigScreen={bigScreen} onToggleBigScreen={toggleBigScreen}
radar={radar} onToggleRadar={toggleRadar}
onToggleFlow={() => setPlay((value) => !value)}
onSelectOrbit={(id) => {
selectOrbit(id);
document.getElementById(`register-${id}`)?.focus({ preventScroll: true });
}}
onSelectSnapshot={openSnapshot}
/>
<OrbitRegister
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 ||
(selected.access === "outpost" && !selected.application_id)}
>
<span aria-hidden="true">↘</span>
<span>{selected.application_id ? "Queue backup for" : selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
</button>
{noticeInInspector && mode !== "orbits" && captureNotice}
</>
)}
/>
</div>
<footer className="vault-footer">
{(!noticeInInspector && mode !== "orbits" && captureNotice) || <p>Vault telemetry</p>}
<p role="status">{restoreBusy ? "Restore active · open Restore to monitor" : "Local backup station"}</p>
</footer>
</main>
<HUDPanel
open={panelOpen}
inert={searchOpen}
title={panelTitles[mode]}
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
onClose={() => setMode("scene")}
>
<AnimatePresence initial={false}>
{mode === "orbits" && (
<SpringPane key="orbits">
<QueryGate query={orbits}>
{() => <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 === "snapshot" && (
<SpringPane key="snapshot">
{snapshot
? <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>
)}
</AnimatePresence>
<SpringPane active={mode === "reconstitute"}>
{restoreTarget && (snaps.data?.length || restoreBusy ? (
<ReconstituteWizard
key={restoreTarget.id ?? "manual"}
snapshots={snaps.data ?? []} selected={restoreTarget.id} scopedExport={!!actor}
onStart={startReconstitute} onPoll={pollReconstitute} onAbort={abortReconstitute} onBusyChange={setRestoreBusy}
/>
) : (
<QueryGate query={snaps} empty={<EmptyState title="No snapshots to restore" body="Capture an orbit to create a recovery point." />}>
{() => null}
</QueryGate>
))}
</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>
);
}